static int stellaris_enet_load(QEMUFile *f, void *opaque, int version_id)

{

    stellaris_enet_state *s = (stellaris_enet_state *)opaque;

    int i;

    if (version_id != 1)

        return -EINVAL;

    s->ris = qemu_get_be32(f);

    s->im = qemu_get_be32(f);

    s->rctl = qemu_get_be32(f);

    s->tctl = qemu_get_be32(f);

    s->thr = qemu_get_be32(f);

    s->mctl = qemu_get_be32(f);

    s->mdv = qemu_get_be32(f);

    s->mtxd = qemu_get_be32(f);

    s->mrxd = qemu_get_be32(f);

    s->np = qemu_get_be32(f);

    s->tx_fifo_len = qemu_get_be32(f);

    qemu_get_buffer(f, s->tx_fifo, sizeof(s->tx_fifo));

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

        s->rx[i].len = qemu_get_be32(f);

        qemu_get_buffer(f, s->rx[i].data, sizeof(s->rx[i].data));

    }

    s->next_packet = qemu_get_be32(f);

    s->rx_fifo_offset = qemu_get_be32(f);

    return 0;

}


AudioState *AUD_init (void)

{

    size_t i;

    int done = 0;

    const char *drvname;

    AudioState *s = &glob_audio_state;

    LIST_INIT (&s->hw_head_out);

    LIST_INIT (&s->hw_head_in);

    LIST_INIT (&s->cap_head);

    atexit (audio_atexit);

    s->ts = qemu_new_timer (vm_clock, audio_timer, s);

    if (!s->ts) {

        dolog ("Could not create audio timer\n");

        return NULL;

    }

    audio_process_options ("AUDIO", audio_options);

    s->nb_hw_voices_out = conf.fixed_out.nb_voices;

    s->nb_hw_voices_in = conf.fixed_in.nb_voices;

    if (s->nb_hw_voices_out <= 0) {

        dolog ("Bogus number of playback voices %d, setting to 1\n",

               s->nb_hw_voices_out);

        s->nb_hw_voices_out = 1;

    }

    if (s->nb_hw_voices_in <= 0) {

        dolog ("Bogus number of capture voices %d, setting to 0\n",

               s->nb_hw_voices_in);

        s->nb_hw_voices_in = 0;

    }

    {

        int def;

        drvname = audio_get_conf_str ("QEMU_AUDIO_DRV", NULL, &def);

    }

    if (drvname) {

        int found = 0;

        for (i = 0; i < ARRAY_SIZE (drvtab); i++) {

            if (!strcmp (drvname, drvtab[i]->name)) {

                done = !audio_driver_init (s, drvtab[i]);

                found = 1;

                break;

            }

        }

        if (!found) {

            dolog ("Unknown audio driver `%s'\n", drvname);

            dolog ("Run with -audio-help to list available drivers\n");

        }

    }

    if (!done) {

        for (i = 0; !done && i < ARRAY_SIZE (drvtab); i++) {

            if (drvtab[i]->can_be_default) {

                done = !audio_driver_init (s, drvtab[i]);

            }

        }

    }

    if (!done) {

        done = !audio_driver_init (s, &no_audio_driver);

        if (!done) {

            dolog ("Could not initialize audio subsystem\n");

        }

        else {

            dolog ("warning: Using timer based audio emulation\n");

        }

    }

    if (done) {

        VMChangeStateEntry *e;

        if (conf.period.hertz <= 0) {

            if (conf.period.hertz < 0) {

                dolog ("warning: Timer period is negative - %d "

                       "treating as zero\n",

                       conf.period.hertz);

            }

            conf.period.ticks = 1;

        }

        else {

            conf.period.ticks = ticks_per_sec / conf.period.hertz;

        }

        e = qemu_add_vm_change_state_handler (audio_vm_change_state_handler, s);

        if (!e) {

            dolog ("warning: Could not register change state handler\n"

                   "(Audio can continue looping even after stopping the VM)\n");

        }

    }

    else {

        qemu_del_timer (s->ts);

        return NULL;

    }

    LIST_INIT (&s->card_head);

    register_savevm ("audio", 0, 1, audio_save, audio_load, s);

    qemu_mod_timer (s->ts, qemu_get_clock (vm_clock) + conf.period.ticks);

    return s;

}


