void gen_intermediate_code(CPUARMState *env, TranslationBlock *tb)

{

    ARMCPU *cpu = arm_env_get_cpu(env);

    CPUState *cs = CPU(cpu);

    DisasContext dc1, *dc = &dc1;

    target_ulong pc_start;

    target_ulong next_page_start;

    int num_insns;

    int max_insns;

    /* generate intermediate code */

    /* The A64 decoder has its own top level loop, because it doesn't need

     * the A32/T32 complexity to do with conditional execution/IT blocks/etc.

     */

    if (ARM_TBFLAG_AARCH64_STATE(tb->flags)) {

        gen_intermediate_code_a64(cpu, tb);

        return;

    }

    pc_start = tb->pc;

    dc->tb = tb;

    dc->is_jmp = DISAS_NEXT;

    dc->pc = pc_start;

    dc->singlestep_enabled = cs->singlestep_enabled;

    dc->condjmp = 0;

    dc->aarch64 = 0;

    /* If we are coming from secure EL0 in a system with a 32-bit EL3, then

     * there is no secure EL1, so we route exceptions to EL3.

     */

    dc->secure_routed_to_el3 = arm_feature(env, ARM_FEATURE_EL3) &&

                               !arm_el_is_aa64(env, 3);

    dc->thumb = ARM_TBFLAG_THUMB(tb->flags);

    dc->bswap_code = ARM_TBFLAG_BSWAP_CODE(tb->flags);

    dc->condexec_mask = (ARM_TBFLAG_CONDEXEC(tb->flags) & 0xf) << 1;

    dc->condexec_cond = ARM_TBFLAG_CONDEXEC(tb->flags) >> 4;

    dc->mmu_idx = ARM_TBFLAG_MMUIDX(tb->flags);

    dc->current_el = arm_mmu_idx_to_el(dc->mmu_idx);

#if !defined(CONFIG_USER_ONLY)

    dc->user = (dc->current_el == 0);

#endif

    dc->ns = ARM_TBFLAG_NS(tb->flags);

    dc->fp_excp_el = ARM_TBFLAG_FPEXC_EL(tb->flags);

    dc->vfp_enabled = ARM_TBFLAG_VFPEN(tb->flags);

    dc->vec_len = ARM_TBFLAG_VECLEN(tb->flags);

    dc->vec_stride = ARM_TBFLAG_VECSTRIDE(tb->flags);

    dc->c15_cpar = ARM_TBFLAG_XSCALE_CPAR(tb->flags);

    dc->cp_regs = cpu->cp_regs;

    dc->features = env->features;

    /* Single step state. The code-generation logic here is:

     *  SS_ACTIVE == 0:

     *   generate code with no special handling for single-stepping (except

     *   that anything that can make us go to SS_ACTIVE == 1 must end the TB;

     *   this happens anyway because those changes are all system register or

     *   PSTATE writes).

     *  SS_ACTIVE == 1, PSTATE.SS == 1: (active-not-pending)

     *   emit code for one insn

     *   emit code to clear PSTATE.SS

     *   emit code to generate software step exception for completed step

     *   end TB (as usual for having generated an exception)

     *  SS_ACTIVE == 1, PSTATE.SS == 0: (active-pending)

     *   emit code to generate a software step exception

     *   end the TB

     */

    dc->ss_active = ARM_TBFLAG_SS_ACTIVE(tb->flags);

    dc->pstate_ss = ARM_TBFLAG_PSTATE_SS(tb->flags);

    dc->is_ldex = false;

    dc->ss_same_el = false; /* Can't be true since EL_d must be AArch64 */

    cpu_F0s = tcg_temp_new_i32();

    cpu_F1s = tcg_temp_new_i32();

    cpu_F0d = tcg_temp_new_i64();

    cpu_F1d = tcg_temp_new_i64();

    cpu_V0 = cpu_F0d;

    cpu_V1 = cpu_F1d;

    /* FIXME: cpu_M0 can probably be the same as cpu_V0.  */

    cpu_M0 = tcg_temp_new_i64();

    next_page_start = (pc_start & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE;

    num_insns = 0;

    max_insns = tb->cflags & CF_COUNT_MASK;

    if (max_insns == 0) {

        max_insns = CF_COUNT_MASK;

    }

    if (max_insns > TCG_MAX_INSNS) {

        max_insns = TCG_MAX_INSNS;

    }

    gen_tb_start(tb);

    tcg_clear_temp_count();

    /* A note on handling of the condexec (IT) bits:

     *

     * We want to avoid the overhead of having to write the updated condexec

     * bits back to the CPUARMState for every instruction in an IT block. So:

     * (1) if the condexec bits are not already zero then we write

     * zero back into the CPUARMState now. This avoids complications trying

     * to do it at the end of the block. (For example if we don't do this

     * it's hard to identify whether we can safely skip writing condexec

     * at the end of the TB, which we definitely want to do for the case

     * where a TB doesn't do anything with the IT state at all.)

     * (2) if we are going to leave the TB then we call gen_set_condexec()

     * which will write the correct value into CPUARMState if zero is wrong.

     * This is done both for leaving the TB at the end, and for leaving

     * it because of an exception we know will happen, which is done in

     * gen_exception_insn(). The latter is necessary because we need to

     * leave the TB with the PC/IT state just prior to execution of the

     * instruction which caused the exception.

     * (3) if we leave the TB unexpectedly (eg a data abort on a load)

     * then the CPUARMState will be wrong and we need to reset it.

     * This is handled in the same way as restoration of the

     * PC in these situations; we save the value of the condexec bits

     * for each PC via tcg_gen_insn_start(), and restore_state_to_opc()

     * then uses this to restore them after an exception.

     *

     * Note that there are no instructions which can read the condexec

     * bits, and none which can write non-static values to them, so

     * we don't need to care about whether CPUARMState is correct in the

     * middle of a TB.

     */

    /* Reset the conditional execution bits immediately. This avoids

       complications trying to do it at the end of the block.  */

    if (dc->condexec_mask || dc->condexec_cond)

      {

        TCGv_i32 tmp = tcg_temp_new_i32();

        tcg_gen_movi_i32(tmp, 0);

        store_cpu_field(tmp, condexec_bits);

      }

    do {

        tcg_gen_insn_start(dc->pc,

                           (dc->condexec_cond << 4) | (dc->condexec_mask >> 1));

        num_insns++;

#ifdef CONFIG_USER_ONLY

        /* Intercept jump to the magic kernel page.  */

        if (dc->pc >= 0xffff0000) {

            /* We always get here via a jump, so know we are not in a

               conditional execution block.  */

            gen_exception_internal(EXCP_KERNEL_TRAP);

            dc->is_jmp = DISAS_UPDATE;

            break;

        }

#else

        if (dc->pc >= 0xfffffff0 && arm_dc_feature(dc, ARM_FEATURE_M)) {

            /* We always get here via a jump, so know we are not in a

               conditional execution block.  */

            gen_exception_internal(EXCP_EXCEPTION_EXIT);

            dc->is_jmp = DISAS_UPDATE;

            break;

        }

#endif

        if (unlikely(!QTAILQ_EMPTY(&cs->breakpoints))) {

            CPUBreakpoint *bp;

            QTAILQ_FOREACH(bp, &cs->breakpoints, entry) {

                if (bp->pc == dc->pc) {

                    gen_exception_internal_insn(dc, 0, EXCP_DEBUG);

                    /* Advance PC so that clearing the breakpoint will

                       invalidate this TB.  */

                    dc->pc += 2;

                    goto done_generating;

                }

            }

        }

        if (num_insns == max_insns && (tb->cflags & CF_LAST_IO)) {

            gen_io_start();

        }

        if (dc->ss_active && !dc->pstate_ss) {

            /* Singlestep state is Active-pending.

             * If we're in this state at the start of a TB then either

             *  a) we just took an exception to an EL which is being debugged

             *     and this is the first insn in the exception handler

             *  b) debug exceptions were masked and we just unmasked them

             *     without changing EL (eg by clearing PSTATE.D)

             * In either case we're going to take a swstep exception in the

             * "did not step an insn" case, and so the syndrome ISV and EX

             * bits should be zero.

             */

            assert(num_insns == 1);

            gen_exception(EXCP_UDEF, syn_swstep(dc->ss_same_el, 0, 0),

                          default_exception_el(dc));

            goto done_generating;

        }

        if (dc->thumb) {

            disas_thumb_insn(env, dc);

            if (dc->condexec_mask) {

                dc->condexec_cond = (dc->condexec_cond & 0xe)

                                   | ((dc->condexec_mask >> 4) & 1);

                dc->condexec_mask = (dc->condexec_mask << 1) & 0x1f;

                if (dc->condexec_mask == 0) {

                    dc->condexec_cond = 0;

                }

            }

        } else {

            unsigned int insn = arm_ldl_code(env, dc->pc, dc->bswap_code);

            dc->pc += 4;

            disas_arm_insn(dc, insn);

        }

        if (dc->condjmp && !dc->is_jmp) {

            gen_set_label(dc->condlabel);

            dc->condjmp = 0;

        }

        if (tcg_check_temp_count()) {

            fprintf(stderr, "TCG temporary leak before "TARGET_FMT_lx"\n",

                    dc->pc);

        }

        /* Translation stops when a conditional branch is encountered.

         * Otherwise the subsequent code could get translated several times.

         * Also stop translation when a page boundary is reached.  This

         * ensures prefetch aborts occur at the right place.  */

    } while (!dc->is_jmp && !tcg_op_buf_full() &&

             !cs->singlestep_enabled &&

             !singlestep &&

             !dc->ss_active &&

             dc->pc < next_page_start &&

             num_insns < max_insns);

    if (tb->cflags & CF_LAST_IO) {

        if (dc->condjmp) {

            /* FIXME:  This can theoretically happen with self-modifying

               code.  */

            cpu_abort(cs, "IO on conditional branch instruction");

        }

        gen_io_end();

    }

    /* At this stage dc->condjmp will only be set when the skipped

       instruction was a conditional branch or trap, and the PC has

       already been written.  */

    if (unlikely(cs->singlestep_enabled || dc->ss_active)) {

        /* Make sure the pc is updated, and raise a debug exception.  */

        if (dc->condjmp) {

            gen_set_condexec(dc);

            if (dc->is_jmp == DISAS_SWI) {

                gen_ss_advance(dc);

                gen_exception(EXCP_SWI, syn_aa32_svc(dc->svc_imm, dc->thumb),

                              default_exception_el(dc));

            } else if (dc->is_jmp == DISAS_HVC) {

                gen_ss_advance(dc);

                gen_exception(EXCP_HVC, syn_aa32_hvc(dc->svc_imm), 2);

            } else if (dc->is_jmp == DISAS_SMC) {

                gen_ss_advance(dc);

                gen_exception(EXCP_SMC, syn_aa32_smc(), 3);

            } else if (dc->ss_active) {

                gen_step_complete_exception(dc);

            } else {

                gen_exception_internal(EXCP_DEBUG);

            }

            gen_set_label(dc->condlabel);

        }

        if (dc->condjmp || !dc->is_jmp) {

            gen_set_pc_im(dc, dc->pc);

            dc->condjmp = 0;

        }

        gen_set_condexec(dc);

        if (dc->is_jmp == DISAS_SWI && !dc->condjmp) {

            gen_ss_advance(dc);

            gen_exception(EXCP_SWI, syn_aa32_svc(dc->svc_imm, dc->thumb),

                          default_exception_el(dc));

        } else if (dc->is_jmp == DISAS_HVC && !dc->condjmp) {

            gen_ss_advance(dc);

            gen_exception(EXCP_HVC, syn_aa32_hvc(dc->svc_imm), 2);

        } else if (dc->is_jmp == DISAS_SMC && !dc->condjmp) {

            gen_ss_advance(dc);

            gen_exception(EXCP_SMC, syn_aa32_smc(), 3);

        } else if (dc->ss_active) {

            gen_step_complete_exception(dc);

        } else {

            /* FIXME: Single stepping a WFI insn will not halt

               the CPU.  */

            gen_exception_internal(EXCP_DEBUG);

        }

    } else {

        /* While branches must always occur at the end of an IT block,

           there are a few other things that can cause us to terminate

           the TB in the middle of an IT block:

            - Exception generating instructions (bkpt, swi, undefined).

            - Page boundaries.

            - Hardware watchpoints.

           Hardware breakpoints have already been handled and skip this code.

         */

        gen_set_condexec(dc);

        switch(dc->is_jmp) {

        case DISAS_NEXT:

            gen_goto_tb(dc, 1, dc->pc);

            break;

        default:

        case DISAS_JUMP:

        case DISAS_UPDATE:

            /* indicate that the hash table must be used to find the next TB */

            tcg_gen_exit_tb(0);

            break;

        case DISAS_TB_JUMP:

            /* nothing more to generate */

            break;

        case DISAS_WFI:

            gen_helper_wfi(cpu_env);

            /* The helper doesn't necessarily throw an exception, but we

             * must go back to the main loop to check for interrupts anyway.

             */

            tcg_gen_exit_tb(0);

            break;

        case DISAS_WFE:

            gen_helper_wfe(cpu_env);

            break;

        case DISAS_YIELD:

            gen_helper_yield(cpu_env);

            break;

        case DISAS_SWI:

            gen_exception(EXCP_SWI, syn_aa32_svc(dc->svc_imm, dc->thumb),

                          default_exception_el(dc));

            break;

        case DISAS_HVC:

            gen_exception(EXCP_HVC, syn_aa32_hvc(dc->svc_imm), 2);

            break;

        case DISAS_SMC:

            gen_exception(EXCP_SMC, syn_aa32_smc(), 3);

            break;

        }

        if (dc->condjmp) {

            gen_set_label(dc->condlabel);

            gen_set_condexec(dc);

            gen_goto_tb(dc, 1, dc->pc);

            dc->condjmp = 0;

        }

    }

done_generating:

    gen_tb_end(tb, num_insns);

#ifdef DEBUG_DISAS

    if (qemu_loglevel_mask(CPU_LOG_TB_IN_ASM)) {

        qemu_log("----------------\n");

        qemu_log("IN: %s\n", lookup_symbol(pc_start));

        log_target_disas(cs, pc_start, dc->pc - pc_start,

                         dc->thumb | (dc->bswap_code << 1));

        qemu_log("\n");

    }

#endif

    tb->size = dc->pc - pc_start;

    tb->icount = num_insns;

}


static inline uint64_t vtd_get_slpte_addr(uint64_t slpte)

{

    return slpte & VTD_SL_PT_BASE_ADDR_MASK(VTD_HOST_ADDRESS_WIDTH);

}


static void open_eth_cleanup(NetClientState *nc)

{

}


void HELPER(wsr_lbeg)(uint32_t v)

{

    if (env->sregs[LBEG] != v) {

        tb_invalidate_phys_page_range(

                env->sregs[LEND] - 1, env->sregs[LEND], 0);

        env->sregs[LBEG] = v;

    }

}


void mips_cpu_do_interrupt(CPUState *cs)

{

#if !defined(CONFIG_USER_ONLY)

    MIPSCPU *cpu = MIPS_CPU(cs);

    CPUMIPSState *env = &cpu->env;

    bool update_badinstr = 0;

    target_ulong offset;

    int cause = -1;

    const char *name;

    if (qemu_loglevel_mask(CPU_LOG_INT)

        && cs->exception_index != EXCP_EXT_INTERRUPT) {

        if (cs->exception_index < 0 || cs->exception_index > EXCP_LAST) {

            name = "unknown";

        } else {

            name = excp_names[cs->exception_index];

        }

        qemu_log("%s enter: PC " TARGET_FMT_lx " EPC " TARGET_FMT_lx

                 " %s exception\n",

                 __func__, env->active_tc.PC, env->CP0_EPC, name);

    }

    if (cs->exception_index == EXCP_EXT_INTERRUPT &&

        (env->hflags & MIPS_HFLAG_DM)) {

        cs->exception_index = EXCP_DINT;

    }

    offset = 0x180;

    switch (cs->exception_index) {

    case EXCP_DSS:

        env->CP0_Debug |= 1 << CP0DB_DSS;

        /* Debug single step cannot be raised inside a delay slot and

           resume will always occur on the next instruction

           (but we assume the pc has always been updated during

           code translation). */

        env->CP0_DEPC = env->active_tc.PC | !!(env->hflags & MIPS_HFLAG_M16);

        goto enter_debug_mode;

    case EXCP_DINT:

        env->CP0_Debug |= 1 << CP0DB_DINT;

        goto set_DEPC;

    case EXCP_DIB:

        env->CP0_Debug |= 1 << CP0DB_DIB;

        goto set_DEPC;

    case EXCP_DBp:

        env->CP0_Debug |= 1 << CP0DB_DBp;

        goto set_DEPC;

    case EXCP_DDBS:

        env->CP0_Debug |= 1 << CP0DB_DDBS;

        goto set_DEPC;

    case EXCP_DDBL:

        env->CP0_Debug |= 1 << CP0DB_DDBL;

    set_DEPC:

        env->CP0_DEPC = exception_resume_pc(env);

        env->hflags &= ~MIPS_HFLAG_BMASK;

 enter_debug_mode:

        if (env->insn_flags & ISA_MIPS3) {

            env->hflags |= MIPS_HFLAG_64;

            if (!(env->insn_flags & ISA_MIPS64R6) ||

                env->CP0_Status & (1 << CP0St_KX)) {

                env->hflags &= ~MIPS_HFLAG_AWRAP;

            }

        }

        env->hflags |= MIPS_HFLAG_DM | MIPS_HFLAG_CP0;

        env->hflags &= ~(MIPS_HFLAG_KSU);

        /* EJTAG probe trap enable is not implemented... */

        if (!(env->CP0_Status & (1 << CP0St_EXL)))

            env->CP0_Cause &= ~(1U << CP0Ca_BD);

        env->active_tc.PC = (int32_t)0xBFC00480;

        set_hflags_for_handler(env);

        break;

    case EXCP_RESET:

        cpu_reset(CPU(cpu));

        break;

    case EXCP_SRESET:

        env->CP0_Status |= (1 << CP0St_SR);

        memset(env->CP0_WatchLo, 0, sizeof(env->CP0_WatchLo));

        goto set_error_EPC;

    case EXCP_NMI:

        env->CP0_Status |= (1 << CP0St_NMI);

 set_error_EPC:

        env->CP0_ErrorEPC = exception_resume_pc(env);

        env->hflags &= ~MIPS_HFLAG_BMASK;

        env->CP0_Status |= (1 << CP0St_ERL) | (1 << CP0St_BEV);

        if (env->insn_flags & ISA_MIPS3) {

            env->hflags |= MIPS_HFLAG_64;

            if (!(env->insn_flags & ISA_MIPS64R6) ||

                env->CP0_Status & (1 << CP0St_KX)) {

                env->hflags &= ~MIPS_HFLAG_AWRAP;

            }

        }

        env->hflags |= MIPS_HFLAG_CP0;

        env->hflags &= ~(MIPS_HFLAG_KSU);

        if (!(env->CP0_Status & (1 << CP0St_EXL)))

            env->CP0_Cause &= ~(1U << CP0Ca_BD);

        env->active_tc.PC = (int32_t)0xBFC00000;

        set_hflags_for_handler(env);

        break;

    case EXCP_EXT_INTERRUPT:

        cause = 0;

        if (env->CP0_Cause & (1 << CP0Ca_IV)) {

            uint32_t spacing = (env->CP0_IntCtl >> CP0IntCtl_VS) & 0x1f;

            if ((env->CP0_Status & (1 << CP0St_BEV)) || spacing == 0) {

                offset = 0x200;

            } else {

                uint32_t vector = 0;

                uint32_t pending = (env->CP0_Cause & CP0Ca_IP_mask) >> CP0Ca_IP;

                if (env->CP0_Config3 & (1 << CP0C3_VEIC)) {

                    /* For VEIC mode, the external interrupt controller feeds

                     * the vector through the CP0Cause IP lines.  */

                    vector = pending;

                } else {

                    /* Vectored Interrupts

                     * Mask with Status.IM7-IM0 to get enabled interrupts. */

                    pending &= (env->CP0_Status >> CP0St_IM) & 0xff;

                    /* Find the highest-priority interrupt. */

                    while (pending >>= 1) {

                        vector++;

                    }

                }

                offset = 0x200 + (vector * (spacing << 5));

            }

        }

        goto set_EPC;

    case EXCP_LTLBL:

        cause = 1;

        update_badinstr = !(env->error_code & EXCP_INST_NOTAVAIL);

        goto set_EPC;

    case EXCP_TLBL:

        cause = 2;

        update_badinstr = !(env->error_code & EXCP_INST_NOTAVAIL);

        if ((env->error_code & EXCP_TLB_NOMATCH) &&

            !(env->CP0_Status & (1 << CP0St_EXL))) {

#if defined(TARGET_MIPS64)

            int R = env->CP0_BadVAddr >> 62;

            int UX = (env->CP0_Status & (1 << CP0St_UX)) != 0;

            int SX = (env->CP0_Status & (1 << CP0St_SX)) != 0;

            int KX = (env->CP0_Status & (1 << CP0St_KX)) != 0;

            if (((R == 0 && UX) || (R == 1 && SX) || (R == 3 && KX)) &&

                (!(env->insn_flags & (INSN_LOONGSON2E | INSN_LOONGSON2F))))

                offset = 0x080;

            else

#endif

                offset = 0x000;

        }

        goto set_EPC;

    case EXCP_TLBS:

        cause = 3;

        update_badinstr = 1;

        if ((env->error_code & EXCP_TLB_NOMATCH) &&

            !(env->CP0_Status & (1 << CP0St_EXL))) {

#if defined(TARGET_MIPS64)

            int R = env->CP0_BadVAddr >> 62;

            int UX = (env->CP0_Status & (1 << CP0St_UX)) != 0;

            int SX = (env->CP0_Status & (1 << CP0St_SX)) != 0;

            int KX = (env->CP0_Status & (1 << CP0St_KX)) != 0;

            if (((R == 0 && UX) || (R == 1 && SX) || (R == 3 && KX)) &&

                (!(env->insn_flags & (INSN_LOONGSON2E | INSN_LOONGSON2F))))

                offset = 0x080;

            else

#endif

                offset = 0x000;

        }

        goto set_EPC;

    case EXCP_AdEL:

        cause = 4;

        update_badinstr = !(env->error_code & EXCP_INST_NOTAVAIL);

        goto set_EPC;

    case EXCP_AdES:

        cause = 5;

        update_badinstr = 1;

        goto set_EPC;

    case EXCP_IBE:

        cause = 6;

        goto set_EPC;

    case EXCP_DBE:

        cause = 7;

        goto set_EPC;

    case EXCP_SYSCALL:

        cause = 8;

        update_badinstr = 1;

        goto set_EPC;

    case EXCP_BREAK:

        cause = 9;

        update_badinstr = 1;

        goto set_EPC;

    case EXCP_RI:

        cause = 10;

        update_badinstr = 1;

        goto set_EPC;

    case EXCP_CpU:

        cause = 11;

        update_badinstr = 1;

        env->CP0_Cause = (env->CP0_Cause & ~(0x3 << CP0Ca_CE)) |

                         (env->error_code << CP0Ca_CE);

        goto set_EPC;

    case EXCP_OVERFLOW:

        cause = 12;

        update_badinstr = 1;

        goto set_EPC;

    case EXCP_TRAP:

        cause = 13;

        update_badinstr = 1;

        goto set_EPC;

    case EXCP_MSAFPE:

        cause = 14;

        update_badinstr = 1;

        goto set_EPC;

    case EXCP_FPE:

        cause = 15;

        update_badinstr = 1;

        goto set_EPC;

    case EXCP_C2E:

        cause = 18;

        goto set_EPC;

    case EXCP_TLBRI:

        cause = 19;

        update_badinstr = 1;

        goto set_EPC;

    case EXCP_TLBXI:

        cause = 20;

        goto set_EPC;

    case EXCP_MSADIS:

        cause = 21;

        update_badinstr = 1;

        goto set_EPC;

    case EXCP_MDMX:

        cause = 22;

        goto set_EPC;

    case EXCP_DWATCH:

        cause = 23;

        /* XXX: TODO: manage deferred watch exceptions */

        goto set_EPC;

    case EXCP_MCHECK:

        cause = 24;

        goto set_EPC;

    case EXCP_THREAD:

        cause = 25;

        goto set_EPC;

    case EXCP_DSPDIS:

        cause = 26;

        goto set_EPC;

    case EXCP_CACHE:

        cause = 30;

        if (env->CP0_Status & (1 << CP0St_BEV)) {

            offset = 0x100;

        } else {

            offset = 0x20000100;

        }

 set_EPC:

        if (!(env->CP0_Status & (1 << CP0St_EXL))) {

            env->CP0_EPC = exception_resume_pc(env);

            if (update_badinstr) {

                set_badinstr_registers(env);

            }

            if (env->hflags & MIPS_HFLAG_BMASK) {

                env->CP0_Cause |= (1U << CP0Ca_BD);

            } else {

                env->CP0_Cause &= ~(1U << CP0Ca_BD);

            }

            env->CP0_Status |= (1 << CP0St_EXL);

            if (env->insn_flags & ISA_MIPS3) {

                env->hflags |= MIPS_HFLAG_64;

                if (!(env->insn_flags & ISA_MIPS64R6) ||

                    env->CP0_Status & (1 << CP0St_KX)) {

                    env->hflags &= ~MIPS_HFLAG_AWRAP;

                }

            }

            env->hflags |= MIPS_HFLAG_CP0;

            env->hflags &= ~(MIPS_HFLAG_KSU);

        }

        env->hflags &= ~MIPS_HFLAG_BMASK;

        if (env->CP0_Status & (1 << CP0St_BEV)) {

            env->active_tc.PC = (int32_t)0xBFC00200;

        } else {

            env->active_tc.PC = (int32_t)(env->CP0_EBase & ~0x3ff);

        }

        env->active_tc.PC += offset;

        set_hflags_for_handler(env);

        env->CP0_Cause = (env->CP0_Cause & ~(0x1f << CP0Ca_EC)) | (cause << CP0Ca_EC);

        break;

    default:

        abort();

    }

    if (qemu_loglevel_mask(CPU_LOG_INT)

        && cs->exception_index != EXCP_EXT_INTERRUPT) {

        qemu_log("%s: PC " TARGET_FMT_lx " EPC " TARGET_FMT_lx " cause %d\n"

                 "    S %08x C %08x A " TARGET_FMT_lx " D " TARGET_FMT_lx "\n",

                 __func__, env->active_tc.PC, env->CP0_EPC, cause,

                 env->CP0_Status, env->CP0_Cause, env->CP0_BadVAddr,

                 env->CP0_DEPC);

    }

#endif

    cs->exception_index = EXCP_NONE;

}


uri_resolve_relative (const char *uri, const char * base)

{

    char *val = NULL;

    int ret;

    int ix;

    int pos = 0;

    int nbslash = 0;

    int len;

    URI *ref = NULL;

    URI *bas = NULL;

    char *bptr, *uptr, *vptr;

    int remove_path = 0;

    if ((uri == NULL) || (*uri == 0))

	return NULL;

    /*

     * First parse URI into a standard form

     */

    ref = uri_new ();

    /* If URI not already in "relative" form */

    if (uri[0] != '.') {

	ret = uri_parse_into (ref, uri);

	if (ret != 0)

	    goto done;		/* Error in URI, return NULL */

    } else

	ref->path = g_strdup(uri);

    /*

     * Next parse base into the same standard form

     */

    if ((base == NULL) || (*base == 0)) {

	val = g_strdup (uri);

	goto done;

    }

    bas = uri_new ();

    if (base[0] != '.') {

	ret = uri_parse_into (bas, base);

	if (ret != 0)

	    goto done;		/* Error in base, return NULL */

    } else

	bas->path = g_strdup(base);

    /*

     * If the scheme / server on the URI differs from the base,

     * just return the URI

     */

    if ((ref->scheme != NULL) &&

	((bas->scheme == NULL) ||

	 (strcmp (bas->scheme, ref->scheme)) ||

	 (strcmp (bas->server, ref->server)))) {

	val = g_strdup (uri);

	goto done;

    }

    if (!strcmp(bas->path, ref->path)) {

	val = g_strdup("");

	goto done;

    }

    if (bas->path == NULL) {

	val = g_strdup(ref->path);

	goto done;

    }

    if (ref->path == NULL) {

        ref->path = (char *) "/";

	remove_path = 1;

    }

    /*

     * At this point (at last!) we can compare the two paths

     *

     * First we take care of the special case where either of the

     * two path components may be missing (bug 316224)

     */

    if (bas->path == NULL) {

	if (ref->path != NULL) {

	    uptr = ref->path;

	    if (*uptr == '/')

		uptr++;

	    /* exception characters from uri_to_string */

	    val = uri_string_escape(uptr, "/;&=+$,");

	}

	goto done;

    }

    bptr = bas->path;

    if (ref->path == NULL) {

	for (ix = 0; bptr[ix] != 0; ix++) {

	    if (bptr[ix] == '/')

		nbslash++;

	}

	uptr = NULL;

	len = 1;	/* this is for a string terminator only */

    } else {

    /*

     * Next we compare the two strings and find where they first differ

     */

	if ((ref->path[pos] == '.') && (ref->path[pos+1] == '/'))

            pos += 2;

	if ((*bptr == '.') && (bptr[1] == '/'))

            bptr += 2;

	else if ((*bptr == '/') && (ref->path[pos] != '/'))

	    bptr++;

	while ((bptr[pos] == ref->path[pos]) && (bptr[pos] != 0))

	    pos++;

	if (bptr[pos] == ref->path[pos]) {

	    val = g_strdup("");

	    goto done;		/* (I can't imagine why anyone would do this) */

	}

	/*

	 * In URI, "back up" to the last '/' encountered.  This will be the

	 * beginning of the "unique" suffix of URI

	 */

	ix = pos;

	if ((ref->path[ix] == '/') && (ix > 0))

	    ix--;

	else if ((ref->path[ix] == 0) && (ix > 1) && (ref->path[ix - 1] == '/'))

	    ix -= 2;

	for (; ix > 0; ix--) {

	    if (ref->path[ix] == '/')

		break;

	}

	if (ix == 0) {

	    uptr = ref->path;

	} else {

	    ix++;

	    uptr = &ref->path[ix];

	}

	/*

	 * In base, count the number of '/' from the differing point

	 */

	if (bptr[pos] != ref->path[pos]) {/* check for trivial URI == base */

	    for (; bptr[ix] != 0; ix++) {

		if (bptr[ix] == '/')

		    nbslash++;

	    }

	}

	len = strlen (uptr) + 1;

    }

    if (nbslash == 0) {

	if (uptr != NULL)

	    /* exception characters from uri_to_string */

	    val = uri_string_escape(uptr, "/;&=+$,");

	goto done;

    }

    /*

     * Allocate just enough space for the returned string -

     * length of the remainder of the URI, plus enough space

     * for the "../" groups, plus one for the terminator

     */

    val = g_malloc (len + 3 * nbslash);

    vptr = val;

    /*

     * Put in as many "../" as needed

     */

    for (; nbslash>0; nbslash--) {

	*vptr++ = '.';

	*vptr++ = '.';

	*vptr++ = '/';

    }

    /*

     * Finish up with the end of the URI

     */

    if (uptr != NULL) {

        if ((vptr > val) && (len > 0) &&

	    (uptr[0] == '/') && (vptr[-1] == '/')) {

	    memcpy (vptr, uptr + 1, len - 1);

	    vptr[len - 2] = 0;

	} else {

	    memcpy (vptr, uptr, len);

	    vptr[len - 1] = 0;

	}

    } else {

	vptr[len - 1] = 0;

    }

    /* escape the freshly-built path */

    vptr = val;

	/* exception characters from uri_to_string */

    val = uri_string_escape(vptr, "/;&=+$,");

    g_free(vptr);

done:

    /*

     * Free the working variables

     */

    if (remove_path != 0)

        ref->path = NULL;

    if (ref != NULL)

	uri_free (ref);

    if (bas != NULL)

	uri_free (bas);

    return val;

}


static uint64_t omap_sti_fifo_read(void *opaque, target_phys_addr_t addr,

                                   unsigned size)

{

    OMAP_BAD_REG(addr);

    return 0;

}


static inline uint64_t hpet_calculate_diff(HPETTimer *t, uint64_t current)

{

    if (t->config & HPET_TN_32BIT) {

        uint32_t diff, cmp;

        cmp = (uint32_t)t->cmp;

        diff = cmp - (uint32_t)current;

        diff = (int32_t)diff > 0 ? diff : (uint32_t)0;

        return (uint64_t)diff;

    } else {

        uint64_t diff, cmp;

        cmp = t->cmp;

        diff = cmp - current;

        diff = (int64_t)diff > 0 ? diff : (uint64_t)0;

        return diff;

    }

}


static int mpc8_decode_frame(AVCodecContext * avctx, void *data,

                             int *got_frame_ptr, AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    MPCContext *c = avctx->priv_data;

    GetBitContext gb2, *gb = &gb2;

    int i, j, k, ch, cnt, res, t;

    Band *bands = c->bands;

    int off;

    int maxband, keyframe;

    int last[2];

    /* get output buffer */

    c->frame.nb_samples = MPC_FRAME_SIZE;

    if ((res = avctx->get_buffer(avctx, &c->frame)) < 0) {

        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");

        return res;

    }

    keyframe = c->cur_frame == 0;

    if(keyframe){

        memset(c->Q, 0, sizeof(c->Q));

        c->last_bits_used = 0;

    }

    init_get_bits(gb, buf, buf_size * 8);

    skip_bits(gb, c->last_bits_used & 7);

    if(keyframe)

        maxband = mpc8_get_mod_golomb(gb, c->maxbands + 1);

    else{

        maxband = c->last_max_band + get_vlc2(gb, band_vlc.table, MPC8_BANDS_BITS, 2);

        if(maxband > 32) maxband -= 33;

    }

    if(maxband > c->maxbands + 1 || maxband >= BANDS) {

        av_log(avctx, AV_LOG_ERROR, "maxband %d too large\n",maxband);

        return AVERROR_INVALIDDATA;

    }

    c->last_max_band = maxband;

    /* read subband indexes */

    if(maxband){

        last[0] = last[1] = 0;

        for(i = maxband - 1; i >= 0; i--){

            for(ch = 0; ch < 2; ch++){

                last[ch] = get_vlc2(gb, res_vlc[last[ch] > 2].table, MPC8_RES_BITS, 2) + last[ch];

                if(last[ch] > 15) last[ch] -= 17;

                bands[i].res[ch] = last[ch];

            }

        }

        if(c->MSS){

            int mask;

            cnt = 0;

            for(i = 0; i < maxband; i++)

                if(bands[i].res[0] || bands[i].res[1])

                    cnt++;

            t = mpc8_get_mod_golomb(gb, cnt);

            mask = mpc8_get_mask(gb, cnt, t);

            for(i = maxband - 1; i >= 0; i--)

                if(bands[i].res[0] || bands[i].res[1]){

                    bands[i].msf = mask & 1;

                    mask >>= 1;

                }

        }

    }

    for(i = maxband; i < c->maxbands; i++)

        bands[i].res[0] = bands[i].res[1] = 0;

    if(keyframe){

        for(i = 0; i < 32; i++)

            c->oldDSCF[0][i] = c->oldDSCF[1][i] = 1;

    }

    for(i = 0; i < maxband; i++){

        if(bands[i].res[0] || bands[i].res[1]){

            cnt = !!bands[i].res[0] + !!bands[i].res[1] - 1;

            if(cnt >= 0){

                t = get_vlc2(gb, scfi_vlc[cnt].table, scfi_vlc[cnt].bits, 1);

                if(bands[i].res[0]) bands[i].scfi[0] = t >> (2 * cnt);

                if(bands[i].res[1]) bands[i].scfi[1] = t & 3;

            }

        }

    }

    for(i = 0; i < maxband; i++){

        for(ch = 0; ch < 2; ch++){

            if(!bands[i].res[ch]) continue;

            if(c->oldDSCF[ch][i]){

                bands[i].scf_idx[ch][0] = get_bits(gb, 7) - 6;

                c->oldDSCF[ch][i] = 0;

            }else{

                t = get_vlc2(gb, dscf_vlc[1].table, MPC8_DSCF1_BITS, 2);

                if(t == 64)

                    t += get_bits(gb, 6);

                bands[i].scf_idx[ch][0] = ((bands[i].scf_idx[ch][2] + t - 25) & 0x7F) - 6;

            }

            for(j = 0; j < 2; j++){

                if((bands[i].scfi[ch] << j) & 2)

                    bands[i].scf_idx[ch][j + 1] = bands[i].scf_idx[ch][j];

                else{

                    t = get_vlc2(gb, dscf_vlc[0].table, MPC8_DSCF0_BITS, 2);

                    if(t == 31)

                        t = 64 + get_bits(gb, 6);

                    bands[i].scf_idx[ch][j + 1] = ((bands[i].scf_idx[ch][j] + t - 25) & 0x7F) - 6;

                }

            }

        }

    }

    for(i = 0, off = 0; i < maxband; i++, off += SAMPLES_PER_BAND){

        for(ch = 0; ch < 2; ch++){

            res = bands[i].res[ch];

            switch(res){

            case -1:

                for(j = 0; j < SAMPLES_PER_BAND; j++)

                    c->Q[ch][off + j] = (av_lfg_get(&c->rnd) & 0x3FC) - 510;

                break;

            case 0:

                break;

            case 1:

                for(j = 0; j < SAMPLES_PER_BAND; j += SAMPLES_PER_BAND / 2){

                    cnt = get_vlc2(gb, q1_vlc.table, MPC8_Q1_BITS, 2);

                    t = mpc8_get_mask(gb, 18, cnt);

                    for(k = 0; k < SAMPLES_PER_BAND / 2; k++, t <<= 1)

                        c->Q[ch][off + j + k] = (t & 0x20000) ? (get_bits1(gb) << 1) - 1 : 0;

                }

                break;

            case 2:

                cnt = 6;//2*mpc8_thres[res]

                for(j = 0; j < SAMPLES_PER_BAND; j += 3){

                    t = get_vlc2(gb, q2_vlc[cnt > 3].table, MPC8_Q2_BITS, 2);

                    c->Q[ch][off + j + 0] = mpc8_idx50[t];

                    c->Q[ch][off + j + 1] = mpc8_idx51[t];

                    c->Q[ch][off + j + 2] = mpc8_idx52[t];

                    cnt = (cnt >> 1) + mpc8_huffq2[t];

                }

                break;

            case 3:

            case 4:

                for(j = 0; j < SAMPLES_PER_BAND; j += 2){

                    t = get_vlc2(gb, q3_vlc[res - 3].table, MPC8_Q3_BITS, 2) + q3_offsets[res - 3];

                    c->Q[ch][off + j + 1] = t >> 4;

                    c->Q[ch][off + j + 0] = (t & 8) ? (t & 0xF) - 16 : (t & 0xF);

                }

                break;

            case 5:

            case 6:

            case 7:

            case 8:

                cnt = 2 * mpc8_thres[res];

                for(j = 0; j < SAMPLES_PER_BAND; j++){

                    t = get_vlc2(gb, quant_vlc[res - 5][cnt > mpc8_thres[res]].table, quant_vlc[res - 5][cnt > mpc8_thres[res]].bits, 2) + quant_offsets[res - 5];

                    c->Q[ch][off + j] = t;

                    cnt = (cnt >> 1) + FFABS(c->Q[ch][off + j]);

                }

                break;

            default:

                for(j = 0; j < SAMPLES_PER_BAND; j++){

                    c->Q[ch][off + j] = get_vlc2(gb, q9up_vlc.table, MPC8_Q9UP_BITS, 2);

                    if(res != 9){

                        c->Q[ch][off + j] <<= res - 9;

                        c->Q[ch][off + j] |= get_bits(gb, res - 9);

                    }

                    c->Q[ch][off + j] -= (1 << (res - 2)) - 1;

                }

            }

        }

    }

    ff_mpc_dequantize_and_synth(c, maxband - 1, c->frame.data[0],

                                avctx->channels);

    c->cur_frame++;

    c->last_bits_used = get_bits_count(gb);

    if(c->cur_frame >= c->frames)

        c->cur_frame = 0;

    *got_frame_ptr   = 1;

    *(AVFrame *)data = c->frame;

    return c->cur_frame ? c->last_bits_used >> 3 : buf_size;

}


int configure_accelerator(MachineState *ms)

{

    const char *p;

    char buf[10];

    int ret;

    bool accel_initialised = false;

    bool init_failed = false;

    AccelClass *acc = NULL;

    p = qemu_opt_get(qemu_get_machine_opts(), "accel");

    if (p == NULL) {

        /* Use the default "accelerator", tcg */

        p = "tcg";

    }

    while (!accel_initialised && *p != '\0') {

        if (*p == ':') {

            p++;

        }

        p = get_opt_name(buf, sizeof(buf), p, ':');

        acc = accel_find(buf);

        if (!acc) {

            fprintf(stderr, "\"%s\" accelerator not found.\n", buf);

            continue;

        }

        if (acc->available && !acc->available()) {

            printf("%s not supported for this target\n",

                   acc->name);

            continue;

        }

        ret = accel_init_machine(acc, ms);

        if (ret < 0) {

            init_failed = true;

            fprintf(stderr, "failed to initialize %s: %s\n",

                    acc->name,

                    strerror(-ret));

        } else {

            accel_initialised = true;

        }

    }

    if (!accel_initialised) {

        if (!init_failed) {

            fprintf(stderr, "No accelerator found!\n");

        }

        exit(1);

    }

    if (init_failed) {

        fprintf(stderr, "Back to %s accelerator.\n", acc->name);

    }

    return !accel_initialised;

}


int bdrv_snapshot_goto(BlockDriverState *bs,

                       const char *snapshot_id,

                       Error **errp)

{

    BlockDriver *drv = bs->drv;

    int ret, open_ret;

    int64_t len;

    if (!drv) {

        error_setg(errp, "Block driver is closed");

        return -ENOMEDIUM;

    }

    len = bdrv_getlength(bs);

    if (len < 0) {

        error_setg_errno(errp, -len, "Cannot get block device size");

        return len;

    }

    /* We should set all bits in all enabled dirty bitmaps, because dirty

     * bitmaps reflect active state of disk and snapshot switch operation

     * actually dirties active state.

     * TODO: It may make sense not to set all bits but analyze block status of

     * current state and destination snapshot and do not set bits corresponding

     * to both-zero or both-unallocated areas. */

    bdrv_set_dirty(bs, 0, len);

    if (drv->bdrv_snapshot_goto) {

        ret = drv->bdrv_snapshot_goto(bs, snapshot_id);

        if (ret < 0) {

            error_setg_errno(errp, -ret, "Failed to load snapshot");

        }

        return ret;

    }

    if (bs->file) {

        BlockDriverState *file;

        QDict *options = qdict_clone_shallow(bs->options);

        QDict *file_options;

        Error *local_err = NULL;

        file = bs->file->bs;

        /* Prevent it from getting deleted when detached from bs */

        bdrv_ref(file);

        qdict_extract_subqdict(options, &file_options, "file.");

        QDECREF(file_options);

        qdict_put_str(options, "file", bdrv_get_node_name(file));

        drv->bdrv_close(bs);

        bdrv_unref_child(bs, bs->file);

        bs->file = NULL;

        ret = bdrv_snapshot_goto(file, snapshot_id, errp);

        open_ret = drv->bdrv_open(bs, options, bs->open_flags, &local_err);

        QDECREF(options);

        if (open_ret < 0) {

            bdrv_unref(file);

            bs->drv = NULL;

            /* A bdrv_snapshot_goto() error takes precedence */

            error_propagate(errp, local_err);

            return ret < 0 ? ret : open_ret;

        }

        assert(bs->file->bs == file);

        bdrv_unref(file);

        return ret;

    }

    error_setg(errp, "Block driver does not support snapshots");

    return -ENOTSUP;

}


static void test_qemu_strtoull_negative(void)

{

    const char *str = "  \t -321";

    char f = 'X';

    const char *endptr = &f;

    uint64_t res = 999;

    int err;

    err = qemu_strtoull(str, &endptr, 0, &res);

    g_assert_cmpint(err, ==, 0);

    g_assert_cmpint(res, ==, -321);

    g_assert(endptr == str + strlen(str));

}


static void omap_clkdsp_write(void *opaque, target_phys_addr_t addr,

                              uint64_t value, unsigned size)

{

    struct omap_mpu_state_s *s = (struct omap_mpu_state_s *) opaque;

    uint16_t diff;

    if (size != 2) {

        return omap_badwidth_write16(opaque, addr, value);

    }

    switch (addr) {

    case 0x04:	/* DSP_IDLECT1 */

        diff = s->clkm.dsp_idlect1 ^ value;

        s->clkm.dsp_idlect1 = value & 0x01f7;

        omap_clkdsp_idlect1_update(s, diff, value);

        break;

    case 0x08:	/* DSP_IDLECT2 */

        s->clkm.dsp_idlect2 = value & 0x0037;

        diff = s->clkm.dsp_idlect1 ^ value;

        omap_clkdsp_idlect2_update(s, diff, value);

        break;

    case 0x14:	/* DSP_RSTCT2 */

        s->clkm.dsp_rstct2 = value & 0x0001;

        break;

    case 0x18:	/* DSP_SYSST */

        s->clkm.cold_start &= value & 0x3f;

        break;

    default:

        OMAP_BAD_REG(addr);

    }

}


uint64_t helper_frsqrte (uint64_t arg)

{

    CPU_DoubleU fone, farg;

    fone.ll = 0x3FF0000000000000ULL; /* 1.0 */

    farg.ll = arg;

    if (unlikely(float64_is_signaling_nan(farg.d))) {

        /* sNaN reciprocal square root */

        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);

    } else if (unlikely(float64_is_neg(farg.d) && !float64_is_zero(farg.d))) {

        /* Reciprocal square root of a negative nonzero number */

        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXSQRT);

    } else if (likely(isnormal(farg.d))) {

        farg.d = float64_sqrt(farg.d, &env->fp_status);

        farg.d = float32_div(fone.d, farg.d, &env->fp_status);

    } else {

        if (farg.ll == 0x8000000000000000ULL) {

            farg.ll = 0xFFF0000000000000ULL;

        } else if (farg.ll == 0x0000000000000000ULL) {

            farg.ll = 0x7FF0000000000000ULL;

        } else if (float64_is_nan(farg.d)) {

            farg.ll |= 0x000FFFFFFFFFFFFFULL;

        } else if (float64_is_neg(farg.d)) {

            farg.ll = 0x7FF8000000000000ULL;

        } else {

            farg.ll = 0x0000000000000000ULL;

        }

    }

    return farg.ll;

}


