void gen_intermediate_code_a64(ARMCPU *cpu, TranslationBlock *tb)

{

    CPUState *cs = CPU(cpu);

    CPUARMState *env = &cpu->env;

    DisasContext dc1, *dc = &dc1;

    target_ulong pc_start;

    target_ulong next_page_start;

    int num_insns;

    int max_insns;

    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 = 1;

    /* 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 = 0;

    dc->bswap_code = 0;

    dc->condexec_mask = 0;

    dc->condexec_cond = 0;

    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->fp_excp_el = ARM_TBFLAG_FPEXC_EL(tb->flags);

    dc->vec_len = 0;

    dc->vec_stride = 0;

    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 = (arm_debug_target_el(env) == dc->current_el);

    init_tmp_a64_array(dc);

    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();

    do {

        tcg_gen_insn_start(dc->pc, 0);

        num_insns++;

        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));

            dc->is_jmp = DISAS_EXC;

            break;

        }

        disas_a64_insn(env, dc);

        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) {

        gen_io_end();

    }

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

        && dc->is_jmp != DISAS_EXC) {

        /* Note that this means single stepping WFI doesn't halt the CPU.

         * For conditional branch insns this is harmless unreachable code as

         * gen_goto_tb() has already handled emitting the debug exception

         * (and thus a tb-jump is not possible when singlestepping).

         */

        assert(dc->is_jmp != DISAS_TB_JUMP);

        if (dc->is_jmp != DISAS_JUMP) {

            gen_a64_set_pc_im(dc->pc);

        }

        if (cs->singlestep_enabled) {

            gen_exception_internal(EXCP_DEBUG);

        } else {

            gen_step_complete_exception(dc);

        }

    } else {

        switch (dc->is_jmp) {

        case DISAS_NEXT:

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

            break;

        default:

        case DISAS_UPDATE:

            gen_a64_set_pc_im(dc->pc);

            /* fall through */

        case DISAS_JUMP:

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

            tcg_gen_exit_tb(0);

            break;

        case DISAS_TB_JUMP:

        case DISAS_EXC:

        case DISAS_SWI:

            break;

        case DISAS_WFE:

            gen_a64_set_pc_im(dc->pc);

            gen_helper_wfe(cpu_env);

            break;

        case DISAS_YIELD:

            gen_a64_set_pc_im(dc->pc);

            gen_helper_yield(cpu_env);

            break;

        case DISAS_WFI:

            /* This is a special case because we don't want to just halt the CPU

             * if trying to debug across a WFI.

             */

            gen_a64_set_pc_im(dc->pc);

            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;

        }

    }

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,

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

        qemu_log("\n");

    }

#endif

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

    tb->icount = num_insns;

}


static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom)

{

    AVStream *st;

    MOVStreamContext *sc;

    unsigned int i, entries;

    if (c->fc->nb_streams < 1)

        return 0;

    st = c->fc->streams[c->fc->nb_streams-1];

    sc = st->priv_data;

    avio_r8(pb); /* version */

    avio_rb24(pb); /* flags */

    entries = avio_rb32(pb);

    av_log(c->fc, AV_LOG_TRACE, "track[%i].stsc.entries = %i\n", c->fc->nb_streams-1, entries);

    if (!entries)

        return 0;

    if (entries >= UINT_MAX / sizeof(*sc->stsc_data))

        return AVERROR_INVALIDDATA;

    sc->stsc_data = av_malloc(entries * sizeof(*sc->stsc_data));

    if (!sc->stsc_data)

        return AVERROR(ENOMEM);

    for (i = 0; i < entries && !pb->eof_reached; i++) {

        sc->stsc_data[i].first = avio_rb32(pb);

        sc->stsc_data[i].count = avio_rb32(pb);

        sc->stsc_data[i].id = avio_rb32(pb);

        if (sc->stsc_data[i].id < 0 || sc->stsc_data[i].id > sc->stsd_count) {

            sc->stsc_data[i].id = 0;

            if (c->fc->error_recognition & AV_EF_EXPLODE) {

                av_log(c->fc, AV_LOG_ERROR, "Invalid stsc index.\n");

                return AVERROR_INVALIDDATA;

            }

        }

    }

    sc->stsc_count = i;

    if (pb->eof_reached)

        return AVERROR_EOF;

    return 0;

}


static int decode_copy(uint8_t *frame, int width, int height,

                       const uint8_t *src, const uint8_t *src_end)

{

    const int size = width * height;

    if (src_end - src < size)

        return -1;

    bytestream_get_buffer(&src, frame, size);

    return 0;

}


static uint16_t nvme_io_cmd(NvmeCtrl *n, NvmeCmd *cmd, NvmeRequest *req)

{

    NvmeNamespace *ns;

    uint32_t nsid = le32_to_cpu(cmd->nsid);

    if (nsid == 0 || nsid > n->num_namespaces) {

        return NVME_INVALID_NSID | NVME_DNR;

    }

    ns = &n->namespaces[nsid - 1];

    switch (cmd->opcode) {

    case NVME_CMD_FLUSH:

        return nvme_flush(n, ns, cmd, req);

    case NVME_CMD_WRITE_ZEROS:

        return nvme_write_zeros(n, ns, cmd, req);

    case NVME_CMD_WRITE:

    case NVME_CMD_READ:

        return nvme_rw(n, ns, cmd, req);

    default:

        return NVME_INVALID_OPCODE | NVME_DNR;

    }

}


void avfilter_link_free(AVFilterLink **link)

{

    if (!*link)

        return;

    if ((*link)->pool) {

        int i;

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

            if ((*link)->pool->pic[i]) {

                AVFilterBufferRef *picref = (*link)->pool->pic[i];

                /* free buffer: picrefs stored in the pool are not

                 * supposed to contain a free callback */

                av_freep(&picref->buf->data[0]);

                av_freep(&picref->buf);

                av_freep(&picref->audio);

                av_freep(&picref->video);

                av_freep(&picref);

            }

        }

        av_freep(&(*link)->pool);

    }

    av_freep(link);

}


static uint64_t pl110_read(void *opaque, hwaddr offset,

                           unsigned size)

{

    pl110_state *s = (pl110_state *)opaque;

    if (offset >= 0xfe0 && offset < 0x1000) {

        return idregs[s->version][(offset - 0xfe0) >> 2];

    }

    if (offset >= 0x200 && offset < 0x400) {

        return s->raw_palette[(offset - 0x200) >> 2];

    }

    switch (offset >> 2) {

    case 0: /* LCDTiming0 */

        return s->timing[0];

    case 1: /* LCDTiming1 */

        return s->timing[1];

    case 2: /* LCDTiming2 */

        return s->timing[2];

    case 3: /* LCDTiming3 */

        return s->timing[3];

    case 4: /* LCDUPBASE */

        return s->upbase;

    case 5: /* LCDLPBASE */

        return s->lpbase;

    case 6: /* LCDIMSC */

        if (s->version != PL110) {

            return s->cr;

        }

        return s->int_mask;

    case 7: /* LCDControl */

        if (s->version != PL110) {

            return s->int_mask;

        }

        return s->cr;

    case 8: /* LCDRIS */

        return s->int_status;

    case 9: /* LCDMIS */

        return s->int_status & s->int_mask;

    case 11: /* LCDUPCURR */

        /* TODO: Implement vertical refresh.  */

        return s->upbase;

    case 12: /* LCDLPCURR */

        return s->lpbase;

    default:

        hw_error("pl110_read: Bad offset %x\n", (int)offset);

        return 0;

    }

}


static void fill_coding_method_array (sb_int8_array tone_level_idx, sb_int8_array tone_level_idx_temp,

                sb_int8_array coding_method, int nb_channels,

                int c, int superblocktype_2_3, int cm_table_select)

{

    int ch, sb, j;

    int tmp, acc, esp_40, comp;

    int add1, add2, add3, add4;

    int64_t multres;

    // This should never happen

    if (nb_channels <= 0)

        return;

    if (!superblocktype_2_3) {

        /* This case is untested, no samples available */

        SAMPLES_NEEDED

        for (ch = 0; ch < nb_channels; ch++)

            for (sb = 0; sb < 30; sb++) {

                for (j = 1; j < 63; j++) {  // The loop only iterates to 63 so the code doesn't overflow the buffer

                    add1 = tone_level_idx[ch][sb][j] - 10;

                    if (add1 < 0)

                        add1 = 0;

                    add2 = add3 = add4 = 0;

                    if (sb > 1) {

                        add2 = tone_level_idx[ch][sb - 2][j] + tone_level_idx_offset_table[sb][0] - 6;

                        if (add2 < 0)

                            add2 = 0;

                    }

                    if (sb > 0) {

                        add3 = tone_level_idx[ch][sb - 1][j] + tone_level_idx_offset_table[sb][1] - 6;

                        if (add3 < 0)

                            add3 = 0;

                    }

                    if (sb < 29) {

                        add4 = tone_level_idx[ch][sb + 1][j] + tone_level_idx_offset_table[sb][3] - 6;

                        if (add4 < 0)

                            add4 = 0;

                    }

                    tmp = tone_level_idx[ch][sb][j + 1] * 2 - add4 - add3 - add2 - add1;

                    if (tmp < 0)

                        tmp = 0;

                    tone_level_idx_temp[ch][sb][j + 1] = tmp & 0xff;

                }

                tone_level_idx_temp[ch][sb][0] = tone_level_idx_temp[ch][sb][1];

            }

            acc = 0;

            for (ch = 0; ch < nb_channels; ch++)

                for (sb = 0; sb < 30; sb++)

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

                        acc += tone_level_idx_temp[ch][sb][j];

            multres = 0x66666667 * (acc * 10);

            esp_40 = (multres >> 32) / 8 + ((multres & 0xffffffff) >> 31);

            for (ch = 0;  ch < nb_channels; ch++)

                for (sb = 0; sb < 30; sb++)

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

                        comp = tone_level_idx_temp[ch][sb][j]* esp_40 * 10;

                        if (comp < 0)

                            comp += 0xff;

                        comp /= 256; // signed shift

                        switch(sb) {

                            case 0:

                                if (comp < 30)

                                    comp = 30;

                                comp += 15;

                                break;

                            case 1:

                                if (comp < 24)

                                    comp = 24;

                                comp += 10;

                                break;

                            case 2:

                            case 3:

                            case 4:

                                if (comp < 16)

                                    comp = 16;

                        }

                        if (comp <= 5)

                            tmp = 0;

                        else if (comp <= 10)

                            tmp = 10;

                        else if (comp <= 16)

                            tmp = 16;

                        else if (comp <= 24)

                            tmp = -1;

                        else

                            tmp = 0;

                        coding_method[ch][sb][j] = ((tmp & 0xfffa) + 30 )& 0xff;

                    }

            for (sb = 0; sb < 30; sb++)

                fix_coding_method_array(sb, nb_channels, coding_method);

            for (ch = 0; ch < nb_channels; ch++)

                for (sb = 0; sb < 30; sb++)

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

                        if (sb >= 10) {

                            if (coding_method[ch][sb][j] < 10)

                                coding_method[ch][sb][j] = 10;

                        } else {

                            if (sb >= 2) {

                                if (coding_method[ch][sb][j] < 16)

                                    coding_method[ch][sb][j] = 16;

                            } else {

                                if (coding_method[ch][sb][j] < 30)

                                    coding_method[ch][sb][j] = 30;

                            }

                        }

    } else { // superblocktype_2_3 != 0

        for (ch = 0; ch < nb_channels; ch++)

            for (sb = 0; sb < 30; sb++)

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

                    coding_method[ch][sb][j] = coding_method_table[cm_table_select][sb];

    }

    return;

}


void arm_cpu_dump_state(CPUState *cs, FILE *f, fprintf_function cpu_fprintf,

                        int flags)