static void s390_cpu_model_initfn(Object *obj)
{


static void spapr_finalize_fdt(sPAPREnvironment *spapr,

                               target_phys_addr_t fdt_addr,

                               target_phys_addr_t rtas_addr,

                               target_phys_addr_t rtas_size)

{

    int ret;

    void *fdt;

    sPAPRPHBState *phb;

    fdt = g_malloc(FDT_MAX_SIZE);

    /* open out the base tree into a temp buffer for the final tweaks */

    _FDT((fdt_open_into(spapr->fdt_skel, fdt, FDT_MAX_SIZE)));

    ret = spapr_populate_vdevice(spapr->vio_bus, fdt);

    if (ret < 0) {

        fprintf(stderr, "couldn't setup vio devices in fdt\n");

        exit(1);

    }

    QLIST_FOREACH(phb, &spapr->phbs, list) {

        ret = spapr_populate_pci_dt(phb, PHANDLE_XICP, fdt);

    }

    if (ret < 0) {

        fprintf(stderr, "couldn't setup PCI devices in fdt\n");

        exit(1);

    }

    /* RTAS */

    ret = spapr_rtas_device_tree_setup(fdt, rtas_addr, rtas_size);

    if (ret < 0) {

        fprintf(stderr, "Couldn't set up RTAS device tree properties\n");

    }

    /* Advertise NUMA via ibm,associativity */

    if (nb_numa_nodes > 1) {

        ret = spapr_set_associativity(fdt, spapr);

        if (ret < 0) {

            fprintf(stderr, "Couldn't set up NUMA device tree properties\n");

        }

    }

    if (!spapr->has_graphics) {

        spapr_populate_chosen_stdout(fdt, spapr->vio_bus);

    }

    _FDT((fdt_pack(fdt)));

    if (fdt_totalsize(fdt) > FDT_MAX_SIZE) {

        hw_error("FDT too big ! 0x%x bytes (max is 0x%x)\n",

                 fdt_totalsize(fdt), FDT_MAX_SIZE);

        exit(1);

    }

    cpu_physical_memory_write(fdt_addr, fdt, fdt_totalsize(fdt));

    g_free(fdt);

}


void ff_check_pixfmt_descriptors(void){

    int i, j;

    for (i=0; i<FF_ARRAY_ELEMS(av_pix_fmt_descriptors); i++) {

        const AVPixFmtDescriptor *d = &av_pix_fmt_descriptors[i];

        uint8_t fill[4][8+6+3] = {{0}};

        uint8_t *data[4] = {fill[0], fill[1], fill[2], fill[3]};

        int linesize[4] = {0,0,0,0};

        uint16_t tmp[2];

        if (!d->name && !d->nb_components && !d->log2_chroma_w && !d->log2_chroma_h && !d->flags)

            continue;

//         av_log(NULL, AV_LOG_DEBUG, "Checking: %s\n", d->name);

        av_assert0(d->log2_chroma_w <= 3);

        av_assert0(d->log2_chroma_h <= 3);

        av_assert0(d->nb_components <= 4);

        av_assert0(d->name && d->name[0]);

        av_assert0((d->nb_components==4 || d->nb_components==2) == !!(d->flags & AV_PIX_FMT_FLAG_ALPHA));

        av_assert2(av_get_pix_fmt(d->name) == i);

        for (j=0; j<FF_ARRAY_ELEMS(d->comp); j++) {

            const AVComponentDescriptor *c = &d->comp[j];

            if(j>=d->nb_components) {

                av_assert0(!c->plane && !c->step_minus1 && !c->offset_plus1 && !c->shift && !c->depth_minus1);

                continue;

            }

            if (d->flags & AV_PIX_FMT_FLAG_BITSTREAM) {

                av_assert0(c->step_minus1 >= c->depth_minus1);

            } else {

                av_assert0(8*(c->step_minus1+1) >= c->depth_minus1+1);

            }

            av_read_image_line(tmp, (void*)data, linesize, d, 0, 0, j, 2, 0);

            if (!strncmp(d->name, "bayer_", 6))

                continue;

            av_assert0(tmp[0] == 0 && tmp[1] == 0);

            tmp[0] = tmp[1] = (1<<(c->depth_minus1 + 1)) - 1;

            av_write_image_line(tmp, data, linesize, d, 0, 0, j, 2);

        }

    }

}


static void disas_thumb_insn(CPUState *env, DisasContext *s)

{

    uint32_t val, insn, op, rm, rn, rd, shift, cond;

    int32_t offset;

    int i;

    TCGv tmp;

    TCGv tmp2;

    TCGv addr;

    if (s->condexec_mask) {

        cond = s->condexec_cond;

        if (cond != 0x0e) {     /* Skip conditional when condition is AL. */

          s->condlabel = gen_new_label();

          gen_test_cc(cond ^ 1, s->condlabel);

          s->condjmp = 1;

        }

    }

    insn = lduw_code(s->pc);

    s->pc += 2;

    switch (insn >> 12) {

    case 0: case 1:

        rd = insn & 7;

        op = (insn >> 11) & 3;

        if (op == 3) {

            /* add/subtract */

            rn = (insn >> 3) & 7;

            tmp = load_reg(s, rn);

            if (insn & (1 << 10)) {

                /* immediate */

                tmp2 = new_tmp();

                tcg_gen_movi_i32(tmp2, (insn >> 6) & 7);

            } else {

                /* reg */

                rm = (insn >> 6) & 7;

                tmp2 = load_reg(s, rm);

            }

            if (insn & (1 << 9)) {

                if (s->condexec_mask)

                    tcg_gen_sub_i32(tmp, tmp, tmp2);

                else

                    gen_helper_sub_cc(tmp, tmp, tmp2);

            } else {

                if (s->condexec_mask)

                    tcg_gen_add_i32(tmp, tmp, tmp2);

                else

                    gen_helper_add_cc(tmp, tmp, tmp2);

            }

            dead_tmp(tmp2);

            store_reg(s, rd, tmp);

        } else {

            /* shift immediate */

            rm = (insn >> 3) & 7;

            shift = (insn >> 6) & 0x1f;

            tmp = load_reg(s, rm);

            gen_arm_shift_im(tmp, op, shift, s->condexec_mask == 0);

            if (!s->condexec_mask)

                gen_logic_CC(tmp);

            store_reg(s, rd, tmp);

        }

        break;

    case 2: case 3:

        /* arithmetic large immediate */

        op = (insn >> 11) & 3;

        rd = (insn >> 8) & 0x7;

        if (op == 0) { /* mov */

            tmp = new_tmp();

            tcg_gen_movi_i32(tmp, insn & 0xff);

            if (!s->condexec_mask)

                gen_logic_CC(tmp);

            store_reg(s, rd, tmp);

        } else {

            tmp = load_reg(s, rd);

            tmp2 = new_tmp();

            tcg_gen_movi_i32(tmp2, insn & 0xff);

            switch (op) {

            case 1: /* cmp */

                gen_helper_sub_cc(tmp, tmp, tmp2);

                dead_tmp(tmp);

                dead_tmp(tmp2);

                break;

            case 2: /* add */

                if (s->condexec_mask)

                    tcg_gen_add_i32(tmp, tmp, tmp2);

                else

                    gen_helper_add_cc(tmp, tmp, tmp2);

                dead_tmp(tmp2);

                store_reg(s, rd, tmp);

                break;

            case 3: /* sub */

                if (s->condexec_mask)

                    tcg_gen_sub_i32(tmp, tmp, tmp2);

                else

                    gen_helper_sub_cc(tmp, tmp, tmp2);

                dead_tmp(tmp2);

                store_reg(s, rd, tmp);

                break;

            }

        }

        break;

    case 4:

        if (insn & (1 << 11)) {

            rd = (insn >> 8) & 7;

            /* load pc-relative.  Bit 1 of PC is ignored.  */

            val = s->pc + 2 + ((insn & 0xff) * 4);

            val &= ~(uint32_t)2;

            addr = new_tmp();

            tcg_gen_movi_i32(addr, val);

            tmp = gen_ld32(addr, IS_USER(s));

            dead_tmp(addr);

            store_reg(s, rd, tmp);

            break;

        }

        if (insn & (1 << 10)) {

            /* data processing extended or blx */

            rd = (insn & 7) | ((insn >> 4) & 8);

            rm = (insn >> 3) & 0xf;

            op = (insn >> 8) & 3;

            switch (op) {

            case 0: /* add */

                tmp = load_reg(s, rd);

                tmp2 = load_reg(s, rm);

                tcg_gen_add_i32(tmp, tmp, tmp2);

                dead_tmp(tmp2);

                store_reg(s, rd, tmp);

                break;

            case 1: /* cmp */

                tmp = load_reg(s, rd);

                tmp2 = load_reg(s, rm);

                gen_helper_sub_cc(tmp, tmp, tmp2);

                dead_tmp(tmp2);

                dead_tmp(tmp);

                break;

            case 2: /* mov/cpy */

                tmp = load_reg(s, rm);

                store_reg(s, rd, tmp);

                break;

            case 3:/* branch [and link] exchange thumb register */

                tmp = load_reg(s, rm);

                if (insn & (1 << 7)) {

                    val = (uint32_t)s->pc | 1;

                    tmp2 = new_tmp();

                    tcg_gen_movi_i32(tmp2, val);

                    store_reg(s, 14, tmp2);

                }

                gen_bx(s, tmp);

                break;

            }

            break;

        }

        /* data processing register */

        rd = insn & 7;

        rm = (insn >> 3) & 7;

        op = (insn >> 6) & 0xf;

        if (op == 2 || op == 3 || op == 4 || op == 7) {

            /* the shift/rotate ops want the operands backwards */

            val = rm;

            rm = rd;

            rd = val;

            val = 1;

        } else {

            val = 0;

        }

        if (op == 9) { /* neg */

            tmp = new_tmp();

            tcg_gen_movi_i32(tmp, 0);

        } else if (op != 0xf) { /* mvn doesn't read its first operand */

            tmp = load_reg(s, rd);

        } else {

            TCGV_UNUSED(tmp);

        }

        tmp2 = load_reg(s, rm);

        switch (op) {

        case 0x0: /* and */

            tcg_gen_and_i32(tmp, tmp, tmp2);

            if (!s->condexec_mask)

                gen_logic_CC(tmp);

            break;

        case 0x1: /* eor */

            tcg_gen_xor_i32(tmp, tmp, tmp2);

            if (!s->condexec_mask)

                gen_logic_CC(tmp);

            break;

        case 0x2: /* lsl */

            if (s->condexec_mask) {

                gen_helper_shl(tmp2, tmp2, tmp);

            } else {

                gen_helper_shl_cc(tmp2, tmp2, tmp);

                gen_logic_CC(tmp2);

            }

            break;

        case 0x3: /* lsr */

            if (s->condexec_mask) {

                gen_helper_shr(tmp2, tmp2, tmp);

            } else {

                gen_helper_shr_cc(tmp2, tmp2, tmp);

                gen_logic_CC(tmp2);

            }

            break;

        case 0x4: /* asr */

            if (s->condexec_mask) {

                gen_helper_sar(tmp2, tmp2, tmp);

            } else {

                gen_helper_sar_cc(tmp2, tmp2, tmp);

                gen_logic_CC(tmp2);

            }

            break;

        case 0x5: /* adc */

            if (s->condexec_mask)

                gen_adc(tmp, tmp2);

            else

                gen_helper_adc_cc(tmp, tmp, tmp2);

            break;

        case 0x6: /* sbc */

            if (s->condexec_mask)

                gen_sub_carry(tmp, tmp, tmp2);

            else

                gen_helper_sbc_cc(tmp, tmp, tmp2);

            break;

        case 0x7: /* ror */

            if (s->condexec_mask) {

                tcg_gen_andi_i32(tmp, tmp, 0x1f);

                tcg_gen_rotr_i32(tmp2, tmp2, tmp);

            } else {

                gen_helper_ror_cc(tmp2, tmp2, tmp);

                gen_logic_CC(tmp2);

            }

            break;

        case 0x8: /* tst */

            tcg_gen_and_i32(tmp, tmp, tmp2);

            gen_logic_CC(tmp);

            rd = 16;

            break;

        case 0x9: /* neg */

            if (s->condexec_mask)

                tcg_gen_neg_i32(tmp, tmp2);

            else

                gen_helper_sub_cc(tmp, tmp, tmp2);

            break;

        case 0xa: /* cmp */

            gen_helper_sub_cc(tmp, tmp, tmp2);

            rd = 16;

            break;

        case 0xb: /* cmn */

            gen_helper_add_cc(tmp, tmp, tmp2);

            rd = 16;

            break;

        case 0xc: /* orr */

            tcg_gen_or_i32(tmp, tmp, tmp2);

            if (!s->condexec_mask)

                gen_logic_CC(tmp);

            break;

        case 0xd: /* mul */

            tcg_gen_mul_i32(tmp, tmp, tmp2);

            if (!s->condexec_mask)

                gen_logic_CC(tmp);

            break;

        case 0xe: /* bic */

            tcg_gen_andc_i32(tmp, tmp, tmp2);

            if (!s->condexec_mask)

                gen_logic_CC(tmp);

            break;

        case 0xf: /* mvn */

            tcg_gen_not_i32(tmp2, tmp2);

            if (!s->condexec_mask)

                gen_logic_CC(tmp2);

            val = 1;

            rm = rd;

            break;

        }

        if (rd != 16) {

            if (val) {

                store_reg(s, rm, tmp2);

                if (op != 0xf)

                    dead_tmp(tmp);

            } else {

                store_reg(s, rd, tmp);

                dead_tmp(tmp2);

            }

        } else {

            dead_tmp(tmp);

            dead_tmp(tmp2);

        }

        break;

    case 5:

        /* load/store register offset.  */

        rd = insn & 7;

        rn = (insn >> 3) & 7;

        rm = (insn >> 6) & 7;

        op = (insn >> 9) & 7;

        addr = load_reg(s, rn);

        tmp = load_reg(s, rm);

        tcg_gen_add_i32(addr, addr, tmp);

        dead_tmp(tmp);

        if (op < 3) /* store */

            tmp = load_reg(s, rd);

        switch (op) {

        case 0: /* str */

            gen_st32(tmp, addr, IS_USER(s));

            break;

        case 1: /* strh */

            gen_st16(tmp, addr, IS_USER(s));

            break;

        case 2: /* strb */

            gen_st8(tmp, addr, IS_USER(s));

            break;

        case 3: /* ldrsb */

            tmp = gen_ld8s(addr, IS_USER(s));

            break;

        case 4: /* ldr */

            tmp = gen_ld32(addr, IS_USER(s));

            break;

        case 5: /* ldrh */

            tmp = gen_ld16u(addr, IS_USER(s));

            break;

        case 6: /* ldrb */

            tmp = gen_ld8u(addr, IS_USER(s));

            break;

        case 7: /* ldrsh */

            tmp = gen_ld16s(addr, IS_USER(s));

            break;

        }

        if (op >= 3) /* load */

            store_reg(s, rd, tmp);

        dead_tmp(addr);

        break;

    case 6:

        /* load/store word immediate offset */

        rd = insn & 7;

        rn = (insn >> 3) & 7;

        addr = load_reg(s, rn);

        val = (insn >> 4) & 0x7c;

        tcg_gen_addi_i32(addr, addr, val);

        if (insn & (1 << 11)) {

            /* load */

            tmp = gen_ld32(addr, IS_USER(s));

            store_reg(s, rd, tmp);

        } else {

            /* store */

            tmp = load_reg(s, rd);

            gen_st32(tmp, addr, IS_USER(s));

        }

        dead_tmp(addr);

        break;

    case 7:

        /* load/store byte immediate offset */

        rd = insn & 7;

        rn = (insn >> 3) & 7;

        addr = load_reg(s, rn);

        val = (insn >> 6) & 0x1f;

        tcg_gen_addi_i32(addr, addr, val);

        if (insn & (1 << 11)) {

            /* load */

            tmp = gen_ld8u(addr, IS_USER(s));

            store_reg(s, rd, tmp);

        } else {

            /* store */

            tmp = load_reg(s, rd);

            gen_st8(tmp, addr, IS_USER(s));

        }

        dead_tmp(addr);

        break;

    case 8:

        /* load/store halfword immediate offset */

        rd = insn & 7;

        rn = (insn >> 3) & 7;

        addr = load_reg(s, rn);

        val = (insn >> 5) & 0x3e;

        tcg_gen_addi_i32(addr, addr, val);

        if (insn & (1 << 11)) {

            /* load */

            tmp = gen_ld16u(addr, IS_USER(s));

            store_reg(s, rd, tmp);

        } else {

            /* store */

            tmp = load_reg(s, rd);

            gen_st16(tmp, addr, IS_USER(s));

        }

        dead_tmp(addr);

        break;

    case 9:

        /* load/store from stack */

        rd = (insn >> 8) & 7;

        addr = load_reg(s, 13);

        val = (insn & 0xff) * 4;

        tcg_gen_addi_i32(addr, addr, val);

        if (insn & (1 << 11)) {

            /* load */

            tmp = gen_ld32(addr, IS_USER(s));

            store_reg(s, rd, tmp);

        } else {

            /* store */

            tmp = load_reg(s, rd);

            gen_st32(tmp, addr, IS_USER(s));

        }

        dead_tmp(addr);

        break;

    case 10:

        /* add to high reg */

        rd = (insn >> 8) & 7;

        if (insn & (1 << 11)) {

            /* SP */

            tmp = load_reg(s, 13);

        } else {

            /* PC. bit 1 is ignored.  */

            tmp = new_tmp();

            tcg_gen_movi_i32(tmp, (s->pc + 2) & ~(uint32_t)2);

        }

        val = (insn & 0xff) * 4;

        tcg_gen_addi_i32(tmp, tmp, val);

        store_reg(s, rd, tmp);

        break;

    case 11:

        /* misc */

        op = (insn >> 8) & 0xf;

        switch (op) {

        case 0:

            /* adjust stack pointer */

            tmp = load_reg(s, 13);

            val = (insn & 0x7f) * 4;

            if (insn & (1 << 7))

                val = -(int32_t)val;

            tcg_gen_addi_i32(tmp, tmp, val);

            store_reg(s, 13, tmp);

            break;

        case 2: /* sign/zero extend.  */

            ARCH(6);

            rd = insn & 7;

            rm = (insn >> 3) & 7;

            tmp = load_reg(s, rm);

            switch ((insn >> 6) & 3) {

            case 0: gen_sxth(tmp); break;

            case 1: gen_sxtb(tmp); break;

            case 2: gen_uxth(tmp); break;

            case 3: gen_uxtb(tmp); break;

            }

            store_reg(s, rd, tmp);

            break;

        case 4: case 5: case 0xc: case 0xd:

            /* push/pop */

            addr = load_reg(s, 13);

            if (insn & (1 << 8))

                offset = 4;

            else

                offset = 0;

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

                if (insn & (1 << i))

                    offset += 4;

            }

            if ((insn & (1 << 11)) == 0) {

                tcg_gen_addi_i32(addr, addr, -offset);

            }

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

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

                    if (insn & (1 << 11)) {

                        /* pop */

                        tmp = gen_ld32(addr, IS_USER(s));

                        store_reg(s, i, tmp);

                    } else {

                        /* push */

                        tmp = load_reg(s, i);

                        gen_st32(tmp, addr, IS_USER(s));

                    }

                    /* advance to the next address.  */

                    tcg_gen_addi_i32(addr, addr, 4);

                }

            }

            TCGV_UNUSED(tmp);

            if (insn & (1 << 8)) {

                if (insn & (1 << 11)) {

                    /* pop pc */

                    tmp = gen_ld32(addr, IS_USER(s));

                    /* don't set the pc until the rest of the instruction

                       has completed */

                } else {

                    /* push lr */

                    tmp = load_reg(s, 14);

                    gen_st32(tmp, addr, IS_USER(s));

                }

                tcg_gen_addi_i32(addr, addr, 4);

            }

            if ((insn & (1 << 11)) == 0) {

                tcg_gen_addi_i32(addr, addr, -offset);

            }

            /* write back the new stack pointer */

            store_reg(s, 13, addr);

            /* set the new PC value */

            if ((insn & 0x0900) == 0x0900)

                gen_bx(s, tmp);

            break;

        case 1: case 3: case 9: case 11: /* czb */

            rm = insn & 7;

            tmp = load_reg(s, rm);

            s->condlabel = gen_new_label();

            s->condjmp = 1;

            if (insn & (1 << 11))

                tcg_gen_brcondi_i32(TCG_COND_EQ, tmp, 0, s->condlabel);

            else

                tcg_gen_brcondi_i32(TCG_COND_NE, tmp, 0, s->condlabel);

            dead_tmp(tmp);

            offset = ((insn & 0xf8) >> 2) | (insn & 0x200) >> 3;

            val = (uint32_t)s->pc + 2;

            val += offset;

            gen_jmp(s, val);

            break;

        case 15: /* IT, nop-hint.  */

            if ((insn & 0xf) == 0) {

                gen_nop_hint(s, (insn >> 4) & 0xf);

                break;

            }

            /* If Then.  */

            s->condexec_cond = (insn >> 4) & 0xe;

            s->condexec_mask = insn & 0x1f;

            /* No actual code generated for this insn, just setup state.  */

            break;

        case 0xe: /* bkpt */

            gen_exception_insn(s, 2, EXCP_BKPT);

            break;

        case 0xa: /* rev */

            ARCH(6);

            rn = (insn >> 3) & 0x7;

            rd = insn & 0x7;

            tmp = load_reg(s, rn);

            switch ((insn >> 6) & 3) {

            case 0: tcg_gen_bswap32_i32(tmp, tmp); break;

            case 1: gen_rev16(tmp); break;

            case 3: gen_revsh(tmp); break;

            default: goto illegal_op;

            }

            store_reg(s, rd, tmp);

            break;

        case 6: /* cps */

            ARCH(6);

            if (IS_USER(s))

                break;

            if (IS_M(env)) {

                tmp = tcg_const_i32((insn & (1 << 4)) != 0);

                /* PRIMASK */

                if (insn & 1) {

                    addr = tcg_const_i32(16);

                    gen_helper_v7m_msr(cpu_env, addr, tmp);

                    tcg_temp_free_i32(addr);

                }

                /* FAULTMASK */

                if (insn & 2) {

                    addr = tcg_const_i32(17);

                    gen_helper_v7m_msr(cpu_env, addr, tmp);

                    tcg_temp_free_i32(addr);

                }

                tcg_temp_free_i32(tmp);

                gen_lookup_tb(s);

            } else {

                if (insn & (1 << 4))

                    shift = CPSR_A | CPSR_I | CPSR_F;

                else

                    shift = 0;

                gen_set_psr_im(s, ((insn & 7) << 6), 0, shift);

            }

            break;

        default:

            goto undef;

        }

        break;

    case 12:

        /* load/store multiple */

        rn = (insn >> 8) & 0x7;

        addr = load_reg(s, rn);

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

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

                if (insn & (1 << 11)) {

                    /* load */

                    tmp = gen_ld32(addr, IS_USER(s));

                    store_reg(s, i, tmp);

                } else {

                    /* store */

                    tmp = load_reg(s, i);

                    gen_st32(tmp, addr, IS_USER(s));

                }

                /* advance to the next address */

                tcg_gen_addi_i32(addr, addr, 4);

            }

        }

        /* Base register writeback.  */

        if ((insn & (1 << rn)) == 0) {

            store_reg(s, rn, addr);

        } else {

            dead_tmp(addr);

        }

        break;

    case 13:

        /* conditional branch or swi */

        cond = (insn >> 8) & 0xf;

        if (cond == 0xe)

            goto undef;

        if (cond == 0xf) {

            /* swi */

            gen_set_pc_im(s->pc);

            s->is_jmp = DISAS_SWI;

            break;

        }

        /* generate a conditional jump to next instruction */

        s->condlabel = gen_new_label();

        gen_test_cc(cond ^ 1, s->condlabel);

        s->condjmp = 1;

        /* jump to the offset */

        val = (uint32_t)s->pc + 2;

        offset = ((int32_t)insn << 24) >> 24;

        val += offset << 1;

        gen_jmp(s, val);

        break;

    case 14:

        if (insn & (1 << 11)) {

            if (disas_thumb2_insn(env, s, insn))

              goto undef32;

            break;

        }

        /* unconditional branch */

        val = (uint32_t)s->pc;

        offset = ((int32_t)insn << 21) >> 21;

        val += (offset << 1) + 2;

        gen_jmp(s, val);

        break;

    case 15:

        if (disas_thumb2_insn(env, s, insn))

            goto undef32;

        break;

    }

    return;