static void gen_compute_compact_branch(DisasContext *ctx, uint32_t opc,

                                       int rs, int rt, int32_t offset)

{

    int bcond_compute = 0;

    TCGv t0 = tcg_temp_new();

    TCGv t1 = tcg_temp_new();

    if (ctx->hflags & MIPS_HFLAG_BMASK) {

#ifdef MIPS_DEBUG_DISAS

        LOG_DISAS("Branch in delay / forbidden slot at PC 0x" TARGET_FMT_lx

                  "\n", ctx->pc);

#endif

        generate_exception(ctx, EXCP_RI);

        goto out;

    }

    /* Load needed operands and calculate btarget */

    switch (opc) {

    /* compact branch */

    case OPC_BOVC: /* OPC_BEQZALC, OPC_BEQC */

    case OPC_BNVC: /* OPC_BNEZALC, OPC_BNEC */

        gen_load_gpr(t0, rs);

        gen_load_gpr(t1, rt);

        bcond_compute = 1;

        ctx->btarget = addr_add(ctx, ctx->pc + 4, offset);

        if (rs <= rt && rs == 0) {

            /* OPC_BEQZALC, OPC_BNEZALC */

            tcg_gen_movi_tl(cpu_gpr[31], ctx->pc + 4);

        }

        break;

    case OPC_BLEZC: /* OPC_BGEZC, OPC_BGEC */

    case OPC_BGTZC: /* OPC_BLTZC, OPC_BLTC */

        gen_load_gpr(t0, rs);

        gen_load_gpr(t1, rt);

        bcond_compute = 1;

        ctx->btarget = addr_add(ctx, ctx->pc + 4, offset);

        break;

    case OPC_BLEZALC: /* OPC_BGEZALC, OPC_BGEUC */

    case OPC_BGTZALC: /* OPC_BLTZALC, OPC_BLTUC */

        if (rs == 0 || rs == rt) {

            /* OPC_BLEZALC, OPC_BGEZALC */

            /* OPC_BGTZALC, OPC_BLTZALC */

            tcg_gen_movi_tl(cpu_gpr[31], ctx->pc + 4);

        }

        gen_load_gpr(t0, rs);

        gen_load_gpr(t1, rt);

        bcond_compute = 1;

        ctx->btarget = addr_add(ctx, ctx->pc + 4, offset);

        break;

    case OPC_BC:

    case OPC_BALC:

        ctx->btarget = addr_add(ctx, ctx->pc + 4, offset);

        break;

    case OPC_BEQZC:

    case OPC_BNEZC:

        if (rs != 0) {

            /* OPC_BEQZC, OPC_BNEZC */

            gen_load_gpr(t0, rs);

            bcond_compute = 1;

            ctx->btarget = addr_add(ctx, ctx->pc + 4, offset);

        } else {

            /* OPC_JIC, OPC_JIALC */

            TCGv tbase = tcg_temp_new();

            TCGv toffset = tcg_temp_new();

            gen_load_gpr(tbase, rt);

            tcg_gen_movi_tl(toffset, offset);

            gen_op_addr_add(ctx, btarget, tbase, toffset);

            tcg_temp_free(tbase);

            tcg_temp_free(toffset);

        }

        break;

    default:

        MIPS_INVAL("Compact branch/jump");

        generate_exception(ctx, EXCP_RI);

        goto out;

    }

    if (bcond_compute == 0) {

        /* Uncoditional compact branch */

        switch (opc) {

        case OPC_JIALC:

            tcg_gen_movi_tl(cpu_gpr[31], ctx->pc + 4);

            /* Fallthrough */

        case OPC_JIC:

            ctx->hflags |= MIPS_HFLAG_BR;

            break;

        case OPC_BALC:

            tcg_gen_movi_tl(cpu_gpr[31], ctx->pc + 4);

            /* Fallthrough */

        case OPC_BC:

            ctx->hflags |= MIPS_HFLAG_B;

            break;

        default:

            MIPS_INVAL("Compact branch/jump");

            generate_exception(ctx, EXCP_RI);

            goto out;

        }

        /* Generating branch here as compact branches don't have delay slot */

        gen_branch(ctx, 4);

    } else {

        /* Conditional compact branch */

        int fs = gen_new_label();

        save_cpu_state(ctx, 0);

        switch (opc) {

        case OPC_BLEZALC: /* OPC_BGEZALC, OPC_BGEUC */

            if (rs == 0 && rt != 0) {

                /* OPC_BLEZALC */

                tcg_gen_brcondi_tl(tcg_invert_cond(TCG_COND_LE), t1, 0, fs);

            } else if (rs != 0 && rt != 0 && rs == rt) {

                /* OPC_BGEZALC */

                tcg_gen_brcondi_tl(tcg_invert_cond(TCG_COND_GE), t1, 0, fs);

            } else {

                /* OPC_BGEUC */

                tcg_gen_brcond_tl(tcg_invert_cond(TCG_COND_GEU), t0, t1, fs);

            }

            break;

        case OPC_BGTZALC: /* OPC_BLTZALC, OPC_BLTUC */

            if (rs == 0 && rt != 0) {

                /* OPC_BGTZALC */

                tcg_gen_brcondi_tl(tcg_invert_cond(TCG_COND_GT), t1, 0, fs);

            } else if (rs != 0 && rt != 0 && rs == rt) {

                /* OPC_BLTZALC */

                tcg_gen_brcondi_tl(tcg_invert_cond(TCG_COND_LT), t1, 0, fs);

            } else {

                /* OPC_BLTUC */

                tcg_gen_brcond_tl(tcg_invert_cond(TCG_COND_LTU), t0, t1, fs);

            }

            break;

        case OPC_BLEZC: /* OPC_BGEZC, OPC_BGEC */

            if (rs == 0 && rt != 0) {

                /* OPC_BLEZC */

                tcg_gen_brcondi_tl(tcg_invert_cond(TCG_COND_LE), t1, 0, fs);

            } else if (rs != 0 && rt != 0 && rs == rt) {

                /* OPC_BGEZC */

                tcg_gen_brcondi_tl(tcg_invert_cond(TCG_COND_GE), t1, 0, fs);

            } else {

                /* OPC_BGEC */

                tcg_gen_brcond_tl(tcg_invert_cond(TCG_COND_GE), t0, t1, fs);

            }

            break;

        case OPC_BGTZC: /* OPC_BLTZC, OPC_BLTC */

            if (rs == 0 && rt != 0) {

                /* OPC_BGTZC */

                tcg_gen_brcondi_tl(tcg_invert_cond(TCG_COND_GT), t1, 0, fs);

            } else if (rs != 0 && rt != 0 && rs == rt) {

                /* OPC_BLTZC */

                tcg_gen_brcondi_tl(tcg_invert_cond(TCG_COND_LT), t1, 0, fs);

            } else {

                /* OPC_BLTC */

                tcg_gen_brcond_tl(tcg_invert_cond(TCG_COND_LT), t0, t1, fs);

            }

            break;

        case OPC_BOVC: /* OPC_BEQZALC, OPC_BEQC */

        case OPC_BNVC: /* OPC_BNEZALC, OPC_BNEC */

            if (rs >= rt) {

                /* OPC_BOVC, OPC_BNVC */

                TCGv t2 = tcg_temp_new();

                TCGv t3 = tcg_temp_new();

                TCGv t4 = tcg_temp_new();

                TCGv input_overflow = tcg_temp_new();

                gen_load_gpr(t0, rs);

                gen_load_gpr(t1, rt);

                tcg_gen_ext32s_tl(t2, t0);

                tcg_gen_setcond_tl(TCG_COND_NE, input_overflow, t2, t0);

                tcg_gen_ext32s_tl(t3, t1);

                tcg_gen_setcond_tl(TCG_COND_NE, t4, t3, t1);

                tcg_gen_or_tl(input_overflow, input_overflow, t4);

                tcg_gen_add_tl(t4, t2, t3);

                tcg_gen_ext32s_tl(t4, t4);

                tcg_gen_xor_tl(t2, t2, t3);

                tcg_gen_xor_tl(t3, t4, t3);

                tcg_gen_andc_tl(t2, t3, t2);

                tcg_gen_setcondi_tl(TCG_COND_LT, t4, t2, 0);

                tcg_gen_or_tl(t4, t4, input_overflow);

                if (opc == OPC_BOVC) {

                    /* OPC_BOVC */

                    tcg_gen_brcondi_tl(tcg_invert_cond(TCG_COND_NE), t4, 0, fs);

                } else {

                    /* OPC_BNVC */

                    tcg_gen_brcondi_tl(tcg_invert_cond(TCG_COND_EQ), t4, 0, fs);

                }

                tcg_temp_free(input_overflow);

                tcg_temp_free(t4);

                tcg_temp_free(t3);

                tcg_temp_free(t2);

            } else if (rs < rt && rs == 0) {

                /* OPC_BEQZALC, OPC_BNEZALC */

                if (opc == OPC_BEQZALC) {

                    /* OPC_BEQZALC */

                    tcg_gen_brcondi_tl(tcg_invert_cond(TCG_COND_EQ), t1, 0, fs);

                } else {

                    /* OPC_BNEZALC */

                    tcg_gen_brcondi_tl(tcg_invert_cond(TCG_COND_NE), t1, 0, fs);

                }

            } else {

                /* OPC_BEQC, OPC_BNEC */

                if (opc == OPC_BEQC) {

                    /* OPC_BEQC */

                    tcg_gen_brcond_tl(tcg_invert_cond(TCG_COND_EQ), t0, t1, fs);

                } else {

                    /* OPC_BNEC */

                    tcg_gen_brcond_tl(tcg_invert_cond(TCG_COND_NE), t0, t1, fs);

                }

            }

            break;

        case OPC_BEQZC:

            tcg_gen_brcondi_tl(tcg_invert_cond(TCG_COND_EQ), t0, 0, fs);

            break;

        case OPC_BNEZC:

            tcg_gen_brcondi_tl(tcg_invert_cond(TCG_COND_NE), t0, 0, fs);

            break;

        default:

            MIPS_INVAL("Compact conditional branch/jump");

            generate_exception(ctx, EXCP_RI);

            goto out;

        }

        /* Generating branch here as compact branches don't have delay slot */

        gen_goto_tb(ctx, 1, ctx->btarget);

        gen_set_label(fs);

        ctx->hflags |= MIPS_HFLAG_FBNSLOT;

        MIPS_DEBUG("Compact conditional branch");

    }

out:

    tcg_temp_free(t0);

    tcg_temp_free(t1);

}