{

    ARMCPU *cpu = ARM_CPU(cs);

    CPUARMState *env = &cpu->env;

    int i;

    if (is_a64(env)) {

        aarch64_cpu_dump_state(cs, f, cpu_fprintf, flags);

        return;

    }

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

        cpu_fprintf(f, "R%02d=%08x", i, env->regs[i]);

        if ((i % 4) == 3)

            cpu_fprintf(f, "\n");

        else

            cpu_fprintf(f, " ");

    }

    if (arm_feature(env, ARM_FEATURE_M)) {

        uint32_t xpsr = xpsr_read(env);

        const char *mode;

        if (xpsr & XPSR_EXCP) {

            mode = "handler";

        } else {

            if (env->v7m.control & R_V7M_CONTROL_NPRIV_MASK) {

                mode = "unpriv-thread";

            } else {

                mode = "priv-thread";

            }

        }

        cpu_fprintf(f, "XPSR=%08x %c%c%c%c %c %s\n",

                    xpsr,

                    xpsr & XPSR_N ? 'N' : '-',

                    xpsr & XPSR_Z ? 'Z' : '-',

                    xpsr & XPSR_C ? 'C' : '-',

                    xpsr & XPSR_V ? 'V' : '-',

                    xpsr & XPSR_T ? 'T' : 'A',

                    mode);

    } else {

        uint32_t psr = cpsr_read(env);

        const char *ns_status = "";

        if (arm_feature(env, ARM_FEATURE_EL3) &&

            (psr & CPSR_M) != ARM_CPU_MODE_MON) {

            ns_status = env->cp15.scr_el3 & SCR_NS ? "NS " : "S ";

        }

        cpu_fprintf(f, "PSR=%08x %c%c%c%c %c %s%s%d\n",

                    psr,

                    psr & CPSR_N ? 'N' : '-',

                    psr & CPSR_Z ? 'Z' : '-',

                    psr & CPSR_C ? 'C' : '-',

                    psr & CPSR_V ? 'V' : '-',

                    psr & CPSR_T ? 'T' : 'A',

                    ns_status,

                    cpu_mode_names[psr & 0xf], (psr & 0x10) ? 32 : 26);

    }

    if (flags & CPU_DUMP_FPU) {

        int numvfpregs = 0;

        if (arm_feature(env, ARM_FEATURE_VFP)) {

            numvfpregs += 16;

        }

        if (arm_feature(env, ARM_FEATURE_VFP3)) {

            numvfpregs += 16;

        }

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

            uint64_t v = float64_val(env->vfp.regs[i]);

            cpu_fprintf(f, "s%02d=%08x s%02d=%08x d%02d=%016" PRIx64 "\n",

                        i * 2, (uint32_t)v,

                        i * 2 + 1, (uint32_t)(v >> 32),

                        i, v);

        }

        cpu_fprintf(f, "FPSCR: %08x\n", (int)env->vfp.xregs[ARM_VFP_FPSCR]);

    }

}


int vmstate_load_state(QEMUFile *f, const VMStateDescription *vmsd,

                       void *opaque, int version_id)

{

    VMStateField *field = vmsd->fields;

    int ret = 0;

    trace_vmstate_load_state(vmsd->name, version_id);

    if (version_id > vmsd->version_id) {

        error_report("%s: incoming version_id %d is too new "

                     "for local version_id %d",

                     vmsd->name, version_id, vmsd->version_id);

        trace_vmstate_load_state_end(vmsd->name, "too new", -EINVAL);

        return -EINVAL;

    }

    if  (version_id < vmsd->minimum_version_id) {

        if (vmsd->load_state_old &&

            version_id >= vmsd->minimum_version_id_old) {

            ret = vmsd->load_state_old(f, opaque, version_id);

            trace_vmstate_load_state_end(vmsd->name, "old path", ret);

            return ret;

        }

        error_report("%s: incoming version_id %d is too old "

                     "for local minimum version_id  %d",

                     vmsd->name, version_id, vmsd->minimum_version_id);

        trace_vmstate_load_state_end(vmsd->name, "too old", -EINVAL);

        return -EINVAL;

    }

    if (vmsd->pre_load) {

        int ret = vmsd->pre_load(opaque);

        if (ret) {

            return ret;

        }

    }

    while (field->name) {

        trace_vmstate_load_state_field(vmsd->name, field->name);

        if ((field->field_exists &&

             field->field_exists(opaque, version_id)) ||

            (!field->field_exists &&

             field->version_id <= version_id)) {

            void *first_elem = opaque + field->offset;

            int i, n_elems = vmstate_n_elems(opaque, field);

            int size = vmstate_size(opaque, field);

            vmstate_handle_alloc(first_elem, field, opaque);

            if (field->flags & VMS_POINTER) {

                first_elem = *(void **)first_elem;

                assert(first_elem  || !n_elems);

            }

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

                void *curr_elem = first_elem + size * i;

                if (field->flags & VMS_ARRAY_OF_POINTER) {

                    curr_elem = *(void **)curr_elem;

                }

                if (field->flags & VMS_STRUCT) {

                    ret = vmstate_load_state(f, field->vmsd, curr_elem,

                                             field->vmsd->version_id);

                } else {

                    ret = field->info->get(f, curr_elem, size, field);

                }

                if (ret >= 0) {

                    ret = qemu_file_get_error(f);

                }

                if (ret < 0) {

                    qemu_file_set_error(f, ret);

                    error_report("Failed to load %s:%s", vmsd->name,

                                 field->name);

                    trace_vmstate_load_field_error(field->name, ret);

                    return ret;

                }

            }

        } else if (field->flags & VMS_MUST_EXIST) {

            error_report("Input validation failed: %s/%s",

                         vmsd->name, field->name);

            return -1;

        }

        field++;

    }

    ret = vmstate_subsection_load(f, vmsd, opaque);

    if (ret != 0) {

        return ret;

    }

    if (vmsd->post_load) {

        ret = vmsd->post_load(opaque, version_id);

    }

    trace_vmstate_load_state_end(vmsd->name, "end", ret);

    return ret;

}


static void xen_log_start(MemoryListener *listener,

                          MemoryRegionSection *section)

{

    XenIOState *state = container_of(listener, XenIOState, memory_listener);

    xen_sync_dirty_bitmap(state, section->offset_within_address_space,

                          int128_get64(section->size));

}


static void mpegvideo_extract_headers(AVCodecParserContext *s,

                                      AVCodecContext *avctx,

                                      const uint8_t *buf, int buf_size)

{

    ParseContext1 *pc = s->priv_data;

    const uint8_t *buf_end;

    uint32_t start_code;

    int frame_rate_index, ext_type, bytes_left;

    int frame_rate_ext_n, frame_rate_ext_d;

    int picture_structure, top_field_first, repeat_first_field, progressive_frame;

    int horiz_size_ext, vert_size_ext, bit_rate_ext;

//FIXME replace the crap with get_bits()

    s->repeat_pict = 0;

    buf_end = buf + buf_size;

    while (buf < buf_end) {

        start_code= -1;

        buf= ff_find_start_code(buf, buf_end, &start_code);

        bytes_left = buf_end - buf;

        switch(start_code) {

        case PICTURE_START_CODE:

            ff_fetch_timestamp(s, buf-buf_start-4, 1);

            if (bytes_left >= 2) {

                s->pict_type = (buf[1] >> 3) & 7;

            }

            break;

        case SEQ_START_CODE:

            if (bytes_left >= 7) {

                pc->width  = (buf[0] << 4) | (buf[1] >> 4);

                pc->height = ((buf[1] & 0x0f) << 8) | buf[2];

                avcodec_set_dimensions(avctx, pc->width, pc->height);

                frame_rate_index = buf[3] & 0xf;

                pc->frame_rate.den = avctx->time_base.den = ff_frame_rate_tab[frame_rate_index].num;

                pc->frame_rate.num = avctx->time_base.num = ff_frame_rate_tab[frame_rate_index].den;

                avctx->bit_rate = ((buf[4]<<10) | (buf[5]<<2) | (buf[6]>>6))*400;

                avctx->codec_id = CODEC_ID_MPEG1VIDEO;

                avctx->sub_id = 1;

            }

            break;

        case EXT_START_CODE:

            if (bytes_left >= 1) {

                ext_type = (buf[0] >> 4);

                switch(ext_type) {

                case 0x1: /* sequence extension */

                    if (bytes_left >= 6) {

                        horiz_size_ext = ((buf[1] & 1) << 1) | (buf[2] >> 7);

                        vert_size_ext = (buf[2] >> 5) & 3;

                        bit_rate_ext = ((buf[2] & 0x1F)<<7) | (buf[3]>>1);

                        frame_rate_ext_n = (buf[5] >> 5) & 3;

                        frame_rate_ext_d = (buf[5] & 0x1f);

                        pc->progressive_sequence = buf[1] & (1 << 3);

                        avctx->has_b_frames= !(buf[5] >> 7);

                        pc->width  |=(horiz_size_ext << 12);

                        pc->height |=( vert_size_ext << 12);

                        avctx->bit_rate += (bit_rate_ext << 18) * 400;

                        avcodec_set_dimensions(avctx, pc->width, pc->height);

                        avctx->time_base.den = pc->frame_rate.den * (frame_rate_ext_n + 1);

                        avctx->time_base.num = pc->frame_rate.num * (frame_rate_ext_d + 1);

                        avctx->codec_id = CODEC_ID_MPEG2VIDEO;

                        avctx->sub_id = 2; /* forces MPEG2 */

                    }

                    break;

                case 0x8: /* picture coding extension */

                    if (bytes_left >= 5) {

                        picture_structure = buf[2]&3;

                        top_field_first = buf[3] & (1 << 7);

                        repeat_first_field = buf[3] & (1 << 1);

                        progressive_frame = buf[4] & (1 << 7);

                        /* check if we must repeat the frame */

                        if (repeat_first_field) {

                            if (pc->progressive_sequence) {

                                if (top_field_first)

                                    s->repeat_pict = 4;

                                else

                                    s->repeat_pict = 2;

                            } else if (progressive_frame) {

                                s->repeat_pict = 1;

                            }

                        }

                    }

                    break;

                }

            }

            break;

        case -1:

            goto the_end;

        default:

            /* we stop parsing when we encounter a slice. It ensures

               that this function takes a negligible amount of time */

            if (start_code >= SLICE_MIN_START_CODE &&

                start_code <= SLICE_MAX_START_CODE)

                goto the_end;

            break;

        }

    }

 the_end: ;

}


static void test_smbios_ep_address(test_data *data)

{

    uint32_t off;

    /* find smbios entry point structure */

    for (off = 0xf0000; off < 0x100000; off += 0x10) {

        uint8_t sig[] = "_SM_";

        int i;

        for (i = 0; i < sizeof sig - 1; ++i) {

            sig[i] = readb(off + i);

        }

        if (!memcmp(sig, "_SM_", sizeof sig)) {

            break;

        }

    }

    g_assert_cmphex(off, <, 0x100000);

    data->smbios_ep_addr = off;

}


static void mov_update_dts_shift(MOVStreamContext *sc, int duration)