undef32:

    gen_exception_insn(s, 4, EXCP_UDEF);

    return;

illegal_op:

undef:

    gen_exception_insn(s, 2, EXCP_UDEF);

}


int qcow2_snapshot_goto(BlockDriverState *bs, const char *snapshot_id)

{

    BDRVQcowState *s = bs->opaque;

    QCowSnapshot *sn;

    int i, snapshot_index, l1_size2;

    snapshot_index = find_snapshot_by_id_or_name(bs, snapshot_id);

    if (snapshot_index < 0)

        return -ENOENT;

    sn = &s->snapshots[snapshot_index];

    if (qcow2_update_snapshot_refcount(bs, s->l1_table_offset, s->l1_size, -1) < 0)

        goto fail;

    if (qcow2_grow_l1_table(bs, sn->l1_size) < 0)

        goto fail;

    s->l1_size = sn->l1_size;

    l1_size2 = s->l1_size * sizeof(uint64_t);

    /* copy the snapshot l1 table to the current l1 table */

    if (bdrv_pread(bs->file, sn->l1_table_offset,

                   s->l1_table, l1_size2) != l1_size2)

        goto fail;

    if (bdrv_pwrite(bs->file, s->l1_table_offset,

                    s->l1_table, l1_size2) != l1_size2)

        goto fail;

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

        be64_to_cpus(&s->l1_table[i]);

    }

    if (qcow2_update_snapshot_refcount(bs, s->l1_table_offset, s->l1_size, 1) < 0)

        goto fail;

#ifdef DEBUG_ALLOC

    qcow2_check_refcounts(bs);

#endif

    return 0;

 fail:

    return -EIO;

}


static int xenstore_scan(const char *type, int dom, struct XenDevOps *ops)

{

    struct XenDevice *xendev;

    char path[XEN_BUFSIZE], token[XEN_BUFSIZE];

    char **dev = NULL, *dom0;

    unsigned int cdev, j;

    /* setup watch */

    dom0 = xs_get_domain_path(xenstore, 0);

    snprintf(token, sizeof(token), "be:%p:%d:%p", type, dom, ops);

    snprintf(path, sizeof(path), "%s/backend/%s/%d", dom0, type, dom);

    free(dom0);

    if (!xs_watch(xenstore, path, token)) {

        xen_be_printf(NULL, 0, "xen be: watching backend path (%s) failed\n", path);

        return -1;

    }

    /* look for backends */

    dev = xs_directory(xenstore, 0, path, &cdev);

    if (!dev) {

        return 0;

    }

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

        xendev = xen_be_get_xendev(type, dom, atoi(dev[j]), ops);

        if (xendev == NULL) {

            continue;

        }

        xen_be_check_state(xendev);

    }

    free(dev);

    return 0;

}


static int ljpeg_decode_yuv_scan(MJpegDecodeContext *s, int predictor,

                                 int point_transform, int nb_components)

{

    int i, mb_x, mb_y, mask;

    int bits= (s->bits+7)&~7;

    int resync_mb_y = 0;

    int resync_mb_x = 0;

    point_transform += bits - s->bits;

    mask = ((1 << s->bits) - 1) << point_transform;

    av_assert0(nb_components>=1 && nb_components<=4);

    for (mb_y = 0; mb_y < s->mb_height; mb_y++) {

        for (mb_x = 0; mb_x < s->mb_width; mb_x++) {

            if (get_bits_left(&s->gb) < 1) {

                av_log(s->avctx, AV_LOG_ERROR, "bitstream end in yuv_scan\n");

                return AVERROR_INVALIDDATA;

            }

            if (s->restart_interval && !s->restart_count){

                s->restart_count = s->restart_interval;

                resync_mb_x = mb_x;

                resync_mb_y = mb_y;

            }

            if(!mb_x || mb_y == resync_mb_y || mb_y == resync_mb_y+1 && mb_x < resync_mb_x || s->interlaced){

                int toprow  = mb_y == resync_mb_y || mb_y == resync_mb_y+1 && mb_x < resync_mb_x;

                int leftcol = !mb_x || mb_y == resync_mb_y && mb_x == resync_mb_x;

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

                    uint8_t *ptr;

                    uint16_t *ptr16;

                    int n, h, v, x, y, c, j, linesize;

                    n = s->nb_blocks[i];

                    c = s->comp_index[i];

                    h = s->h_scount[i];

                    v = s->v_scount[i];

                    x = 0;

                    y = 0;

                    linesize= s->linesize[c];

                    if(bits>8) linesize /= 2;

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

                        int pred, dc;

                        dc = mjpeg_decode_dc(s, s->dc_index[i]);

                        if(dc == 0xFFFFF)

                            return -1;

                        if (   h * mb_x + x >= s->width

                            || v * mb_y + y >= s->height) {

                            // Nothing to do

                        } else if (bits<=8) {

                        ptr = s->picture_ptr->data[c] + (linesize * (v * mb_y + y)) + (h * mb_x + x); //FIXME optimize this crap

                        if(y==0 && toprow){

                            if(x==0 && leftcol){

                                pred= 1 << (bits - 1);

                            }else{

                                pred= ptr[-1];

                            }

                        }else{

                            if(x==0 && leftcol){

                                pred= ptr[-linesize];

                            }else{

                                PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);

                            }

                        }

                        if (s->interlaced && s->bottom_field)

                            ptr += linesize >> 1;

                        pred &= mask;

                        *ptr= pred + ((unsigned)dc << point_transform);

                        }else{

                            ptr16 = (uint16_t*)(s->picture_ptr->data[c] + 2*(linesize * (v * mb_y + y)) + 2*(h * mb_x + x)); //FIXME optimize this crap

                            if(y==0 && toprow){

                                if(x==0 && leftcol){

                                    pred= 1 << (bits - 1);

                                }else{

                                    pred= ptr16[-1];

                                }

                            }else{

                                if(x==0 && leftcol){

                                    pred= ptr16[-linesize];

                                }else{

                                    PREDICT(pred, ptr16[-linesize-1], ptr16[-linesize], ptr16[-1], predictor);

                                }

                            }

                            if (s->interlaced && s->bottom_field)

                                ptr16 += linesize >> 1;

                            pred &= mask;

                            *ptr16= pred + (dc << point_transform);

                        }

                        if (++x == h) {

                            x = 0;

                            y++;

                        }

                    }

                }

            } else {

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

                    uint8_t *ptr;

                    uint16_t *ptr16;

                    int n, h, v, x, y, c, j, linesize, dc;

                    n        = s->nb_blocks[i];

                    c        = s->comp_index[i];

                    h        = s->h_scount[i];

                    v        = s->v_scount[i];

                    x        = 0;

                    y        = 0;

                    linesize = s->linesize[c];

                    if(bits>8) linesize /= 2;

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

                        int pred;

                        dc = mjpeg_decode_dc(s, s->dc_index[i]);

                        if(dc == 0xFFFFF)

                            return -1;

                        if (   h * mb_x + x >= s->width

                            || v * mb_y + y >= s->height) {

                            // Nothing to do

                        } else if (bits<=8) {

                            ptr = s->picture_ptr->data[c] +

                              (linesize * (v * mb_y + y)) +

                              (h * mb_x + x); //FIXME optimize this crap

                            PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);

                            pred &= mask;

                            *ptr = pred + (dc << point_transform);

                        }else{

                            ptr16 = (uint16_t*)(s->picture_ptr->data[c] + 2*(linesize * (v * mb_y + y)) + 2*(h * mb_x + x)); //FIXME optimize this crap

                            PREDICT(pred, ptr16[-linesize-1], ptr16[-linesize], ptr16[-1], predictor);

                            pred &= mask;

                            *ptr16= pred + (dc << point_transform);

                        }

                        if (++x == h) {

                            x = 0;

                            y++;

                        }

                    }

                }

            }

            if (s->restart_interval && !--s->restart_count) {

                align_get_bits(&s->gb);

                skip_bits(&s->gb, 16); /* skip RSTn */

            }

        }

    }

    return 0;

}


inline static int push_frame(AVFilterLink *outlink)

{

    AVFilterContext *ctx = outlink->src;

    AVFilterLink *inlink = ctx->inputs[0];

    ShowWavesContext *showwaves = outlink->src->priv;

    int nb_channels = inlink->channels;

    int ret, i;

    if ((ret = ff_filter_frame(outlink, showwaves->outpicref)) >= 0)

        showwaves->req_fullfilled = 1;

    showwaves->outpicref = NULL;

    showwaves->buf_idx = 0;

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

        showwaves->buf_idy[i] = 0;

    return ret;

}


static void virtio_blk_handle_scsi(VirtIOBlockReq *req)

{

    int status;

    status = virtio_blk_handle_scsi_req(req->dev, req->elem);

    virtio_blk_req_complete(req, status);

    virtio_blk_free_request(req);

}


static int generate_fake_vps(QSVEncContext *q, AVCodecContext *avctx)