int qemu_chr_fe_get_msgfd(CharDriverState *s)

{

    int fd;

    return (qemu_chr_fe_get_msgfds(s, &fd, 1) == 1) ? fd : -1;

}


static void vnc_client_write_locked(void *opaque)

{

    VncState *vs = opaque;

#ifdef CONFIG_VNC_SASL

    if (vs->sasl.conn &&

        vs->sasl.runSSF &&

        !vs->sasl.waitWriteSSF) {

        vnc_client_write_sasl(vs);

    } else

#endif /* CONFIG_VNC_SASL */

    {

#ifdef CONFIG_VNC_WS

        if (vs->encode_ws) {

            vnc_client_write_ws(vs);

        } else

#endif /* CONFIG_VNC_WS */

        {

            vnc_client_write_plain(vs);

        }

    }

}


iscsi_aio_write16_cb(struct iscsi_context *iscsi, int status,

                     void *command_data, void *opaque)

{

    IscsiAIOCB *acb = opaque;

    trace_iscsi_aio_write16_cb(iscsi, status, acb, acb->canceled);

    g_free(acb->buf);

    acb->buf = NULL;

    if (acb->canceled != 0) {

        return;

    }

    acb->status = 0;

    if (status < 0) {

        error_report("Failed to write16 data to iSCSI lun. %s",

                     iscsi_get_error(iscsi));

        acb->status = -EIO;

    }

    iscsi_schedule_bh(acb);

}