{

    if (duration < 0) {

        sc->dts_shift = FFMAX(sc->dts_shift, -duration);


static void fft_calc_c(FFTContext *s, FFTComplex *z) {

    int nbits, i, n, num_transforms, offset, step;

    int n4, n2, n34;

    FFTSample tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7, tmp8;

    FFTComplex *tmpz;

    const int fft_size = (1 << s->nbits);

    int64_t accu;

    num_transforms = (0x2aab >> (16 - s->nbits)) | 1;

    for (n=0; n<num_transforms; n++){

        offset = ff_fft_offsets_lut[n] << 2;

        tmpz = z + offset;

        tmp1 = tmpz[0].re + tmpz[1].re;

        tmp5 = tmpz[2].re + tmpz[3].re;

        tmp2 = tmpz[0].im + tmpz[1].im;

        tmp6 = tmpz[2].im + tmpz[3].im;

        tmp3 = tmpz[0].re - tmpz[1].re;

        tmp8 = tmpz[2].im - tmpz[3].im;

        tmp4 = tmpz[0].im - tmpz[1].im;

        tmp7 = tmpz[2].re - tmpz[3].re;

        tmpz[0].re = tmp1 + tmp5;

        tmpz[2].re = tmp1 - tmp5;

        tmpz[0].im = tmp2 + tmp6;

        tmpz[2].im = tmp2 - tmp6;

        tmpz[1].re = tmp3 + tmp8;

        tmpz[3].re = tmp3 - tmp8;

        tmpz[1].im = tmp4 - tmp7;

        tmpz[3].im = tmp4 + tmp7;

    }

    if (fft_size < 8)

        return;

    num_transforms = (num_transforms >> 1) | 1;

    for (n=0; n<num_transforms; n++){

        offset = ff_fft_offsets_lut[n] << 3;

        tmpz = z + offset;

        tmp1 = tmpz[4].re + tmpz[5].re;

        tmp3 = tmpz[6].re + tmpz[7].re;

        tmp2 = tmpz[4].im + tmpz[5].im;

        tmp4 = tmpz[6].im + tmpz[7].im;

        tmp5 = tmp1 + tmp3;

        tmp7 = tmp1 - tmp3;

        tmp6 = tmp2 + tmp4;

        tmp8 = tmp2 - tmp4;

        tmp1 = tmpz[4].re - tmpz[5].re;

        tmp2 = tmpz[4].im - tmpz[5].im;

        tmp3 = tmpz[6].re - tmpz[7].re;

        tmp4 = tmpz[6].im - tmpz[7].im;

        tmpz[4].re = tmpz[0].re - tmp5;

        tmpz[0].re = tmpz[0].re + tmp5;

        tmpz[4].im = tmpz[0].im - tmp6;

        tmpz[0].im = tmpz[0].im + tmp6;

        tmpz[6].re = tmpz[2].re - tmp8;

        tmpz[2].re = tmpz[2].re + tmp8;

        tmpz[6].im = tmpz[2].im + tmp7;

        tmpz[2].im = tmpz[2].im - tmp7;

        accu = (int64_t)Q31(M_SQRT1_2)*(tmp1 + tmp2);

        tmp5 = (int32_t)((accu + 0x40000000) >> 31);

        accu = (int64_t)Q31(M_SQRT1_2)*(tmp3 - tmp4);

        tmp7 = (int32_t)((accu + 0x40000000) >> 31);

        accu = (int64_t)Q31(M_SQRT1_2)*(tmp2 - tmp1);

        tmp6 = (int32_t)((accu + 0x40000000) >> 31);

        accu = (int64_t)Q31(M_SQRT1_2)*(tmp3 + tmp4);

        tmp8 = (int32_t)((accu + 0x40000000) >> 31);

        tmp1 = tmp5 + tmp7;

        tmp3 = tmp5 - tmp7;

        tmp2 = tmp6 + tmp8;

        tmp4 = tmp6 - tmp8;

        tmpz[5].re = tmpz[1].re - tmp1;

        tmpz[1].re = tmpz[1].re + tmp1;

        tmpz[5].im = tmpz[1].im - tmp2;

        tmpz[1].im = tmpz[1].im + tmp2;

        tmpz[7].re = tmpz[3].re - tmp4;

        tmpz[3].re = tmpz[3].re + tmp4;

        tmpz[7].im = tmpz[3].im + tmp3;

        tmpz[3].im = tmpz[3].im - tmp3;

    }

    step = 1 << ((MAX_LOG2_NFFT-4) - 4);

    n4 = 4;

    for (nbits=4; nbits<=s->nbits; nbits++){

        n2  = 2*n4;

        n34 = 3*n4;

        num_transforms = (num_transforms >> 1) | 1;

        for (n=0; n<num_transforms; n++){

            const FFTSample *w_re_ptr = ff_w_tab_sr + step;

            const FFTSample *w_im_ptr = ff_w_tab_sr + MAX_FFT_SIZE/(4*16) - step;

            offset = ff_fft_offsets_lut[n] << nbits;

            tmpz = z + offset;

            tmp5 = tmpz[ n2].re + tmpz[n34].re;

            tmp1 = tmpz[ n2].re - tmpz[n34].re;

            tmp6 = tmpz[ n2].im + tmpz[n34].im;

            tmp2 = tmpz[ n2].im - tmpz[n34].im;

            tmpz[ n2].re = tmpz[ 0].re - tmp5;

            tmpz[  0].re = tmpz[ 0].re + tmp5;

            tmpz[ n2].im = tmpz[ 0].im - tmp6;

            tmpz[  0].im = tmpz[ 0].im + tmp6;

            tmpz[n34].re = tmpz[n4].re - tmp2;

            tmpz[ n4].re = tmpz[n4].re + tmp2;

            tmpz[n34].im = tmpz[n4].im + tmp1;

            tmpz[ n4].im = tmpz[n4].im - tmp1;

            for (i=1; i<n4; i++){

                FFTSample w_re = w_re_ptr[0];

                FFTSample w_im = w_im_ptr[0];

                accu  = (int64_t)w_re*tmpz[ n2+i].re;

                accu += (int64_t)w_im*tmpz[ n2+i].im;

                tmp1 = (int32_t)((accu + 0x40000000) >> 31);

                accu  = (int64_t)w_re*tmpz[ n2+i].im;

                accu -= (int64_t)w_im*tmpz[ n2+i].re;

                tmp2 = (int32_t)((accu + 0x40000000) >> 31);

                accu  = (int64_t)w_re*tmpz[n34+i].re;

                accu -= (int64_t)w_im*tmpz[n34+i].im;

                tmp3 = (int32_t)((accu + 0x40000000) >> 31);

                accu  = (int64_t)w_re*tmpz[n34+i].im;

                accu += (int64_t)w_im*tmpz[n34+i].re;

                tmp4 = (int32_t)((accu + 0x40000000) >> 31);

                tmp5 = tmp1 + tmp3;

                tmp1 = tmp1 - tmp3;

                tmp6 = tmp2 + tmp4;

                tmp2 = tmp2 - tmp4;

                tmpz[ n2+i].re = tmpz[   i].re - tmp5;

                tmpz[    i].re = tmpz[   i].re + tmp5;

                tmpz[ n2+i].im = tmpz[   i].im - tmp6;

                tmpz[    i].im = tmpz[   i].im + tmp6;

                tmpz[n34+i].re = tmpz[n4+i].re - tmp2;

                tmpz[ n4+i].re = tmpz[n4+i].re + tmp2;

                tmpz[n34+i].im = tmpz[n4+i].im + tmp1;

                tmpz[ n4+i].im = tmpz[n4+i].im - tmp1;

                w_re_ptr += step;

                w_im_ptr -= step;

            }

        }

        step >>= 1;

        n4   <<= 1;

    }

}


int cpu_ppc_handle_mmu_fault(CPUPPCState *env, target_ulong address, int rw,

                             int mmu_idx)

{

    mmu_ctx_t ctx;

    int access_type;

    int ret = 0;

    if (rw == 2) {

        /* code access */

        rw = 0;

        access_type = ACCESS_CODE;

    } else {

        /* data access */

        access_type = env->access_type;

    }

    ret = get_physical_address(env, &ctx, address, rw, access_type);

    if (ret == 0) {

        tlb_set_page(env, address & TARGET_PAGE_MASK,

                     ctx.raddr & TARGET_PAGE_MASK, ctx.prot,

                     mmu_idx, TARGET_PAGE_SIZE);

        ret = 0;

    } else if (ret < 0) {

        LOG_MMU_STATE(env);

        if (access_type == ACCESS_CODE) {

            switch (ret) {

            case -1:

                /* No matches in page tables or TLB */

                switch (env->mmu_model) {

                case POWERPC_MMU_SOFT_6xx:

                    env->exception_index = POWERPC_EXCP_IFTLB;

                    env->error_code = 1 << 18;

                    env->spr[SPR_IMISS] = address;

                    env->spr[SPR_ICMP] = 0x80000000 | ctx.ptem;

                    goto tlb_miss;

                case POWERPC_MMU_SOFT_74xx:

                    env->exception_index = POWERPC_EXCP_IFTLB;

                    goto tlb_miss_74xx;

                case POWERPC_MMU_SOFT_4xx:

                case POWERPC_MMU_SOFT_4xx_Z:

                    env->exception_index = POWERPC_EXCP_ITLB;

                    env->error_code = 0;

                    env->spr[SPR_40x_DEAR] = address;

                    env->spr[SPR_40x_ESR] = 0x00000000;

                    break;

                case POWERPC_MMU_32B:

                case POWERPC_MMU_601:

#if defined(TARGET_PPC64)

                case POWERPC_MMU_620:

                case POWERPC_MMU_64B:

                case POWERPC_MMU_2_06:

#endif

                    env->exception_index = POWERPC_EXCP_ISI;

                    env->error_code = 0x40000000;

                    break;

                case POWERPC_MMU_BOOKE206:

                    booke206_update_mas_tlb_miss(env, address, rw);

                    /* fall through */

                case POWERPC_MMU_BOOKE:

                    env->exception_index = POWERPC_EXCP_ITLB;

                    env->error_code = 0;

                    env->spr[SPR_BOOKE_DEAR] = address;

                    return -1;

                case POWERPC_MMU_MPC8xx:

                    /* XXX: TODO */

                    cpu_abort(env, "MPC8xx MMU model is not implemented\n");

                    break;

                case POWERPC_MMU_REAL:

                    cpu_abort(env, "PowerPC in real mode should never raise "

                              "any MMU exceptions\n");

                    return -1;

                default:

                    cpu_abort(env, "Unknown or invalid MMU model\n");

                    return -1;

                }

                break;

            case -2:

                /* Access rights violation */

                env->exception_index = POWERPC_EXCP_ISI;

                env->error_code = 0x08000000;

                break;

            case -3:

                /* No execute protection violation */

                if ((env->mmu_model == POWERPC_MMU_BOOKE) ||

                    (env->mmu_model == POWERPC_MMU_BOOKE206)) {

                    env->spr[SPR_BOOKE_ESR] = 0x00000000;

                }

                env->exception_index = POWERPC_EXCP_ISI;

                env->error_code = 0x10000000;

                break;

            case -4:

                /* Direct store exception */

                /* No code fetch is allowed in direct-store areas */

                env->exception_index = POWERPC_EXCP_ISI;

                env->error_code = 0x10000000;

                break;

#if defined(TARGET_PPC64)

            case -5:

                /* No match in segment table */

                if (env->mmu_model == POWERPC_MMU_620) {

                    env->exception_index = POWERPC_EXCP_ISI;

                    /* XXX: this might be incorrect */

                    env->error_code = 0x40000000;

                } else {

                    env->exception_index = POWERPC_EXCP_ISEG;

                    env->error_code = 0;

                }

                break;

#endif

            }

        } else {

            switch (ret) {

            case -1:

                /* No matches in page tables or TLB */

                switch (env->mmu_model) {

                case POWERPC_MMU_SOFT_6xx:

                    if (rw == 1) {

                        env->exception_index = POWERPC_EXCP_DSTLB;

                        env->error_code = 1 << 16;

                    } else {

                        env->exception_index = POWERPC_EXCP_DLTLB;

                        env->error_code = 0;

                    }

                    env->spr[SPR_DMISS] = address;

                    env->spr[SPR_DCMP] = 0x80000000 | ctx.ptem;

                tlb_miss:

                    env->error_code |= ctx.key << 19;

                    env->spr[SPR_HASH1] = env->htab_base +

                        get_pteg_offset(env, ctx.hash[0], HASH_PTE_SIZE_32);

                    env->spr[SPR_HASH2] = env->htab_base +

                        get_pteg_offset(env, ctx.hash[1], HASH_PTE_SIZE_32);

                    break;

                case POWERPC_MMU_SOFT_74xx:

                    if (rw == 1) {

                        env->exception_index = POWERPC_EXCP_DSTLB;

                    } else {

                        env->exception_index = POWERPC_EXCP_DLTLB;

                    }

                tlb_miss_74xx:

                    /* Implement LRU algorithm */

                    env->error_code = ctx.key << 19;

                    env->spr[SPR_TLBMISS] = (address & ~((target_ulong)0x3)) |

                        ((env->last_way + 1) & (env->nb_ways - 1));

                    env->spr[SPR_PTEHI] = 0x80000000 | ctx.ptem;

                    break;

                case POWERPC_MMU_SOFT_4xx:

                case POWERPC_MMU_SOFT_4xx_Z:

                    env->exception_index = POWERPC_EXCP_DTLB;

                    env->error_code = 0;

                    env->spr[SPR_40x_DEAR] = address;

                    if (rw) {

                        env->spr[SPR_40x_ESR] = 0x00800000;

                    } else {

                        env->spr[SPR_40x_ESR] = 0x00000000;

                    }

                    break;

                case POWERPC_MMU_32B:

                case POWERPC_MMU_601:

#if defined(TARGET_PPC64)

                case POWERPC_MMU_620:

                case POWERPC_MMU_64B:

                case POWERPC_MMU_2_06:

#endif

                    env->exception_index = POWERPC_EXCP_DSI;

                    env->error_code = 0;

                    env->spr[SPR_DAR] = address;

                    if (rw == 1) {

                        env->spr[SPR_DSISR] = 0x42000000;

                    } else {

                        env->spr[SPR_DSISR] = 0x40000000;

                    }

                    break;

                case POWERPC_MMU_MPC8xx:

                    /* XXX: TODO */

                    cpu_abort(env, "MPC8xx MMU model is not implemented\n");

                    break;

                case POWERPC_MMU_BOOKE206:

                    booke206_update_mas_tlb_miss(env, address, rw);

                    /* fall through */

                case POWERPC_MMU_BOOKE:

                    env->exception_index = POWERPC_EXCP_DTLB;

                    env->error_code = 0;

                    env->spr[SPR_BOOKE_DEAR] = address;

                    env->spr[SPR_BOOKE_ESR] = rw ? ESR_ST : 0;

                    return -1;

                case POWERPC_MMU_REAL:

                    cpu_abort(env, "PowerPC in real mode should never raise "

                              "any MMU exceptions\n");

                    return -1;

                default:

                    cpu_abort(env, "Unknown or invalid MMU model\n");

                    return -1;

                }

                break;

            case -2:

                /* Access rights violation */

                env->exception_index = POWERPC_EXCP_DSI;

                env->error_code = 0;

                if (env->mmu_model == POWERPC_MMU_SOFT_4xx

                    || env->mmu_model == POWERPC_MMU_SOFT_4xx_Z) {

                    env->spr[SPR_40x_DEAR] = address;

                    if (rw) {

                        env->spr[SPR_40x_ESR] |= 0x00800000;

                    }

                } else if ((env->mmu_model == POWERPC_MMU_BOOKE) ||

                           (env->mmu_model == POWERPC_MMU_BOOKE206)) {

                    env->spr[SPR_BOOKE_DEAR] = address;

                    env->spr[SPR_BOOKE_ESR] = rw ? ESR_ST : 0;

                } else {

                    env->spr[SPR_DAR] = address;

                    if (rw == 1) {

                        env->spr[SPR_DSISR] = 0x0A000000;

                    } else {

                        env->spr[SPR_DSISR] = 0x08000000;

                    }

                }

                break;

            case -4:

                /* Direct store exception */

                switch (access_type) {

                case ACCESS_FLOAT:

                    /* Floating point load/store */

                    env->exception_index = POWERPC_EXCP_ALIGN;

                    env->error_code = POWERPC_EXCP_ALIGN_FP;

                    env->spr[SPR_DAR] = address;

                    break;

                case ACCESS_RES:

                    /* lwarx, ldarx or stwcx. */

                    env->exception_index = POWERPC_EXCP_DSI;

                    env->error_code = 0;

                    env->spr[SPR_DAR] = address;

                    if (rw == 1) {

                        env->spr[SPR_DSISR] = 0x06000000;

                    } else {

                        env->spr[SPR_DSISR] = 0x04000000;

                    }

                    break;

                case ACCESS_EXT:

                    /* eciwx or ecowx */

                    env->exception_index = POWERPC_EXCP_DSI;

                    env->error_code = 0;

                    env->spr[SPR_DAR] = address;

                    if (rw == 1) {

                        env->spr[SPR_DSISR] = 0x06100000;

                    } else {

                        env->spr[SPR_DSISR] = 0x04100000;

                    }

                    break;

                default:

                    printf("DSI: invalid exception (%d)\n", ret);

                    env->exception_index = POWERPC_EXCP_PROGRAM;

                    env->error_code =

                        POWERPC_EXCP_INVAL | POWERPC_EXCP_INVAL_INVAL;

                    env->spr[SPR_DAR] = address;

                    break;

                }

                break;

#if defined(TARGET_PPC64)

            case -5:

                /* No match in segment table */

                if (env->mmu_model == POWERPC_MMU_620) {

                    env->exception_index = POWERPC_EXCP_DSI;

                    env->error_code = 0;

                    env->spr[SPR_DAR] = address;

                    /* XXX: this might be incorrect */

                    if (rw == 1) {

                        env->spr[SPR_DSISR] = 0x42000000;

                    } else {

                        env->spr[SPR_DSISR] = 0x40000000;

                    }

                } else {

                    env->exception_index = POWERPC_EXCP_DSEG;

                    env->error_code = 0;

                    env->spr[SPR_DAR] = address;

                }

                break;

#endif

            }

        }

#if 0

        printf("%s: set exception to %d %02x\n", __func__,

               env->exception, env->error_code);

#endif

        ret = 1;

    }

    return ret;

}


void qemu_spice_display_init(DisplayState *ds)

{

    assert(sdpy.ds == NULL);

    qemu_spice_display_init_common(&sdpy, ds);

    register_displaychangelistener(ds, &display_listener);

    sdpy.qxl.base.sif = &dpy_interface.base;

    qemu_spice_add_interface(&sdpy.qxl.base);

    assert(sdpy.worker);

    qemu_spice_create_host_memslot(&sdpy);

    qemu_spice_create_host_primary(&sdpy);

}


static int qcow2_is_allocated(BlockDriverState *bs, int64_t sector_num,

                              int nb_sectors, int *pnum)

{

    uint64_t cluster_offset;

    int ret;

    *pnum = nb_sectors;

    /* FIXME We can get errors here, but the bdrv_is_allocated interface can't

     * pass them on today */

    ret = qcow2_get_cluster_offset(bs, sector_num << 9, pnum, &cluster_offset);

    if (ret < 0) {

        *pnum = 0;

    }

    return (cluster_offset != 0);

}


static void migrate_params_test_apply(MigrateSetParameters *params,

                                      MigrationParameters *dest)

{

    *dest = migrate_get_current()->parameters;

    /* TODO use QAPI_CLONE() instead of duplicating it inline */

    if (params->has_compress_level) {

        dest->compress_level = params->compress_level;

    }

    if (params->has_compress_threads) {

        dest->compress_threads = params->compress_threads;

    }

    if (params->has_decompress_threads) {

        dest->decompress_threads = params->decompress_threads;

    }

    if (params->has_cpu_throttle_initial) {

        dest->cpu_throttle_initial = params->cpu_throttle_initial;

    }

    if (params->has_cpu_throttle_increment) {

        dest->cpu_throttle_increment = params->cpu_throttle_increment;

    }

    if (params->has_tls_creds) {

        dest->tls_creds = g_strdup(params->tls_creds);

    }

    if (params->has_tls_hostname) {

        dest->tls_hostname = g_strdup(params->tls_hostname);

    }

    if (params->has_max_bandwidth) {

        dest->max_bandwidth = params->max_bandwidth;

    }

    if (params->has_downtime_limit) {

        dest->downtime_limit = params->downtime_limit;

    }

    if (params->has_x_checkpoint_delay) {

        dest->x_checkpoint_delay = params->x_checkpoint_delay;

    }

    if (params->has_block_incremental) {

        dest->block_incremental = params->block_incremental;

    }

}


void cpu_state_reset(CPUMIPSState *env)

{

    if (qemu_loglevel_mask(CPU_LOG_RESET)) {

        qemu_log("CPU Reset (CPU %d)\n", env->cpu_index);

        log_cpu_state(env, 0);

    }

    memset(env, 0, offsetof(CPUMIPSState, breakpoints));

    tlb_flush(env, 1);

    /* Reset registers to their default values */

    env->CP0_PRid = env->cpu_model->CP0_PRid;

    env->CP0_Config0 = env->cpu_model->CP0_Config0;

#ifdef TARGET_WORDS_BIGENDIAN

    env->CP0_Config0 |= (1 << CP0C0_BE);

#endif

    env->CP0_Config1 = env->cpu_model->CP0_Config1;

    env->CP0_Config2 = env->cpu_model->CP0_Config2;

    env->CP0_Config3 = env->cpu_model->CP0_Config3;

    env->CP0_Config6 = env->cpu_model->CP0_Config6;

    env->CP0_Config7 = env->cpu_model->CP0_Config7;

    env->CP0_LLAddr_rw_bitmask = env->cpu_model->CP0_LLAddr_rw_bitmask

                                 << env->cpu_model->CP0_LLAddr_shift;

    env->CP0_LLAddr_shift = env->cpu_model->CP0_LLAddr_shift;

    env->SYNCI_Step = env->cpu_model->SYNCI_Step;

    env->CCRes = env->cpu_model->CCRes;

    env->CP0_Status_rw_bitmask = env->cpu_model->CP0_Status_rw_bitmask;

    env->CP0_TCStatus_rw_bitmask = env->cpu_model->CP0_TCStatus_rw_bitmask;

    env->CP0_SRSCtl = env->cpu_model->CP0_SRSCtl;

    env->current_tc = 0;

    env->SEGBITS = env->cpu_model->SEGBITS;

    env->SEGMask = (target_ulong)((1ULL << env->cpu_model->SEGBITS) - 1);

#if defined(TARGET_MIPS64)

    if (env->cpu_model->insn_flags & ISA_MIPS3) {

        env->SEGMask |= 3ULL << 62;

    }

#endif

    env->PABITS = env->cpu_model->PABITS;

    env->PAMask = (target_ulong)((1ULL << env->cpu_model->PABITS) - 1);

    env->CP0_SRSConf0_rw_bitmask = env->cpu_model->CP0_SRSConf0_rw_bitmask;

    env->CP0_SRSConf0 = env->cpu_model->CP0_SRSConf0;

    env->CP0_SRSConf1_rw_bitmask = env->cpu_model->CP0_SRSConf1_rw_bitmask;

    env->CP0_SRSConf1 = env->cpu_model->CP0_SRSConf1;

    env->CP0_SRSConf2_rw_bitmask = env->cpu_model->CP0_SRSConf2_rw_bitmask;

    env->CP0_SRSConf2 = env->cpu_model->CP0_SRSConf2;

    env->CP0_SRSConf3_rw_bitmask = env->cpu_model->CP0_SRSConf3_rw_bitmask;

    env->CP0_SRSConf3 = env->cpu_model->CP0_SRSConf3;

    env->CP0_SRSConf4_rw_bitmask = env->cpu_model->CP0_SRSConf4_rw_bitmask;

    env->CP0_SRSConf4 = env->cpu_model->CP0_SRSConf4;

    env->active_fpu.fcr0 = env->cpu_model->CP1_fcr0;

    env->insn_flags = env->cpu_model->insn_flags;

#if defined(CONFIG_USER_ONLY)

    env->hflags = MIPS_HFLAG_UM;

    /* Enable access to the CPUNum, SYNCI_Step, CC, and CCRes RDHWR

       hardware registers.  */

    env->CP0_HWREna |= 0x0000000F;

    if (env->CP0_Config1 & (1 << CP0C1_FP)) {

        env->hflags |= MIPS_HFLAG_FPU;

    }

#ifdef TARGET_MIPS64

    if (env->active_fpu.fcr0 & (1 << FCR0_F64)) {

        env->hflags |= MIPS_HFLAG_F64;

    }

#endif

#else

    if (env->hflags & MIPS_HFLAG_BMASK) {

        /* If the exception was raised from a delay slot,

           come back to the jump.  */

        env->CP0_ErrorEPC = env->active_tc.PC - 4;

    } else {

        env->CP0_ErrorEPC = env->active_tc.PC;

    }

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

    env->CP0_Random = env->tlb->nb_tlb - 1;

    env->tlb->tlb_in_use = env->tlb->nb_tlb;

    env->CP0_Wired = 0;

    env->CP0_EBase = 0x80000000 | (env->cpu_index & 0x3FF);

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

    /* vectored interrupts not implemented, timer on int 7,

       no performance counters. */

    env->CP0_IntCtl = 0xe0000000;

    {

        int i;

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

            env->CP0_WatchLo[i] = 0;

            env->CP0_WatchHi[i] = 0x80000000;

        }

        env->CP0_WatchLo[7] = 0;

        env->CP0_WatchHi[7] = 0;

    }

    /* Count register increments in debug mode, EJTAG version 1 */

    env->CP0_Debug = (1 << CP0DB_CNT) | (0x1 << CP0DB_VER);

    env->hflags = MIPS_HFLAG_CP0;

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

        int i;

        /* Only TC0 on VPE 0 starts as active.  */

        for (i = 0; i < ARRAY_SIZE(env->tcs); i++) {

            env->tcs[i].CP0_TCBind = env->cpu_index << CP0TCBd_CurVPE;

            env->tcs[i].CP0_TCHalt = 1;

        }

        env->active_tc.CP0_TCHalt = 1;

        env->halted = 1;

        if (!env->cpu_index) {

            /* VPE0 starts up enabled.  */

            env->mvp->CP0_MVPControl |= (1 << CP0MVPCo_EVP);

            env->CP0_VPEConf0 |= (1 << CP0VPEC0_MVP) | (1 << CP0VPEC0_VPA);

            /* TC0 starts up unhalted.  */

            env->halted = 0;

            env->active_tc.CP0_TCHalt = 0;

            env->tcs[0].CP0_TCHalt = 0;

            /* With thread 0 active.  */

            env->active_tc.CP0_TCStatus = (1 << CP0TCSt_A);

            env->tcs[0].CP0_TCStatus = (1 << CP0TCSt_A);

        }

    }

#endif

#if defined(TARGET_MIPS64)

    if (env->cpu_model->insn_flags & ISA_MIPS3) {

        env->hflags |= MIPS_HFLAG_64;

    }

#endif

    env->exception_index = EXCP_NONE;

}


bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)

{

    BdrvOpBlocker *blocker;

    assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);

    if (!QLIST_EMPTY(&bs->op_blockers[op])) {

        blocker = QLIST_FIRST(&bs->op_blockers[op]);

        if (errp) {

            *errp = error_copy(blocker->reason);

            error_prepend(errp, "Node '%s' is busy: ",

                          bdrv_get_device_or_node_name(bs));

        }

        return true;

    }

    return false;

}


static BlockJob *find_block_job(const char *device, AioContext **aio_context,

                                Error **errp)

{

    BlockBackend *blk;

    BlockDriverState *bs;

    *aio_context = NULL;

    blk = blk_by_name(device);

    if (!blk) {

        goto notfound;

    }

    *aio_context = blk_get_aio_context(blk);

    aio_context_acquire(*aio_context);

    if (!blk_is_available(blk)) {

        goto notfound;

    }

    bs = blk_bs(blk);

    if (!bs->job) {

        goto notfound;

    }

    return bs->job;

notfound:

    error_set(errp, ERROR_CLASS_DEVICE_NOT_ACTIVE,

              "No active block job on device '%s'", device);

    if (*aio_context) {

        aio_context_release(*aio_context);

        *aio_context = NULL;

    }

    return NULL;

}


static int bt_hci_parse(const char *str)