{

    GetByteContext gbc;

    PutByteContext pbc;

    GetBitContext gb;

    H2645NAL sps_nal = { NULL };

    HEVCSPS sps = { 0 };

    HEVCVPS vps = { 0 };

    uint8_t vps_buf[128], vps_rbsp_buf[128];

    uint8_t *new_extradata;

    unsigned int sps_id;

    int ret, i, type, vps_size;

    if (!avctx->extradata_size) {

        av_log(avctx, AV_LOG_ERROR, "No extradata returned from libmfx\n");

        return AVERROR_UNKNOWN;

    }

    /* parse the SPS */

    ret = ff_h2645_extract_rbsp(avctx->extradata + 4, avctx->extradata_size - 4, &sps_nal);

    if (ret < 0) {

        av_log(avctx, AV_LOG_ERROR, "Error unescaping the SPS buffer\n");

        return ret;

    }

    ret = init_get_bits8(&gb, sps_nal.data, sps_nal.size);

    if (ret < 0) {

        av_freep(&sps_nal.rbsp_buffer);

        return ret;

    }

    get_bits(&gb, 1);

    type = get_bits(&gb, 6);

    if (type != NAL_SPS) {

        av_log(avctx, AV_LOG_ERROR, "Unexpected NAL type in the extradata: %d\n",

               type);

        av_freep(&sps_nal.rbsp_buffer);

        return AVERROR_INVALIDDATA;

    }

    get_bits(&gb, 9);

    ret = ff_hevc_parse_sps(&sps, &gb, &sps_id, 0, NULL, avctx);

    av_freep(&sps_nal.rbsp_buffer);

    if (ret < 0) {

        av_log(avctx, AV_LOG_ERROR, "Error parsing the SPS\n");

        return ret;

    }

    /* generate the VPS */

    vps.vps_max_layers     = 1;

    vps.vps_max_sub_layers = sps.max_sub_layers;

    memcpy(&vps.ptl, &sps.ptl, sizeof(vps.ptl));

    vps.vps_sub_layer_ordering_info_present_flag = 1;

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

        vps.vps_max_dec_pic_buffering[i] = sps.temporal_layer[i].max_dec_pic_buffering;

        vps.vps_num_reorder_pics[i]      = sps.temporal_layer[i].num_reorder_pics;

        vps.vps_max_latency_increase[i]  = sps.temporal_layer[i].max_latency_increase;

    }

    vps.vps_num_layer_sets                  = 1;

    vps.vps_timing_info_present_flag        = sps.vui.vui_timing_info_present_flag;

    vps.vps_num_units_in_tick               = sps.vui.vui_num_units_in_tick;

    vps.vps_time_scale                      = sps.vui.vui_time_scale;

    vps.vps_poc_proportional_to_timing_flag = sps.vui.vui_poc_proportional_to_timing_flag;

    vps.vps_num_ticks_poc_diff_one          = sps.vui.vui_num_ticks_poc_diff_one_minus1 + 1;

    /* generate the encoded RBSP form of the VPS */

    ret = ff_hevc_encode_nal_vps(&vps, sps.vps_id, vps_rbsp_buf, sizeof(vps_rbsp_buf));

    if (ret < 0) {

        av_log(avctx, AV_LOG_ERROR, "Error writing the VPS\n");

        return ret;

    }

    /* escape and add the startcode */

    bytestream2_init(&gbc, vps_rbsp_buf, ret);

    bytestream2_init_writer(&pbc, vps_buf, sizeof(vps_buf));

    bytestream2_put_be32(&pbc, 1);              // startcode

    bytestream2_put_byte(&pbc, NAL_VPS << 1);   // NAL

    bytestream2_put_byte(&pbc, 1);              // header

    while (bytestream2_get_bytes_left(&gbc)) {

        uint32_t b = bytestream2_peek_be24(&gbc);

        if (b <= 3) {

            bytestream2_put_be24(&pbc, 3);

            bytestream2_skip(&gbc, 2);

        } else

            bytestream2_put_byte(&pbc, bytestream2_get_byte(&gbc));

    }

    vps_size = bytestream2_tell_p(&pbc);

    new_extradata = av_mallocz(vps_size + avctx->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);

    if (!new_extradata)

        return AVERROR(ENOMEM);

    memcpy(new_extradata, vps_buf, vps_size);

    memcpy(new_extradata + vps_size, avctx->extradata, avctx->extradata_size);

    av_freep(&avctx->extradata);

    avctx->extradata       = new_extradata;

    avctx->extradata_size += vps_size;

    return 0;

}


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

                              AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    QCELPContext *q = avctx->priv_data;

    float *outbuffer = data;

    int   i;

    float quantized_lspf[10], lpc[10];

    float gain[16];

    float *formant_mem;

    if((q->bitrate = determine_bitrate(avctx, buf_size, &buf)) == I_F_Q)

    {

        warn_insufficient_frame_quality(avctx, "bitrate cannot be determined.");

        goto erasure;

    }

    if(q->bitrate == RATE_OCTAVE &&

       (q->first16bits = AV_RB16(buf)) == 0xFFFF)

    {

        warn_insufficient_frame_quality(avctx, "Bitrate is 1/8 and first 16 bits are on.");

        goto erasure;

    }

    if(q->bitrate > SILENCE)

    {

        const QCELPBitmap *bitmaps     = qcelp_unpacking_bitmaps_per_rate[q->bitrate];

        const QCELPBitmap *bitmaps_end = qcelp_unpacking_bitmaps_per_rate[q->bitrate]

                                       + qcelp_unpacking_bitmaps_lengths[q->bitrate];

        uint8_t           *unpacked_data = (uint8_t *)&q->frame;

        init_get_bits(&q->gb, buf, 8*buf_size);

        memset(&q->frame, 0, sizeof(QCELPFrame));

        for(; bitmaps < bitmaps_end; bitmaps++)

            unpacked_data[bitmaps->index] |= get_bits(&q->gb, bitmaps->bitlen) << bitmaps->bitpos;

        // Check for erasures/blanks on rates 1, 1/4 and 1/8.

        if(q->frame.reserved)

        {

            warn_insufficient_frame_quality(avctx, "Wrong data in reserved frame area.");

            goto erasure;

        }

        if(q->bitrate == RATE_QUARTER &&

           codebook_sanity_check_for_rate_quarter(q->frame.cbgain))

        {

            warn_insufficient_frame_quality(avctx, "Codebook gain sanity check failed.");

            goto erasure;

        }

        if(q->bitrate >= RATE_HALF)

        {

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

            {

                if(q->frame.pfrac[i] && q->frame.plag[i] >= 124)

                {

                    warn_insufficient_frame_quality(avctx, "Cannot initialize pitch filter.");

                    goto erasure;

                }

            }

        }

    }

    decode_gain_and_index(q, gain);

    compute_svector(q, gain, outbuffer);

    if(decode_lspf(q, quantized_lspf) < 0)

    {

        warn_insufficient_frame_quality(avctx, "Badly received packets in frame.");

        goto erasure;

    }

    apply_pitch_filters(q, outbuffer);

    if(q->bitrate == I_F_Q)

    {

erasure:

        q->bitrate = I_F_Q;

        q->erasure_count++;

        decode_gain_and_index(q, gain);

        compute_svector(q, gain, outbuffer);

        decode_lspf(q, quantized_lspf);

        apply_pitch_filters(q, outbuffer);

    }else

        q->erasure_count = 0;

    formant_mem = q->formant_mem + 10;

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

    {

        interpolate_lpc(q, quantized_lspf, lpc, i);

        ff_celp_lp_synthesis_filterf(formant_mem, lpc, outbuffer + i * 40, 40,

                                     10);

        formant_mem += 40;

    }

    // postfilter, as per TIA/EIA/IS-733 2.4.8.6

    postfilter(q, outbuffer, lpc);

    memcpy(q->formant_mem, q->formant_mem + 160, 10 * sizeof(float));

    memcpy(q->prev_lspf, quantized_lspf, sizeof(q->prev_lspf));

    q->prev_bitrate = q->bitrate;

    *data_size = 160 * sizeof(*outbuffer);

    return buf_size;

}


int avio_read(AVIOContext *s, unsigned char *buf, int size)

{

    int len, size1;

    size1 = size;

    while (size > 0) {

        len = FFMIN(s->buf_end - s->buf_ptr, size);

        if (len == 0 || s->write_flag) {

            if((s->direct || size > s->buffer_size) && !s->update_checksum) {

                // bypass the buffer and read data directly into buf

                if(s->read_packet)

                    len = s->read_packet(s->opaque, buf, size);

                else

                    len = AVERROR_EOF;

                if (len == AVERROR_EOF) {

                    /* do not modify buffer if EOF reached so that a seek back can

                    be done without rereading data */

                    s->eof_reached = 1;

                    break;

                } else if (len < 0) {

                    s->eof_reached = 1;

                    s->error= len;

                    break;

                } else {

                    s->pos += len;

                    s->bytes_read += len;

                    size -= len;

                    buf += len;

                    // reset the buffer

                    s->buf_ptr = s->buffer;

                    s->buf_end = s->buffer/* + len*/;

                }

            } else {

                fill_buffer(s);

                len = s->buf_end - s->buf_ptr;

                if (len == 0)

                    break;

            }

        } else {

            memcpy(buf, s->buf_ptr, len);

            buf += len;

            s->buf_ptr += len;

            size -= len;

        }

    }

    if (size1 == size) {

        if (s->error)      return s->error;

        if (avio_feof(s))  return AVERROR_EOF;

    }

    return size1 - size;

}


static int hls_probe(AVProbeData *p)

{

    /* Require #EXTM3U at the start, and either one of the ones below

     * somewhere for a proper match. */

    if (strncmp(p->buf, "#EXTM3U", 7))

        return 0;

    if (p->filename && !av_match_ext(p->filename, "m3u8,m3u"))

        return 0;

    if (strstr(p->buf, "#EXT-X-STREAM-INF:")     ||

        strstr(p->buf, "#EXT-X-TARGETDURATION:") ||

        strstr(p->buf, "#EXT-X-MEDIA-SEQUENCE:"))

        return AVPROBE_SCORE_MAX;

    return 0;

}


static int svq1_motion_inter_block(MpegEncContext *s, GetBitContext *bitbuf,

                                   uint8_t *current, uint8_t *previous,

                                   int pitch, svq1_pmv *motion, int x, int y)

{

    uint8_t *src;

    uint8_t *dst;

    svq1_pmv mv;

    svq1_pmv *pmv[3];

    int result;

    /* predict and decode motion vector */

    pmv[0] = &motion[0];

    if (y == 0) {

        pmv[1] =

        pmv[2] = pmv[0];

    } else {

        pmv[1] = &motion[x / 8 + 2];

        pmv[2] = &motion[x / 8 + 4];

    }

    result = svq1_decode_motion_vector(bitbuf, &mv, pmv);

    if (result != 0)

        return result;

    motion[0].x         =

    motion[x / 8 + 2].x =

    motion[x / 8 + 3].x = mv.x;

    motion[0].y         =

    motion[x / 8 + 2].y =

    motion[x / 8 + 3].y = mv.y;

    if (y + (mv.y >> 1) < 0)

        mv.y = 0;

    if (x + (mv.x >> 1) < 0)

        mv.x = 0;

    src = &previous[(x + (mv.x >> 1)) + (y + (mv.y >> 1)) * pitch];

    dst = current;

    s->dsp.put_pixels_tab[0][(mv.y & 1) << 1 | (mv.x & 1)](dst, src, pitch, 16);

    return 0;

}


int opt_default(void *optctx, const char *opt, const char *arg)