static void spr_write_40x_sler (void *opaque, int sprn)

{

    DisasContext *ctx = opaque;

    gen_op_store_40x_sler();

    /* We must stop the translation as we may have changed

     * some regions endianness

     */

    RET_STOP(ctx);

}


static void sclp_execute(SCLPDevice *sclp, SCCB *sccb, uint32_t code)

{

    SCLPDeviceClass *sclp_c = SCLP_GET_CLASS(sclp);

    SCLPEventFacility *ef = sclp->event_facility;

    SCLPEventFacilityClass *efc = EVENT_FACILITY_GET_CLASS(ef);

    switch (code & SCLP_CMD_CODE_MASK) {

    case SCLP_CMDW_READ_SCP_INFO:

    case SCLP_CMDW_READ_SCP_INFO_FORCED:

        sclp_c->read_SCP_info(sclp, sccb);

        break;

    case SCLP_CMDW_READ_CPU_INFO:

        sclp_c->read_cpu_info(sclp, sccb);

        break;

    case SCLP_READ_STORAGE_ELEMENT_INFO:

        if (code & 0xff00) {

            sclp_c->read_storage_element1_info(sclp, sccb);

        } else {

            sclp_c->read_storage_element0_info(sclp, sccb);

        }

        break;

    case SCLP_ATTACH_STORAGE_ELEMENT:

        sclp_c->attach_storage_element(sclp, sccb, (code & 0xff00) >> 8);

        break;

    case SCLP_ASSIGN_STORAGE:

        sclp_c->assign_storage(sclp, sccb);

        break;

    case SCLP_UNASSIGN_STORAGE:

        sclp_c->unassign_storage(sclp, sccb);

        break;

    case SCLP_CMDW_CONFIGURE_PCI:

        s390_pci_sclp_configure(sccb);

        break;

    case SCLP_CMDW_DECONFIGURE_PCI:

        s390_pci_sclp_deconfigure(sccb);

        break;

    default:

        efc->command_handler(ef, sccb, code);

        break;

    }

}