{

    struct HCIInfo *hci;

    bdaddr_t bdaddr;

    if (nb_hcis >= MAX_NICS) {

        fprintf(stderr, "qemu: Too many bluetooth HCIs (max %i).\n", MAX_NICS);

        return -1;

    }

    hci = hci_init(str);

    if (!hci)

        return -1;

    bdaddr.b[0] = 0x52;

    bdaddr.b[1] = 0x54;

    bdaddr.b[2] = 0x00;

    bdaddr.b[3] = 0x12;

    bdaddr.b[4] = 0x34;

    bdaddr.b[5] = 0x56 + nb_hcis;

    hci->bdaddr_set(hci, bdaddr.b);

    hci_table[nb_hcis++] = hci;

    return 0;

}


static int cris_mmu_translate_page(struct cris_mmu_result *res,

				   CPUState *env, uint32_t vaddr,

				   int rw, int usermode, int debug)

{

	unsigned int vpage;

	unsigned int idx;

	uint32_t pid, lo, hi;

	uint32_t tlb_vpn, tlb_pfn = 0;

	int tlb_pid, tlb_g, tlb_v, tlb_k, tlb_w, tlb_x;

	int cfg_v, cfg_k, cfg_w, cfg_x;

	int set, match = 0;

	uint32_t r_cause;

	uint32_t r_cfg;

	int rwcause;

	int mmu = 1; /* Data mmu is default.  */

	int vect_base;

	r_cause = env->sregs[SFR_R_MM_CAUSE];

	r_cfg = env->sregs[SFR_RW_MM_CFG];

	pid = env->pregs[PR_PID] & 0xff;

	switch (rw) {

		case 2: rwcause = CRIS_MMU_ERR_EXEC; mmu = 0; break;

		case 1: rwcause = CRIS_MMU_ERR_WRITE; break;

		default:

		case 0: rwcause = CRIS_MMU_ERR_READ; break;

	}

	/* I exception vectors 4 - 7, D 8 - 11.  */

	vect_base = (mmu + 1) * 4;

	vpage = vaddr >> 13;

	/* We know the index which to check on each set.

	   Scan both I and D.  */

#if 0

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

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

			lo = env->tlbsets[mmu][set][idx].lo;

			hi = env->tlbsets[mmu][set][idx].hi;

			tlb_vpn = EXTRACT_FIELD(hi, 13, 31);

			tlb_pfn = EXTRACT_FIELD(lo, 13, 31);

			printf ("TLB: [%d][%d] hi=%x lo=%x v=%x p=%x\n",

					set, idx, hi, lo, tlb_vpn, tlb_pfn);

		}

	}

#endif

	idx = vpage & 15;

	for (set = 0; set < 4; set++)

	{

		lo = env->tlbsets[mmu][set][idx].lo;

		hi = env->tlbsets[mmu][set][idx].hi;

		tlb_vpn = hi >> 13;

		tlb_pid = EXTRACT_FIELD(hi, 0, 7);

		tlb_g  = EXTRACT_FIELD(lo, 4, 4);

		D_LOG("TLB[%d][%d][%d] v=%x vpage=%x lo=%x hi=%x\n",

			 mmu, set, idx, tlb_vpn, vpage, lo, hi);

		if ((tlb_g || (tlb_pid == pid))

		    && tlb_vpn == vpage) {

			match = 1;

			break;

		}

	}

	res->bf_vec = vect_base;

	if (match) {

		cfg_w  = EXTRACT_FIELD(r_cfg, 19, 19);

		cfg_k  = EXTRACT_FIELD(r_cfg, 18, 18);

		cfg_x  = EXTRACT_FIELD(r_cfg, 17, 17);

		cfg_v  = EXTRACT_FIELD(r_cfg, 16, 16);

		tlb_pfn = EXTRACT_FIELD(lo, 13, 31);

		tlb_v = EXTRACT_FIELD(lo, 3, 3);

		tlb_k = EXTRACT_FIELD(lo, 2, 2);

		tlb_w = EXTRACT_FIELD(lo, 1, 1);

		tlb_x = EXTRACT_FIELD(lo, 0, 0);

		/*

		set_exception_vector(0x04, i_mmu_refill);

		set_exception_vector(0x05, i_mmu_invalid);

		set_exception_vector(0x06, i_mmu_access);

		set_exception_vector(0x07, i_mmu_execute);

		set_exception_vector(0x08, d_mmu_refill);

		set_exception_vector(0x09, d_mmu_invalid);

		set_exception_vector(0x0a, d_mmu_access);

		set_exception_vector(0x0b, d_mmu_write);

		*/

		if (cfg_k && tlb_k && usermode) {

			D(printf ("tlb: kernel protected %x lo=%x pc=%x\n",

				  vaddr, lo, env->pc));

			match = 0;

			res->bf_vec = vect_base + 2;

		} else if (rw == 1 && cfg_w && !tlb_w) {

			D(printf ("tlb: write protected %x lo=%x pc=%x\n",

				  vaddr, lo, env->pc));

			match = 0;

			/* write accesses never go through the I mmu.  */

			res->bf_vec = vect_base + 3;

		} else if (rw == 2 && cfg_x && !tlb_x) {

			D(printf ("tlb: exec protected %x lo=%x pc=%x\n",

				 vaddr, lo, env->pc));

			match = 0;

			res->bf_vec = vect_base + 3;

		} else if (cfg_v && !tlb_v) {

			D(printf ("tlb: invalid %x\n", vaddr));

			match = 0;

			res->bf_vec = vect_base + 1;

		}

		res->prot = 0;

		if (match) {

			res->prot |= PAGE_READ;

			if (tlb_w)

				res->prot |= PAGE_WRITE;

			if (tlb_x)

				res->prot |= PAGE_EXEC;

		}

		else

			D(dump_tlb(env, mmu));

	} else {

		/* If refill, provide a randomized set.  */

		set = env->mmu_rand_lfsr & 3;

	}

	if (!match && !debug) {

		cris_mmu_update_rand_lfsr(env);

		/* Compute index.  */

		idx = vpage & 15;

		/* Update RW_MM_TLB_SEL.  */

		env->sregs[SFR_RW_MM_TLB_SEL] = 0;

		set_field(&env->sregs[SFR_RW_MM_TLB_SEL], idx, 0, 4);

		set_field(&env->sregs[SFR_RW_MM_TLB_SEL], set, 4, 2);

		/* Update RW_MM_CAUSE.  */

		set_field(&r_cause, rwcause, 8, 2);

		set_field(&r_cause, vpage, 13, 19);

		set_field(&r_cause, pid, 0, 8);

		env->sregs[SFR_R_MM_CAUSE] = r_cause;

		D(printf("refill vaddr=%x pc=%x\n", vaddr, env->pc));

	}

	D(printf ("%s rw=%d mtch=%d pc=%x va=%x vpn=%x tlbvpn=%x pfn=%x pid=%x"

		  " %x cause=%x sel=%x sp=%x %x %x\n",

		  __func__, rw, match, env->pc,

		  vaddr, vpage,

		  tlb_vpn, tlb_pfn, tlb_pid,

		  pid,

		  r_cause,

		  env->sregs[SFR_RW_MM_TLB_SEL],

		  env->regs[R_SP], env->pregs[PR_USP], env->ksp));

	res->phy = tlb_pfn << TARGET_PAGE_BITS;

	return !match;

}


static void gen_dst(DisasContext *ctx)

{

    if (rA(ctx->opcode) == 0) {

        gen_inval_exception(ctx, POWERPC_EXCP_INVAL_LSWX);

    } else {

        /* interpreted as no-op */

    }

}


static void x86_cpu_enable_xsave_components(X86CPU *cpu)

{

    CPUX86State *env = &cpu->env;

    int i;

    if (!(env->features[FEAT_1_ECX] & CPUID_EXT_XSAVE)) {

        return;

    }

    env->xsave_components = (XSTATE_FP_MASK | XSTATE_SSE_MASK);

    for (i = 2; i < ARRAY_SIZE(x86_ext_save_areas); i++) {

        const ExtSaveArea *esa = &x86_ext_save_areas[i];

        if (env->features[esa->feature] & esa->bits) {

            env->xsave_components |= (1ULL << i);

        }

    }

    if (kvm_enabled()) {

        KVMState *s = kvm_state;

        uint64_t kvm_mask = kvm_arch_get_supported_cpuid(s, 0xd, 0, R_EDX);

        kvm_mask <<= 32;

        kvm_mask |= kvm_arch_get_supported_cpuid(s, 0xd, 0, R_EAX);

        env->xsave_components &= kvm_mask;

    }

}


int mmu_translate_real(CPUS390XState *env, target_ulong raddr, int rw,

                       target_ulong *addr, int *flags)

{

    /* TODO: low address protection once we flush the tlb on cr changes */

    *flags = PAGE_READ | PAGE_WRITE;

    *addr = mmu_real2abs(env, raddr);

    /* TODO: storage key handling */

    return 0;

}


static void nic_selective_reset(EEPRO100State * s)

{

    size_t i;

    uint16_t *eeprom_contents = eeprom93xx_data(s->eeprom);

    //~ eeprom93xx_reset(s->eeprom);

    memcpy(eeprom_contents, s->conf.macaddr.a, 6);

    eeprom_contents[0xa] = 0x4000;

    if (s->device == i82557B || s->device == i82557C)

        eeprom_contents[5] = 0x0100;

    uint16_t sum = 0;

    for (i = 0; i < EEPROM_SIZE - 1; i++) {

        sum += eeprom_contents[i];

    }

    eeprom_contents[EEPROM_SIZE - 1] = 0xbaba - sum;

    TRACE(EEPROM, logout("checksum=0x%04x\n", eeprom_contents[EEPROM_SIZE - 1]));

    memset(s->mem, 0, sizeof(s->mem));

    uint32_t val = BIT(21);

    memcpy(&s->mem[SCBCtrlMDI], &val, sizeof(val));

    assert(sizeof(s->mdimem) == sizeof(eepro100_mdi_default));

    memcpy(&s->mdimem[0], &eepro100_mdi_default[0], sizeof(s->mdimem));

}


void pci_bridge_reset_reg(PCIDevice *dev)

{

    uint8_t *conf = dev->config;

    conf[PCI_PRIMARY_BUS] = 0;

    conf[PCI_SECONDARY_BUS] = 0;

    conf[PCI_SUBORDINATE_BUS] = 0;

    conf[PCI_SEC_LATENCY_TIMER] = 0;

    conf[PCI_IO_BASE] = 0;

    conf[PCI_IO_LIMIT] = 0;

    pci_set_word(conf + PCI_MEMORY_BASE, 0);

    pci_set_word(conf + PCI_MEMORY_LIMIT, 0);

    pci_set_word(conf + PCI_PREF_MEMORY_BASE, 0);

    pci_set_word(conf + PCI_PREF_MEMORY_LIMIT, 0);

    pci_set_word(conf + PCI_PREF_BASE_UPPER32, 0);

    pci_set_word(conf + PCI_PREF_LIMIT_UPPER32, 0);

    pci_set_word(conf + PCI_BRIDGE_CONTROL, 0);

}


static int kvm_client_sync_dirty_bitmap(struct CPUPhysMemoryClient *client,

                                        target_phys_addr_t start_addr,

                                        target_phys_addr_t end_addr)

{

    return kvm_physical_sync_dirty_bitmap(start_addr, end_addr);

}


static uint32_t bonito_readl(void *opaque, target_phys_addr_t addr)