{

    const AVOption *o;

    int consumed = 0;

    char opt_stripped[128];

    const char *p;

    const AVClass *cc = avcodec_get_class(), *fc = avformat_get_class();

#if CONFIG_AVRESAMPLE

    const AVClass *rc = avresample_get_class();

#endif

    const AVClass *sc, *swr_class;

    if (!strcmp(opt, "debug") || !strcmp(opt, "fdebug"))

        av_log_set_level(AV_LOG_DEBUG);

    if (!(p = strchr(opt, ':')))

        p = opt + strlen(opt);

    av_strlcpy(opt_stripped, opt, FFMIN(sizeof(opt_stripped), p - opt + 1));

    if ((o = opt_find(&cc, opt_stripped, NULL, 0,

                         AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ)) ||

        ((opt[0] == 'v' || opt[0] == 'a' || opt[0] == 's') &&

         (o = opt_find(&cc, opt + 1, NULL, 0, AV_OPT_SEARCH_FAKE_OBJ)))) {

        av_dict_set(&codec_opts, opt, arg, FLAGS);

        consumed = 1;

    }

    if ((o = opt_find(&fc, opt, NULL, 0,

                         AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {

        av_dict_set(&format_opts, opt, arg, FLAGS);

        if (consumed)

            av_log(NULL, AV_LOG_VERBOSE, "Routing option %s to both codec and muxer layer\n", opt);

        consumed = 1;

    }

#if CONFIG_SWSCALE

    sc = sws_get_class();

    if (!consumed && (o = opt_find(&sc, opt, NULL, 0,

                         AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {

        struct SwsContext *sws = sws_alloc_context();

        int ret = av_opt_set(sws, opt, arg, 0);

        sws_freeContext(sws);

        if (!strcmp(opt, "srcw") || !strcmp(opt, "srch") ||

            !strcmp(opt, "dstw") || !strcmp(opt, "dsth") ||

            !strcmp(opt, "src_format") || !strcmp(opt, "dst_format")) {

            av_log(NULL, AV_LOG_ERROR, "Directly using swscale dimensions/format options is not supported, please use the -s or -pix_fmt options\n");

            return AVERROR(EINVAL);

        }

        if (ret < 0) {

            av_log(NULL, AV_LOG_ERROR, "Error setting option %s.\n", opt);

            return ret;

        }

        av_dict_set(&sws_dict, opt, arg, FLAGS);

        consumed = 1;

    }

#else

    if (!consumed && !strcmp(opt, "sws_flags")) {

        av_log(NULL, AV_LOG_WARNING, "Ignoring %s %s, due to disabled swscale\n", opt, arg);

        consumed = 1;

    }

#endif

#if CONFIG_SWRESAMPLE

    swr_class = swr_get_class();

    if (!consumed && (o=opt_find(&swr_class, opt, NULL, 0,

                                    AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {

        struct SwrContext *swr = swr_alloc();

        int ret = av_opt_set(swr, opt, arg, 0);

        swr_free(&swr);

        if (ret < 0) {

            av_log(NULL, AV_LOG_ERROR, "Error setting option %s.\n", opt);

            return ret;

        }

        av_dict_set(&swr_opts, opt, arg, FLAGS);

        consumed = 1;

    }

#endif

#if CONFIG_AVRESAMPLE

    if ((o=opt_find(&rc, opt, NULL, 0,

                       AV_OPT_SEARCH_CHILDREN | AV_OPT_SEARCH_FAKE_OBJ))) {

        av_dict_set(&resample_opts, opt, arg, FLAGS);

        consumed = 1;

    }

#endif

    if (consumed)

        return 0;

    return AVERROR_OPTION_NOT_FOUND;

}


static void usb_xhci_realize(struct PCIDevice *dev, Error **errp)

{

    int i, ret;

    Error *err = NULL;

    XHCIState *xhci = XHCI(dev);

    dev->config[PCI_CLASS_PROG] = 0x30;    /* xHCI */

    dev->config[PCI_INTERRUPT_PIN] = 0x01; /* interrupt pin 1 */

    dev->config[PCI_CACHE_LINE_SIZE] = 0x10;

    dev->config[0x60] = 0x30; /* release number */

    usb_xhci_init(xhci);

    if (xhci->msi != ON_OFF_AUTO_OFF) {

        ret = msi_init(dev, 0x70, xhci->numintrs, true, false, &err);

        /* Any error other than -ENOTSUP(board's MSI support is broken)

         * is a programming error */

        assert(!ret || ret == -ENOTSUP);

        if (ret && xhci->msi == ON_OFF_AUTO_ON) {

            /* Can't satisfy user's explicit msi=on request, fail */

            error_append_hint(&err, "You have to use msi=auto (default) or "

                    "msi=off with this machine type.\n");

            error_propagate(errp, err);

            return;

        }

        assert(!err || xhci->msi == ON_OFF_AUTO_AUTO);

        /* With msi=auto, we fall back to MSI off silently */

        error_free(err);

    }

    if (xhci->numintrs > MAXINTRS) {

        xhci->numintrs = MAXINTRS;

    }

    while (xhci->numintrs & (xhci->numintrs - 1)) {   /* ! power of 2 */

        xhci->numintrs++;

    }

    if (xhci->numintrs < 1) {

        xhci->numintrs = 1;

    }

    if (xhci->numslots > MAXSLOTS) {

        xhci->numslots = MAXSLOTS;

    }

    if (xhci->numslots < 1) {

        xhci->numslots = 1;

    }

    if (xhci_get_flag(xhci, XHCI_FLAG_ENABLE_STREAMS)) {

        xhci->max_pstreams_mask = 7; /* == 256 primary streams */

    } else {

        xhci->max_pstreams_mask = 0;

    }

    xhci->mfwrap_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, xhci_mfwrap_timer, xhci);

    memory_region_init(&xhci->mem, OBJECT(xhci), "xhci", LEN_REGS);

    memory_region_init_io(&xhci->mem_cap, OBJECT(xhci), &xhci_cap_ops, xhci,

                          "capabilities", LEN_CAP);

    memory_region_init_io(&xhci->mem_oper, OBJECT(xhci), &xhci_oper_ops, xhci,

                          "operational", 0x400);

    memory_region_init_io(&xhci->mem_runtime, OBJECT(xhci), &xhci_runtime_ops, xhci,

                          "runtime", LEN_RUNTIME);

    memory_region_init_io(&xhci->mem_doorbell, OBJECT(xhci), &xhci_doorbell_ops, xhci,

                          "doorbell", LEN_DOORBELL);

    memory_region_add_subregion(&xhci->mem, 0,            &xhci->mem_cap);

    memory_region_add_subregion(&xhci->mem, OFF_OPER,     &xhci->mem_oper);

    memory_region_add_subregion(&xhci->mem, OFF_RUNTIME,  &xhci->mem_runtime);

    memory_region_add_subregion(&xhci->mem, OFF_DOORBELL, &xhci->mem_doorbell);

    for (i = 0; i < xhci->numports; i++) {

        XHCIPort *port = &xhci->ports[i];

        uint32_t offset = OFF_OPER + 0x400 + 0x10 * i;

        port->xhci = xhci;

        memory_region_init_io(&port->mem, OBJECT(xhci), &xhci_port_ops, port,

                              port->name, 0x10);

        memory_region_add_subregion(&xhci->mem, offset, &port->mem);

    }

    pci_register_bar(dev, 0,

                     PCI_BASE_ADDRESS_SPACE_MEMORY|PCI_BASE_ADDRESS_MEM_TYPE_64,

                     &xhci->mem);

    if (pci_bus_is_express(dev->bus) ||

        xhci_get_flag(xhci, XHCI_FLAG_FORCE_PCIE_ENDCAP)) {

        ret = pcie_endpoint_cap_init(dev, 0xa0);

        assert(ret >= 0);

    }

    if (xhci->msix != ON_OFF_AUTO_OFF) {

        /* TODO check for errors */

        msix_init(dev, xhci->numintrs,

                  &xhci->mem, 0, OFF_MSIX_TABLE,

                  &xhci->mem, 0, OFF_MSIX_PBA,

                  0x90);

    }

}


int fw_cfg_add_file(FWCfgState *s,  const char *filename, uint8_t *data,

                    uint32_t len)

{

    int i, index;

    if (!s->files) {

        int dsize = sizeof(uint32_t) + sizeof(FWCfgFile) * FW_CFG_FILE_SLOTS;

        s->files = g_malloc0(dsize);

        fw_cfg_add_bytes(s, FW_CFG_FILE_DIR, (uint8_t*)s->files, dsize);

    }

    index = be32_to_cpu(s->files->count);

    if (index == FW_CFG_FILE_SLOTS) {

        fprintf(stderr, "fw_cfg: out of file slots\n");

        return 0;

    }

    fw_cfg_add_bytes(s, FW_CFG_FILE_FIRST + index, data, len);

    pstrcpy(s->files->f[index].name, sizeof(s->files->f[index].name),

            filename);

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

        if (strcmp(s->files->f[index].name, s->files->f[i].name) == 0) {

            trace_fw_cfg_add_file_dupe(s, s->files->f[index].name);

            return 1;

        }

    }

    s->files->f[index].size   = cpu_to_be32(len);

    s->files->f[index].select = cpu_to_be16(FW_CFG_FILE_FIRST + index);

    trace_fw_cfg_add_file(s, index, s->files->f[index].name, len);

    s->files->count = cpu_to_be32(index+1);

    return 1;

}


static void *postcopy_ram_fault_thread(void *opaque)

{

    MigrationIncomingState *mis = opaque;

    struct uffd_msg msg;

    int ret;

    RAMBlock *rb = NULL;

    RAMBlock *last_rb = NULL; /* last RAMBlock we sent part of */

    trace_postcopy_ram_fault_thread_entry();

    qemu_sem_post(&mis->fault_thread_sem);

    while (true) {

        ram_addr_t rb_offset;

        struct pollfd pfd[2];

        /*

         * We're mainly waiting for the kernel to give us a faulting HVA,

         * however we can be told to quit via userfault_quit_fd which is

         * an eventfd

         */

        pfd[0].fd = mis->userfault_fd;

        pfd[0].events = POLLIN;

        pfd[0].revents = 0;

        pfd[1].fd = mis->userfault_quit_fd;

        pfd[1].events = POLLIN; /* Waiting for eventfd to go positive */

        pfd[1].revents = 0;

        if (poll(pfd, 2, -1 /* Wait forever */) == -1) {

            error_report("%s: userfault poll: %s", __func__, strerror(errno));

            break;

        }

        if (pfd[1].revents) {

            trace_postcopy_ram_fault_thread_quit();

            break;

        }

        ret = read(mis->userfault_fd, &msg, sizeof(msg));

        if (ret != sizeof(msg)) {

            if (errno == EAGAIN) {

                /*

                 * if a wake up happens on the other thread just after

                 * the poll, there is nothing to read.

                 */

                continue;

            }

            if (ret < 0) {

                error_report("%s: Failed to read full userfault message: %s",

                             __func__, strerror(errno));

                break;

            } else {

                error_report("%s: Read %d bytes from userfaultfd expected %zd",

                             __func__, ret, sizeof(msg));

                break; /* Lost alignment, don't know what we'd read next */

            }

        }

        if (msg.event != UFFD_EVENT_PAGEFAULT) {

            error_report("%s: Read unexpected event %ud from userfaultfd",

                         __func__, msg.event);

            continue; /* It's not a page fault, shouldn't happen */

        }

        rb = qemu_ram_block_from_host(

                 (void *)(uintptr_t)msg.arg.pagefault.address,

                 true, &rb_offset);

        if (!rb) {

            error_report("postcopy_ram_fault_thread: Fault outside guest: %"

                         PRIx64, (uint64_t)msg.arg.pagefault.address);

            break;

        }

        rb_offset &= ~(qemu_ram_pagesize(rb) - 1);

        trace_postcopy_ram_fault_thread_request(msg.arg.pagefault.address,

                                                qemu_ram_get_idstr(rb),

                                                rb_offset);

        /*

         * Send the request to the source - we want to request one

         * of our host page sizes (which is >= TPS)

         */

        if (rb != last_rb) {

            last_rb = rb;

            migrate_send_rp_req_pages(mis, qemu_ram_get_idstr(rb),

                                     rb_offset, qemu_ram_pagesize(rb));

        } else {

            /* Save some space */

            migrate_send_rp_req_pages(mis, NULL,

                                     rb_offset, qemu_ram_pagesize(rb));

        }

    }

    trace_postcopy_ram_fault_thread_exit();

    return NULL;

}


static ssize_t qio_channel_websock_decode_header(QIOChannelWebsock *ioc,

                                                 Error **errp)

{

    unsigned char opcode, fin, has_mask;

    size_t header_size;

    size_t payload_len;

    QIOChannelWebsockHeader *header =

        (QIOChannelWebsockHeader *)ioc->encinput.buffer;

    if (ioc->payload_remain) {

        error_setg(errp,

                   "Decoding header but %zu bytes of payload remain",

                   ioc->payload_remain);

        return -1;

    }

    if (ioc->encinput.offset < QIO_CHANNEL_WEBSOCK_HEADER_LEN_7_BIT) {

        /* header not complete */

        return QIO_CHANNEL_ERR_BLOCK;

    }

    fin = (header->b0 & QIO_CHANNEL_WEBSOCK_HEADER_FIELD_FIN) >>

        QIO_CHANNEL_WEBSOCK_HEADER_SHIFT_FIN;

    opcode = header->b0 & QIO_CHANNEL_WEBSOCK_HEADER_FIELD_OPCODE;

    has_mask = (header->b1 & QIO_CHANNEL_WEBSOCK_HEADER_FIELD_HAS_MASK) >>

        QIO_CHANNEL_WEBSOCK_HEADER_SHIFT_HAS_MASK;

    payload_len = header->b1 & QIO_CHANNEL_WEBSOCK_HEADER_FIELD_PAYLOAD_LEN;

    if (opcode == QIO_CHANNEL_WEBSOCK_OPCODE_CLOSE) {

        /* disconnect */

        return 0;

    }

    /* Websocket frame sanity check:

     * * Websocket fragmentation is not supported.

     * * All  websockets frames sent by a client have to be masked.

     * * Only binary encoding is supported.

     */

    if (!fin) {

        error_setg(errp, "websocket fragmentation is not supported");

        return -1;

    }

    if (!has_mask) {

        error_setg(errp, "websocket frames must be masked");

        return -1;

    }

    if (opcode != QIO_CHANNEL_WEBSOCK_OPCODE_BINARY_FRAME) {

        error_setg(errp, "only binary websocket frames are supported");

        return -1;

    }

    if (payload_len < QIO_CHANNEL_WEBSOCK_PAYLOAD_LEN_MAGIC_16_BIT) {

        ioc->payload_remain = payload_len;

        header_size = QIO_CHANNEL_WEBSOCK_HEADER_LEN_7_BIT;

        ioc->mask = header->u.m;

    } else if (payload_len == QIO_CHANNEL_WEBSOCK_PAYLOAD_LEN_MAGIC_16_BIT &&

               ioc->encinput.offset >= QIO_CHANNEL_WEBSOCK_HEADER_LEN_16_BIT) {

        ioc->payload_remain = be16_to_cpu(header->u.s16.l16);

        header_size = QIO_CHANNEL_WEBSOCK_HEADER_LEN_16_BIT;

        ioc->mask = header->u.s16.m16;

    } else if (payload_len == QIO_CHANNEL_WEBSOCK_PAYLOAD_LEN_MAGIC_64_BIT &&

               ioc->encinput.offset >= QIO_CHANNEL_WEBSOCK_HEADER_LEN_64_BIT) {

        ioc->payload_remain = be64_to_cpu(header->u.s64.l64);

        header_size = QIO_CHANNEL_WEBSOCK_HEADER_LEN_64_BIT;

        ioc->mask = header->u.s64.m64;

    } else {

        /* header not complete */

        return QIO_CHANNEL_ERR_BLOCK;

    }

    buffer_advance(&ioc->encinput, header_size);

    return 1;

}


static int vscsi_send_iu(VSCSIState *s, vscsi_req *req,

                         uint64_t length, uint8_t format)

{

    long rc, rc1;

    /* First copy the SRP */

    rc = spapr_vio_dma_write(&s->vdev, req->crq.s.IU_data_ptr,

                             &req->iu, length);

    if (rc) {

        fprintf(stderr, "vscsi_send_iu: DMA write failure !\n");

    }

    req->crq.s.valid = 0x80;

    req->crq.s.format = format;

    req->crq.s.reserved = 0x00;

    req->crq.s.timeout = cpu_to_be16(0x0000);

    req->crq.s.IU_length = cpu_to_be16(length);

    req->crq.s.IU_data_ptr = req->iu.srp.rsp.tag; /* right byte order */

    if (rc == 0) {

        req->crq.s.status = 0x99; /* Just needs to be non-zero */

    } else {

        req->crq.s.status = 0x00;

    }

    rc1 = spapr_vio_send_crq(&s->vdev, req->crq.raw);

    if (rc1) {

        fprintf(stderr, "vscsi_send_iu: Error sending response\n");

        return rc1;

    }

    return rc;

}


static int r3d_read_reda(AVFormatContext *s, AVPacket *pkt, Atom *atom)

{

    AVStream *st = s->streams[1];

    int av_unused tmp, tmp2;

    int samples, size;

    uint64_t pos = avio_tell(s->pb);

    unsigned dts;

    int ret;

    dts = avio_rb32(s->pb);

    st->codec->sample_rate = avio_rb32(s->pb);

    samples = avio_rb32(s->pb);

    tmp = avio_rb32(s->pb);

    av_dlog(s, "packet num %d\n", tmp);

    tmp = avio_rb16(s->pb); // unknown

    av_dlog(s, "unknown %d\n", tmp);

    tmp  = avio_r8(s->pb); // major version

    tmp2 = avio_r8(s->pb); // minor version

    av_dlog(s, "version %d.%d\n", tmp, tmp2);

    tmp = avio_rb32(s->pb); // unknown

    av_dlog(s, "unknown %d\n", tmp);

    size = atom->size - 8 - (avio_tell(s->pb) - pos);

    if (size < 0)

        return -1;

    ret = av_get_packet(s->pb, pkt, size);

    if (ret < 0) {

        av_log(s, AV_LOG_ERROR, "error reading audio packet\n");

        return ret;

    }

    pkt->stream_index = 1;

    pkt->dts = dts;

    pkt->duration = av_rescale(samples, st->time_base.den, st->codec->sample_rate);

    av_dlog(s, "pkt dts %"PRId64" duration %d samples %d sample rate %d\n",

            pkt->dts, pkt->duration, samples, st->codec->sample_rate);

    return 0;

}


MigrationParameters *qmp_query_migrate_parameters(Error **errp)

{

    MigrationParameters *params;

    MigrationState *s = migrate_get_current();

    params = g_malloc0(sizeof(*params));

    params->compress_level = s->parameters.compress_level;

    params->compress_threads = s->parameters.compress_threads;

    params->decompress_threads = s->parameters.decompress_threads;

    params->cpu_throttle_initial = s->parameters.cpu_throttle_initial;

    params->cpu_throttle_increment = s->parameters.cpu_throttle_increment;

    return params;

}


static int kvm_ppc_register_host_cpu_type(void)

{

    TypeInfo type_info = {

        .name = TYPE_HOST_POWERPC_CPU,

        .instance_init = kvmppc_host_cpu_initfn,

        .class_init = kvmppc_host_cpu_class_init,

    };

    PowerPCCPUClass *pvr_pcc;

    DeviceClass *dc;

    pvr_pcc = kvm_ppc_get_host_cpu_class();

    if (pvr_pcc == NULL) {

        return -1;

    }

    type_info.parent = object_class_get_name(OBJECT_CLASS(pvr_pcc));

    type_register(&type_info);

    /* Register generic family CPU class for a family */

    pvr_pcc = ppc_cpu_get_family_class(pvr_pcc);

    dc = DEVICE_CLASS(pvr_pcc);

    type_info.parent = object_class_get_name(OBJECT_CLASS(pvr_pcc));

    type_info.name = g_strdup_printf("%s-"TYPE_POWERPC_CPU, dc->desc);

    type_register(&type_info);

#if defined(TARGET_PPC64)

    type_info.name = g_strdup_printf("%s-"TYPE_SPAPR_CPU_CORE, "host");

    type_info.parent = TYPE_SPAPR_CPU_CORE,

    type_info.instance_size = sizeof(sPAPRCPUCore),

    type_info.instance_init = spapr_cpu_core_host_initfn,

    type_info.class_init = NULL;

    type_register(&type_info);

    g_free((void *)type_info.name);

    /* Register generic spapr CPU family class for current host CPU type */

    type_info.name = g_strdup_printf("%s-"TYPE_SPAPR_CPU_CORE, dc->desc);

    type_register(&type_info);

    g_free((void *)type_info.name);

#endif

    return 0;

}


static inline int tcg_gen_code_common(TCGContext *s,

                                      tcg_insn_unit *gen_code_buf,

                                      long search_pc)

{

    int oi, oi_next;

#ifdef DEBUG_DISAS

    if (unlikely(qemu_loglevel_mask(CPU_LOG_TB_OP))) {

        qemu_log("OP:\n");

        tcg_dump_ops(s);

        qemu_log("\n");

    }

#endif

#ifdef CONFIG_PROFILER

    s->opt_time -= profile_getclock();

#endif

#ifdef USE_TCG_OPTIMIZATIONS

    tcg_optimize(s);

#endif

#ifdef CONFIG_PROFILER

    s->opt_time += profile_getclock();

    s->la_time -= profile_getclock();

#endif

    tcg_liveness_analysis(s);

#ifdef CONFIG_PROFILER

    s->la_time += profile_getclock();

#endif

#ifdef DEBUG_DISAS

    if (unlikely(qemu_loglevel_mask(CPU_LOG_TB_OP_OPT))) {

        qemu_log("OP after optimization and liveness analysis:\n");

        tcg_dump_ops(s);

        qemu_log("\n");

    }

#endif

    tcg_reg_alloc_start(s);

    s->code_buf = gen_code_buf;

    s->code_ptr = gen_code_buf;

    tcg_out_tb_init(s);

    for (oi = s->gen_first_op_idx; oi >= 0; oi = oi_next) {

        TCGOp * const op = &s->gen_op_buf[oi];

        TCGArg * const args = &s->gen_opparam_buf[op->args];

        TCGOpcode opc = op->opc;

        const TCGOpDef *def = &tcg_op_defs[opc];

        uint16_t dead_args = s->op_dead_args[oi];

        uint8_t sync_args = s->op_sync_args[oi];

        oi_next = op->next;

#ifdef CONFIG_PROFILER

        tcg_table_op_count[opc]++;

#endif

        switch (opc) {

        case INDEX_op_mov_i32:

        case INDEX_op_mov_i64:

            tcg_reg_alloc_mov(s, def, args, dead_args, sync_args);

            break;

        case INDEX_op_movi_i32:

        case INDEX_op_movi_i64:

            tcg_reg_alloc_movi(s, args, dead_args, sync_args);

            break;

        case INDEX_op_debug_insn_start:

            break;

        case INDEX_op_discard:

            temp_dead(s, args[0]);

            break;

        case INDEX_op_set_label:

            tcg_reg_alloc_bb_end(s, s->reserved_regs);

            tcg_out_label(s, args[0], s->code_ptr);

            break;

        case INDEX_op_call:

            tcg_reg_alloc_call(s, op->callo, op->calli, args,

                               dead_args, sync_args);

            break;

        default:

            /* Sanity check that we've not introduced any unhandled opcodes. */

            if (def->flags & TCG_OPF_NOT_PRESENT) {

                tcg_abort();

            }

            /* Note: in order to speed up the code, it would be much

               faster to have specialized register allocator functions for

               some common argument patterns */

            tcg_reg_alloc_op(s, def, opc, args, dead_args, sync_args);

            break;

        }

        if (search_pc >= 0 && search_pc < tcg_current_code_size(s)) {

            return oi;

        }

#ifndef NDEBUG

        check_regs(s);

#endif

    }

    /* Generate TB finalization at the end of block */

    tcg_out_tb_finalize(s);

    return -1;

}


void timer_mod_anticipate_ns(QEMUTimer *ts, int64_t expire_time)

{

    QEMUTimerList *timer_list = ts->timer_list;

    bool rearm;

    qemu_mutex_lock(&timer_list->active_timers_lock);

    if (ts->expire_time == -1 || ts->expire_time > expire_time) {

        if (ts->expire_time != -1) {

            timer_del_locked(timer_list, ts);

        }

        rearm = timer_mod_ns_locked(timer_list, ts, expire_time);

    } else {

        rearm = false;

    }

    qemu_mutex_unlock(&timer_list->active_timers_lock);

    if (rearm) {

        timerlist_rearm(timer_list);

    }

}


static void pxa2xx_rtc_write(void *opaque, hwaddr addr,

                             uint64_t value64, unsigned size)

{

    PXA2xxRTCState *s = (PXA2xxRTCState *) opaque;

    uint32_t value = value64;

    switch (addr) {

    case RTTR:

        if (!(s->rttr & (1U << 31))) {

            pxa2xx_rtc_hzupdate(s);

            s->rttr = value;

            pxa2xx_rtc_alarm_update(s, s->rtsr);

        }

        break;

    case RTSR:

        if ((s->rtsr ^ value) & (1 << 15))

            pxa2xx_rtc_piupdate(s);

        if ((s->rtsr ^ value) & (1 << 12))

            pxa2xx_rtc_swupdate(s);

        if (((s->rtsr ^ value) & 0x4aac) | (value & ~0xdaac))

            pxa2xx_rtc_alarm_update(s, value);

        s->rtsr = (value & 0xdaac) | (s->rtsr & ~(value & ~0xdaac));

        pxa2xx_rtc_int_update(s);

        break;

    case RTAR:

        s->rtar = value;

        pxa2xx_rtc_alarm_update(s, s->rtsr);

        break;

    case RDAR1:

        s->rdar1 = value;

        pxa2xx_rtc_alarm_update(s, s->rtsr);

        break;

    case RDAR2:

        s->rdar2 = value;

        pxa2xx_rtc_alarm_update(s, s->rtsr);

        break;

    case RYAR1:

        s->ryar1 = value;

        pxa2xx_rtc_alarm_update(s, s->rtsr);

        break;

    case RYAR2:

        s->ryar2 = value;

        pxa2xx_rtc_alarm_update(s, s->rtsr);

        break;

    case SWAR1:

        pxa2xx_rtc_swupdate(s);

        s->swar1 = value;

        s->last_swcr = 0;

        pxa2xx_rtc_alarm_update(s, s->rtsr);

        break;

    case SWAR2:

        s->swar2 = value;

        pxa2xx_rtc_alarm_update(s, s->rtsr);

        break;

    case PIAR:

        s->piar = value;

        pxa2xx_rtc_alarm_update(s, s->rtsr);

        break;

    case RCNR:

        pxa2xx_rtc_hzupdate(s);

        s->last_rcnr = value;

        pxa2xx_rtc_alarm_update(s, s->rtsr);

        break;

    case RDCR:

        pxa2xx_rtc_hzupdate(s);

        s->last_rdcr = value;

        pxa2xx_rtc_alarm_update(s, s->rtsr);

        break;

    case RYCR:

        s->last_rycr = value;

        break;

    case SWCR:

        pxa2xx_rtc_swupdate(s);

        s->last_swcr = value;

        pxa2xx_rtc_alarm_update(s, s->rtsr);

        break;

    case RTCPICR:

        pxa2xx_rtc_piupdate(s);

        s->last_rtcpicr = value & 0xffff;

        pxa2xx_rtc_alarm_update(s, s->rtsr);

        break;

    default:

        printf("%s: Bad register " REG_FMT "\n", __FUNCTION__, addr);

    }

}


static void omap_disc_write(void *opaque, hwaddr addr,

                            uint64_t value, unsigned size)

{

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

    if (size != 4) {

        omap_badwidth_write32(opaque, addr, value);

        return;

    }

    switch (addr) {

    case 0x010:	/* DISPC_SYSCONFIG */

        if (value & 2)						/* SOFTRESET */

            omap_dss_reset(s);

        s->dispc.idlemode = value & 0x301b;

        break;

    case 0x018:	/* DISPC_IRQSTATUS */

        s->dispc.irqst &= ~value;

        omap_dispc_interrupt_update(s);

        break;

    case 0x01c:	/* DISPC_IRQENABLE */

        s->dispc.irqen = value & 0xffff;

        omap_dispc_interrupt_update(s);

        break;

    case 0x040:	/* DISPC_CONTROL */

        s->dispc.control = value & 0x07ff9fff;

        s->dig.enable = (value >> 1) & 1;

        s->lcd.enable = (value >> 0) & 1;

        if (value & (1 << 12))			/* OVERLAY_OPTIMIZATION */

            if (!((s->dispc.l[1].attr | s->dispc.l[2].attr) & 1)) {

                fprintf(stderr, "%s: Overlay Optimization when no overlay "

                        "region effectively exists leads to "

                        "unpredictable behaviour!\n", __func__);

            }

        if (value & (1 << 6)) {				/* GODIGITAL */

            /* XXX: Shadowed fields are:

             * s->dispc.config

             * s->dispc.capable

             * s->dispc.bg[0]

             * s->dispc.bg[1]

             * s->dispc.trans[0]

             * s->dispc.trans[1]

             * s->dispc.line

             * s->dispc.timing[0]

             * s->dispc.timing[1]

             * s->dispc.timing[2]

             * s->dispc.timing[3]

             * s->lcd.nx

             * s->lcd.ny

             * s->dig.nx

             * s->dig.ny

             * s->dispc.l[0].addr[0]

             * s->dispc.l[0].addr[1]

             * s->dispc.l[0].addr[2]

             * s->dispc.l[0].posx

             * s->dispc.l[0].posy

             * s->dispc.l[0].nx

             * s->dispc.l[0].ny

             * s->dispc.l[0].tresh

             * s->dispc.l[0].rowinc

             * s->dispc.l[0].colinc

             * s->dispc.l[0].wininc

             * All they need to be loaded here from their shadow registers.

             */

        }

        if (value & (1 << 5)) {				/* GOLCD */

             /* XXX: Likewise for LCD here.  */

        }

        s->dispc.invalidate = 1;

        break;

    case 0x044:	/* DISPC_CONFIG */

        s->dispc.config = value & 0x3fff;

        /* XXX:

         * bits 2:1 (LOADMODE) reset to 0 after set to 1 and palette loaded

         * bits 2:1 (LOADMODE) reset to 2 after set to 3 and palette loaded

         */

        s->dispc.invalidate = 1;

        break;

    case 0x048:	/* DISPC_CAPABLE */

        s->dispc.capable = value & 0x3ff;

        break;

    case 0x04c:	/* DISPC_DEFAULT_COLOR0 */

        s->dispc.bg[0] = value & 0xffffff;

        s->dispc.invalidate = 1;

        break;

    case 0x050:	/* DISPC_DEFAULT_COLOR1 */

        s->dispc.bg[1] = value & 0xffffff;

        s->dispc.invalidate = 1;

        break;

    case 0x054:	/* DISPC_TRANS_COLOR0 */

        s->dispc.trans[0] = value & 0xffffff;

        s->dispc.invalidate = 1;

        break;

    case 0x058:	/* DISPC_TRANS_COLOR1 */

        s->dispc.trans[1] = value & 0xffffff;

        s->dispc.invalidate = 1;

        break;

    case 0x060:	/* DISPC_LINE_NUMBER */

        s->dispc.line = value & 0x7ff;

        break;

    case 0x064:	/* DISPC_TIMING_H */

        s->dispc.timing[0] = value & 0x0ff0ff3f;

        break;

    case 0x068:	/* DISPC_TIMING_V */

        s->dispc.timing[1] = value & 0x0ff0ff3f;

        break;

    case 0x06c:	/* DISPC_POL_FREQ */

        s->dispc.timing[2] = value & 0x0003ffff;

        break;

    case 0x070:	/* DISPC_DIVISOR */

        s->dispc.timing[3] = value & 0x00ff00ff;

        break;

    case 0x078:	/* DISPC_SIZE_DIG */

        s->dig.nx = ((value >>  0) & 0x7ff) + 1;		/* PPL */

        s->dig.ny = ((value >> 16) & 0x7ff) + 1;		/* LPP */

        s->dispc.invalidate = 1;

        break;

    case 0x07c:	/* DISPC_SIZE_LCD */

        s->lcd.nx = ((value >>  0) & 0x7ff) + 1;		/* PPL */

        s->lcd.ny = ((value >> 16) & 0x7ff) + 1;		/* LPP */

        s->dispc.invalidate = 1;

        break;

    case 0x080:	/* DISPC_GFX_BA0 */

        s->dispc.l[0].addr[0] = (hwaddr) value;

        s->dispc.invalidate = 1;

        break;

    case 0x084:	/* DISPC_GFX_BA1 */

        s->dispc.l[0].addr[1] = (hwaddr) value;

        s->dispc.invalidate = 1;

        break;

    case 0x088:	/* DISPC_GFX_POSITION */

        s->dispc.l[0].posx = ((value >>  0) & 0x7ff);		/* GFXPOSX */

        s->dispc.l[0].posy = ((value >> 16) & 0x7ff);		/* GFXPOSY */

        s->dispc.invalidate = 1;

        break;

    case 0x08c:	/* DISPC_GFX_SIZE */

        s->dispc.l[0].nx = ((value >>  0) & 0x7ff) + 1;		/* GFXSIZEX */

        s->dispc.l[0].ny = ((value >> 16) & 0x7ff) + 1;		/* GFXSIZEY */

        s->dispc.invalidate = 1;

        break;

    case 0x0a0:	/* DISPC_GFX_ATTRIBUTES */

        s->dispc.l[0].attr = value & 0x7ff;

        if (value & (3 << 9))

            fprintf(stderr, "%s: Big-endian pixel format not supported\n",

                            __FUNCTION__);

        s->dispc.l[0].enable = value & 1;

        s->dispc.l[0].bpp = (value >> 1) & 0xf;

        s->dispc.invalidate = 1;

        break;

    case 0x0a4:	/* DISPC_GFX_FIFO_TRESHOLD */

        s->dispc.l[0].tresh = value & 0x01ff01ff;

        break;

    case 0x0ac:	/* DISPC_GFX_ROW_INC */

        s->dispc.l[0].rowinc = value;

        s->dispc.invalidate = 1;

        break;

    case 0x0b0:	/* DISPC_GFX_PIXEL_INC */

        s->dispc.l[0].colinc = value;

        s->dispc.invalidate = 1;

        break;

    case 0x0b4:	/* DISPC_GFX_WINDOW_SKIP */

        s->dispc.l[0].wininc = value;

        break;

    case 0x0b8:	/* DISPC_GFX_TABLE_BA */

        s->dispc.l[0].addr[2] = (hwaddr) value;

        s->dispc.invalidate = 1;

        break;

    case 0x0bc:	/* DISPC_VID1_BA0 */

    case 0x0c0:	/* DISPC_VID1_BA1 */

    case 0x0c4:	/* DISPC_VID1_POSITION */

    case 0x0c8:	/* DISPC_VID1_SIZE */

    case 0x0cc:	/* DISPC_VID1_ATTRIBUTES */

    case 0x0d0:	/* DISPC_VID1_FIFO_TRESHOLD */

    case 0x0d8:	/* DISPC_VID1_ROW_INC */

    case 0x0dc:	/* DISPC_VID1_PIXEL_INC */

    case 0x0e0:	/* DISPC_VID1_FIR */

    case 0x0e4:	/* DISPC_VID1_PICTURE_SIZE */

    case 0x0e8:	/* DISPC_VID1_ACCU0 */

    case 0x0ec:	/* DISPC_VID1_ACCU1 */

    case 0x0f0 ... 0x140:	/* DISPC_VID1_FIR_COEF, DISPC_VID1_CONV_COEF */

    case 0x14c:	/* DISPC_VID2_BA0 */

    case 0x150:	/* DISPC_VID2_BA1 */

    case 0x154:	/* DISPC_VID2_POSITION */

    case 0x158:	/* DISPC_VID2_SIZE */

    case 0x15c:	/* DISPC_VID2_ATTRIBUTES */

    case 0x160:	/* DISPC_VID2_FIFO_TRESHOLD */

    case 0x168:	/* DISPC_VID2_ROW_INC */

    case 0x16c:	/* DISPC_VID2_PIXEL_INC */

    case 0x170:	/* DISPC_VID2_FIR */

    case 0x174:	/* DISPC_VID2_PICTURE_SIZE */

    case 0x178:	/* DISPC_VID2_ACCU0 */

    case 0x17c:	/* DISPC_VID2_ACCU1 */

    case 0x180 ... 0x1d0:	/* DISPC_VID2_FIR_COEF, DISPC_VID2_CONV_COEF */

    case 0x1d4:	/* DISPC_DATA_CYCLE1 */

    case 0x1d8:	/* DISPC_DATA_CYCLE2 */

    case 0x1dc:	/* DISPC_DATA_CYCLE3 */

        break;

    default:

        OMAP_BAD_REG(addr);

    }

}


static void bdrv_replace_child(BdrvChild *child, BlockDriverState *new_bs,

                               bool check_new_perm)

{

    BlockDriverState *old_bs = child->bs;

    uint64_t perm, shared_perm;

    if (old_bs) {

        /* Update permissions for old node. This is guaranteed to succeed

         * because we're just taking a parent away, so we're loosening

         * restrictions. */

        bdrv_get_cumulative_perm(old_bs, &perm, &shared_perm);

        bdrv_check_perm(old_bs, perm, shared_perm, NULL, &error_abort);

        bdrv_set_perm(old_bs, perm, shared_perm);

    }

    bdrv_replace_child_noperm(child, new_bs);

    if (new_bs) {

        bdrv_get_cumulative_perm(new_bs, &perm, &shared_perm);

        if (check_new_perm) {

            bdrv_check_perm(new_bs, perm, shared_perm, NULL, &error_abort);

        }

        bdrv_set_perm(new_bs, perm, shared_perm);

    }

}


void cpu_exec_init(CPUState *cpu, Error **errp)

{

    CPUClass *cc = CPU_GET_CLASS(cpu);

    int cpu_index;

    Error *local_err = NULL;

#ifndef CONFIG_USER_ONLY

    cpu->as = &address_space_memory;

    cpu->thread_id = qemu_get_thread_id();

#endif

#if defined(CONFIG_USER_ONLY)

    cpu_list_lock();

#endif

    cpu_index = cpu->cpu_index = cpu_get_free_index(&local_err);

    if (local_err) {

        error_propagate(errp, local_err);

#if defined(CONFIG_USER_ONLY)

        cpu_list_unlock();

#endif

        return;

    }

    QTAILQ_INSERT_TAIL(&cpus, cpu, node);

#if defined(CONFIG_USER_ONLY)

    cpu_list_unlock();

#endif

    if (qdev_get_vmsd(DEVICE(cpu)) == NULL) {

        vmstate_register(NULL, cpu_index, &vmstate_cpu_common, cpu);

    }

#if defined(CPU_SAVE_VERSION) && !defined(CONFIG_USER_ONLY)

    register_savevm(NULL, "cpu", cpu_index, CPU_SAVE_VERSION,

                    cpu_save, cpu_load, cpu->env_ptr);

    assert(cc->vmsd == NULL);

    assert(qdev_get_vmsd(DEVICE(cpu)) == NULL);

#endif

    if (cc->vmsd != NULL) {

        vmstate_register(NULL, cpu_index, cc->vmsd, cpu);

    }

}


static int ide_qdev_init(DeviceState *qdev)

{

    IDEDevice *dev = IDE_DEVICE(qdev);

    IDEDeviceClass *dc = IDE_DEVICE_GET_CLASS(dev);

    IDEBus *bus = DO_UPCAST(IDEBus, qbus, qdev->parent_bus);

    if (!dev->conf.bs) {

        error_report("No drive specified");

        goto err;

    }

    if (dev->unit == -1) {

        dev->unit = bus->master ? 1 : 0;

    }

    if (dev->unit >= bus->max_units) {

        error_report("Can't create IDE unit %d, bus supports only %d units",

                     dev->unit, bus->max_units);

        goto err;

    }

    switch (dev->unit) {

    case 0:

        if (bus->master) {

            error_report("IDE unit %d is in use", dev->unit);

            goto err;

        }

        bus->master = dev;

        break;

    case 1:

        if (bus->slave) {

            error_report("IDE unit %d is in use", dev->unit);

            goto err;

        }

        bus->slave = dev;

        break;

    default:

        error_report("Invalid IDE unit %d", dev->unit);

        goto err;

    }

    return dc->init(dev);

err:

    return -1;

}


static int default_fdset_dup_fd_remove(int dup_fd)

{

    return -1;

}


void pc_hot_add_cpu(const int64_t id, Error **errp)

{

    X86CPU *cpu;

    ObjectClass *oc;

    PCMachineState *pcms = PC_MACHINE(qdev_get_machine());

    int64_t apic_id = x86_cpu_apic_id_from_index(id);

    Error *local_err = NULL;

    if (id < 0) {

        error_setg(errp, "Invalid CPU id: %" PRIi64, id);

        return;

    }

    if (cpu_exists(apic_id)) {

        error_setg(errp, "Unable to add CPU: %" PRIi64

                   ", it already exists", id);

        return;

    }

    if (id >= max_cpus) {

        error_setg(errp, "Unable to add CPU: %" PRIi64

                   ", max allowed: %d", id, max_cpus - 1);

        return;

    }

    if (apic_id >= ACPI_CPU_HOTPLUG_ID_LIMIT) {

        error_setg(errp, "Unable to add CPU: %" PRIi64

                   ", resulting APIC ID (%" PRIi64 ") is too large",

                   id, apic_id);

        return;

    }

    assert(pcms->possible_cpus->cpus[0].cpu); /* BSP is always present */

    oc = OBJECT_CLASS(CPU_GET_CLASS(pcms->possible_cpus->cpus[0].cpu));

    cpu = pc_new_cpu(object_class_get_name(oc), apic_id, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        return;

    }

    object_unref(OBJECT(cpu));

}


static void show_packet(AVFormatContext *fmt_ctx, AVPacket *pkt)

{

    char val_str[128];

    AVStream *st = fmt_ctx->streams[pkt->stream_index];

    printf("[PACKET]\n");

    printf("codec_type=%s\n", media_type_string(st->codec->codec_type));

    printf("stream_index=%d\n", pkt->stream_index);

    printf("pts=%s\n", ts_value_string(val_str, sizeof(val_str), pkt->pts));

    printf("pts_time=%s\n", time_value_string(val_str, sizeof(val_str),

                                              pkt->pts, &st->time_base));

    printf("dts=%s\n", ts_value_string(val_str, sizeof(val_str), pkt->dts));

    printf("dts_time=%s\n", time_value_string(val_str, sizeof(val_str),

                                              pkt->dts, &st->time_base));

    printf("duration=%s\n", ts_value_string(val_str, sizeof(val_str),

                                            pkt->duration));

    printf("duration_time=%s\n", time_value_string(val_str, sizeof(val_str),

                                                   pkt->duration,

                                                   &st->time_base));

    printf("size=%s\n", value_string(val_str, sizeof(val_str),

                                     pkt->size, unit_byte_str));

    printf("pos=%"PRId64"\n", pkt->pos);

    printf("flags=%c\n", pkt->flags & AV_PKT_FLAG_KEY ? 'K' : '_');

    printf("[/PACKET]\n");

}


BusState *qbus_create(BusInfo *info, DeviceState *parent, const char *name)

{

    BusState *bus;

    char *buf;

    int i,len;

    bus = qemu_mallocz(info->size);

    bus->info = info;

    bus->parent = parent;

    if (name) {

        /* use supplied name */

        bus->name = qemu_strdup(name);

    } else if (parent && parent->id) {

        /* parent device has id -> use it for bus name */

        len = strlen(parent->id) + 16;

        buf = qemu_malloc(len);

        snprintf(buf, len, "%s.%d", parent->id, parent->num_child_bus);

        bus->name = buf;

    } else {

        /* no id -> use lowercase bus type for bus name */

        len = strlen(info->name) + 16;

        buf = qemu_malloc(len);

        len = snprintf(buf, len, "%s.%d", info->name,

                       parent ? parent->num_child_bus : 0);

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

            buf[i] = qemu_tolower(buf[i]);

        bus->name = buf;

    }

    LIST_INIT(&bus->children);

    if (parent) {

        LIST_INSERT_HEAD(&parent->child_bus, bus, sibling);

        parent->num_child_bus++;

    }

    return bus;

}


static int64_t coroutine_fn iscsi_co_get_block_status(BlockDriverState *bs,

                                                  int64_t sector_num,

                                                  int nb_sectors, int *pnum)

{

    IscsiLun *iscsilun = bs->opaque;

    struct scsi_get_lba_status *lbas = NULL;

    struct scsi_lba_status_descriptor *lbasd = NULL;

    struct IscsiTask iTask;

    int64_t ret;

    iscsi_co_init_iscsitask(iscsilun, &iTask);

    if (!is_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {

        ret = -EINVAL;

        goto out;

    }

    /* default to all sectors allocated */

    ret = BDRV_BLOCK_DATA;

    ret |= (sector_num << BDRV_SECTOR_BITS) | BDRV_BLOCK_OFFSET_VALID;

    *pnum = nb_sectors;

    /* LUN does not support logical block provisioning */

    if (!iscsilun->lbpme) {

        goto out;

    }

retry:

    if (iscsi_get_lba_status_task(iscsilun->iscsi, iscsilun->lun,

                                  sector_qemu2lun(sector_num, iscsilun),

                                  8 + 16, iscsi_co_generic_cb,

                                  &iTask) == NULL) {

        ret = -ENOMEM;

        goto out;

    }

    while (!iTask.complete) {

        iscsi_set_events(iscsilun);

        qemu_coroutine_yield();

    }

    if (iTask.do_retry) {

        if (iTask.task != NULL) {

            scsi_free_scsi_task(iTask.task);

            iTask.task = NULL;

        }

        iTask.complete = 0;

        goto retry;

    }

    if (iTask.status != SCSI_STATUS_GOOD) {

        /* in case the get_lba_status_callout fails (i.e.

         * because the device is busy or the cmd is not

         * supported) we pretend all blocks are allocated

         * for backwards compatibility */

        goto out;

    }

    lbas = scsi_datain_unmarshall(iTask.task);

    if (lbas == NULL) {

        ret = -EIO;

        goto out;

    }

    lbasd = &lbas->descriptors[0];

    if (sector_qemu2lun(sector_num, iscsilun) != lbasd->lba) {

        ret = -EIO;

        goto out;

    }

    *pnum = sector_lun2qemu(lbasd->num_blocks, iscsilun);

    if (lbasd->provisioning == SCSI_PROVISIONING_TYPE_DEALLOCATED ||

        lbasd->provisioning == SCSI_PROVISIONING_TYPE_ANCHORED) {

        ret &= ~BDRV_BLOCK_DATA;

        if (iscsilun->lbprz) {

            ret |= BDRV_BLOCK_ZERO;

        }

    }

    if (ret & BDRV_BLOCK_ZERO) {

        iscsi_allocationmap_clear(iscsilun, sector_num, *pnum);

    } else {

        iscsi_allocationmap_set(iscsilun, sector_num, *pnum);

    }

    if (*pnum > nb_sectors) {

        *pnum = nb_sectors;

    }

out:

    if (iTask.task != NULL) {

        scsi_free_scsi_task(iTask.task);

    }

    return ret;

}


static inline void assert_fp_access_checked(DisasContext *s)

{

#ifdef CONFIG_DEBUG_TCG

    if (unlikely(!s->fp_access_checked || !s->cpacr_fpen)) {

        fprintf(stderr, "target-arm: FP access check missing for "

                "instruction 0x%08x\n", s->insn);

        abort();

    }

#endif

}


static void dp8393x_writew(void *opaque, target_phys_addr_t addr, uint32_t val)

{

    dp8393xState *s = opaque;

    int reg;

    if ((addr & ((1 << s->it_shift) - 1)) != 0) {

        return;

    }

    reg = addr >> s->it_shift;

    write_register(s, reg, (uint16_t)val);

}


socket_sockaddr_to_address_vsock(struct sockaddr_storage *sa,

                                 socklen_t salen,

                                 Error **errp)

{

    SocketAddressLegacy *addr;

    VsockSocketAddress *vaddr;

    struct sockaddr_vm *svm = (struct sockaddr_vm *)sa;

    addr = g_new0(SocketAddressLegacy, 1);

    addr->type = SOCKET_ADDRESS_LEGACY_KIND_VSOCK;

    addr->u.vsock.data = vaddr = g_new0(VsockSocketAddress, 1);

    vaddr->cid = g_strdup_printf("%u", svm->svm_cid);

    vaddr->port = g_strdup_printf("%u", svm->svm_port);

    return addr;

}


QObject *object_property_get_qobject(Object *obj, const char *name,

                                     Error **errp)

{

    QObject *ret = NULL;

    Error *local_err = NULL;

    Visitor *v;

    v = qmp_output_visitor_new(&ret);

    object_property_get(obj, v, name, &local_err);

    if (!local_err) {

        visit_complete(v, &ret);

    }

    error_propagate(errp, local_err);

    visit_free(v);

    return ret;

}


static KVMSlot *kvm_alloc_slot(KVMState *s)

{

    int i;

    for (i = 0; i < ARRAY_SIZE(s->slots); i++) {

        /* KVM private memory slots */

        if (i >= 8 && i < 12)

            continue;

        if (s->slots[i].memory_size == 0)

            return &s->slots[i];

    }

    fprintf(stderr, "%s: no free slot available\n", __func__);

    abort();

}


static void virtio_scsi_handle_event(VirtIODevice *vdev, VirtQueue *vq)

{

    VirtIOSCSI *s = VIRTIO_SCSI(vdev);

    if (s->ctx) {

        virtio_scsi_dataplane_start(s);

        if (!s->dataplane_fenced) {

            return;

        }

    }

    virtio_scsi_handle_event_vq(s, vq);

}


static void mirror_do_zero_or_discard(MirrorBlockJob *s,

                                      int64_t sector_num,

                                      int nb_sectors,

                                      bool is_discard)

{

    MirrorOp *op;

    /* Allocate a MirrorOp that is used as an AIO callback. The qiov is zeroed

     * so the freeing in mirror_iteration_done is nop. */

    op = g_new0(MirrorOp, 1);

    op->s = s;

    op->sector_num = sector_num;

    op->nb_sectors = nb_sectors;

    s->in_flight++;

    s->sectors_in_flight += nb_sectors;

    if (is_discard) {

        blk_aio_pdiscard(s->target, sector_num << BDRV_SECTOR_BITS,

                         op->nb_sectors << BDRV_SECTOR_BITS,

                         mirror_write_complete, op);

    } else {

        blk_aio_pwrite_zeroes(s->target, sector_num * BDRV_SECTOR_SIZE,

                              op->nb_sectors * BDRV_SECTOR_SIZE,

                              s->unmap ? BDRV_REQ_MAY_UNMAP : 0,

                              mirror_write_complete, op);

    }

}


static int encode_individual_channel(AVCodecContext *avctx, AACEncContext *s,

                                     SingleChannelElement *sce,

                                     int common_window)

{

    put_bits(&s->pb, 8, sce->sf_idx[0]);

    if (!common_window) {

        put_ics_info(s, &sce->ics);

        if (s->coder->encode_main_pred)

            s->coder->encode_main_pred(s, sce);

    }

    encode_band_info(s, sce);

    encode_scale_factors(avctx, s, sce);

    encode_pulses(s, &sce->pulse);

    if (s->coder->encode_tns_info)

        s->coder->encode_tns_info(s, sce);

    else

        put_bits(&s->pb, 1, 0);

    put_bits(&s->pb, 1, 0); //ssr

    encode_spectral_coeffs(s, sce);

    return 0;

}


int float32_eq_signaling( float32 a, float32 b STATUS_PARAM )

{

    if (    ( ( extractFloat32Exp( a ) == 0xFF ) && extractFloat32Frac( a ) )

         || ( ( extractFloat32Exp( b ) == 0xFF ) && extractFloat32Frac( b ) )

       ) {

        float_raise( float_flag_invalid STATUS_VAR);

        return 0;

    }

    return ( a == b ) || ( (bits32) ( ( a | b )<<1 ) == 0 );

}


static void ich9_lpc_update_pic(ICH9LPCState *lpc, int gsi)

{

    int i, pic_level;

    assert(gsi < ICH9_LPC_PIC_NUM_PINS);

    /* The pic level is the logical OR of all the PCI irqs mapped to it */

    pic_level = 0;

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

        int tmp_irq;

        int tmp_dis;

        ich9_lpc_pic_irq(lpc, i, &tmp_irq, &tmp_dis);

        if (!tmp_dis && tmp_irq == gsi) {

            pic_level |= pci_bus_get_irq_level(lpc->d.bus, i);

        }

    }

    if (gsi == lpc->sci_gsi) {

        pic_level |= lpc->sci_level;

    }

    qemu_set_irq(lpc->gsi[gsi], pic_level);

}


static void FUNCC(pred8x8_top_dc)(uint8_t *_src, int stride){

    int i;

    int dc0, dc1;

    pixel4 dc0splat, dc1splat;

    pixel *src = (pixel*)_src;

    stride /= sizeof(pixel);

    dc0=dc1=0;

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

        dc0+= src[i-stride];

        dc1+= src[4+i-stride];

    }

    dc0splat = PIXEL_SPLAT_X4((dc0 + 2)>>2);

    dc1splat = PIXEL_SPLAT_X4((dc1 + 2)>>2);

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

        ((pixel4*)(src+i*stride))[0]= dc0splat;

        ((pixel4*)(src+i*stride))[1]= dc1splat;

    }

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

        ((pixel4*)(src+i*stride))[0]= dc0splat;

        ((pixel4*)(src+i*stride))[1]= dc1splat;

    }

}


static uint64_t strongarm_gpio_read(void *opaque, hwaddr offset,

                                    unsigned size)

{

    StrongARMGPIOInfo *s = opaque;

    switch (offset) {

    case GPDR:        /* GPIO Pin-Direction registers */

        return s->dir;

    case GPSR:        /* GPIO Pin-Output Set registers */

        DPRINTF("%s: Read from a write-only register 0x" TARGET_FMT_plx "\n",

                        __func__, offset);

        return s->gpsr;    /* Return last written value.  */

    case GPCR:        /* GPIO Pin-Output Clear registers */

        DPRINTF("%s: Read from a write-only register 0x" TARGET_FMT_plx "\n",

                        __func__, offset);

        return 31337;        /* Specified as unpredictable in the docs.  */

    case GRER:        /* GPIO Rising-Edge Detect Enable registers */

        return s->rising;

    case GFER:        /* GPIO Falling-Edge Detect Enable registers */

        return s->falling;

    case GAFR:        /* GPIO Alternate Function registers */

        return s->gafr;

    case GPLR:        /* GPIO Pin-Level registers */

        return (s->olevel & s->dir) |

               (s->ilevel & ~s->dir);

    case GEDR:        /* GPIO Edge Detect Status registers */

        return s->status;

    default:

        printf("%s: Bad offset 0x" TARGET_FMT_plx "\n", __func__, offset);

    }

    return 0;

}


static int draw_glyphs(DrawTextContext *dtext, AVFilterBufferRef *picref,

                       int width, int height, const uint8_t rgbcolor[4], const uint8_t yuvcolor[4], int x, int y)

{

    char *text = dtext->text;

    uint32_t code = 0;

    int i;

    uint8_t *p;

    Glyph *glyph = NULL;

    for (i = 0, p = text; *p; i++) {

        Glyph dummy = { 0 };

        GET_UTF8(code, *p++, continue;);

        /* skip new line chars, just go to new line */

        if (code == '\n' || code == '\r' || code == '\t')

            continue;

        dummy.code = code;

        glyph = av_tree_find(dtext->glyphs, &dummy, (void *)glyph_cmp, NULL);

        if (glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&

            glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)

            return AVERROR(EINVAL);

        if (dtext->is_packed_rgb) {

            draw_glyph_rgb(picref, &glyph->bitmap,

                           dtext->positions[i].x+x, dtext->positions[i].y+y, width, height,

                           dtext->pixel_step[0], rgbcolor, dtext->rgba_map);

        } else {

            draw_glyph_yuv(picref, &glyph->bitmap,

                           dtext->positions[i].x+x, dtext->positions[i].y+y, width, height,

                           yuvcolor, dtext->hsub, dtext->vsub);

        }

    }

    return 0;

}


static void text_console_resize(QemuConsole *s)

{

    TextCell *cells, *c, *c1;

    int w1, x, y, last_width;

    last_width = s->width;

    s->width = surface_width(s->surface) / FONT_WIDTH;

    s->height = surface_height(s->surface) / FONT_HEIGHT;

    w1 = last_width;

    if (s->width < w1)

        w1 = s->width;

    cells = g_malloc(s->width * s->total_height * sizeof(TextCell));

    for(y = 0; y < s->total_height; y++) {

        c = &cells[y * s->width];

        if (w1 > 0) {

            c1 = &s->cells[y * last_width];

            for(x = 0; x < w1; x++) {

                *c++ = *c1++;

            }

        }

        for(x = w1; x < s->width; x++) {

            c->ch = ' ';

            c->t_attrib = s->t_attrib_default;

            c++;

        }

    }

    g_free(s->cells);

    s->cells = cells;

}