static void smbios_build_type_0_fields(const char *t)

{

    char buf[1024];

    unsigned char major, minor;

    if (get_param_value(buf, sizeof(buf), "vendor", t))

        smbios_add_field(0, offsetof(struct smbios_type_0, vendor_str),

                         buf, strlen(buf) + 1);

    if (get_param_value(buf, sizeof(buf), "version", t))

        smbios_add_field(0, offsetof(struct smbios_type_0, bios_version_str),

                         buf, strlen(buf) + 1);

    if (get_param_value(buf, sizeof(buf), "date", t))

        smbios_add_field(0, offsetof(struct smbios_type_0,

                                     bios_release_date_str),

                         buf, strlen(buf) + 1);

    if (get_param_value(buf, sizeof(buf), "release", t)) {

        sscanf(buf, "%hhu.%hhu", &major, &minor);

        smbios_add_field(0, offsetof(struct smbios_type_0,

                                     system_bios_major_release),

                         &major, 1);

        smbios_add_field(0, offsetof(struct smbios_type_0,

                                     system_bios_minor_release),

                         &minor, 1);

    }

}


truncate_f(int argc, char **argv)

{

	int64_t offset;

	int ret;

	offset = cvtnum(argv[1]);

	if (offset < 0) {

		printf("non-numeric truncate argument -- %s\n", argv[1]);

		return 0;

	}

	ret = bdrv_truncate(bs, offset);

	if (ret < 0) {

		printf("truncate: %s", strerror(ret));

		return 0;

	}

	return 0;

}


static inline void *host_from_stream_offset(QEMUFile *f,

                                            ram_addr_t offset,

                                            int flags)

{

    static RAMBlock *block = NULL;

    char id[256];

    uint8_t len;

    if (flags & RAM_SAVE_FLAG_CONTINUE) {

        if (!block || block->max_length <= offset) {

            error_report("Ack, bad migration stream!");

            return NULL;

        }

        return block->host + offset;

    }

    len = qemu_get_byte(f);

    qemu_get_buffer(f, (uint8_t *)id, len);

    id[len] = 0;

    QLIST_FOREACH_RCU(block, &ram_list.blocks, next) {

        if (!strncmp(id, block->idstr, sizeof(id)) &&

            block->max_length > offset) {

            return block->host + offset;

        }

    }

    error_report("Can't find block %s!", id);

    return NULL;

}


int mpcifc_service_call(S390CPU *cpu, uint8_t r1, uint64_t fiba, uint8_t ar)

{

    CPUS390XState *env = &cpu->env;

    uint8_t oc, dmaas;

    uint32_t fh;

    ZpciFib fib;

    S390PCIBusDevice *pbdev;

    uint64_t cc = ZPCI_PCI_LS_OK;

    if (env->psw.mask & PSW_MASK_PSTATE) {

        program_interrupt(env, PGM_PRIVILEGED, 6);

        return 0;

    }

    oc = env->regs[r1] & 0xff;

    dmaas = (env->regs[r1] >> 16) & 0xff;

    fh = env->regs[r1] >> 32;

    if (fiba & 0x7) {

        program_interrupt(env, PGM_SPECIFICATION, 6);

        return 0;

    }

    pbdev = s390_pci_find_dev_by_fh(fh);

    if (!pbdev || !(pbdev->fh & FH_MASK_ENABLE)) {

        DPRINTF("mpcifc no pci dev fh 0x%x\n", fh);

        setcc(cpu, ZPCI_PCI_LS_INVAL_HANDLE);

        return 0;

    }

    if (s390_cpu_virt_mem_read(cpu, fiba, ar, (uint8_t *)&fib, sizeof(fib))) {

        return 0;

    }

    if (fib.fmt != 0) {

        program_interrupt(env, PGM_OPERAND, 6);

        return 0;

    }

    switch (oc) {

    case ZPCI_MOD_FC_REG_INT:

        if (pbdev->summary_ind) {

            cc = ZPCI_PCI_LS_ERR;

            s390_set_status_code(env, r1, ZPCI_MOD_ST_SEQUENCE);

        } else if (reg_irqs(env, pbdev, fib)) {

            cc = ZPCI_PCI_LS_ERR;

            s390_set_status_code(env, r1, ZPCI_MOD_ST_RES_NOT_AVAIL);

        }

        break;

    case ZPCI_MOD_FC_DEREG_INT:

        if (!pbdev->summary_ind) {

            cc = ZPCI_PCI_LS_ERR;

            s390_set_status_code(env, r1, ZPCI_MOD_ST_SEQUENCE);

        } else {

            pci_dereg_irqs(pbdev);

        }

        break;

    case ZPCI_MOD_FC_REG_IOAT:

        if (dmaas != 0) {

            cc = ZPCI_PCI_LS_ERR;

            s390_set_status_code(env, r1, ZPCI_MOD_ST_DMAAS_INVAL);

        } else if (pbdev->iommu_enabled) {

            cc = ZPCI_PCI_LS_ERR;

            s390_set_status_code(env, r1, ZPCI_MOD_ST_SEQUENCE);

        } else if (reg_ioat(env, pbdev, fib)) {

            cc = ZPCI_PCI_LS_ERR;

            s390_set_status_code(env, r1, ZPCI_MOD_ST_INSUF_RES);

        }

        break;

    case ZPCI_MOD_FC_DEREG_IOAT:

        if (dmaas != 0) {

            cc = ZPCI_PCI_LS_ERR;

            s390_set_status_code(env, r1, ZPCI_MOD_ST_DMAAS_INVAL);

        } else if (!pbdev->iommu_enabled) {

            cc = ZPCI_PCI_LS_ERR;

            s390_set_status_code(env, r1, ZPCI_MOD_ST_SEQUENCE);

        } else {

            pci_dereg_ioat(pbdev);

        }

        break;

    case ZPCI_MOD_FC_REREG_IOAT:

        if (dmaas != 0) {

            cc = ZPCI_PCI_LS_ERR;

            s390_set_status_code(env, r1, ZPCI_MOD_ST_DMAAS_INVAL);

        } else if (!pbdev->iommu_enabled) {

            cc = ZPCI_PCI_LS_ERR;

            s390_set_status_code(env, r1, ZPCI_MOD_ST_SEQUENCE);

        } else {

            pci_dereg_ioat(pbdev);

            if (reg_ioat(env, pbdev, fib)) {

                cc = ZPCI_PCI_LS_ERR;

                s390_set_status_code(env, r1, ZPCI_MOD_ST_INSUF_RES);

            }

        }

        break;

    case ZPCI_MOD_FC_RESET_ERROR:

        pbdev->error_state = false;

        pbdev->lgstg_blocked = false;

        break;

    case ZPCI_MOD_FC_RESET_BLOCK:

        pbdev->lgstg_blocked = false;

        break;

    case ZPCI_MOD_FC_SET_MEASURE:

        pbdev->fmb_addr = ldq_p(&fib.fmb_addr);

        break;

    default:

        program_interrupt(&cpu->env, PGM_OPERAND, 6);

        cc = ZPCI_PCI_LS_ERR;

    }

    setcc(cpu, cc);

    return 0;

}


static void s390_cpu_plug(HotplugHandler *hotplug_dev,

                        DeviceState *dev, Error **errp)

{

    gchar *name;

    S390CPU *cpu = S390_CPU(dev);

    CPUState *cs = CPU(dev);

    name = g_strdup_printf("cpu[%i]", cpu->env.cpu_num);

    object_property_set_link(OBJECT(hotplug_dev), OBJECT(cs), name,

                             errp);

    g_free(name);

}


static void gen_maskg(DisasContext *ctx)

{

    int l1 = gen_new_label();

    TCGv t0 = tcg_temp_new();

    TCGv t1 = tcg_temp_new();

    TCGv t2 = tcg_temp_new();

    TCGv t3 = tcg_temp_new();

    tcg_gen_movi_tl(t3, 0xFFFFFFFF);

    tcg_gen_andi_tl(t0, cpu_gpr[rB(ctx->opcode)], 0x1F);

    tcg_gen_andi_tl(t1, cpu_gpr[rS(ctx->opcode)], 0x1F);

    tcg_gen_addi_tl(t2, t0, 1);

    tcg_gen_shr_tl(t2, t3, t2);

    tcg_gen_shr_tl(t3, t3, t1);

    tcg_gen_xor_tl(cpu_gpr[rA(ctx->opcode)], t2, t3);

    tcg_gen_brcond_tl(TCG_COND_GE, t0, t1, l1);

    tcg_gen_neg_tl(cpu_gpr[rA(ctx->opcode)], cpu_gpr[rA(ctx->opcode)]);

    gen_set_label(l1);

    tcg_temp_free(t0);

    tcg_temp_free(t1);

    tcg_temp_free(t2);

    tcg_temp_free(t3);

    if (unlikely(Rc(ctx->opcode) != 0))

        gen_set_Rc0(ctx, cpu_gpr[rA(ctx->opcode)]);

}