{

    PCIBonitoState *s = opaque;

    uint32_t saddr;

    saddr = (addr - BONITO_REGBASE) >> 2;

    DPRINTF("bonito_readl "TARGET_FMT_plx"  \n", addr);

    switch (saddr) {

    case BONITO_INTISR:

        return s->regs[saddr];

    default:

        return s->regs[saddr];

    }

}


struct omap_mpu_state_s *omap310_mpu_init(MemoryRegion *system_memory,

                unsigned long sdram_size,

                const char *core)

{

    int i;

    struct omap_mpu_state_s *s = (struct omap_mpu_state_s *)

            g_malloc0(sizeof(struct omap_mpu_state_s));

    qemu_irq dma_irqs[6];

    DriveInfo *dinfo;

    SysBusDevice *busdev;

    if (!core)

        core = "ti925t";

    /* Core */

    s->mpu_model = omap310;

    s->cpu = cpu_arm_init(core);

    if (s->cpu == NULL) {

        fprintf(stderr, "Unable to find CPU definition\n");

        exit(1);

    }

    s->sdram_size = sdram_size;

    s->sram_size = OMAP15XX_SRAM_SIZE;

    s->wakeup = qemu_allocate_irq(omap_mpu_wakeup, s, 0);

    /* Clocks */

    omap_clk_init(s);

    /* Memory-mapped stuff */

    memory_region_init_ram(&s->emiff_ram, NULL, "omap1.dram", s->sdram_size,

                           &error_abort);

    vmstate_register_ram_global(&s->emiff_ram);

    memory_region_add_subregion(system_memory, OMAP_EMIFF_BASE, &s->emiff_ram);

    memory_region_init_ram(&s->imif_ram, NULL, "omap1.sram", s->sram_size,

                           &error_abort);

    vmstate_register_ram_global(&s->imif_ram);

    memory_region_add_subregion(system_memory, OMAP_IMIF_BASE, &s->imif_ram);

    omap_clkm_init(system_memory, 0xfffece00, 0xe1008000, s);

    s->ih[0] = qdev_create(NULL, "omap-intc");

    qdev_prop_set_uint32(s->ih[0], "size", 0x100);

    qdev_prop_set_ptr(s->ih[0], "clk", omap_findclk(s, "arminth_ck"));

    qdev_init_nofail(s->ih[0]);

    busdev = SYS_BUS_DEVICE(s->ih[0]);

    sysbus_connect_irq(busdev, 0,

                       qdev_get_gpio_in(DEVICE(s->cpu), ARM_CPU_IRQ));

    sysbus_connect_irq(busdev, 1,

                       qdev_get_gpio_in(DEVICE(s->cpu), ARM_CPU_FIQ));

    sysbus_mmio_map(busdev, 0, 0xfffecb00);

    s->ih[1] = qdev_create(NULL, "omap-intc");

    qdev_prop_set_uint32(s->ih[1], "size", 0x800);

    qdev_prop_set_ptr(s->ih[1], "clk", omap_findclk(s, "arminth_ck"));

    qdev_init_nofail(s->ih[1]);

    busdev = SYS_BUS_DEVICE(s->ih[1]);

    sysbus_connect_irq(busdev, 0,

                       qdev_get_gpio_in(s->ih[0], OMAP_INT_15XX_IH2_IRQ));

    /* The second interrupt controller's FIQ output is not wired up */

    sysbus_mmio_map(busdev, 0, 0xfffe0000);

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

        dma_irqs[i] = qdev_get_gpio_in(s->ih[omap1_dma_irq_map[i].ih],

                                       omap1_dma_irq_map[i].intr);

    }

    s->dma = omap_dma_init(0xfffed800, dma_irqs, system_memory,

                           qdev_get_gpio_in(s->ih[0], OMAP_INT_DMA_LCD),

                           s, omap_findclk(s, "dma_ck"), omap_dma_3_1);

    s->port[emiff    ].addr_valid = omap_validate_emiff_addr;

    s->port[emifs    ].addr_valid = omap_validate_emifs_addr;

    s->port[imif     ].addr_valid = omap_validate_imif_addr;

    s->port[tipb     ].addr_valid = omap_validate_tipb_addr;

    s->port[local    ].addr_valid = omap_validate_local_addr;

    s->port[tipb_mpui].addr_valid = omap_validate_tipb_mpui_addr;

    /* Register SDRAM and SRAM DMA ports for fast transfers.  */

    soc_dma_port_add_mem(s->dma, memory_region_get_ram_ptr(&s->emiff_ram),

                         OMAP_EMIFF_BASE, s->sdram_size);

    soc_dma_port_add_mem(s->dma, memory_region_get_ram_ptr(&s->imif_ram),

                         OMAP_IMIF_BASE, s->sram_size);

    s->timer[0] = omap_mpu_timer_init(system_memory, 0xfffec500,

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_TIMER1),

                    omap_findclk(s, "mputim_ck"));

    s->timer[1] = omap_mpu_timer_init(system_memory, 0xfffec600,

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_TIMER2),

                    omap_findclk(s, "mputim_ck"));

    s->timer[2] = omap_mpu_timer_init(system_memory, 0xfffec700,

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_TIMER3),

                    omap_findclk(s, "mputim_ck"));

    s->wdt = omap_wd_timer_init(system_memory, 0xfffec800,

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_WD_TIMER),

                    omap_findclk(s, "armwdt_ck"));

    s->os_timer = omap_os_timer_init(system_memory, 0xfffb9000,

                    qdev_get_gpio_in(s->ih[1], OMAP_INT_OS_TIMER),

                    omap_findclk(s, "clk32-kHz"));

    s->lcd = omap_lcdc_init(system_memory, 0xfffec000,

                            qdev_get_gpio_in(s->ih[0], OMAP_INT_LCD_CTRL),

                            omap_dma_get_lcdch(s->dma),

                            omap_findclk(s, "lcd_ck"));

    omap_ulpd_pm_init(system_memory, 0xfffe0800, s);

    omap_pin_cfg_init(system_memory, 0xfffe1000, s);

    omap_id_init(system_memory, s);

    omap_mpui_init(system_memory, 0xfffec900, s);

    s->private_tipb = omap_tipb_bridge_init(system_memory, 0xfffeca00,

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_BRIDGE_PRIV),

                    omap_findclk(s, "tipb_ck"));

    s->public_tipb = omap_tipb_bridge_init(system_memory, 0xfffed300,

                    qdev_get_gpio_in(s->ih[0], OMAP_INT_BRIDGE_PUB),

                    omap_findclk(s, "tipb_ck"));

    omap_tcmi_init(system_memory, 0xfffecc00, s);

    s->uart[0] = omap_uart_init(0xfffb0000,

                                qdev_get_gpio_in(s->ih[1], OMAP_INT_UART1),

                    omap_findclk(s, "uart1_ck"),

                    omap_findclk(s, "uart1_ck"),

                    s->drq[OMAP_DMA_UART1_TX], s->drq[OMAP_DMA_UART1_RX],

                    "uart1",

                    serial_hds[0]);

    s->uart[1] = omap_uart_init(0xfffb0800,

                                qdev_get_gpio_in(s->ih[1], OMAP_INT_UART2),

                    omap_findclk(s, "uart2_ck"),

                    omap_findclk(s, "uart2_ck"),

                    s->drq[OMAP_DMA_UART2_TX], s->drq[OMAP_DMA_UART2_RX],

                    "uart2",

                    serial_hds[0] ? serial_hds[1] : NULL);

    s->uart[2] = omap_uart_init(0xfffb9800,

                                qdev_get_gpio_in(s->ih[0], OMAP_INT_UART3),

                    omap_findclk(s, "uart3_ck"),

                    omap_findclk(s, "uart3_ck"),

                    s->drq[OMAP_DMA_UART3_TX], s->drq[OMAP_DMA_UART3_RX],

                    "uart3",

                    serial_hds[0] && serial_hds[1] ? serial_hds[2] : NULL);

    s->dpll[0] = omap_dpll_init(system_memory, 0xfffecf00,

                                omap_findclk(s, "dpll1"));

    s->dpll[1] = omap_dpll_init(system_memory, 0xfffed000,

                                omap_findclk(s, "dpll2"));

    s->dpll[2] = omap_dpll_init(system_memory, 0xfffed100,

                                omap_findclk(s, "dpll3"));

    dinfo = drive_get(IF_SD, 0, 0);

    if (!dinfo) {

        fprintf(stderr, "qemu: missing SecureDigital device\n");

        exit(1);

    }

    s->mmc = omap_mmc_init(0xfffb7800, system_memory,

                           blk_bs(blk_by_legacy_dinfo(dinfo)),

                           qdev_get_gpio_in(s->ih[1], OMAP_INT_OQN),

                           &s->drq[OMAP_DMA_MMC_TX],

                    omap_findclk(s, "mmc_ck"));

    s->mpuio = omap_mpuio_init(system_memory, 0xfffb5000,

                               qdev_get_gpio_in(s->ih[1], OMAP_INT_KEYBOARD),

                               qdev_get_gpio_in(s->ih[1], OMAP_INT_MPUIO),

                               s->wakeup, omap_findclk(s, "clk32-kHz"));

    s->gpio = qdev_create(NULL, "omap-gpio");

    qdev_prop_set_int32(s->gpio, "mpu_model", s->mpu_model);

    qdev_prop_set_ptr(s->gpio, "clk", omap_findclk(s, "arm_gpio_ck"));

    qdev_init_nofail(s->gpio);

    sysbus_connect_irq(SYS_BUS_DEVICE(s->gpio), 0,

                       qdev_get_gpio_in(s->ih[0], OMAP_INT_GPIO_BANK1));

    sysbus_mmio_map(SYS_BUS_DEVICE(s->gpio), 0, 0xfffce000);

    s->microwire = omap_uwire_init(system_memory, 0xfffb3000,

                                   qdev_get_gpio_in(s->ih[1], OMAP_INT_uWireTX),

                                   qdev_get_gpio_in(s->ih[1], OMAP_INT_uWireRX),

                    s->drq[OMAP_DMA_UWIRE_TX], omap_findclk(s, "mpuper_ck"));

    s->pwl = omap_pwl_init(system_memory, 0xfffb5800,

                           omap_findclk(s, "armxor_ck"));

    s->pwt = omap_pwt_init(system_memory, 0xfffb6000,

                           omap_findclk(s, "armxor_ck"));

    s->i2c[0] = qdev_create(NULL, "omap_i2c");

    qdev_prop_set_uint8(s->i2c[0], "revision", 0x11);

    qdev_prop_set_ptr(s->i2c[0], "fclk", omap_findclk(s, "mpuper_ck"));

    qdev_init_nofail(s->i2c[0]);

    busdev = SYS_BUS_DEVICE(s->i2c[0]);

    sysbus_connect_irq(busdev, 0, qdev_get_gpio_in(s->ih[1], OMAP_INT_I2C));

    sysbus_connect_irq(busdev, 1, s->drq[OMAP_DMA_I2C_TX]);

    sysbus_connect_irq(busdev, 2, s->drq[OMAP_DMA_I2C_RX]);

    sysbus_mmio_map(busdev, 0, 0xfffb3800);

    s->rtc = omap_rtc_init(system_memory, 0xfffb4800,

                           qdev_get_gpio_in(s->ih[1], OMAP_INT_RTC_TIMER),

                           qdev_get_gpio_in(s->ih[1], OMAP_INT_RTC_ALARM),

                    omap_findclk(s, "clk32-kHz"));

    s->mcbsp1 = omap_mcbsp_init(system_memory, 0xfffb1800,

                                qdev_get_gpio_in(s->ih[1], OMAP_INT_McBSP1TX),

                                qdev_get_gpio_in(s->ih[1], OMAP_INT_McBSP1RX),

                    &s->drq[OMAP_DMA_MCBSP1_TX], omap_findclk(s, "dspxor_ck"));

    s->mcbsp2 = omap_mcbsp_init(system_memory, 0xfffb1000,

                                qdev_get_gpio_in(s->ih[0],

                                                 OMAP_INT_310_McBSP2_TX),

                                qdev_get_gpio_in(s->ih[0],

                                                 OMAP_INT_310_McBSP2_RX),

                    &s->drq[OMAP_DMA_MCBSP2_TX], omap_findclk(s, "mpuper_ck"));

    s->mcbsp3 = omap_mcbsp_init(system_memory, 0xfffb7000,

                                qdev_get_gpio_in(s->ih[1], OMAP_INT_McBSP3TX),

                                qdev_get_gpio_in(s->ih[1], OMAP_INT_McBSP3RX),

                    &s->drq[OMAP_DMA_MCBSP3_TX], omap_findclk(s, "dspxor_ck"));

    s->led[0] = omap_lpg_init(system_memory,

                              0xfffbd000, omap_findclk(s, "clk32-kHz"));

    s->led[1] = omap_lpg_init(system_memory,

                              0xfffbd800, omap_findclk(s, "clk32-kHz"));

    /* Register mappings not currenlty implemented:

     * MCSI2 Comm	fffb2000 - fffb27ff (not mapped on OMAP310)

     * MCSI1 Bluetooth	fffb2800 - fffb2fff (not mapped on OMAP310)

     * USB W2FC		fffb4000 - fffb47ff

     * Camera Interface	fffb6800 - fffb6fff

     * USB Host		fffba000 - fffba7ff

     * FAC		fffba800 - fffbafff

     * HDQ/1-Wire	fffbc000 - fffbc7ff

     * TIPB switches	fffbc800 - fffbcfff

     * Mailbox		fffcf000 - fffcf7ff

     * Local bus IF	fffec100 - fffec1ff

     * Local bus MMU	fffec200 - fffec2ff

     * DSP MMU		fffed200 - fffed2ff

     */

    omap_setup_dsp_mapping(system_memory, omap15xx_dsp_mm);

    omap_setup_mpui_io(system_memory, s);

    qemu_register_reset(omap1_mpu_reset, s);

    return s;

}