uint64_t qcow2_get_cluster_offset(BlockDriverState *bs, uint64_t offset,

    int *num)

{

    BDRVQcowState *s = bs->opaque;

    unsigned int l1_index, l2_index;

    uint64_t l2_offset, *l2_table, cluster_offset;

    int l1_bits, c;

    unsigned int index_in_cluster, nb_clusters;

    uint64_t nb_available, nb_needed;

    index_in_cluster = (offset >> 9) & (s->cluster_sectors - 1);

    nb_needed = *num + index_in_cluster;

    l1_bits = s->l2_bits + s->cluster_bits;

    /* compute how many bytes there are between the offset and

     * the end of the l1 entry

     */

    nb_available = (1ULL << l1_bits) - (offset & ((1ULL << l1_bits) - 1));

    /* compute the number of available sectors */

    nb_available = (nb_available >> 9) + index_in_cluster;

    if (nb_needed > nb_available) {

        nb_needed = nb_available;

    }

    cluster_offset = 0;

    /* seek the the l2 offset in the l1 table */

    l1_index = offset >> l1_bits;

    if (l1_index >= s->l1_size)

        goto out;

    l2_offset = s->l1_table[l1_index];

    /* seek the l2 table of the given l2 offset */

    if (!l2_offset)

        goto out;

    /* load the l2 table in memory */

    l2_offset &= ~QCOW_OFLAG_COPIED;

    l2_table = l2_load(bs, l2_offset);

    if (l2_table == NULL)

        return 0;

    /* find the cluster offset for the given disk offset */

    l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);

    cluster_offset = be64_to_cpu(l2_table[l2_index]);

    nb_clusters = size_to_clusters(s, nb_needed << 9);

    if (!cluster_offset) {

        /* how many empty clusters ? */

        c = count_contiguous_free_clusters(nb_clusters, &l2_table[l2_index]);

    } else {

        /* how many allocated clusters ? */

        c = count_contiguous_clusters(nb_clusters, s->cluster_size,

                &l2_table[l2_index], 0, QCOW_OFLAG_COPIED);

    }

   nb_available = (c * s->cluster_sectors);

out:

    if (nb_available > nb_needed)

        nb_available = nb_needed;

    *num = nb_available - index_in_cluster;

    return cluster_offset & ~QCOW_OFLAG_COPIED;

}


static bool lowprot_enabled(const CPUS390XState *env)

{

    if (!(env->cregs[0] & CR0_LOWPROT)) {

        return false;

    }

    if (!(env->psw.mask & PSW_MASK_DAT)) {

        return true;

    }

    /* Check the private-space control bit */

    switch (env->psw.mask & PSW_MASK_ASC) {

    case PSW_ASC_PRIMARY:

        return !(env->cregs[1] & _ASCE_PRIVATE_SPACE);

    case PSW_ASC_SECONDARY:

        return !(env->cregs[7] & _ASCE_PRIVATE_SPACE);

    case PSW_ASC_HOME:

        return !(env->cregs[13] & _ASCE_PRIVATE_SPACE);

    default:

        /* We don't support access register mode */

        error_report("unsupported addressing mode");

        exit(1);

    }

}


static int net_slirp_init(VLANState *vlan, const char *model, const char *name,

                          int restricted, const char *ip)

{

    if (slirp_in_use) {

        /* slirp only supports a single instance so far */

        return -1;

    }

    if (!slirp_inited) {

        slirp_inited = 1;

        slirp_init(restricted, ip);

        while (slirp_redirs) {

            struct slirp_config_str *config = slirp_redirs;

            slirp_redirection(NULL, config->str);

            slirp_redirs = config->next;

            qemu_free(config);

        }

#ifndef _WIN32

        if (slirp_smb_export) {

            slirp_smb(slirp_smb_export);

        }

#endif

    }

    slirp_vc = qemu_new_vlan_client(vlan, model, name, NULL, slirp_receive,

                                    NULL, net_slirp_cleanup, NULL);

    slirp_vc->info_str[0] = '\0';

    slirp_in_use = 1;

    return 0;

}


static uint64_t hpdmc_read(void *opaque, target_phys_addr_t addr,

                           unsigned size)

{

    MilkymistHpdmcState *s = opaque;

    uint32_t r = 0;

    addr >>= 2;

    switch (addr) {

    case R_SYSTEM:

    case R_BYPASS:

    case R_TIMING:

    case R_IODELAY:

        r = s->regs[addr];

        break;

    default:

        error_report("milkymist_hpdmc: read access to unknown register 0x"

                TARGET_FMT_plx, addr << 2);

        break;

    }

    trace_milkymist_hpdmc_memory_read(addr << 2, r);

    return r;

}


int qemu_init_main_loop(Error **errp)

{

    int ret;

    GSource *src;

    Error *local_error = NULL;

    init_clocks();

    ret = qemu_signal_init();

    if (ret) {

        return ret;

    }

    qemu_aio_context = aio_context_new(&local_error);

    if (!qemu_aio_context) {

        error_propagate(errp, local_error);

        return -EMFILE;

    }

    qemu_notify_bh = qemu_bh_new(notify_event_cb, NULL);

    gpollfds = g_array_new(FALSE, FALSE, sizeof(GPollFD));

    src = aio_get_g_source(qemu_aio_context);

    g_source_set_name(src, "aio-context");

    g_source_attach(src, NULL);

    g_source_unref(src);

    src = iohandler_get_g_source();

    g_source_set_name(src, "io-handler");

    g_source_attach(src, NULL);

    g_source_unref(src);

    return 0;

}


static int os_host_main_loop_wait(uint32_t timeout)

{

    int ret;

    glib_select_fill(&nfds, &rfds, &wfds, &xfds, &timeout);

    if (timeout > 0) {

        qemu_mutex_unlock_iothread();

    }

    /* We'll eventually drop fd_set completely.  But for now we still have

     * *_fill() and *_poll() functions that use rfds/wfds/xfds.

     */

    gpollfds_from_select();

    ret = g_poll((GPollFD *)gpollfds->data, gpollfds->len, timeout);

    gpollfds_to_select(ret);

    if (timeout > 0) {

        qemu_mutex_lock_iothread();

    }

    glib_select_poll(&rfds, &wfds, &xfds, (ret < 0));

    return ret;

}


static int cris_mmu_segmented_addr(int seg, uint32_t rw_mm_cfg)

{

	return (1 << seg) & rw_mm_cfg;

}


static uint64_t pfpu_read(void *opaque, target_phys_addr_t addr,

                          unsigned size)

{

    MilkymistPFPUState *s = opaque;

    uint32_t r = 0;

    addr >>= 2;

    switch (addr) {

    case R_CTL:

    case R_MESHBASE:

    case R_HMESHLAST:

    case R_VMESHLAST:

    case R_CODEPAGE:

    case R_VERTICES:

    case R_COLLISIONS:

    case R_STRAYWRITES:

    case R_LASTDMA:

    case R_PC:

    case R_DREGBASE:

    case R_CODEBASE:

        r = s->regs[addr];

        break;

    case GPR_BEGIN ... GPR_END:

        r = s->gp_regs[addr - GPR_BEGIN];

        break;

    case MICROCODE_BEGIN ...  MICROCODE_END:

        r = s->microcode[get_microcode_address(s, addr)];

        break;

    default:

        error_report("milkymist_pfpu: read access to unknown register 0x"

                TARGET_FMT_plx, addr << 2);

        break;

    }

    trace_milkymist_pfpu_memory_read(addr << 2, r);

    return r;

}


static void qdev_reset(void *opaque)

{

    DeviceState *dev = opaque;

    if (dev->info->reset)

        dev->info->reset(dev);

}


static void disas_cond_b_imm(DisasContext *s, uint32_t insn)

{

    unsigned int cond;

    uint64_t addr;

    if ((insn & (1 << 4)) || (insn & (1 << 24))) {

        unallocated_encoding(s);

        return;

    }

    addr = s->pc + sextract32(insn, 5, 19) * 4 - 4;

    cond = extract32(insn, 0, 4);

    if (cond < 0x0e) {

        /* genuinely conditional branches */

        int label_match = gen_new_label();

        arm_gen_test_cc(cond, label_match);

        gen_goto_tb(s, 0, s->pc);

        gen_set_label(label_match);

        gen_goto_tb(s, 1, addr);

    } else {

        /* 0xe and 0xf are both "always" conditions */

        gen_goto_tb(s, 0, addr);

    }

}


void tcg_gen_atomic_cmpxchg_i64(TCGv_i64 retv, TCGv addr, TCGv_i64 cmpv,

                                TCGv_i64 newv, TCGArg idx, TCGMemOp memop)

{

    memop = tcg_canonicalize_memop(memop, 1, 0);

    if (!parallel_cpus) {

        TCGv_i64 t1 = tcg_temp_new_i64();

        TCGv_i64 t2 = tcg_temp_new_i64();

        tcg_gen_ext_i64(t2, cmpv, memop & MO_SIZE);

        tcg_gen_qemu_ld_i64(t1, addr, idx, memop & ~MO_SIGN);

        tcg_gen_movcond_i64(TCG_COND_EQ, t2, t1, t2, newv, t1);

        tcg_gen_qemu_st_i64(t2, addr, idx, memop);

        tcg_temp_free_i64(t2);

        if (memop & MO_SIGN) {

            tcg_gen_ext_i64(retv, t1, memop);

        } else {

            tcg_gen_mov_i64(retv, t1);

        }

        tcg_temp_free_i64(t1);

    } else if ((memop & MO_SIZE) == MO_64) {

#ifdef CONFIG_ATOMIC64

        gen_atomic_cx_i64 gen;

        gen = table_cmpxchg[memop & (MO_SIZE | MO_BSWAP)];

        tcg_debug_assert(gen != NULL);

#ifdef CONFIG_SOFTMMU

        {

            TCGv_i32 oi = tcg_const_i32(make_memop_idx(memop, idx));

            gen(retv, tcg_ctx.tcg_env, addr, cmpv, newv, oi);

            tcg_temp_free_i32(oi);

        }

#else

        gen(retv, tcg_ctx.tcg_env, addr, cmpv, newv);

#endif

#else

        gen_helper_exit_atomic(tcg_ctx.tcg_env);

        /* Produce a result, so that we have a well-formed opcode stream

           with respect to uses of the result in the (dead) code following.  */

        tcg_gen_movi_i64(retv, 0);

#endif /* CONFIG_ATOMIC64 */

    } else {

        TCGv_i32 c32 = tcg_temp_new_i32();

        TCGv_i32 n32 = tcg_temp_new_i32();

        TCGv_i32 r32 = tcg_temp_new_i32();

        tcg_gen_extrl_i64_i32(c32, cmpv);

        tcg_gen_extrl_i64_i32(n32, newv);

        tcg_gen_atomic_cmpxchg_i32(r32, addr, c32, n32, idx, memop & ~MO_SIGN);

        tcg_temp_free_i32(c32);

        tcg_temp_free_i32(n32);

        tcg_gen_extu_i32_i64(retv, r32);

        tcg_temp_free_i32(r32);

        if (memop & MO_SIGN) {

            tcg_gen_ext_i64(retv, retv, memop);

        }

    }

}


static void scsi_disk_unit_attention_reported(SCSIDevice *dev)

{

    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, dev);

    if (s->media_changed) {

        s->media_changed = false;

        s->qdev.unit_attention = SENSE_CODE(MEDIUM_CHANGED);

    }

}


static void lsi_command_complete(SCSIBus *bus, int reason, uint32_t tag,

                                 uint32_t arg)

{

    LSIState *s = DO_UPCAST(LSIState, dev.qdev, bus->qbus.parent);

    int out;

    out = (s->sstat1 & PHASE_MASK) == PHASE_DO;

    if (reason == SCSI_REASON_DONE) {

        DPRINTF("Command complete status=%d\n", (int)arg);

        s->status = arg;

        s->command_complete = 2;

        if (s->waiting && s->dbc != 0) {

            /* Raise phase mismatch for short transfers.  */

            lsi_bad_phase(s, out, PHASE_ST);

        } else {

            lsi_set_phase(s, PHASE_ST);

        }

        qemu_free(s->current);

        s->current = NULL;

        lsi_resume_script(s);

        return;

    }

    if (s->waiting == 1 || !s->current || tag != s->current->tag ||

        (lsi_irq_on_rsl(s) && !(s->scntl1 & LSI_SCNTL1_CON))) {

        if (lsi_queue_tag(s, tag, arg))

            return;

    }

    /* host adapter (re)connected */

    DPRINTF("Data ready tag=0x%x len=%d\n", tag, arg);

    s->current->dma_len = arg;

    s->command_complete = 1;

    if (!s->waiting)

        return;

    if (s->waiting == 1 || s->dbc == 0) {

        lsi_resume_script(s);

    } else {

        lsi_do_dma(s, out);

    }

}


static void xenstore_record_dm_state(struct xs_handle *xs, const char *state)

{

    char path[50];

    if (xs == NULL) {

        fprintf(stderr, "xenstore connection not initialized\n");

        exit(1);

    }

    snprintf(path, sizeof (path), "/local/domain/0/device-model/%u/state", xen_domid);

    if (!xs_write(xs, XBT_NULL, path, state, strlen(state))) {

        fprintf(stderr, "error recording dm state\n");

        exit(1);

    }

}


static void *ff_realloc_static(void *ptr, unsigned int size)

{

    int i;

    if(!ptr)

      return av_mallocz_static(size);

    /* Look for the old ptr */

    for(i = 0; i < last_static; i++) {

        if(array_static[i] == ptr) {

            array_static[i] = av_realloc(array_static[i], size);

            return array_static[i];

        }

    }

    return NULL;

}


static int vhdx_log_read_desc(BlockDriverState *bs, BDRVVHDXState *s,

                              VHDXLogEntries *log, VHDXLogDescEntries **buffer,

                              bool convert_endian)

{

    int ret = 0;

    uint32_t desc_sectors;

    uint32_t sectors_read;

    VHDXLogEntryHeader hdr;

    VHDXLogDescEntries *desc_entries = NULL;

    VHDXLogDescriptor desc;

    int i;

    assert(*buffer == NULL);

    ret = vhdx_log_peek_hdr(bs, log, &hdr);

    if (ret < 0) {

        goto exit;

    }

    if (vhdx_log_hdr_is_valid(log, &hdr, s) == false) {

        ret = -EINVAL;

        goto exit;

    }

    desc_sectors = vhdx_compute_desc_sectors(hdr.descriptor_count);

    desc_entries = qemu_blockalign(bs, desc_sectors * VHDX_LOG_SECTOR_SIZE);

    ret = vhdx_log_read_sectors(bs, log, &sectors_read, desc_entries,

                                desc_sectors, false);

    if (ret < 0) {

        goto free_and_exit;

    }

    if (sectors_read != desc_sectors) {

        ret = -EINVAL;

        goto free_and_exit;

    }

    /* put in proper endianness, and validate each desc */

    for (i = 0; i < hdr.descriptor_count; i++) {

        desc = desc_entries->desc[i];

        vhdx_log_desc_le_import(&desc);

        if (convert_endian) {

            desc_entries->desc[i] = desc;

        }

        if (vhdx_log_desc_is_valid(&desc, &hdr) == false) {

            ret = -EINVAL;

            goto free_and_exit;

        }

    }

    if (convert_endian) {

        desc_entries->hdr = hdr;

    }

    *buffer = desc_entries;

    goto exit;

free_and_exit:

    qemu_vfree(desc_entries);

exit:

    return ret;

}


static int irq_cpu_hotplug_init(SCLPEvent *event)

{

    irq_cpu_hotplug = *qemu_allocate_irqs(trigger_signal, event, 1);

    return 0;

}


static int escape124_decode_frame(AVCodecContext *avctx,

                                  void *data, int *got_frame,

                                  AVPacket *avpkt)

{

    int buf_size = avpkt->size;

    Escape124Context *s = avctx->priv_data;

    AVFrame *frame = data;

    GetBitContext gb;

    unsigned frame_flags, frame_size;

    unsigned i;

    unsigned superblock_index, cb_index = 1,

             superblock_col_index = 0,

             superblocks_per_row = avctx->width / 8, skip = -1;

    uint16_t* old_frame_data, *new_frame_data;

    unsigned old_stride, new_stride;

    int ret;

    if ((ret = init_get_bits8(&gb, avpkt->data, avpkt->size)) < 0)

        return ret;

    // This call also guards the potential depth reads for the

    // codebook unpacking.

    if (!can_safely_read(&gb, 64))

        return -1;

    frame_flags = get_bits_long(&gb, 32);

    frame_size  = get_bits_long(&gb, 32);

    // Leave last frame unchanged

    // FIXME: Is this necessary?  I haven't seen it in any real samples

    if (!(frame_flags & 0x114) || !(frame_flags & 0x7800000)) {

        if (!s->frame.data[0])

            return AVERROR_INVALIDDATA;

        av_log(avctx, AV_LOG_DEBUG, "Skipping frame\n");

        *got_frame = 1;

        if ((ret = av_frame_ref(frame, &s->frame)) < 0)

            return ret;

        return frame_size;

    }

    for (i = 0; i < 3; i++) {

        if (frame_flags & (1 << (17 + i))) {

            unsigned cb_depth, cb_size;

            if (i == 2) {

                // This codebook can be cut off at places other than

                // powers of 2, leaving some of the entries undefined.

                cb_size = get_bits_long(&gb, 20);

                cb_depth = av_log2(cb_size - 1) + 1;

            } else {

                cb_depth = get_bits(&gb, 4);

                if (i == 0) {

                    // This is the most basic codebook: pow(2,depth) entries

                    // for a depth-length key

                    cb_size = 1 << cb_depth;

                } else {

                    // This codebook varies per superblock

                    // FIXME: I don't think this handles integer overflow

                    // properly

                    cb_size = s->num_superblocks << cb_depth;

                }

            }

            av_free(s->codebooks[i].blocks);

            s->codebooks[i] = unpack_codebook(&gb, cb_depth, cb_size);

            if (!s->codebooks[i].blocks)

                return -1;

        }

    }

    if ((ret = ff_get_buffer(avctx, frame, AV_GET_BUFFER_FLAG_REF)) < 0)

        return ret;

    new_frame_data = (uint16_t*)frame->data[0];

    new_stride = frame->linesize[0] / 2;

    old_frame_data = (uint16_t*)s->frame.data[0];

    old_stride = s->frame.linesize[0] / 2;

    for (superblock_index = 0; superblock_index < s->num_superblocks;

         superblock_index++) {

        MacroBlock mb;

        SuperBlock sb;

        unsigned multi_mask = 0;

        if (skip == -1) {

            // Note that this call will make us skip the rest of the blocks

            // if the frame prematurely ends

            skip = decode_skip_count(&gb);

        }

        if (skip) {

            copy_superblock(new_frame_data, new_stride,

                            old_frame_data, old_stride);

        } else {

            copy_superblock(sb.pixels, 8,

                            old_frame_data, old_stride);

            while (can_safely_read(&gb, 1) && !get_bits1(&gb)) {

                unsigned mask;

                mb = decode_macroblock(s, &gb, &cb_index, superblock_index);

                mask = get_bits(&gb, 16);

                multi_mask |= mask;

                for (i = 0; i < 16; i++) {

                    if (mask & mask_matrix[i]) {

                        insert_mb_into_sb(&sb, mb, i);

                    }

                }

            }

            if (can_safely_read(&gb, 1) && !get_bits1(&gb)) {

                unsigned inv_mask = get_bits(&gb, 4);

                for (i = 0; i < 4; i++) {

                    if (inv_mask & (1 << i)) {

                        multi_mask ^= 0xF << i*4;

                    } else {

                        multi_mask ^= get_bits(&gb, 4) << i*4;

                    }

                }

                for (i = 0; i < 16; i++) {

                    if (multi_mask & mask_matrix[i]) {

                        if (!can_safely_read(&gb, 1))

                            break;

                        mb = decode_macroblock(s, &gb, &cb_index,

                                               superblock_index);

                        insert_mb_into_sb(&sb, mb, i);

                    }

                }

            } else if (frame_flags & (1 << 16)) {

                while (can_safely_read(&gb, 1) && !get_bits1(&gb)) {

                    mb = decode_macroblock(s, &gb, &cb_index, superblock_index);

                    insert_mb_into_sb(&sb, mb, get_bits(&gb, 4));

                }

            }

            copy_superblock(new_frame_data, new_stride, sb.pixels, 8);

        }

        superblock_col_index++;

        new_frame_data += 8;

        if (old_frame_data)

            old_frame_data += 8;

        if (superblock_col_index == superblocks_per_row) {

            new_frame_data += new_stride * 8 - superblocks_per_row * 8;

            if (old_frame_data)

                old_frame_data += old_stride * 8 - superblocks_per_row * 8;

            superblock_col_index = 0;

        }

        skip--;

    }

    av_log(avctx, AV_LOG_DEBUG,

           "Escape sizes: %i, %i, %i\n",

           frame_size, buf_size, get_bits_count(&gb) / 8);

    av_frame_unref(&s->frame);

    if ((ret = av_frame_ref(&s->frame, frame)) < 0)

        return ret;

    *got_frame = 1;

    return frame_size;

}


static int adx_decode_frame(AVCodecContext *avctx, void *data, int *data_size,

                            AVPacket *avpkt)

{

    const uint8_t *buf0 = avpkt->data;

    int buf_size        = avpkt->size;

    ADXContext *c       = avctx->priv_data;

    int16_t *samples    = data;

    const uint8_t *buf  = buf0;

    int rest            = buf_size;

    if (!c->header_parsed) {

        int hdrsize = adx_decode_header(avctx, buf, rest);

        if (!hdrsize)

            return -1;

        c->header_parsed = 1;

        buf  += hdrsize;

        rest -= hdrsize;

    }

    /* 18 bytes of data are expanded into 32*2 bytes of audio,

       so guard against buffer overflows */

    if (rest / 18 > *data_size / 64)

        rest = (*data_size / 64) * 18;

    if (c->in_temp) {

        int copysize = 18 * avctx->channels - c->in_temp;

        memcpy(c->dec_temp + c->in_temp, buf, copysize);

        rest -= copysize;

        buf  += copysize;

        if (avctx->channels == 1) {

            adx_decode(samples, c->dec_temp, c->prev);

            samples += 32;

        } else {

            adx_decode_stereo(samples, c->dec_temp, c->prev);

            samples += 32*2;

        }

    }

    if (avctx->channels == 1) {

        while (rest >= 18) {

            adx_decode(samples, buf, c->prev);

            rest    -= 18;

            buf     += 18;

            samples += 32;

        }

    } else {

        while (rest >= 18 * 2) {

            adx_decode_stereo(samples, buf, c->prev);

            rest    -= 18 * 2;

            buf     += 18 * 2;

            samples += 32 * 2;

        }

    }

    c->in_temp = rest;

    if (rest) {

        memcpy(c->dec_temp, buf, rest);

        buf += rest;

    }

    *data_size = (uint8_t*)samples - (uint8_t*)data;

    return buf - buf0;

}


static int vc1_decode_i_block_adv(VC1Context *v, DCTELEM block[64], int n, int coded, int codingset, int mquant)

{

    GetBitContext *gb = &v->s.gb;

    MpegEncContext *s = &v->s;

    int dc_pred_dir = 0; /* Direction of the DC prediction used */

    int run_diff, i;

    int16_t *dc_val;

    int16_t *ac_val, *ac_val2;

    int dcdiff;

    int a_avail = v->a_avail, c_avail = v->c_avail;

    int use_pred = s->ac_pred;

    int scale;

    int q1, q2 = 0;

    int mb_pos = s->mb_x + s->mb_y * s->mb_stride;

    /* Get DC differential */

    if (n < 4) {

        dcdiff = get_vlc2(&s->gb, ff_msmp4_dc_luma_vlc[s->dc_table_index].table, DC_VLC_BITS, 3);

    } else {

        dcdiff = get_vlc2(&s->gb, ff_msmp4_dc_chroma_vlc[s->dc_table_index].table, DC_VLC_BITS, 3);

    }

    if (dcdiff < 0){

        av_log(s->avctx, AV_LOG_ERROR, "Illegal DC VLC\n");

        return -1;

    }

    if (dcdiff)

    {

        if (dcdiff == 119 /* ESC index value */)

        {

            /* TODO: Optimize */

            if (mquant == 1) dcdiff = get_bits(gb, 10);

            else if (mquant == 2) dcdiff = get_bits(gb, 9);

            else dcdiff = get_bits(gb, 8);

        }

        else

        {

            if (mquant == 1)

                dcdiff = (dcdiff<<2) + get_bits(gb, 2) - 3;

            else if (mquant == 2)

                dcdiff = (dcdiff<<1) + get_bits(gb, 1) - 1;

        }

        if (get_bits(gb, 1))

            dcdiff = -dcdiff;

    }

    /* Prediction */

    dcdiff += vc1_pred_dc(&v->s, v->overlap, mquant, n, v->a_avail, v->c_avail, &dc_val, &dc_pred_dir);

    *dc_val = dcdiff;

    /* Store the quantized DC coeff, used for prediction */

    if (n < 4) {

        block[0] = dcdiff * s->y_dc_scale;

    } else {

        block[0] = dcdiff * s->c_dc_scale;

    }

    /* Skip ? */

    run_diff = 0;

    i = 0;

    //AC Decoding

    i = 1;

    /* check if AC is needed at all and adjust direction if needed */

    if(!a_avail) dc_pred_dir = 1;

    if(!c_avail) dc_pred_dir = 0;

    if(!a_avail && !c_avail) use_pred = 0;

    ac_val = s->ac_val[0][0] + s->block_index[n] * 16;

    ac_val2 = ac_val;

    scale = mquant * 2 + v->halfpq;

    if(dc_pred_dir) //left

        ac_val -= 16;

    else //top

        ac_val -= 16 * s->block_wrap[n];

    q1 = s->current_picture.qscale_table[mb_pos];

    if(dc_pred_dir && c_avail) q2 = s->current_picture.qscale_table[mb_pos - 1];

    if(!dc_pred_dir && a_avail) q2 = s->current_picture.qscale_table[mb_pos - s->mb_stride];

    if(n && n<4) q2 = q1;

    if(coded) {

        int last = 0, skip, value;

        const int8_t *zz_table;

        int k;

        if(v->s.ac_pred) {

            if(!dc_pred_dir)

                zz_table = vc1_horizontal_zz;

            else

                zz_table = vc1_vertical_zz;

        } else

            zz_table = vc1_normal_zz;

        while (!last) {

            vc1_decode_ac_coeff(v, &last, &skip, &value, codingset);

            i += skip;

            if(i > 63)

                break;

            block[zz_table[i++]] = value;

        }

        /* apply AC prediction if needed */

        if(use_pred) {

            /* scale predictors if needed*/

            if(q2 && q1!=q2) {

                q1 = q1 * 2 + ((q1 == v->pq) ? v->halfpq : 0) - 1;

                q2 = q2 * 2 + ((q2 == v->pq) ? v->halfpq : 0) - 1;

                if(dc_pred_dir) { //left

                    for(k = 1; k < 8; k++)

                        block[k << 3] += (ac_val[k] * q2 * vc1_dqscale[q1 - 1] + 0x20000) >> 18;

                } else { //top

                    for(k = 1; k < 8; k++)

                        block[k] += (ac_val[k + 8] * q2 * vc1_dqscale[q1 - 1] + 0x20000) >> 18;

                }

            } else {

                if(dc_pred_dir) { //left

                    for(k = 1; k < 8; k++)

                        block[k << 3] += ac_val[k];

                } else { //top

                    for(k = 1; k < 8; k++)

                        block[k] += ac_val[k + 8];

                }

            }

        }

        /* save AC coeffs for further prediction */

        for(k = 1; k < 8; k++) {

            ac_val2[k] = block[k << 3];

            ac_val2[k + 8] = block[k];

        }

        /* scale AC coeffs */

        for(k = 1; k < 64; k++)

            if(block[k]) {

                block[k] *= scale;

                if(!v->pquantizer)

                    block[k] += (block[k] < 0) ? -mquant : mquant;

            }

        if(use_pred) i = 63;

    } else { // no AC coeffs

        int k;

        memset(ac_val2, 0, 16 * 2);

        if(dc_pred_dir) {//left

            if(use_pred) {

                memcpy(ac_val2, ac_val, 8 * 2);

                if(q2 && q1!=q2) {

                    q1 = q1 * 2 + ((q1 == v->pq) ? v->halfpq : 0) - 1;

                    q2 = q2 * 2 + ((q2 == v->pq) ? v->halfpq : 0) - 1;

                    for(k = 1; k < 8; k++)

                        ac_val2[k] = (ac_val2[k] * q2 * vc1_dqscale[q1 - 1] + 0x20000) >> 18;

                }

            }

        } else {//top

            if(use_pred) {

                memcpy(ac_val2 + 8, ac_val + 8, 8 * 2);

                if(q2 && q1!=q2) {

                    q1 = q1 * 2 + ((q1 == v->pq) ? v->halfpq : 0) - 1;

                    q2 = q2 * 2 + ((q2 == v->pq) ? v->halfpq : 0) - 1;

                    for(k = 1; k < 8; k++)

                        ac_val2[k + 8] = (ac_val2[k + 8] * q2 * vc1_dqscale[q1 - 1] + 0x20000) >> 18;

                }

            }

        }

        /* apply AC prediction if needed */

        if(use_pred) {

            if(dc_pred_dir) { //left

                for(k = 1; k < 8; k++) {

                    block[k << 3] = ac_val2[k] * scale;

                    if(!v->pquantizer && block[k << 3])

                        block[k << 3] += (block[k << 3] < 0) ? -mquant : mquant;

                }

            } else { //top

                for(k = 1; k < 8; k++) {

                    block[k] = ac_val2[k + 8] * scale;

                    if(!v->pquantizer && block[k])

                        block[k] += (block[k] < 0) ? -mquant : mquant;

                }

            }

            i = 63;

        }

    }

    s->block_last_index[n] = i;

    return 0;

}