void nbd_client_close(NBDClient *client)

{

    if (client->closing) {

        return;

    }

    client->closing = true;

    /* Force requests to finish.  They will drop their own references,

     * then we'll close the socket and free the NBDClient.

     */

    shutdown(client->sock, 2);

    /* Also tell the client, so that they release their reference.  */

    if (client->close) {

        client->close(client);

    }

}


static bool find_dirty_block(RAMState *rs, PageSearchStatus *pss,

                             bool *again, ram_addr_t *ram_addr_abs)

{

    pss->offset = migration_bitmap_find_dirty(rs, pss->block, pss->offset,

                                              ram_addr_abs);

    if (pss->complete_round && pss->block == rs->last_seen_block &&

        pss->offset >= rs->last_offset) {

        /*

         * We've been once around the RAM and haven't found anything.

         * Give up.

         */

        *again = false;

        return false;

    }

    if (pss->offset >= pss->block->used_length) {

        /* Didn't find anything in this RAM Block */

        pss->offset = 0;

        pss->block = QLIST_NEXT_RCU(pss->block, next);

        if (!pss->block) {

            /* Hit the end of the list */

            pss->block = QLIST_FIRST_RCU(&ram_list.blocks);

            /* Flag that we've looped */

            pss->complete_round = true;

            rs->ram_bulk_stage = false;

            if (migrate_use_xbzrle()) {

                /* If xbzrle is on, stop using the data compression at this

                 * point. In theory, xbzrle can do better than compression.

                 */

                flush_compressed_data(rs);

            }

        }

        /* Didn't find anything this time, but try again on the new block */

        *again = true;

        return false;

    } else {

        /* Can go around again, but... */

        *again = true;

        /* We've found something so probably don't need to */

        return true;

    }

}


void OPPROTO op_POWER_doz (void)

{

    if (Ts1 > Ts0)

        T0 = T1 - T0;

    else

        T0 = 0;

    RETURN();

}


int ff_wmv2_decode_secondary_picture_header(MpegEncContext *s)

{

    Wmv2Context *const w = (Wmv2Context *) s;

    if (s->pict_type == AV_PICTURE_TYPE_I) {

        if (w->j_type_bit)

            w->j_type = get_bits1(&s->gb);

        else

            w->j_type = 0; // FIXME check

        if (!w->j_type) {

            if (w->per_mb_rl_bit)

                s->per_mb_rl_table = get_bits1(&s->gb);

            else

                s->per_mb_rl_table = 0;

            if (!s->per_mb_rl_table) {

                s->rl_chroma_table_index = decode012(&s->gb);

                s->rl_table_index        = decode012(&s->gb);

            }

            s->dc_table_index = get_bits1(&s->gb);

        }

        s->inter_intra_pred = 0;

        s->no_rounding      = 1;

        if (s->avctx->debug & FF_DEBUG_PICT_INFO) {

            av_log(s->avctx, AV_LOG_DEBUG,

                   "qscale:%d rlc:%d rl:%d dc:%d mbrl:%d j_type:%d \n",

                   s->qscale, s->rl_chroma_table_index, s->rl_table_index,

                   s->dc_table_index, s->per_mb_rl_table, w->j_type);

        }

    } else {

        int cbp_index;

        w->j_type = 0;

        parse_mb_skip(w);

        cbp_index = decode012(&s->gb);

        if (s->qscale <= 10) {

            int map[3]         = { 0, 2, 1 };

            w->cbp_table_index = map[cbp_index];

        } else if (s->qscale <= 20) {

            int map[3]         = { 1, 0, 2 };

            w->cbp_table_index = map[cbp_index];

        } else {

            int map[3]         = {2,1,0};

            w->cbp_table_index = map[cbp_index];

        }

        if (w->mspel_bit)

            s->mspel = get_bits1(&s->gb);

        else

            s->mspel = 0; // FIXME check

        if (w->abt_flag) {

            w->per_mb_abt = get_bits1(&s->gb) ^ 1;

            if (!w->per_mb_abt)

                w->abt_type = decode012(&s->gb);

        }

        if (w->per_mb_rl_bit)

            s->per_mb_rl_table = get_bits1(&s->gb);

        else

            s->per_mb_rl_table = 0;

        if (!s->per_mb_rl_table) {

            s->rl_table_index        = decode012(&s->gb);

            s->rl_chroma_table_index = s->rl_table_index;

        }

        s->dc_table_index   = get_bits1(&s->gb);

        s->mv_table_index   = get_bits1(&s->gb);

        s->inter_intra_pred = 0; // (s->width * s->height < 320 * 240 && s->bit_rate <= II_BITRATE);

        s->no_rounding     ^= 1;

        if (s->avctx->debug & FF_DEBUG_PICT_INFO) {

            av_log(s->avctx, AV_LOG_DEBUG,

                   "rl:%d rlc:%d dc:%d mv:%d mbrl:%d qp:%d mspel:%d "

                   "per_mb_abt:%d abt_type:%d cbp:%d ii:%d\n",

                   s->rl_table_index, s->rl_chroma_table_index,

                   s->dc_table_index, s->mv_table_index,

                   s->per_mb_rl_table, s->qscale, s->mspel,

                   w->per_mb_abt, w->abt_type, w->cbp_table_index,

                   s->inter_intra_pred);

        }

    }

    s->esc3_level_length = 0;

    s->esc3_run_length   = 0;

    s->picture_number++; // FIXME ?

    if (w->j_type) {

        ff_intrax8_decode_picture(&w->x8, 2 * s->qscale, (s->qscale - 1) | 1);

        ff_er_add_slice(&w->s.er, 0, 0,

                        (w->s.mb_x >> 1) - 1, (w->s.mb_y >> 1) - 1,

                        ER_MB_END);

        return 1;

    }

    return 0;

}


static void fill_table(uint8_t* table[256 + 2*YUVRGB_TABLE_HEADROOM], const int elemsize,

                       const int inc, void *y_tab)

{

    int i;

    uint8_t *y_table = y_tab;

    y_table -= elemsize * (inc >> 9);

    for (i = 0; i < 256 + 2*YUVRGB_TABLE_HEADROOM; i++) {

        int64_t cb = av_clip(i-YUVRGB_TABLE_HEADROOM, 0, 255)*inc;

        table[i] = y_table + elemsize * (cb >> 16);

    }

}


static int allocate_buffers(ALACContext *alac)

{

    int ch;

    for (ch = 0; ch < FFMIN(alac->channels, 2); ch++) {

        int buf_size = alac->max_samples_per_frame * sizeof(int32_t);

        FF_ALLOC_OR_GOTO(alac->avctx, alac->predict_error_buffer[ch],

                         buf_size, buf_alloc_fail);

        if (alac->sample_size == 16) {

            FF_ALLOC_OR_GOTO(alac->avctx, alac->output_samples_buffer[ch],

                             buf_size, buf_alloc_fail);

        }

        FF_ALLOC_OR_GOTO(alac->avctx, alac->extra_bits_buffer[ch],

                         buf_size, buf_alloc_fail);

    }

    return 0;

buf_alloc_fail:

    alac_decode_close(alac->avctx);

    return AVERROR(ENOMEM);

}


static int put_cod(Jpeg2000EncoderContext *s)

{

    Jpeg2000CodingStyle *codsty = &s->codsty;

    if (s->buf_end - s->buf < 14)

        return -1;

    bytestream_put_be16(&s->buf, JPEG2000_COD);

    bytestream_put_be16(&s->buf, 12); // Lcod

    bytestream_put_byte(&s->buf, 0);  // Scod

    // SGcod

    bytestream_put_byte(&s->buf, 0); // progression level

    bytestream_put_be16(&s->buf, 1); // num of layers

    if(s->avctx->pix_fmt == AV_PIX_FMT_YUV444P){

        bytestream_put_byte(&s->buf, 2); // ICT

    }else{

        bytestream_put_byte(&s->buf, 0); // unspecified

    }

    // SPcod

    bytestream_put_byte(&s->buf, codsty->nreslevels - 1); // num of decomp. levels

    bytestream_put_byte(&s->buf, codsty->log2_cblk_width-2); // cblk width

    bytestream_put_byte(&s->buf, codsty->log2_cblk_height-2); // cblk height

    bytestream_put_byte(&s->buf, 0); // cblk style

    bytestream_put_byte(&s->buf, codsty->transform); // transformation

    return 0;

}


bool memory_region_test_and_clear_dirty(MemoryRegion *mr, hwaddr addr,

                                        hwaddr size, unsigned client)

{

    assert(mr->terminates);

    return cpu_physical_memory_test_and_clear_dirty(mr->ram_addr + addr,

                                                    size, client);

}


static int bdrv_get_cluster_size(BlockDriverState *bs)

{

    BlockDriverInfo bdi;

    int ret;

    ret = bdrv_get_info(bs, &bdi);

    if (ret < 0 || bdi.cluster_size == 0) {

        return bs->request_alignment;

    } else {

        return bdi.cluster_size;

    }

}


static int libschroedinger_encode_frame(AVCodecContext *avctx, AVPacket *pkt,

                                        const AVFrame *frame, int *got_packet)