int qcow2_alloc_clusters_at(BlockDriverState *bs, uint64_t offset,
    int nb_clusters)
{
    BDRVQcowState *s = bs->opaque;
    uint64_t cluster_index;
    uint64_t old_free_cluster_index;
    int i, refcount, ret;
    /* Check how many clusters there are free */
    cluster_index = offset >> s->cluster_bits;
    for(i = 0; i < nb_clusters; i++) {
        refcount = get_refcount(bs, cluster_index++);
        if (refcount < 0) {
            return refcount;
        } else if (refcount != 0) {
            break;
        }
    }
    /* And then allocate them */
    ret = update_refcount(bs, offset, i << s->cluster_bits, 1);
    if (ret < 0) {
        return ret;
    }
    return i;
}


static void oledate_to_iso8601(char *buf, int buf_size, int64_t value)

{

    time_t t = 631112400LL + 86400*av_int2dbl(value);

    strftime(buf, buf_size, "%Y-%m-%d %H:%M:%S", gmtime(&t));

}


const char *get_register_name_32(unsigned int reg)

{

    if (reg > CPU_NB_REGS32) {

        return NULL;

    }

    return x86_reg_info_32[reg].name;

}


struct pxa2xx_state_s *pxa255_init(unsigned int sdram_size,

                DisplayState *ds)

{

    struct pxa2xx_state_s *s;

    struct pxa2xx_ssp_s *ssp;

    int iomemtype, i;

    s = (struct pxa2xx_state_s *) qemu_mallocz(sizeof(struct pxa2xx_state_s));

    s->env = cpu_init();

    cpu_arm_set_model(s->env, "pxa255");

    register_savevm("cpu", 0, 0, cpu_save, cpu_load, s->env);

    /* SDRAM & Internal Memory Storage */

    cpu_register_physical_memory(PXA2XX_SDRAM_BASE, sdram_size,

                    qemu_ram_alloc(sdram_size) | IO_MEM_RAM);

    cpu_register_physical_memory(PXA2XX_INTERNAL_BASE, PXA2XX_INTERNAL_SIZE,

                    qemu_ram_alloc(PXA2XX_INTERNAL_SIZE) | IO_MEM_RAM);

    s->pic = pxa2xx_pic_init(0x40d00000, s->env);

    s->dma = pxa255_dma_init(0x40000000, s->pic[PXA2XX_PIC_DMA]);

    pxa25x_timer_init(0x40a00000, &s->pic[PXA2XX_PIC_OST_0]);

    s->gpio = pxa2xx_gpio_init(0x40e00000, s->env, s->pic, 85);

    s->mmc = pxa2xx_mmci_init(0x41100000, s->pic[PXA2XX_PIC_MMC], s->dma);

    for (i = 0; pxa255_serial[i].io_base; i ++)

        if (serial_hds[i])

            serial_mm_init(pxa255_serial[i].io_base, 2,

                            s->pic[pxa255_serial[i].irqn], serial_hds[i], 1);

        else

            break;

    if (serial_hds[i])

        s->fir = pxa2xx_fir_init(0x40800000, s->pic[PXA2XX_PIC_ICP],

                        s->dma, serial_hds[i]);

    if (ds)

        s->lcd = pxa2xx_lcdc_init(0x44000000, s->pic[PXA2XX_PIC_LCD], ds);

    s->cm_base = 0x41300000;

    s->cm_regs[CCCR >> 4] = 0x02000210;	/* 416.0 MHz */

    s->clkcfg = 0x00000009;		/* Turbo mode active */

    iomemtype = cpu_register_io_memory(0, pxa2xx_cm_readfn,

                    pxa2xx_cm_writefn, s);

    cpu_register_physical_memory(s->cm_base, 0xfff, iomemtype);

    register_savevm("pxa2xx_cm", 0, 0, pxa2xx_cm_save, pxa2xx_cm_load, s);

    cpu_arm_set_cp_io(s->env, 14, pxa2xx_cp14_read, pxa2xx_cp14_write, s);

    s->mm_base = 0x48000000;

    s->mm_regs[MDMRS >> 2] = 0x00020002;

    s->mm_regs[MDREFR >> 2] = 0x03ca4000;

    s->mm_regs[MECR >> 2] = 0x00000001;	/* Two PC Card sockets */

    iomemtype = cpu_register_io_memory(0, pxa2xx_mm_readfn,

                    pxa2xx_mm_writefn, s);

    cpu_register_physical_memory(s->mm_base, 0xfff, iomemtype);

    register_savevm("pxa2xx_mm", 0, 0, pxa2xx_mm_save, pxa2xx_mm_load, s);

    s->pm_base = 0x40f00000;

    iomemtype = cpu_register_io_memory(0, pxa2xx_pm_readfn,

                    pxa2xx_pm_writefn, s);

    cpu_register_physical_memory(s->pm_base, 0xff, iomemtype);

    register_savevm("pxa2xx_pm", 0, 0, pxa2xx_pm_save, pxa2xx_pm_load, s);

    for (i = 0; pxa255_ssp[i].io_base; i ++);

    s->ssp = (struct pxa2xx_ssp_s **)

            qemu_mallocz(sizeof(struct pxa2xx_ssp_s *) * i);

    ssp = (struct pxa2xx_ssp_s *)

            qemu_mallocz(sizeof(struct pxa2xx_ssp_s) * i);

    for (i = 0; pxa255_ssp[i].io_base; i ++) {

        s->ssp[i] = &ssp[i];

        ssp[i].base = pxa255_ssp[i].io_base;

        ssp[i].irq = s->pic[pxa255_ssp[i].irqn];

        iomemtype = cpu_register_io_memory(0, pxa2xx_ssp_readfn,

                        pxa2xx_ssp_writefn, &ssp[i]);

        cpu_register_physical_memory(ssp[i].base, 0xfff, iomemtype);

        register_savevm("pxa2xx_ssp", i, 0,

                        pxa2xx_ssp_save, pxa2xx_ssp_load, s);

    }

    if (usb_enabled) {

        usb_ohci_init_pxa(0x4c000000, 3, -1, s->pic[PXA2XX_PIC_USBH1]);

    }

    s->pcmcia[0] = pxa2xx_pcmcia_init(0x20000000);

    s->pcmcia[1] = pxa2xx_pcmcia_init(0x30000000);

    s->rtc_base = 0x40900000;

    iomemtype = cpu_register_io_memory(0, pxa2xx_rtc_readfn,

                    pxa2xx_rtc_writefn, s);

    cpu_register_physical_memory(s->rtc_base, 0xfff, iomemtype);

    pxa2xx_rtc_init(s);

    register_savevm("pxa2xx_rtc", 0, 0, pxa2xx_rtc_save, pxa2xx_rtc_load, s);

    s->i2c[0] = pxa2xx_i2c_init(0x40301600, s->pic[PXA2XX_PIC_I2C], 0xffff);

    s->i2c[1] = pxa2xx_i2c_init(0x40f00100, s->pic[PXA2XX_PIC_PWRI2C], 0xff);

    s->i2s = pxa2xx_i2s_init(0x40400000, s->pic[PXA2XX_PIC_I2S], s->dma);

    /* GPIO1 resets the processor */

    /* The handler can be overriden by board-specific code */

    pxa2xx_gpio_handler_set(s->gpio, 1, pxa2xx_reset, s);

    return s;

}


int av_read_packet(AVFormatContext *s, AVPacket *pkt)

{

    int ret, i;

    AVStream *st;

    for(;;){

        AVPacketList *pktl = s->raw_packet_buffer;

        if (pktl) {

            *pkt = pktl->pkt;

            if(s->streams[pkt->stream_index]->codec->codec_id != CODEC_ID_PROBE ||

               !s->streams[pkt->stream_index]->probe_packets){

                s->raw_packet_buffer = pktl->next;

                av_free(pktl);

                return 0;

            }

        }

        av_init_packet(pkt);

        ret= s->iformat->read_packet(s, pkt);

        if (ret < 0) {

            if (!pktl || ret == AVERROR(EAGAIN))

                return ret;

            for (i = 0; i < s->nb_streams; i++)

                s->streams[i]->probe_packets = 0;

            continue;

        }

        st= s->streams[pkt->stream_index];

        switch(st->codec->codec_type){

        case CODEC_TYPE_VIDEO:

            if(s->video_codec_id)   st->codec->codec_id= s->video_codec_id;

            break;

        case CODEC_TYPE_AUDIO:

            if(s->audio_codec_id)   st->codec->codec_id= s->audio_codec_id;

            break;

        case CODEC_TYPE_SUBTITLE:

            if(s->subtitle_codec_id)st->codec->codec_id= s->subtitle_codec_id;

            break;

        }

        if(!pktl && (st->codec->codec_id != CODEC_ID_PROBE ||

                     !st->probe_packets))

            return ret;

        add_to_pktbuf(&s->raw_packet_buffer, pkt, &s->raw_packet_buffer_end);

        if(st->codec->codec_id == CODEC_ID_PROBE){

            AVProbeData *pd = &st->probe_data;

            --st->probe_packets;

            pd->buf = av_realloc(pd->buf, pd->buf_size+pkt->size+AVPROBE_PADDING_SIZE);

            memcpy(pd->buf+pd->buf_size, pkt->data, pkt->size);

            pd->buf_size += pkt->size;

            memset(pd->buf+pd->buf_size, 0, AVPROBE_PADDING_SIZE);

            if(av_log2(pd->buf_size) != av_log2(pd->buf_size - pkt->size)){

                set_codec_from_probe_data(st, pd, 1);

                if(st->codec->codec_id != CODEC_ID_PROBE){

                    pd->buf_size=0;

                    av_freep(&pd->buf);

                }

            }

        }

    }

}


void nbd_export_close(NBDExport *exp)

{

    NBDClient *client, *next;

    nbd_export_get(exp);

    QTAILQ_FOREACH_SAFE(client, &exp->clients, next, next) {

        client_close(client);

    }

    nbd_export_set_name(exp, NULL);

    nbd_export_put(exp);

    if (exp->blk) {

        blk_remove_aio_context_notifier(exp->blk, blk_aio_attached,

                                        blk_aio_detach, exp);

        blk_unref(exp->blk);

        exp->blk = NULL;

    }

}


void iothread_stop(IOThread *iothread)

{

    if (!iothread->ctx || iothread->stopping) {

        return;

    }

    iothread->stopping = true;

    aio_notify(iothread->ctx);

    if (atomic_read(&iothread->main_loop)) {

        g_main_loop_quit(iothread->main_loop);

    }

    qemu_thread_join(&iothread->thread);

}


void qmp_stop(Error **errp)

{

    vm_stop(RUN_STATE_PAUSED);

}


const char *postproc_configuration(void)

{

    return FFMPEG_CONFIGURATION;

}