{

    int enc_size = 0;

    SchroEncoderParams *p_schro_params = avctx->priv_data;

    SchroEncoder *encoder = p_schro_params->encoder;

    struct FFSchroEncodedFrame *p_frame_output = NULL;

    int go = 1;

    SchroBuffer *enc_buf;

    int presentation_frame;

    int parse_code;

    int last_frame_in_sequence = 0;

    int pkt_size, ret;

    if (!frame) {

        /* Push end of sequence if not already signalled. */

        if (!p_schro_params->eos_signalled) {

            schro_encoder_end_of_stream(encoder);

            p_schro_params->eos_signalled = 1;

        }

    } else {

        /* Allocate frame data to schro input buffer. */

        SchroFrame *in_frame = libschroedinger_frame_from_data(avctx, frame);

        if (!in_frame)

            return AVERROR(ENOMEM);

        /* Load next frame. */

        schro_encoder_push_frame(encoder, in_frame);

    }

    if (p_schro_params->eos_pulled)

        go = 0;

    /* Now check to see if we have any output from the encoder. */

    while (go) {

        int err;

        SchroStateEnum state;

        state = schro_encoder_wait(encoder);

        switch (state) {

        case SCHRO_STATE_HAVE_BUFFER:

        case SCHRO_STATE_END_OF_STREAM:

            enc_buf = schro_encoder_pull(encoder, &presentation_frame);

            if (enc_buf->length <= 0)

                return AVERROR_BUG;

            parse_code = enc_buf->data[4];

            /* All non-frame data is prepended to actual frame data to

             * be able to set the pts correctly. So we don't write data

             * to the frame output queue until we actually have a frame

             */

            if ((err = av_reallocp(&p_schro_params->enc_buf,

                                   p_schro_params->enc_buf_size +

                                   enc_buf->length)) < 0) {

                p_schro_params->enc_buf_size = 0;

                return err;

            }

            memcpy(p_schro_params->enc_buf + p_schro_params->enc_buf_size,

                   enc_buf->data, enc_buf->length);

            p_schro_params->enc_buf_size += enc_buf->length;

            if (state == SCHRO_STATE_END_OF_STREAM) {

                p_schro_params->eos_pulled = 1;

                go = 0;

            }

            if (!SCHRO_PARSE_CODE_IS_PICTURE(parse_code)) {

                schro_buffer_unref(enc_buf);

                break;

            }

            /* Create output frame. */

            p_frame_output = av_mallocz(sizeof(FFSchroEncodedFrame));

            if (!p_frame_output)

                return AVERROR(ENOMEM);

            /* Set output data. */

            p_frame_output->size     = p_schro_params->enc_buf_size;

            p_frame_output->p_encbuf = p_schro_params->enc_buf;

            if (SCHRO_PARSE_CODE_IS_INTRA(parse_code) &&

                SCHRO_PARSE_CODE_IS_REFERENCE(parse_code))

                p_frame_output->key_frame = 1;

            /* Parse the coded frame number from the bitstream. Bytes 14

             * through 17 represesent the frame number. */

            p_frame_output->frame_num = AV_RB32(enc_buf->data + 13);

            ff_schro_queue_push_back(&p_schro_params->enc_frame_queue,

                                     p_frame_output);

            p_schro_params->enc_buf_size = 0;

            p_schro_params->enc_buf      = NULL;

            schro_buffer_unref(enc_buf);

            break;

        case SCHRO_STATE_NEED_FRAME:

            go = 0;

            break;

        case SCHRO_STATE_AGAIN:

            break;

        default:

            av_log(avctx, AV_LOG_ERROR, "Unknown Schro Encoder state\n");

            return -1;

        }

    }

    /* Copy 'next' frame in queue. */

    if (p_schro_params->enc_frame_queue.size == 1 &&

        p_schro_params->eos_pulled)

        last_frame_in_sequence = 1;

    p_frame_output = ff_schro_queue_pop(&p_schro_params->enc_frame_queue);

    if (!p_frame_output)

        return 0;

    pkt_size = p_frame_output->size;

    if (last_frame_in_sequence && p_schro_params->enc_buf_size > 0)

        pkt_size += p_schro_params->enc_buf_size;

    if ((ret = ff_alloc_packet(pkt, pkt_size)) < 0) {

        av_log(avctx, AV_LOG_ERROR, "Error getting output packet of size %d.\n", pkt_size);

        goto error;

    }

    memcpy(pkt->data, p_frame_output->p_encbuf, p_frame_output->size);

    avctx->coded_frame->key_frame = p_frame_output->key_frame;

    /* Use the frame number of the encoded frame as the pts. It is OK to

     * do so since Dirac is a constant frame rate codec. It expects input

     * to be of constant frame rate. */

    pkt->pts =

    avctx->coded_frame->pts = p_frame_output->frame_num;

    pkt->dts = p_schro_params->dts++;

    enc_size = p_frame_output->size;

    /* Append the end of sequence information to the last frame in the

     * sequence. */

    if (last_frame_in_sequence && p_schro_params->enc_buf_size > 0) {

        memcpy(pkt->data + enc_size, p_schro_params->enc_buf,

               p_schro_params->enc_buf_size);

        enc_size += p_schro_params->enc_buf_size;

        av_freep(&p_schro_params->enc_buf);

        p_schro_params->enc_buf_size = 0;

    }

    if (p_frame_output->key_frame)

        pkt->flags |= AV_PKT_FLAG_KEY;

    *got_packet = 1;

error:

    /* free frame */

    libschroedinger_free_frame(p_frame_output);

    return ret;

}


static int fill_default_ref_list(H264Context *h){

    MpegEncContext * const s = &h->s;

    int i;

    int smallest_poc_greater_than_current = -1;

    int structure_sel;

    Picture sorted_short_ref[32];

    Picture field_entry_list[2][32];

    Picture *frame_list[2];

    if (FIELD_PICTURE) {

        structure_sel = PICT_FRAME;

        frame_list[0] = field_entry_list[0];

        frame_list[1] = field_entry_list[1];

    } else {

        structure_sel = 0;

        frame_list[0] = h->default_ref_list[0];

        frame_list[1] = h->default_ref_list[1];

    }

    if(h->slice_type_nos==FF_B_TYPE){

        int list;

        int len[2];

        int short_len[2];

        int out_i;

        int limit= INT_MIN;

        /* sort frame according to POC in B slice */

        for(out_i=0; out_i<h->short_ref_count; out_i++){

            int best_i=INT_MIN;

            int best_poc=INT_MAX;

            for(i=0; i<h->short_ref_count; i++){

                const int poc= h->short_ref[i]->poc;

                if(poc > limit && poc < best_poc){

                    best_poc= poc;

                    best_i= i;

                }

            }

            assert(best_i != INT_MIN);

            limit= best_poc;

            sorted_short_ref[out_i]= *h->short_ref[best_i];

            tprintf(h->s.avctx, "sorted poc: %d->%d poc:%d fn:%d\n", best_i, out_i, sorted_short_ref[out_i].poc, sorted_short_ref[out_i].frame_num);

            if (-1 == smallest_poc_greater_than_current) {

                if (h->short_ref[best_i]->poc >= s->current_picture_ptr->poc) {

                    smallest_poc_greater_than_current = out_i;

                }

            }

        }

        tprintf(h->s.avctx, "current poc: %d, smallest_poc_greater_than_current: %d\n", s->current_picture_ptr->poc, smallest_poc_greater_than_current);

        // find the largest POC

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

            int index = 0;

            int j= -99;

            int step= list ? -1 : 1;

            for(i=0; i<h->short_ref_count && index < h->ref_count[list]; i++, j+=step) {

                int sel;

                while(j<0 || j>= h->short_ref_count){

                    if(j != -99 && step == (list ? -1 : 1))

                        return -1;

                    step = -step;

                    j= smallest_poc_greater_than_current + (step>>1);

                }

                sel = sorted_short_ref[j].reference | structure_sel;

                if(sel != PICT_FRAME) continue;

                frame_list[list][index  ]= sorted_short_ref[j];

                frame_list[list][index++].pic_id= sorted_short_ref[j].frame_num;

            }

            short_len[list] = index;

            for(i = 0; i < 16 && index < h->ref_count[ list ]; i++){

                int sel;

                if(h->long_ref[i] == NULL) continue;

                sel = h->long_ref[i]->reference | structure_sel;

                if(sel != PICT_FRAME) continue;

                frame_list[ list ][index  ]= *h->long_ref[i];

                frame_list[ list ][index++].pic_id= i;

            }

            len[list] = index;

        }

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

            if (FIELD_PICTURE)

                len[list] = split_field_ref_list(h->default_ref_list[list],

                                                 h->ref_count[list],

                                                 frame_list[list],

                                                 len[list],

                                                 s->picture_structure,

                                                 short_len[list]);

            // swap the two first elements of L1 when L0 and L1 are identical

            if(list && len[0] > 1 && len[0] == len[1])

                for(i=0; h->default_ref_list[0][i].data[0] == h->default_ref_list[1][i].data[0]; i++)

                    if(i == len[0]){

                        FFSWAP(Picture, h->default_ref_list[1][0], h->default_ref_list[1][1]);

                        break;

                    }

            if(len[list] < h->ref_count[ list ])

                memset(&h->default_ref_list[list][len[list]], 0, sizeof(Picture)*(h->ref_count[ list ] - len[list]));

        }

    }else{

        int index=0;

        int short_len;

        for(i=0; i<h->short_ref_count; i++){

            int sel;

            sel = h->short_ref[i]->reference | structure_sel;

            if(sel != PICT_FRAME) continue;

            frame_list[0][index  ]= *h->short_ref[i];

            frame_list[0][index++].pic_id= h->short_ref[i]->frame_num;

        }

        short_len = index;

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

            int sel;

            if(h->long_ref[i] == NULL) continue;

            sel = h->long_ref[i]->reference | structure_sel;

            if(sel != PICT_FRAME) continue;

            frame_list[0][index  ]= *h->long_ref[i];

            frame_list[0][index++].pic_id= i;

        }

        if (FIELD_PICTURE)

            index = split_field_ref_list(h->default_ref_list[0],

                                         h->ref_count[0], frame_list[0],

                                         index, s->picture_structure,

                                         short_len);

        if(index < h->ref_count[0])

            memset(&h->default_ref_list[0][index], 0, sizeof(Picture)*(h->ref_count[0] - index));

    }

#ifdef TRACE

    for (i=0; i<h->ref_count[0]; i++) {

        tprintf(h->s.avctx, "List0: %s fn:%d 0x%p\n", (h->default_ref_list[0][i].long_ref ? "LT" : "ST"), h->default_ref_list[0][i].pic_id, h->default_ref_list[0][i].data[0]);

    }

    if(h->slice_type_nos==FF_B_TYPE){

        for (i=0; i<h->ref_count[1]; i++) {

            tprintf(h->s.avctx, "List1: %s fn:%d 0x%p\n", (h->default_ref_list[1][i].long_ref ? "LT" : "ST"), h->default_ref_list[1][i].pic_id, h->default_ref_list[1][i].data[0]);

        }

    }

#endif

    return 0;

}


void qemu_savevm_state_complete(QEMUFile *f)

{

    QJSON *vmdesc;

    int vmdesc_len;

    SaveStateEntry *se;

    int ret;

    trace_savevm_state_complete();

    cpu_synchronize_all_states();

    QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {

        if (!se->ops || !se->ops->save_live_complete) {

            continue;

        }

        if (se->ops && se->ops->is_active) {

            if (!se->ops->is_active(se->opaque)) {

                continue;

            }

        }

        trace_savevm_section_start(se->idstr, se->section_id);

        save_section_header(f, se, QEMU_VM_SECTION_END);

        ret = se->ops->save_live_complete(f, se->opaque);

        trace_savevm_section_end(se->idstr, se->section_id, ret);

        if (ret < 0) {

            qemu_file_set_error(f, ret);

            return;

        }

    }

    vmdesc = qjson_new();

    json_prop_int(vmdesc, "page_size", TARGET_PAGE_SIZE);

    json_start_array(vmdesc, "devices");

    QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {

        if ((!se->ops || !se->ops->save_state) && !se->vmsd) {

            continue;

        }

        trace_savevm_section_start(se->idstr, se->section_id);

        json_start_object(vmdesc, NULL);

        json_prop_str(vmdesc, "name", se->idstr);

        json_prop_int(vmdesc, "instance_id", se->instance_id);

        save_section_header(f, se, QEMU_VM_SECTION_FULL);

        vmstate_save(f, se, vmdesc);

        json_end_object(vmdesc);

        trace_savevm_section_end(se->idstr, se->section_id, 0);

    }

    qemu_put_byte(f, QEMU_VM_EOF);

    json_end_array(vmdesc);

    qjson_finish(vmdesc);

    vmdesc_len = strlen(qjson_get_str(vmdesc));

    if (should_send_vmdesc()) {

        qemu_put_byte(f, QEMU_VM_VMDESCRIPTION);

        qemu_put_be32(f, vmdesc_len);

        qemu_put_buffer(f, (uint8_t *)qjson_get_str(vmdesc), vmdesc_len);

    }

    object_unref(OBJECT(vmdesc));

    qemu_fflush(f);

}


static void mvp_init (CPUMIPSState *env, const mips_def_t *def)

{

    env->mvp = g_malloc0(sizeof(CPUMIPSMVPContext));

    /* MVPConf1 implemented, TLB sharable, no gating storage support,

       programmable cache partitioning implemented, number of allocatable

       and sharable TLB entries, MVP has allocatable TCs, 2 VPEs

       implemented, 5 TCs implemented. */

    env->mvp->CP0_MVPConf0 = (1 << CP0MVPC0_M) | (1 << CP0MVPC0_TLBS) |

                             (0 << CP0MVPC0_GS) | (1 << CP0MVPC0_PCP) |

// TODO: actually do 2 VPEs.

//                             (1 << CP0MVPC0_TCA) | (0x1 << CP0MVPC0_PVPE) |

//                             (0x04 << CP0MVPC0_PTC);

                             (1 << CP0MVPC0_TCA) | (0x0 << CP0MVPC0_PVPE) |

                             (0x00 << CP0MVPC0_PTC);

#if !defined(CONFIG_USER_ONLY)

    /* Usermode has no TLB support */

    env->mvp->CP0_MVPConf0 |= (env->tlb->nb_tlb << CP0MVPC0_PTLBE);

#endif

    /* Allocatable CP1 have media extensions, allocatable CP1 have FP support,

       no UDI implemented, no CP2 implemented, 1 CP1 implemented. */

    env->mvp->CP0_MVPConf1 = (1 << CP0MVPC1_CIM) | (1 << CP0MVPC1_CIF) |

                             (0x0 << CP0MVPC1_PCX) | (0x0 << CP0MVPC1_PCP2) |

                             (0x1 << CP0MVPC1_PCP1);

}