static inline void tcg_out_op(TCGContext *s, TCGOpcode opc,

                              const TCGArg *args, const int *const_args)

{

    int c, vexop, rexw = 0;

#if TCG_TARGET_REG_BITS == 64

# define OP_32_64(x) \

        case glue(glue(INDEX_op_, x), _i64): \

            rexw = P_REXW; /* FALLTHRU */    \

        case glue(glue(INDEX_op_, x), _i32)

#else

# define OP_32_64(x) \

        case glue(glue(INDEX_op_, x), _i32)

#endif

    switch(opc) {

    case INDEX_op_exit_tb:

        tcg_out_movi(s, TCG_TYPE_PTR, TCG_REG_EAX, args[0]);

        tcg_out_jmp(s, tb_ret_addr);

        break;

    case INDEX_op_goto_tb:

        if (s->tb_jmp_offset) {

            /* direct jump method */

            tcg_out8(s, OPC_JMP_long); /* jmp im */

            s->tb_jmp_offset[args[0]] = tcg_current_code_size(s);

            tcg_out32(s, 0);

        } else {

            /* indirect jump method */

            tcg_out_modrm_offset(s, OPC_GRP5, EXT5_JMPN_Ev, -1,

                                 (intptr_t)(s->tb_next + args[0]));

        }

        s->tb_next_offset[args[0]] = tcg_current_code_size(s);

        break;

    case INDEX_op_br:

        tcg_out_jxx(s, JCC_JMP, args[0], 0);

        break;

    OP_32_64(ld8u):

        /* Note that we can ignore REXW for the zero-extend to 64-bit.  */

        tcg_out_modrm_offset(s, OPC_MOVZBL, args[0], args[1], args[2]);

        break;

    OP_32_64(ld8s):

        tcg_out_modrm_offset(s, OPC_MOVSBL + rexw, args[0], args[1], args[2]);

        break;

    OP_32_64(ld16u):

        /* Note that we can ignore REXW for the zero-extend to 64-bit.  */

        tcg_out_modrm_offset(s, OPC_MOVZWL, args[0], args[1], args[2]);

        break;

    OP_32_64(ld16s):

        tcg_out_modrm_offset(s, OPC_MOVSWL + rexw, args[0], args[1], args[2]);

        break;

#if TCG_TARGET_REG_BITS == 64

    case INDEX_op_ld32u_i64:

#endif

    case INDEX_op_ld_i32:

        tcg_out_ld(s, TCG_TYPE_I32, args[0], args[1], args[2]);

        break;

    OP_32_64(st8):

        if (const_args[0]) {

            tcg_out_modrm_offset(s, OPC_MOVB_EvIz,

                                 0, args[1], args[2]);

            tcg_out8(s, args[0]);

        } else {

            tcg_out_modrm_offset(s, OPC_MOVB_EvGv | P_REXB_R,

                                 args[0], args[1], args[2]);

        }

        break;

    OP_32_64(st16):

        if (const_args[0]) {

            tcg_out_modrm_offset(s, OPC_MOVL_EvIz | P_DATA16,

                                 0, args[1], args[2]);

            tcg_out16(s, args[0]);

        } else {

            tcg_out_modrm_offset(s, OPC_MOVL_EvGv | P_DATA16,

                                 args[0], args[1], args[2]);

        }

        break;

#if TCG_TARGET_REG_BITS == 64

    case INDEX_op_st32_i64:

#endif

    case INDEX_op_st_i32:

        if (const_args[0]) {

            tcg_out_modrm_offset(s, OPC_MOVL_EvIz, 0, args[1], args[2]);

            tcg_out32(s, args[0]);

        } else {

            tcg_out_st(s, TCG_TYPE_I32, args[0], args[1], args[2]);

        }

        break;

    OP_32_64(add):

        /* For 3-operand addition, use LEA.  */

        if (args[0] != args[1]) {

            TCGArg a0 = args[0], a1 = args[1], a2 = args[2], c3 = 0;

            if (const_args[2]) {

                c3 = a2, a2 = -1;

            } else if (a0 == a2) {

                /* Watch out for dest = src + dest, since we've removed

                   the matching constraint on the add.  */

                tgen_arithr(s, ARITH_ADD + rexw, a0, a1);

                break;

            }

            tcg_out_modrm_sib_offset(s, OPC_LEA + rexw, a0, a1, a2, 0, c3);

            break;

        }

        c = ARITH_ADD;

        goto gen_arith;

    OP_32_64(sub):

        c = ARITH_SUB;

        goto gen_arith;

    OP_32_64(and):

        c = ARITH_AND;

        goto gen_arith;

    OP_32_64(or):

        c = ARITH_OR;

        goto gen_arith;

    OP_32_64(xor):

        c = ARITH_XOR;

        goto gen_arith;

    gen_arith:

        if (const_args[2]) {

            tgen_arithi(s, c + rexw, args[0], args[2], 0);

        } else {

            tgen_arithr(s, c + rexw, args[0], args[2]);

        }

        break;

    OP_32_64(andc):

        if (const_args[2]) {

            tcg_out_mov(s, rexw ? TCG_TYPE_I64 : TCG_TYPE_I32,

                        args[0], args[1]);

            tgen_arithi(s, ARITH_AND + rexw, args[0], ~args[2], 0);

        } else {

            tcg_out_vex_modrm(s, OPC_ANDN + rexw, args[0], args[2], args[1]);

        }

        break;

    OP_32_64(mul):

        if (const_args[2]) {

            int32_t val;

            val = args[2];

            if (val == (int8_t)val) {

                tcg_out_modrm(s, OPC_IMUL_GvEvIb + rexw, args[0], args[0]);

                tcg_out8(s, val);

            } else {

                tcg_out_modrm(s, OPC_IMUL_GvEvIz + rexw, args[0], args[0]);

                tcg_out32(s, val);

            }

        } else {

            tcg_out_modrm(s, OPC_IMUL_GvEv + rexw, args[0], args[2]);

        }

        break;

    OP_32_64(div2):

        tcg_out_modrm(s, OPC_GRP3_Ev + rexw, EXT3_IDIV, args[4]);

        break;

    OP_32_64(divu2):

        tcg_out_modrm(s, OPC_GRP3_Ev + rexw, EXT3_DIV, args[4]);

        break;

    OP_32_64(shl):

        c = SHIFT_SHL;

        vexop = OPC_SHLX;

        goto gen_shift_maybe_vex;

    OP_32_64(shr):

        c = SHIFT_SHR;

        vexop = OPC_SHRX;

        goto gen_shift_maybe_vex;

    OP_32_64(sar):

        c = SHIFT_SAR;

        vexop = OPC_SARX;

        goto gen_shift_maybe_vex;

    OP_32_64(rotl):

        c = SHIFT_ROL;

        goto gen_shift;

    OP_32_64(rotr):

        c = SHIFT_ROR;

        goto gen_shift;

    gen_shift_maybe_vex:

        if (have_bmi2 && !const_args[2]) {

            tcg_out_vex_modrm(s, vexop + rexw, args[0], args[2], args[1]);

            break;

        }

        /* FALLTHRU */

    gen_shift:

        if (const_args[2]) {

            tcg_out_shifti(s, c + rexw, args[0], args[2]);

        } else {

            tcg_out_modrm(s, OPC_SHIFT_cl + rexw, c, args[0]);

        }

        break;

    case INDEX_op_brcond_i32:

        tcg_out_brcond32(s, args[2], args[0], args[1], const_args[1],

                         args[3], 0);

        break;

    case INDEX_op_setcond_i32:

        tcg_out_setcond32(s, args[3], args[0], args[1],

                          args[2], const_args[2]);

        break;

    case INDEX_op_movcond_i32:

        tcg_out_movcond32(s, args[5], args[0], args[1],

                          args[2], const_args[2], args[3]);

        break;

    OP_32_64(bswap16):

        tcg_out_rolw_8(s, args[0]);

        break;

    OP_32_64(bswap32):

        tcg_out_bswap32(s, args[0]);

        break;

    OP_32_64(neg):

        tcg_out_modrm(s, OPC_GRP3_Ev + rexw, EXT3_NEG, args[0]);

        break;

    OP_32_64(not):

        tcg_out_modrm(s, OPC_GRP3_Ev + rexw, EXT3_NOT, args[0]);

        break;

    OP_32_64(ext8s):

        tcg_out_ext8s(s, args[0], args[1], rexw);

        break;

    OP_32_64(ext16s):

        tcg_out_ext16s(s, args[0], args[1], rexw);

        break;

    OP_32_64(ext8u):

        tcg_out_ext8u(s, args[0], args[1]);

        break;

    OP_32_64(ext16u):

        tcg_out_ext16u(s, args[0], args[1]);

        break;

    case INDEX_op_qemu_ld_i32:

        tcg_out_qemu_ld(s, args, 0);

        break;

    case INDEX_op_qemu_ld_i64:

        tcg_out_qemu_ld(s, args, 1);

        break;

    case INDEX_op_qemu_st_i32:

        tcg_out_qemu_st(s, args, 0);

        break;

    case INDEX_op_qemu_st_i64:

        tcg_out_qemu_st(s, args, 1);

        break;

    OP_32_64(mulu2):

        tcg_out_modrm(s, OPC_GRP3_Ev + rexw, EXT3_MUL, args[3]);

        break;

    OP_32_64(muls2):

        tcg_out_modrm(s, OPC_GRP3_Ev + rexw, EXT3_IMUL, args[3]);

        break;

    OP_32_64(add2):

        if (const_args[4]) {

            tgen_arithi(s, ARITH_ADD + rexw, args[0], args[4], 1);

        } else {

            tgen_arithr(s, ARITH_ADD + rexw, args[0], args[4]);

        }

        if (const_args[5]) {

            tgen_arithi(s, ARITH_ADC + rexw, args[1], args[5], 1);

        } else {

            tgen_arithr(s, ARITH_ADC + rexw, args[1], args[5]);

        }

        break;

    OP_32_64(sub2):

        if (const_args[4]) {

            tgen_arithi(s, ARITH_SUB + rexw, args[0], args[4], 1);

        } else {

            tgen_arithr(s, ARITH_SUB + rexw, args[0], args[4]);

        }

        if (const_args[5]) {

            tgen_arithi(s, ARITH_SBB + rexw, args[1], args[5], 1);

        } else {

            tgen_arithr(s, ARITH_SBB + rexw, args[1], args[5]);

        }

        break;

#if TCG_TARGET_REG_BITS == 32

    case INDEX_op_brcond2_i32:

        tcg_out_brcond2(s, args, const_args, 0);

        break;

    case INDEX_op_setcond2_i32:

        tcg_out_setcond2(s, args, const_args);

        break;

#else /* TCG_TARGET_REG_BITS == 64 */

    case INDEX_op_ld32s_i64:

        tcg_out_modrm_offset(s, OPC_MOVSLQ, args[0], args[1], args[2]);

        break;

    case INDEX_op_ld_i64:

        tcg_out_ld(s, TCG_TYPE_I64, args[0], args[1], args[2]);

        break;

    case INDEX_op_st_i64:

        if (const_args[0]) {

            tcg_out_modrm_offset(s, OPC_MOVL_EvIz | P_REXW,

                                 0, args[1], args[2]);

            tcg_out32(s, args[0]);

        } else {

            tcg_out_st(s, TCG_TYPE_I64, args[0], args[1], args[2]);

        }

        break;

    case INDEX_op_brcond_i64:

        tcg_out_brcond64(s, args[2], args[0], args[1], const_args[1],

                         args[3], 0);

        break;

    case INDEX_op_setcond_i64:

        tcg_out_setcond64(s, args[3], args[0], args[1],

                          args[2], const_args[2]);

        break;

    case INDEX_op_movcond_i64:

        tcg_out_movcond64(s, args[5], args[0], args[1],

                          args[2], const_args[2], args[3]);

        break;

    case INDEX_op_bswap64_i64:

        tcg_out_bswap64(s, args[0]);

        break;

    case INDEX_op_ext32u_i64:

        tcg_out_ext32u(s, args[0], args[1]);

        break;

    case INDEX_op_ext32s_i64:

        tcg_out_ext32s(s, args[0], args[1]);

        break;

#endif

    OP_32_64(deposit):

        if (args[3] == 0 && args[4] == 8) {

            /* load bits 0..7 */

            tcg_out_modrm(s, OPC_MOVB_EvGv | P_REXB_R | P_REXB_RM,

                          args[2], args[0]);

        } else if (args[3] == 8 && args[4] == 8) {

            /* load bits 8..15 */

            tcg_out_modrm(s, OPC_MOVB_EvGv, args[2], args[0] + 4);

        } else if (args[3] == 0 && args[4] == 16) {

            /* load bits 0..15 */

            tcg_out_modrm(s, OPC_MOVL_EvGv | P_DATA16, args[2], args[0]);

        } else {

            tcg_abort();

        }

        break;

    case INDEX_op_mov_i32:  /* Always emitted via tcg_out_mov.  */

    case INDEX_op_mov_i64:

    case INDEX_op_movi_i32: /* Always emitted via tcg_out_movi.  */

    case INDEX_op_movi_i64:

    case INDEX_op_call:     /* Always emitted via tcg_out_call.  */

    default:

        tcg_abort();

    }

#undef OP_32_64

}


static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,

    int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)

{

    BlockDriver *drv = bs->drv;

    QEMUIOVector qiov;

    struct iovec iov = {0};

    int ret = 0;

    int max_write_zeroes = bs->bl.max_write_zeroes ?

                           bs->bl.max_write_zeroes : INT_MAX;

    while (nb_sectors > 0 && !ret) {

        int num = nb_sectors;

        /* Align request.  Block drivers can expect the "bulk" of the request

         * to be aligned.

         */

        if (bs->bl.write_zeroes_alignment

            && num > bs->bl.write_zeroes_alignment) {

            if (sector_num % bs->bl.write_zeroes_alignment != 0) {

                /* Make a small request up to the first aligned sector.  */

                num = bs->bl.write_zeroes_alignment;

                num -= sector_num % bs->bl.write_zeroes_alignment;

            } else if ((sector_num + num) % bs->bl.write_zeroes_alignment != 0) {

                /* Shorten the request to the last aligned sector.  num cannot

                 * underflow because num > bs->bl.write_zeroes_alignment.

                 */

                num -= (sector_num + num) % bs->bl.write_zeroes_alignment;

            }

        }

        /* limit request size */

        if (num > max_write_zeroes) {

            num = max_write_zeroes;

        }

        ret = -ENOTSUP;

        /* First try the efficient write zeroes operation */

        if (drv->bdrv_co_write_zeroes) {

            ret = drv->bdrv_co_write_zeroes(bs, sector_num, num, flags);

        }

        if (ret == -ENOTSUP) {

            /* Fall back to bounce buffer if write zeroes is unsupported */

            int max_xfer_len = MIN_NON_ZERO(bs->bl.max_transfer_length,

                                            MAX_WRITE_ZEROES_BOUNCE_BUFFER);

            num = MIN(num, max_xfer_len);

            iov.iov_len = num * BDRV_SECTOR_SIZE;

            if (iov.iov_base == NULL) {

                iov.iov_base = qemu_try_blockalign(bs, num * BDRV_SECTOR_SIZE);

                if (iov.iov_base == NULL) {

                    ret = -ENOMEM;

                    goto fail;

                }

                memset(iov.iov_base, 0, num * BDRV_SECTOR_SIZE);

            }

            qemu_iovec_init_external(&qiov, &iov, 1);

            ret = drv->bdrv_co_writev(bs, sector_num, num, &qiov);

            /* Keep bounce buffer around if it is big enough for all

             * all future requests.

             */

            if (num < max_xfer_len) {

                qemu_vfree(iov.iov_base);

                iov.iov_base = NULL;

            }

        }

        sector_num += num;

        nb_sectors -= num;

    }

fail:

    qemu_vfree(iov.iov_base);

    return ret;

}


static void sigp_cpu_reset(CPUState *cs, run_on_cpu_data arg)

{

    S390CPU *cpu = S390_CPU(cs);

    S390CPUClass *scc = S390_CPU_GET_CLASS(cpu);

    SigpInfo *si = arg.host_ptr;

    cpu_synchronize_state(cs);

    scc->cpu_reset(cs);

    cpu_synchronize_post_reset(cs);

    si->cc = SIGP_CC_ORDER_CODE_ACCEPTED;

}


static void GCC_FMT_ATTR(3, 4) parse_error(JSONParserContext *ctxt,

                                           QObject *token, const char *msg, ...)

{

    va_list ap;

    char message[1024];

    va_start(ap, msg);

    vsnprintf(message, sizeof(message), msg, ap);

    va_end(ap);

    if (ctxt->err) {

        error_free(ctxt->err);

        ctxt->err = NULL;

    }

    error_setg(&ctxt->err, "JSON parse error, %s", message);

}


static int cpu_x86_register (CPUX86State *env, const char *cpu_model)

{

    x86_def_t def1, *def = &def1;

    if (cpu_x86_find_by_name(def, cpu_model) < 0)

        return -1;

    if (def->vendor1) {

        env->cpuid_vendor1 = def->vendor1;

        env->cpuid_vendor2 = def->vendor2;

        env->cpuid_vendor3 = def->vendor3;

    } else {

        env->cpuid_vendor1 = CPUID_VENDOR_INTEL_1;

        env->cpuid_vendor2 = CPUID_VENDOR_INTEL_2;

        env->cpuid_vendor3 = CPUID_VENDOR_INTEL_3;

    }

    env->cpuid_vendor_override = def->vendor_override;

    env->cpuid_level = def->level;

    if (def->family > 0x0f)

        env->cpuid_version = 0xf00 | ((def->family - 0x0f) << 20);

    else

        env->cpuid_version = def->family << 8;

    env->cpuid_version |= ((def->model & 0xf) << 4) | ((def->model >> 4) << 16);

    env->cpuid_version |= def->stepping;

    env->cpuid_features = def->features;

    env->pat = 0x0007040600070406ULL;

    env->cpuid_ext_features = def->ext_features;

    env->cpuid_ext2_features = def->ext2_features;

    env->cpuid_xlevel = def->xlevel;

    env->cpuid_ext3_features = def->ext3_features;

    {

        const char *model_id = def->model_id;

        int c, len, i;

        if (!model_id)

            model_id = "";

        len = strlen(model_id);

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

            if (i >= len)

                c = '\0';

            else

                c = (uint8_t)model_id[i];

            env->cpuid_model[i >> 2] |= c << (8 * (i & 3));

        }

    }

    return 0;

}


void bdrv_info(void)

{

    BlockDriverState *bs;

    for (bs = bdrv_first; bs != NULL; bs = bs->next) {

        term_printf("%s:", bs->device_name);

        term_printf(" type=");

        switch(bs->type) {

        case BDRV_TYPE_HD:

            term_printf("hd");

            break;

        case BDRV_TYPE_CDROM:

            term_printf("cdrom");

            break;

        case BDRV_TYPE_FLOPPY:

            term_printf("floppy");

            break;

        }

        term_printf(" removable=%d", bs->removable);

        if (bs->removable) {

            term_printf(" locked=%d", bs->locked);

        }

        if (bs->drv) {

            term_printf(" file=");

	    term_print_filename(bs->filename);

            if (bs->backing_file[0] != '\0') {

                term_printf(" backing_file=");

		term_print_filename(bs->backing_file);

	    }

            term_printf(" ro=%d", bs->read_only);

            term_printf(" drv=%s", bs->drv->format_name);

            if (bs->encrypted)

                term_printf(" encrypted");

        } else {

            term_printf(" [not inserted]");

        }

        term_printf("\n");

    }

}


int qcrypto_hash_bytesv(QCryptoHashAlgorithm alg,

                        const struct iovec *iov,

                        size_t niov,

                        uint8_t **result,

                        size_t *resultlen,

                        Error **errp)

{

    int i, ret;

    gnutls_hash_hd_t dig;

    if (alg >= G_N_ELEMENTS(qcrypto_hash_alg_map)) {

        error_setg(errp,

                   "Unknown hash algorithm %d",

                   alg);

        return -1;

    }

    ret = gnutls_hash_init(&dig, qcrypto_hash_alg_map[alg]);

    if (ret < 0) {

        error_setg(errp,

                   "Unable to initialize hash algorithm: %s",

                   gnutls_strerror(ret));

        return -1;

    }

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

        ret = gnutls_hash(dig, iov[i].iov_base, iov[i].iov_len);

        if (ret < 0) {

            error_setg(errp,

                       "Unable process hash data: %s",

                       gnutls_strerror(ret));

            goto error;

        }

    }

    ret = gnutls_hash_get_len(qcrypto_hash_alg_map[alg]);

    if (ret <= 0) {

        error_setg(errp,

                   "Unable to get hash length: %s",

                   gnutls_strerror(ret));

        goto error;

    }

    if (*resultlen == 0) {

        *resultlen = ret;

        *result = g_new0(uint8_t, *resultlen);

    } else if (*resultlen != ret) {

        error_setg(errp,

                   "Result buffer size %zu is smaller than hash %d",

                   *resultlen, ret);

        goto error;

    }

    gnutls_hash_deinit(dig, *result);

    return 0;

 error:

    gnutls_hash_deinit(dig, NULL);

    return -1;

}


static void start_input(DBDMA_channel *ch, int key, uint32_t addr,

                       uint16_t req_count, int is_last)

{

    DBDMA_DPRINTF("start_input\n");

    /* KEY_REGS, KEY_DEVICE and KEY_STREAM

     * are not implemented in the mac-io chip

     */

    if (!addr || key > KEY_STREAM3) {

        kill_channel(ch);

        return;

    }

    ch->io.addr = addr;

    ch->io.len = req_count;

    ch->io.is_last = is_last;

    ch->io.dma_end = dbdma_end;

    ch->io.is_dma_out = 0;

    ch->processing = 1;

    ch->rw(&ch->io);

}


static void spapr_core_release(DeviceState *dev, void *opaque)

{

    HotplugHandler *hotplug_ctrl;

    hotplug_ctrl = qdev_get_hotplug_handler(dev);

    hotplug_handler_unplug(hotplug_ctrl, dev, &error_abort);

}


static uint64_t macio_nvram_readb(void *opaque, target_phys_addr_t addr,

                                  unsigned size)

{

    MacIONVRAMState *s = opaque;

    uint32_t value;

    addr = (addr >> s->it_shift) & (s->size - 1);

    value = s->data[addr];

    NVR_DPRINTF("readb addr %04x val %x\n", (int)addr, value);

    return value;

}


static const HWAccel *get_hwaccel(enum AVPixelFormat pix_fmt, enum HWAccelID selected_hwaccel_id)

{

    int i;

    for (i = 0; hwaccels[i].name; i++)

        if (hwaccels[i].pix_fmt == pix_fmt &&

            (!selected_hwaccel_id || selected_hwaccel_id == HWACCEL_AUTO || hwaccels[i].id == selected_hwaccel_id))

            return &hwaccels[i];

    return NULL;

}


static int ir2_decode_frame(AVCodecContext *avctx,

                        void *data, int *got_frame,

                        AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    Ir2Context * const s = avctx->priv_data;

    AVFrame *picture = data;

    AVFrame * const p = &s->picture;

    int start, ret;

    if(p->data[0])

        avctx->release_buffer(avctx, p);

    p->reference = 1;

    p->buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE | FF_BUFFER_HINTS_REUSABLE;

    if ((ret = avctx->reget_buffer(avctx, p)) < 0) {

        av_log(s->avctx, AV_LOG_ERROR, "reget_buffer() failed\n");

        return ret;

    }

    start = 48; /* hardcoded for now */

    if (start >= buf_size) {

        av_log(s->avctx, AV_LOG_ERROR, "input buffer size too small (%d)\n", buf_size);

        return AVERROR_INVALIDDATA;

    }

    s->decode_delta = buf[18];

    /* decide whether frame uses deltas or not */

#ifndef BITSTREAM_READER_LE

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

        buf[i] = ff_reverse[buf[i]];

#endif

    init_get_bits(&s->gb, buf + start, (buf_size - start) * 8);

    if (s->decode_delta) { /* intraframe */

        ir2_decode_plane(s, avctx->width, avctx->height,

                         s->picture.data[0], s->picture.linesize[0], ir2_luma_table);

        /* swapped U and V */

        ir2_decode_plane(s, avctx->width >> 2, avctx->height >> 2,

                         s->picture.data[2], s->picture.linesize[2], ir2_luma_table);

        ir2_decode_plane(s, avctx->width >> 2, avctx->height >> 2,

                         s->picture.data[1], s->picture.linesize[1], ir2_luma_table);

    } else { /* interframe */

        ir2_decode_plane_inter(s, avctx->width, avctx->height,

                         s->picture.data[0], s->picture.linesize[0], ir2_luma_table);

        /* swapped U and V */

        ir2_decode_plane_inter(s, avctx->width >> 2, avctx->height >> 2,

                         s->picture.data[2], s->picture.linesize[2], ir2_luma_table);

        ir2_decode_plane_inter(s, avctx->width >> 2, avctx->height >> 2,

                         s->picture.data[1], s->picture.linesize[1], ir2_luma_table);

    }

    *picture   = s->picture;

    *got_frame = 1;

    return buf_size;

}


static int rsd_read_packet(AVFormatContext *s, AVPacket *pkt)

{

    AVCodecContext *codec = s->streams[0]->codec;

    int ret, size = 1024;

    if (avio_feof(s->pb))

        return AVERROR_EOF;

    if (codec->codec_id == AV_CODEC_ID_ADPCM_IMA_RAD ||

        codec->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {

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

    } else if (codec->codec_tag == MKTAG('W','A','D','P') &&

               codec->channels > 1) {

        int i, ch;

        av_new_packet(pkt, codec->block_align);

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

            for (ch = 0; ch < codec->channels; ch++) {

                pkt->data[ch * 8 + i * 2 + 0] = avio_r8(s->pb);

                pkt->data[ch * 8 + i * 2 + 1] = avio_r8(s->pb);

            }

        }

        ret = 0;

    } else {

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

    }

    pkt->stream_index = 0;

    return ret;

}


static TCGv_i64 gen_muls_i64_i32(TCGv a, TCGv b)

{

    TCGv_i64 tmp1 = tcg_temp_new_i64();

    TCGv_i64 tmp2 = tcg_temp_new_i64();

    tcg_gen_ext_i32_i64(tmp1, a);

    dead_tmp(a);

    tcg_gen_ext_i32_i64(tmp2, b);

    dead_tmp(b);

    tcg_gen_mul_i64(tmp1, tmp1, tmp2);

    tcg_temp_free_i64(tmp2);

    return tmp1;

}


void av_fast_malloc(void *ptr, unsigned int *size, size_t min_size)

{

    void **p = ptr;

    if (min_size < *size)

        return;

    min_size= FFMAX(17*min_size/16 + 32, min_size);

    av_free(*p);

    *p = av_malloc(min_size);

    if (!*p) min_size = 0;

    *size= min_size;

}


static void vmxnet3_fill_stats(VMXNET3State *s)

{

    int i;

    if (!s->device_active)

        return;

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

        pci_dma_write(PCI_DEVICE(s),

                      s->txq_descr[i].tx_stats_pa,

                      &s->txq_descr[i].txq_stats,

                      sizeof(s->txq_descr[i].txq_stats));

    }

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

        pci_dma_write(PCI_DEVICE(s),

                      s->rxq_descr[i].rx_stats_pa,

                      &s->rxq_descr[i].rxq_stats,

                      sizeof(s->rxq_descr[i].rxq_stats));

    }

}


static int ljpeg_decode_yuv_scan(MJpegDecodeContext *s, int predictor,

                                 int point_transform)

{

    int i, mb_x, mb_y;

    const int nb_components=s->nb_components;

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

    int resync_mb_y = 0;

    int resync_mb_x = 0;

    point_transform += bits - s->bits;

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

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

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

            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 == 0xFFFF)

                            return -1;

                        if(bits<=8){

                        ptr = s->picture.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 &= (-1)<<(8-s->bits);

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

                        }else{

                            ptr16 = (uint16_t*)(s->picture.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 &= (-1)<<(16-s->bits);

                            *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 == 0xFFFF)

                            return -1;

                        if(bits<=8){

                            ptr = s->picture.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 &= (-1)<<(8-s->bits);

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

                        }else{

                            ptr16 = (uint16_t*)(s->picture.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 &= (-1)<<(16-s->bits);

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

}


static void map_exec(void *addr, long size)

{

    DWORD old_protect;

    VirtualProtect(addr, size,

                   PAGE_EXECUTE_READWRITE, &old_protect);

}


static void gen_exception_insn(DisasContext *s, int offset, int excp,

                               int syn, uint32_t target_el)

{

    gen_set_condexec(s);

    gen_set_pc_im(s, s->pc - offset);

    gen_exception(excp, syn, target_el);

    s->is_jmp = DISAS_JUMP;

}


static int omap2_validate_addr(struct omap_mpu_state_s *s,

                target_phys_addr_t addr)

{

    return 1;

}


static void htab_save_first_pass(QEMUFile *f, sPAPRMachineState *spapr,

                                 int64_t max_ns)

{

    int htabslots = HTAB_SIZE(spapr) / HASH_PTE_SIZE_64;

    int index = spapr->htab_save_index;

    int64_t starttime = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);

    assert(spapr->htab_first_pass);

    do {

        int chunkstart;

        /* Consume invalid HPTEs */

        while ((index < htabslots)

               && !HPTE_VALID(HPTE(spapr->htab, index))) {

            index++;

            CLEAN_HPTE(HPTE(spapr->htab, index));

        }

        /* Consume valid HPTEs */

        chunkstart = index;

        while ((index < htabslots) && (index - chunkstart < USHRT_MAX)

               && HPTE_VALID(HPTE(spapr->htab, index))) {

            index++;

            CLEAN_HPTE(HPTE(spapr->htab, index));

        }

        if (index > chunkstart) {

            int n_valid = index - chunkstart;

            qemu_put_be32(f, chunkstart);

            qemu_put_be16(f, n_valid);

            qemu_put_be16(f, 0);

            qemu_put_buffer(f, HPTE(spapr->htab, chunkstart),

                            HASH_PTE_SIZE_64 * n_valid);

            if ((qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - starttime) > max_ns) {

                break;

            }

        }

    } while ((index < htabslots) && !qemu_file_rate_limit(f));

    if (index >= htabslots) {

        assert(index == htabslots);

        index = 0;

        spapr->htab_first_pass = false;

    }

    spapr->htab_save_index = index;

}


void tcg_gen_brcondi_i64(TCGCond cond, TCGv_i64 arg1, int64_t arg2, int label)

{

    if (cond == TCG_COND_ALWAYS) {

        tcg_gen_br(label);

    } else if (cond != TCG_COND_NEVER) {

        TCGv_i64 t0 = tcg_const_i64(arg2);

        tcg_gen_brcond_i64(cond, arg1, t0, label);

        tcg_temp_free_i64(t0);

    }

}


QObject *qlist_peek(QList *qlist)

{

    QListEntry *entry;

    QObject *ret;

    if (qlist == NULL || QTAILQ_EMPTY(&qlist->head)) {

        return NULL;

    }

    entry = QTAILQ_FIRST(&qlist->head);

    ret = entry->value;

    return ret;

}


static int wav_read_header(AVFormatContext *s,

                           AVFormatParameters *ap)

{

    int64_t size, av_uninit(data_size);

    int64_t sample_count=0;

    int rf64;

    unsigned int tag;

    AVIOContext *pb = s->pb;

    AVStream *st;

    WAVContext *wav = s->priv_data;

    int ret, got_fmt = 0;

    int64_t next_tag_ofs, data_ofs = -1;

    /* check RIFF header */

    tag = avio_rl32(pb);

    rf64 = tag == MKTAG('R', 'F', '6', '4');

    if (!rf64 && tag != MKTAG('R', 'I', 'F', 'F'))

        return -1;

    avio_rl32(pb); /* file size */

    tag = avio_rl32(pb);

    if (tag != MKTAG('W', 'A', 'V', 'E'))

        return -1;

    if (rf64) {

        if (avio_rl32(pb) != MKTAG('d', 's', '6', '4'))

            return -1;

        size = avio_rl32(pb);

        if (size < 16)

            return -1;

        avio_rl64(pb); /* RIFF size */

        data_size = avio_rl64(pb);

        sample_count = avio_rl64(pb);

        if (data_size < 0 || sample_count < 0) {

            av_log(s, AV_LOG_ERROR, "negative data_size and/or sample_count in "

                   "ds64: data_size = %"PRId64", sample_count = %"PRId64"\n",

                   data_size, sample_count);

            return AVERROR_INVALIDDATA;

        }

        avio_skip(pb, size - 24); /* skip rest of ds64 chunk */

    }

    for (;;) {

        size = next_tag(pb, &tag);

        next_tag_ofs = avio_tell(pb) + size;

        if (url_feof(pb))

            break;

        switch (tag) {

        case MKTAG('f', 'm', 't', ' '):

            /* only parse the first 'fmt ' tag found */

            if (!got_fmt && (ret = wav_parse_fmt_tag(s, size, &st) < 0)) {

                return ret;

            } else if (got_fmt)

                av_log(s, AV_LOG_WARNING, "found more than one 'fmt ' tag\n");

            got_fmt = 1;

            break;

        case MKTAG('d', 'a', 't', 'a'):

            if (!got_fmt) {

                av_log(s, AV_LOG_ERROR, "found no 'fmt ' tag before the 'data' tag\n");

                return AVERROR_INVALIDDATA;

            }

            if (rf64) {

                next_tag_ofs = wav->data_end = avio_tell(pb) + data_size;

            } else {

                data_size = size;

                next_tag_ofs = wav->data_end = size ? next_tag_ofs : INT64_MAX;

            }

            data_ofs = avio_tell(pb);

            /* don't look for footer metadata if we can't seek or if we don't

             * know where the data tag ends

             */

            if (!pb->seekable || (!rf64 && !size))

                goto break_loop;

            break;

        case MKTAG('f','a','c','t'):

            if(!sample_count)

                sample_count = avio_rl32(pb);

            break;

        case MKTAG('b','e','x','t'):

            if ((ret = wav_parse_bext_tag(s, size)) < 0)

                return ret;

            break;

        }

        /* seek to next tag unless we know that we'll run into EOF */

        if ((avio_size(pb) > 0 && next_tag_ofs >= avio_size(pb)) ||

            avio_seek(pb, next_tag_ofs, SEEK_SET) < 0) {

            break;

        }

    }

break_loop:

    if (data_ofs < 0) {

        av_log(s, AV_LOG_ERROR, "no 'data' tag found\n");

        return AVERROR_INVALIDDATA;

    }

    avio_seek(pb, data_ofs, SEEK_SET);

    if (!sample_count && st->codec->channels && av_get_bits_per_sample(st->codec->codec_id))

        sample_count = (data_size<<3) / (st->codec->channels * (uint64_t)av_get_bits_per_sample(st->codec->codec_id));

    if (sample_count)

        st->duration = sample_count;

    ff_metadata_conv_ctx(s, NULL, wav_metadata_conv);

    return 0;

}


static void init_native_list(UserDefNativeListUnion *cvalue)

{

    int i;

    switch (cvalue->type) {

    case USER_DEF_NATIVE_LIST_UNION_KIND_INTEGER: {

        intList **list = &cvalue->u.integer.data;

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

            *list = g_new0(intList, 1);

            (*list)->value = i;

            (*list)->next = NULL;

            list = &(*list)->next;

        }

        break;

    }

    case USER_DEF_NATIVE_LIST_UNION_KIND_S8: {

        int8List **list = &cvalue->u.s8.data;

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

            *list = g_new0(int8List, 1);

            (*list)->value = i;

            (*list)->next = NULL;

            list = &(*list)->next;

        }

        break;

    }

    case USER_DEF_NATIVE_LIST_UNION_KIND_S16: {

        int16List **list = &cvalue->u.s16.data;

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

            *list = g_new0(int16List, 1);

            (*list)->value = i;

            (*list)->next = NULL;

            list = &(*list)->next;

        }

        break;

    }

    case USER_DEF_NATIVE_LIST_UNION_KIND_S32: {

        int32List **list = &cvalue->u.s32.data;

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

            *list = g_new0(int32List, 1);

            (*list)->value = i;

            (*list)->next = NULL;

            list = &(*list)->next;

        }

        break;

    }

    case USER_DEF_NATIVE_LIST_UNION_KIND_S64: {

        int64List **list = &cvalue->u.s64.data;

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

            *list = g_new0(int64List, 1);

            (*list)->value = i;

            (*list)->next = NULL;

            list = &(*list)->next;

        }

        break;

    }

    case USER_DEF_NATIVE_LIST_UNION_KIND_U8: {

        uint8List **list = &cvalue->u.u8.data;

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

            *list = g_new0(uint8List, 1);

            (*list)->value = i;

            (*list)->next = NULL;

            list = &(*list)->next;

        }

        break;

    }

    case USER_DEF_NATIVE_LIST_UNION_KIND_U16: {

        uint16List **list = &cvalue->u.u16.data;

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

            *list = g_new0(uint16List, 1);

            (*list)->value = i;

            (*list)->next = NULL;

            list = &(*list)->next;

        }

        break;

    }

    case USER_DEF_NATIVE_LIST_UNION_KIND_U32: {

        uint32List **list = &cvalue->u.u32.data;

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

            *list = g_new0(uint32List, 1);

            (*list)->value = i;

            (*list)->next = NULL;

            list = &(*list)->next;

        }

        break;

    }

    case USER_DEF_NATIVE_LIST_UNION_KIND_U64: {

        uint64List **list = &cvalue->u.u64.data;

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

            *list = g_new0(uint64List, 1);

            (*list)->value = i;

            (*list)->next = NULL;

            list = &(*list)->next;

        }

        break;

    }

    case USER_DEF_NATIVE_LIST_UNION_KIND_BOOLEAN: {

        boolList **list = &cvalue->u.boolean.data;

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

            *list = g_new0(boolList, 1);

            (*list)->value = (i % 3 == 0);

            (*list)->next = NULL;

            list = &(*list)->next;

        }

        break;

    }

    case USER_DEF_NATIVE_LIST_UNION_KIND_STRING: {

        strList **list = &cvalue->u.string.data;

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

            *list = g_new0(strList, 1);

            (*list)->value = g_strdup_printf("%d", i);

            (*list)->next = NULL;

            list = &(*list)->next;

        }

        break;

    }

    case USER_DEF_NATIVE_LIST_UNION_KIND_NUMBER: {

        numberList **list = &cvalue->u.number.data;

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

            *list = g_new0(numberList, 1);

            (*list)->value = (double)i / 3;

            (*list)->next = NULL;

            list = &(*list)->next;

        }

        break;

    }

    default:

        g_assert_not_reached();

    }

}


static void internal_snapshot_prepare(BlkTransactionState *common,

                                      Error **errp)

{

    Error *local_err = NULL;

    const char *device;

    const char *name;

    BlockBackend *blk;

    BlockDriverState *bs;

    QEMUSnapshotInfo old_sn, *sn;

    bool ret;

    qemu_timeval tv;

    BlockdevSnapshotInternal *internal;

    InternalSnapshotState *state;

    int ret1;

    g_assert(common->action->kind ==

             TRANSACTION_ACTION_KIND_BLOCKDEV_SNAPSHOT_INTERNAL_SYNC);

    internal = common->action->blockdev_snapshot_internal_sync;

    state = DO_UPCAST(InternalSnapshotState, common, common);

    /* 1. parse input */

    device = internal->device;

    name = internal->name;

    /* 2. check for validation */

    blk = blk_by_name(device);

    if (!blk) {

        error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,

                  "Device '%s' not found", device);

        return;

    }

    /* AioContext is released in .clean() */

    state->aio_context = blk_get_aio_context(blk);

    aio_context_acquire(state->aio_context);

    if (!blk_is_available(blk)) {

        error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);

        return;

    }

    bs = blk_bs(blk);

    state->bs = bs;

    bdrv_drained_begin(bs);

    if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_INTERNAL_SNAPSHOT, errp)) {

        return;

    }

    if (bdrv_is_read_only(bs)) {

        error_setg(errp, "Device '%s' is read only", device);

        return;

    }

    if (!bdrv_can_snapshot(bs)) {

        error_setg(errp, "Block format '%s' used by device '%s' "

                   "does not support internal snapshots",

                   bs->drv->format_name, device);

        return;

    }

    if (!strlen(name)) {

        error_setg(errp, "Name is empty");

        return;

    }

    /* check whether a snapshot with name exist */

    ret = bdrv_snapshot_find_by_id_and_name(bs, NULL, name, &old_sn,

                                            &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        return;

    } else if (ret) {

        error_setg(errp,

                   "Snapshot with name '%s' already exists on device '%s'",

                   name, device);

        return;

    }

    /* 3. take the snapshot */

    sn = &state->sn;

    pstrcpy(sn->name, sizeof(sn->name), name);

    qemu_gettimeofday(&tv);

    sn->date_sec = tv.tv_sec;

    sn->date_nsec = tv.tv_usec * 1000;

    sn->vm_clock_nsec = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);

    ret1 = bdrv_snapshot_create(bs, sn);

    if (ret1 < 0) {

        error_setg_errno(errp, -ret1,

                         "Failed to create snapshot '%s' on device '%s'",

                         name, device);

        return;

    }

    /* 4. succeed, mark a snapshot is created */

    state->created = true;

}


void thread_pool_free(ThreadPool *pool)

{

    if (!pool) {

        return;

    }

    assert(QLIST_EMPTY(&pool->head));

    qemu_mutex_lock(&pool->lock);

    /* Stop new threads from spawning */

    qemu_bh_delete(pool->new_thread_bh);

    pool->cur_threads -= pool->new_threads;

    pool->new_threads = 0;

    /* Wait for worker threads to terminate */

    pool->stopping = true;

    while (pool->cur_threads > 0) {

        qemu_sem_post(&pool->sem);

        qemu_cond_wait(&pool->worker_stopped, &pool->lock);

    }

    qemu_mutex_unlock(&pool->lock);

    qemu_bh_delete(pool->completion_bh);

    qemu_sem_destroy(&pool->sem);

    qemu_cond_destroy(&pool->worker_stopped);

    qemu_mutex_destroy(&pool->lock);

    g_free(pool);

}


static int find_real_tpr_addr(VAPICROMState *s, CPUX86State *env)

{

    target_phys_addr_t paddr;

    target_ulong addr;

    if (s->state == VAPIC_ACTIVE) {

        return 0;

    }

    /*

     * If there is no prior TPR access instruction we could analyze (which is

     * the case after resume from hibernation), we need to scan the possible

     * virtual address space for the APIC mapping.

     */

    for (addr = 0xfffff000; addr >= 0x80000000; addr -= TARGET_PAGE_SIZE) {

        paddr = cpu_get_phys_page_debug(env, addr);

        if (paddr != APIC_DEFAULT_ADDRESS) {

            continue;

        }

        s->real_tpr_addr = addr + 0x80;

        update_guest_rom_state(s);

        return 0;

    }

    return -1;

}


void memory_region_ram_resize(MemoryRegion *mr, ram_addr_t newsize, Error **errp)

{

    assert(mr->terminates);

    qemu_ram_resize(mr->ram_addr, newsize, errp);

}


void replay_read_events(int checkpoint)

{

    while (replay_data_kind == EVENT_ASYNC) {

        Event *event = replay_read_event(checkpoint);

        if (!event) {

            break;

        }

        replay_mutex_unlock();

        replay_run_event(event);

        replay_mutex_lock();

        g_free(event);

        replay_finish_event();

        read_event_kind = -1;

    }

}


void qmp_block_resize(bool has_device, const char *device,

                      bool has_node_name, const char *node_name,

                      int64_t size, Error **errp)

{

    Error *local_err = NULL;

    BlockDriverState *bs;

    AioContext *aio_context;

    int ret;

    bs = bdrv_lookup_bs(has_device ? device : NULL,

                        has_node_name ? node_name : NULL,

                        &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        return;

    }

    aio_context = bdrv_get_aio_context(bs);

    aio_context_acquire(aio_context);

    if (!bdrv_is_first_non_filter(bs)) {

        error_setg(errp, QERR_FEATURE_DISABLED, "resize");

        goto out;

    }

    if (size < 0) {

        error_setg(errp, QERR_INVALID_PARAMETER_VALUE, "size", "a >0 size");

        goto out;

    }

    if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_RESIZE, NULL)) {

        error_setg(errp, QERR_DEVICE_IN_USE, device);

        goto out;

    }

    /* complete all in-flight operations before resizing the device */

    bdrv_drain_all();

    ret = bdrv_truncate(bs, size);

    switch (ret) {

    case 0:

        break;

    case -ENOMEDIUM:

        error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);

        break;

    case -ENOTSUP:

        error_setg(errp, QERR_UNSUPPORTED);

        break;

    case -EACCES:

        error_setg(errp, "Device '%s' is read only", device);

        break;

    case -EBUSY:

        error_setg(errp, QERR_DEVICE_IN_USE, device);

        break;

    default:

        error_setg_errno(errp, -ret, "Could not resize");

        break;

    }

out:

    aio_context_release(aio_context);

}


uint64_t mcf_uart_read(void *opaque, target_phys_addr_t addr,

                       unsigned size)

{

    mcf_uart_state *s = (mcf_uart_state *)opaque;

    switch (addr & 0x3f) {

    case 0x00:

        return s->mr[s->current_mr];

    case 0x04:

        return s->sr;

    case 0x0c:

        {

            uint8_t val;

            int i;

            if (s->fifo_len == 0)

                return 0;

            val = s->fifo[0];

            s->fifo_len--;

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

                s->fifo[i] = s->fifo[i + 1];

            s->sr &= ~MCF_UART_FFULL;

            if (s->fifo_len == 0)

                s->sr &= ~MCF_UART_RxRDY;

            mcf_uart_update(s);

            qemu_chr_accept_input(s->chr);

            return val;

        }

    case 0x10:

        /* TODO: Implement IPCR.  */

        return 0;

    case 0x14:

        return s->isr;

    case 0x18:

        return s->bg1;

    case 0x1c:

        return s->bg2;

    default:

        return 0;

    }

}


int qcow2_zero_clusters(BlockDriverState *bs, uint64_t offset, int nb_sectors,

                        int flags)

{

    BDRVQcow2State *s = bs->opaque;

    uint64_t end_offset;

    uint64_t nb_clusters;

    int ret;

    end_offset = offset + (nb_sectors << BDRV_SECTOR_BITS);

    /* Caller must pass aligned values, except at image end */

    assert(QEMU_IS_ALIGNED(offset, s->cluster_size));

    assert(QEMU_IS_ALIGNED(end_offset, s->cluster_size) ||

           end_offset == bs->total_sectors << BDRV_SECTOR_BITS);

    /* The zero flag is only supported by version 3 and newer */

    if (s->qcow_version < 3) {

        return -ENOTSUP;

    }

    /* Each L2 table is handled by its own loop iteration */

    nb_clusters = size_to_clusters(s, nb_sectors << BDRV_SECTOR_BITS);

    s->cache_discards = true;

    while (nb_clusters > 0) {

        ret = zero_single_l2(bs, offset, nb_clusters, flags);

        if (ret < 0) {

            goto fail;

        }

        nb_clusters -= ret;

        offset += (ret * s->cluster_size);

    }

    ret = 0;

fail:

    s->cache_discards = false;

    qcow2_process_discards(bs, ret);

    return ret;

}


void bdrv_append_temp_snapshot(BlockDriverState *bs, Error **errp)

{

    /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */

    char tmp_filename[PATH_MAX + 1];

    int64_t total_size;

    BlockDriver *bdrv_qcow2;

    QEMUOptionParameter *create_options;

    QDict *snapshot_options;

    BlockDriverState *bs_snapshot;

    Error *local_err;

    int ret;

    /* if snapshot, we create a temporary backing file and open it

       instead of opening 'filename' directly */

    /* Get the required size from the image */

    total_size = bdrv_getlength(bs);

    if (total_size < 0) {

        error_setg_errno(errp, -total_size, "Could not get image size");

        return;

    }

    total_size &= BDRV_SECTOR_MASK;

    /* Create the temporary image */

    ret = get_tmp_filename(tmp_filename, sizeof(tmp_filename));

    if (ret < 0) {

        error_setg_errno(errp, -ret, "Could not get temporary filename");

        return;

    }

    bdrv_qcow2 = bdrv_find_format("qcow2");

    create_options = parse_option_parameters("", bdrv_qcow2->create_options,

                                             NULL);

    set_option_parameter_int(create_options, BLOCK_OPT_SIZE, total_size);

    ret = bdrv_create(bdrv_qcow2, tmp_filename, create_options, &local_err);

    free_option_parameters(create_options);

    if (ret < 0) {

        error_setg_errno(errp, -ret, "Could not create temporary overlay "

                         "'%s': %s", tmp_filename,

                         error_get_pretty(local_err));

        error_free(local_err);

        return;

    }

    /* Prepare a new options QDict for the temporary file */

    snapshot_options = qdict_new();

    qdict_put(snapshot_options, "file.driver",

              qstring_from_str("file"));

    qdict_put(snapshot_options, "file.filename",

              qstring_from_str(tmp_filename));

    bs_snapshot = bdrv_new("");

    bs_snapshot->is_temporary = 1;

    ret = bdrv_open(&bs_snapshot, NULL, NULL, snapshot_options,

                    bs->open_flags & ~BDRV_O_SNAPSHOT, bdrv_qcow2, &local_err);

    if (ret < 0) {

        error_propagate(errp, local_err);

        return;

    }

    bdrv_append(bs_snapshot, bs);

}


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

{

    AVStream *st;

    enum AVAudioServiceType *ast;

    int eac3info, acmod, lfeon, bsmod;

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

        return 0;

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

    ast = (enum AVAudioServiceType*)ff_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE,

                                                            sizeof(*ast));

    if (!ast)

        return AVERROR(ENOMEM);

    /* No need to parse fields for additional independent substreams and its

     * associated dependent substreams since libavcodec's E-AC-3 decoder

     * does not support them yet. */

    avio_rb16(pb); /* data_rate and num_ind_sub */

    eac3info = avio_rb24(pb);

    bsmod = (eac3info >> 12) & 0x1f;

    acmod = (eac3info >>  9) & 0x7;

    lfeon = (eac3info >>  8) & 0x1;

    st->codec->channel_layout = avpriv_ac3_channel_layout_tab[acmod];

    if (lfeon)

        st->codec->channel_layout |= AV_CH_LOW_FREQUENCY;

    st->codec->channels = av_get_channel_layout_nb_channels(st->codec->channel_layout);

    *ast = bsmod;

    if (st->codec->channels > 1 && bsmod == 0x7)

        *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE;

    st->codec->audio_service_type = *ast;

    return 0;

}


Visitor *visitor_input_test_init(TestInputVisitorData *data,

                                 const char *json_string, ...)

{

    Visitor *v;

    va_list ap;

    va_start(ap, json_string);

    v = visitor_input_test_init_internal(data, json_string, &ap);

    va_end(ap);

    return v;

}


int qemu_pixman_get_type(int rshift, int gshift, int bshift)

{

    int type = PIXMAN_TYPE_OTHER;

    if (rshift > gshift && gshift > bshift) {

        if (bshift == 0) {

            type = PIXMAN_TYPE_ARGB;

        } else {

#if PIXMAN_VERSION >= PIXMAN_VERSION_ENCODE(0, 21, 8)

            type = PIXMAN_TYPE_RGBA;

#endif

        }

    } else if (rshift < gshift && gshift < bshift) {

        if (rshift == 0) {

            type = PIXMAN_TYPE_ABGR;

        } else {

#if PIXMAN_VERSION >= PIXMAN_VERSION_ENCODE(0, 21, 8)

            type = PIXMAN_TYPE_BGRA;

#endif

        }

    }

    return type;

}


static struct omap_32khz_timer_s *omap_os_timer_init(MemoryRegion *memory,

                target_phys_addr_t base,

                qemu_irq irq, omap_clk clk)

{

    struct omap_32khz_timer_s *s = (struct omap_32khz_timer_s *)

            g_malloc0(sizeof(struct omap_32khz_timer_s));

    s->timer.irq = irq;

    s->timer.clk = clk;

    s->timer.timer = qemu_new_timer_ns(vm_clock, omap_timer_tick, &s->timer);

    omap_os_timer_reset(s);

    omap_timer_clk_setup(&s->timer);

    memory_region_init_io(&s->iomem, &omap_os_timer_ops, s,

                          "omap-os-timer", 0x800);

    memory_region_add_subregion(memory, base, &s->iomem);

    return s;

}


static void acpi_pcihp_eject_slot(AcpiPciHpState *s, unsigned bsel, unsigned slots)

{

    BusChild *kid, *next;

    int slot = ffs(slots) - 1;

    PCIBus *bus = acpi_pcihp_find_hotplug_bus(s, bsel);

    if (!bus) {

        return;

    }

    /* Mark request as complete */

    s->acpi_pcihp_pci_status[bsel].down &= ~(1U << slot);

    s->acpi_pcihp_pci_status[bsel].up &= ~(1U << slot);

    QTAILQ_FOREACH_SAFE(kid, &bus->qbus.children, sibling, next) {

        DeviceState *qdev = kid->child;

        PCIDevice *dev = PCI_DEVICE(qdev);

        if (PCI_SLOT(dev->devfn) == slot) {

            if (!acpi_pcihp_pc_no_hotplug(s, dev)) {

                object_unparent(OBJECT(qdev));

            }

        }

    }

}


static void machine_cpu_reset(MicroBlazeCPU *cpu)

{

    CPUMBState *env = &cpu->env;

    env->pvr.regs[10] = 0x0e000000; /* virtex 6 */

    /* setup pvr to match kernel setting */

    env->pvr.regs[0] |= (0x14 << 8);

    env->pvr.regs[4] = 0xc56b8000;

    env->pvr.regs[5] = 0xc56be000;

}


static int nbd_handle_list(NBDClient *client, uint32_t length)

{

    int csock;

    NBDExport *exp;

    csock = client->sock;

    if (length) {

        return nbd_send_rep(csock, NBD_REP_ERR_INVALID, NBD_OPT_LIST);

    /* For each export, send a NBD_REP_SERVER reply. */

    QTAILQ_FOREACH(exp, &exports, next) {

        if (nbd_send_rep_list(csock, exp)) {

            return -EINVAL;

    /* Finish with a NBD_REP_ACK. */

    return nbd_send_rep(csock, NBD_REP_ACK, NBD_OPT_LIST);


static void create_header32(DumpState *s, Error **errp)
{
    DiskDumpHeader32 *dh = NULL;
    KdumpSubHeader32 *kh = NULL;
    size_t size;
    uint32_t block_size;
    uint32_t sub_hdr_size;
    uint32_t bitmap_blocks;
    uint32_t status = 0;
    uint64_t offset_note;
    Error *local_err = NULL;
    /* write common header, the version of kdump-compressed format is 6th */
    size = sizeof(DiskDumpHeader32);
    dh = g_malloc0(size);
    strncpy(dh->signature, KDUMP_SIGNATURE, strlen(KDUMP_SIGNATURE));
    dh->header_version = cpu_to_dump32(s, 6);
    block_size = s->dump_info.page_size;
    dh->block_size = cpu_to_dump32(s, block_size);
    sub_hdr_size = sizeof(struct KdumpSubHeader32) + s->note_size;
    sub_hdr_size = DIV_ROUND_UP(sub_hdr_size, block_size);
    dh->sub_hdr_size = cpu_to_dump32(s, sub_hdr_size);
    /* dh->max_mapnr may be truncated, full 64bit is in kh.max_mapnr_64 */
    dh->max_mapnr = cpu_to_dump32(s, MIN(s->max_mapnr, UINT_MAX));
    dh->nr_cpus = cpu_to_dump32(s, s->nr_cpus);
    bitmap_blocks = DIV_ROUND_UP(s->len_dump_bitmap, block_size) * 2;
    dh->bitmap_blocks = cpu_to_dump32(s, bitmap_blocks);
    strncpy(dh->utsname.machine, ELF_MACHINE_UNAME, sizeof(dh->utsname.machine));
    if (s->flag_compress & DUMP_DH_COMPRESSED_ZLIB) {
        status |= DUMP_DH_COMPRESSED_ZLIB;
#ifdef CONFIG_LZO
    if (s->flag_compress & DUMP_DH_COMPRESSED_LZO) {
        status |= DUMP_DH_COMPRESSED_LZO;
#endif
#ifdef CONFIG_SNAPPY
    if (s->flag_compress & DUMP_DH_COMPRESSED_SNAPPY) {
        status |= DUMP_DH_COMPRESSED_SNAPPY;
#endif
    dh->status = cpu_to_dump32(s, status);
    if (write_buffer(s->fd, 0, dh, size) < 0) {
        error_setg(errp, "dump: failed to write disk dump header");
        goto out;
    /* write sub header */
    size = sizeof(KdumpSubHeader32);
    kh = g_malloc0(size);
    /* 64bit max_mapnr_64 */
    kh->max_mapnr_64 = cpu_to_dump64(s, s->max_mapnr);
    kh->phys_base = cpu_to_dump32(s, s->dump_info.phys_base);
    kh->dump_level = cpu_to_dump32(s, DUMP_LEVEL);
    offset_note = DISKDUMP_HEADER_BLOCKS * block_size + size;
    kh->offset_note = cpu_to_dump64(s, offset_note);
    kh->note_size = cpu_to_dump32(s, s->note_size);
    if (write_buffer(s->fd, DISKDUMP_HEADER_BLOCKS *
                     block_size, kh, size) < 0) {
        error_setg(errp, "dump: failed to write kdump sub header");
        goto out;
    /* write note */
    s->note_buf = g_malloc0(s->note_size);
    s->note_buf_offset = 0;
    /* use s->note_buf to store notes temporarily */
    write_elf32_notes(buf_write_note, s, &local_err);
    if (local_err) {
        error_propagate(errp, local_err);
        goto out;
    if (write_buffer(s->fd, offset_note, s->note_buf,
                     s->note_size) < 0) {
        error_setg(errp, "dump: failed to write notes");
        goto out;
    /* get offset of dump_bitmap */
    s->offset_dump_bitmap = (DISKDUMP_HEADER_BLOCKS + sub_hdr_size) *
                             block_size;
    /* get offset of page */
    s->offset_page = (DISKDUMP_HEADER_BLOCKS + sub_hdr_size + bitmap_blocks) *
                     block_size;
out:
    g_free(dh);
    g_free(kh);
    g_free(s->note_buf);


static void test_qemu_strtoull_invalid(void)

{

    const char *str = "   xxxx  \t abc";

    char f = 'X';

    const char *endptr = &f;

    uint64_t res = 999;

    int err;

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

    g_assert_cmpint(err, ==, 0);

    g_assert(endptr == str);

}


static void scsi_remove_request(SCSIGenericReq *r)

{

    qemu_free(r->buf);

    scsi_req_free(&r->req);

}


static int get_device_guid(

    char *name,

    int name_size,

    char *actual_name,

    int actual_name_size)

{

    LONG status;

    HKEY control_net_key;

    DWORD len;

    int i = 0;

    int stop = 0;

    status = RegOpenKeyEx(

        HKEY_LOCAL_MACHINE,

        NETWORK_CONNECTIONS_KEY,

        0,

        KEY_READ,

        &control_net_key);

    if (status != ERROR_SUCCESS) {

        return -1;

    }

    while (!stop)

    {

        char enum_name[256];

        char connection_string[256];

        HKEY connection_key;

        char name_data[256];

        DWORD name_type;

        const char name_string[] = "Name";

        len = sizeof (enum_name);

        status = RegEnumKeyEx(

            control_net_key,

            i,

            enum_name,

            &len,

            NULL,

            NULL,

            NULL,

            NULL);

        if (status == ERROR_NO_MORE_ITEMS)

            break;

        else if (status != ERROR_SUCCESS) {

            return -1;

        }

        snprintf(connection_string,

             sizeof(connection_string),

             "%s\\%s\\Connection",

             NETWORK_CONNECTIONS_KEY, enum_name);

        status = RegOpenKeyEx(

            HKEY_LOCAL_MACHINE,

            connection_string,

            0,

            KEY_READ,

            &connection_key);

        if (status == ERROR_SUCCESS) {

            len = sizeof (name_data);

            status = RegQueryValueEx(

                connection_key,

                name_string,

                NULL,

                &name_type,

                (LPBYTE)name_data,

                &len);

            if (status != ERROR_SUCCESS || name_type != REG_SZ) {

                    return -1;

            }

            else {

                if (is_tap_win32_dev(enum_name)) {

                    snprintf(name, name_size, "%s", enum_name);

                    if (actual_name) {

                        if (strcmp(actual_name, "") != 0) {

                            if (strcmp(name_data, actual_name) != 0) {

                                RegCloseKey (connection_key);

                                ++i;

                                continue;

                            }

                        }

                        else {

                            snprintf(actual_name, actual_name_size, "%s", name_data);

                        }

                    }

                    stop = 1;

                }

            }

            RegCloseKey (connection_key);

        }

        ++i;

    }

    RegCloseKey (control_net_key);

    if (stop == 0)

        return -1;

    return 0;

}


static void show_frame(WriterContext *w, AVFrame *frame, AVStream *stream,

                       AVFormatContext *fmt_ctx)

{

    AVBPrint pbuf;

    char val_str[128];

    const char *s;

    int i;

    av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);

    writer_print_section_header(w, SECTION_ID_FRAME);

    s = av_get_media_type_string(stream->codecpar->codec_type);

    if (s) print_str    ("media_type", s);

    else   print_str_opt("media_type", "unknown");

    print_int("stream_index",           stream->index);

    print_int("key_frame",              frame->key_frame);

    print_ts  ("pkt_pts",               frame->pts);

    print_time("pkt_pts_time",          frame->pts, &stream->time_base);

    print_ts  ("pkt_dts",               frame->pkt_dts);

    print_time("pkt_dts_time",          frame->pkt_dts, &stream->time_base);

    print_ts  ("best_effort_timestamp", frame->best_effort_timestamp);

    print_time("best_effort_timestamp_time", frame->best_effort_timestamp, &stream->time_base);

    print_duration_ts  ("pkt_duration",      frame->pkt_duration);

    print_duration_time("pkt_duration_time", frame->pkt_duration, &stream->time_base);

    if (frame->pkt_pos != -1) print_fmt    ("pkt_pos", "%"PRId64, frame->pkt_pos);

    else                      print_str_opt("pkt_pos", "N/A");

    if (frame->pkt_size != -1) print_val    ("pkt_size", frame->pkt_size, unit_byte_str);

    else                       print_str_opt("pkt_size", "N/A");

    switch (stream->codecpar->codec_type) {

        AVRational sar;

    case AVMEDIA_TYPE_VIDEO:

        print_int("width",                  frame->width);

        print_int("height",                 frame->height);

        s = av_get_pix_fmt_name(frame->format);

        if (s) print_str    ("pix_fmt", s);

        else   print_str_opt("pix_fmt", "unknown");

        sar = av_guess_sample_aspect_ratio(fmt_ctx, stream, frame);

        if (sar.num) {

            print_q("sample_aspect_ratio", sar, ':');

        } else {

            print_str_opt("sample_aspect_ratio", "N/A");

        }

        print_fmt("pict_type",              "%c", av_get_picture_type_char(frame->pict_type));

        print_int("coded_picture_number",   frame->coded_picture_number);

        print_int("display_picture_number", frame->display_picture_number);

        print_int("interlaced_frame",       frame->interlaced_frame);

        print_int("top_field_first",        frame->top_field_first);

        print_int("repeat_pict",            frame->repeat_pict);

        if (frame->color_range != AVCOL_RANGE_UNSPECIFIED)

            print_str("color_range", av_color_range_name(frame->color_range));

        else

            print_str_opt("color_range", av_color_range_name(frame->color_range));

        if (frame->colorspace != AVCOL_SPC_UNSPECIFIED)

            print_str("color_space", av_color_space_name(frame->colorspace));

        else

            print_str_opt("color_space", av_color_space_name(frame->colorspace));

        if (frame->color_primaries != AVCOL_PRI_UNSPECIFIED)

            print_str("color_primaries", av_color_primaries_name(frame->color_primaries));

        else

            print_str_opt("color_primaries", av_color_primaries_name(frame->color_primaries));

        if (frame->color_trc != AVCOL_TRC_UNSPECIFIED)

            print_str("color_transfer", av_color_transfer_name(frame->color_trc));

        else

            print_str_opt("color_transfer", av_color_transfer_name(frame->color_trc));

        if (frame->chroma_location != AVCHROMA_LOC_UNSPECIFIED)

            print_str("chroma_location", av_chroma_location_name(frame->chroma_location));

        else

            print_str_opt("chroma_location", av_chroma_location_name(frame->chroma_location));

        break;

    case AVMEDIA_TYPE_AUDIO:

        s = av_get_sample_fmt_name(frame->format);

        if (s) print_str    ("sample_fmt", s);

        else   print_str_opt("sample_fmt", "unknown");

        print_int("nb_samples",         frame->nb_samples);

        print_int("channels", frame->channels);

        if (frame->channel_layout) {

            av_bprint_clear(&pbuf);

            av_bprint_channel_layout(&pbuf, frame->channels,

                                     frame->channel_layout);

            print_str    ("channel_layout", pbuf.str);

        } else

            print_str_opt("channel_layout", "unknown");

        break;

    }

    if (do_show_frame_tags)

        show_tags(w, frame->metadata, SECTION_ID_FRAME_TAGS);

    if (do_show_log)

        show_log(w, SECTION_ID_FRAME_LOGS, SECTION_ID_FRAME_LOG, do_show_log);

    if (frame->nb_side_data) {

        writer_print_section_header(w, SECTION_ID_FRAME_SIDE_DATA_LIST);

        for (i = 0; i < frame->nb_side_data; i++) {

            AVFrameSideData *sd = frame->side_data[i];

            const char *name;

            writer_print_section_header(w, SECTION_ID_FRAME_SIDE_DATA);

            name = av_frame_side_data_name(sd->type);

            print_str("side_data_type", name ? name : "unknown");

            if (sd->type == AV_FRAME_DATA_DISPLAYMATRIX && sd->size >= 9*4) {

                writer_print_integers(w, "displaymatrix", sd->data, 9, " %11d", 3, 4, 1);

                print_int("rotation", av_display_rotation_get((int32_t *)sd->data));

            } else if (sd->type == AV_FRAME_DATA_GOP_TIMECODE && sd->size >= 8) {

                char tcbuf[AV_TIMECODE_STR_SIZE];

                av_timecode_make_mpeg_tc_string(tcbuf, *(int64_t *)(sd->data));

                print_str("timecode", tcbuf);

            } else if (sd->type == AV_FRAME_DATA_MASTERING_DISPLAY_METADATA) {

                AVMasteringDisplayMetadata *metadata = (AVMasteringDisplayMetadata *)sd->data;

                if (metadata->has_primaries) {

                    print_q("red_x", metadata->display_primaries[0][0], '/');

                    print_q("red_y", metadata->display_primaries[0][1], '/');

                    print_q("green_x", metadata->display_primaries[1][0], '/');

                    print_q("green_y", metadata->display_primaries[1][1], '/');

                    print_q("blue_x", metadata->display_primaries[2][0], '/');

                    print_q("blue_y", metadata->display_primaries[2][1], '/');

                    print_q("white_point_x", metadata->white_point[0], '/');

                    print_q("white_point_y", metadata->white_point[1], '/');

                }

                if (metadata->has_luminance) {

                    print_q("min_luminance", metadata->min_luminance, '/');

                    print_q("max_luminance", metadata->max_luminance, '/');

                }

            } else if (sd->type == AV_FRAME_DATA_CONTENT_LIGHT_LEVEL) {

                AVContentLightMetadata *metadata = (AVContentLightMetadata *)sd->data;

                print_int("max_content", metadata->MaxCLL);

                print_int("max_average", metadata->MaxFALL);

            } else if (sd->type == AV_FRAME_DATA_ICC_PROFILE) {

                AVDictionaryEntry *tag = av_dict_get(sd->metadata, "name", NULL, AV_DICT_MATCH_CASE);

                if (tag)

                    print_str(tag->key, tag->value);

                print_int("size", sd->size);

            }

            writer_print_section_footer(w);

        }

        writer_print_section_footer(w);

    }

    writer_print_section_footer(w);

    av_bprint_finalize(&pbuf, NULL);

    fflush(stdout);

}


void ff_xface_generate_face(uint8_t *dst, uint8_t * const src)

{

    int h, i, j, k, l, m;

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

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

            h = i + j * XFACE_WIDTH;

            k = 0;

            /*

               Compute k, encoding the bits *before* the current one, contained in the

               image buffer. That is, given the grid:

                l      i

                |      |

                v      v

               +--+--+--+--+--+

          m -> | 1| 2| 3| 4| 5|

               +--+--+--+--+--+

               | 6| 7| 8| 9|10|

               +--+--+--+--+--+

          j -> |11|12| *|  |  |

               +--+--+--+--+--+

               the value k for the pixel marked as "*" will contain the bit encoding of

               the values in the matrix marked from "1" to "12". In case the pixel is

               near the border of the grid, the number of values contained within the

               grid will be lesser than 12.

             */

            for (l = i - 2; l <= i + 2; l++) {

                for (m = j - 2; m <= j; m++) {

                    if (l >= i && m == j)

                        continue;

                    if (l > 0 && l <= XFACE_WIDTH && m > 0)

                        k = 2*k + src[l + m * XFACE_WIDTH];

                }

            }

            /*

              Use the guess for the given position and the computed value of k.

              The following table shows the number of digits in k, depending on

              the position of the pixel, and shows the corresponding guess table

              to use:

                 i=1  i=2  i=3       i=w-1 i=w

               +----+----+----+ ... +----+----+

           j=1 |  0 |  1 |  2 |     |  2 |  2 |

               |g22 |g12 |g02 |     |g42 |g32 |

               +----+----+----+ ... +----+----+

           j=2 |  3 |  5 |  7 |     |  6 |  5 |

               |g21 |g11 |g01 |     |g41 |g31 |

               +----+----+----+ ... +----+----+

           j=3 |  5 |  9 | 12 |     | 10 |  8 |

               |g20 |g10 |g00 |     |g40 |g30 |

               +----+----+----+ ... +----+----+

            */

#define GEN(table) dst[h] ^= (table[k>>3]>>(7-(k&7)))&1

            switch (i) {

            case 1:

                switch (j) {

                case 1:  GEN(g_22); break;

                case 2:  GEN(g_21); break;

                default: GEN(g_20); break;

                }

                break;

            case 2:

                switch (j) {

                case 1:  GEN(g_12); break;

                case 2:  GEN(g_11); break;

                default: GEN(g_10); break;

                }

                break;

            case XFACE_WIDTH - 1:

                switch (j) {

                case 1:  GEN(g_42); break;

                case 2:  GEN(g_41); break;

                default: GEN(g_40); break;

                }

                break;

            case XFACE_WIDTH:

                switch (j) {

                case 1:  GEN(g_32); break;

                case 2:  GEN(g_31); break;

                default: GEN(g_30); break;

                }

                break;

            default:

                switch (j) {

                case 1:  GEN(g_02); break;

                case 2:  GEN(g_01); break;

                default: GEN(g_00); break;

                }

                break;

            }

        }

    }

}


void ff_imdct_half_3dn2(FFTContext *s, FFTSample *output, const FFTSample *input)

{

    x86_reg j, k;

    long n = s->mdct_size;

    long n2 = n >> 1;

    long n4 = n >> 2;

    long n8 = n >> 3;

    const uint16_t *revtab = s->revtab;

    const FFTSample *tcos = s->tcos;

    const FFTSample *tsin = s->tsin;

    const FFTSample *in1, *in2;

    FFTComplex *z = (FFTComplex *)output;

    /* pre rotation */

    in1 = input;

    in2 = input + n2 - 1;

#ifdef EMULATE_3DNOWEXT

    __asm__ volatile("movd %0, %%mm7" ::"r"(1<<31));

#endif

    for(k = 0; k < n4; k++) {

        // FIXME a single block is faster, but gcc 2.95 and 3.4.x on 32bit can't compile it

        __asm__ volatile(

            "movd         %0, %%mm0 \n"

            "movd         %2, %%mm1 \n"

            "punpckldq    %1, %%mm0 \n"

            "punpckldq    %3, %%mm1 \n"

            "movq      %%mm0, %%mm2 \n"

            PSWAPD(    %%mm1, %%mm3 )

            "pfmul     %%mm1, %%mm0 \n"

            "pfmul     %%mm3, %%mm2 \n"

#ifdef EMULATE_3DNOWEXT

            "movq      %%mm0, %%mm1 \n"

            "punpckhdq %%mm2, %%mm0 \n"

            "punpckldq %%mm2, %%mm1 \n"

            "pxor      %%mm7, %%mm0 \n"

            "pfadd     %%mm1, %%mm0 \n"

#else

            "pfpnacc   %%mm2, %%mm0 \n"

#endif

            ::"m"(in2[-2*k]), "m"(in1[2*k]),

              "m"(tcos[k]), "m"(tsin[k])

        );

        __asm__ volatile(

            "movq    %%mm0, %0    \n\t"

            :"=m"(z[revtab[k]])

        );

    }

    ff_fft_dispatch_3dn2(z, s->nbits);

#define CMUL(j,mm0,mm1)\

        "movq  (%2,"#j",2), %%mm6 \n"\

        "movq 8(%2,"#j",2), "#mm0"\n"\

        "movq        %%mm6, "#mm1"\n"\

        "movq        "#mm0",%%mm7 \n"\

        "pfmul   (%3,"#j"), %%mm6 \n"\

        "pfmul   (%4,"#j"), "#mm0"\n"\

        "pfmul   (%4,"#j"), "#mm1"\n"\

        "pfmul   (%3,"#j"), %%mm7 \n"\

        "pfsub       %%mm6, "#mm0"\n"\

        "pfadd       %%mm7, "#mm1"\n"

    /* post rotation */

    j = -n2;

    k = n2-8;

    __asm__ volatile(

        "1: \n"

        CMUL(%0, %%mm0, %%mm1)

        CMUL(%1, %%mm2, %%mm3)

        "movd   %%mm0,  (%2,%0,2) \n"

        "movd   %%mm1,12(%2,%1,2) \n"

        "movd   %%mm2,  (%2,%1,2) \n"

        "movd   %%mm3,12(%2,%0,2) \n"

        "psrlq  $32,   %%mm0 \n"

        "psrlq  $32,   %%mm1 \n"

        "psrlq  $32,   %%mm2 \n"

        "psrlq  $32,   %%mm3 \n"

        "movd   %%mm0, 8(%2,%0,2) \n"

        "movd   %%mm1, 4(%2,%1,2) \n"

        "movd   %%mm2, 8(%2,%1,2) \n"

        "movd   %%mm3, 4(%2,%0,2) \n"

        "sub $8, %1 \n"

        "add $8, %0 \n"

        "jl 1b \n"

        :"+r"(j), "+r"(k)

        :"r"(z+n8), "r"(tcos+n8), "r"(tsin+n8)

        :"memory"

    );

    __asm__ volatile("femms");

}


static av_cold int decimate_init(AVFilterContext *ctx)

{

    DecimateContext *dm = ctx->priv;

    AVFilterPad pad = {

        .name         = av_strdup("main"),

        .type         = AVMEDIA_TYPE_VIDEO,

        .filter_frame = filter_frame,

        .config_props = config_input,

    };

    if (!pad.name)

        return AVERROR(ENOMEM);

    ff_insert_inpad(ctx, INPUT_MAIN, &pad);

    if (dm->ppsrc) {

        pad.name = av_strdup("clean_src");

        pad.config_props = NULL;

        if (!pad.name)

            return AVERROR(ENOMEM);

        ff_insert_inpad(ctx, INPUT_CLEANSRC, &pad);

    }

    if ((dm->blockx & (dm->blockx - 1)) ||

        (dm->blocky & (dm->blocky - 1))) {

        av_log(ctx, AV_LOG_ERROR, "blockx and blocky settings must be power of two\n");

        return AVERROR(EINVAL);

    }

    dm->start_pts = AV_NOPTS_VALUE;

    return 0;

}


static int get_qcc(J2kDecoderContext *s, int n, J2kQuantStyle *q, uint8_t *properties)

{

    int compno;

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

        return AVERROR(EINVAL);

    compno = bytestream_get_byte(&s->buf);

    properties[compno] |= HAD_QCC;

    return get_qcx(s, n-1, q+compno);

}


void migration_incoming_state_destroy(void)
{
    struct MigrationIncomingState *mis = migration_incoming_get_current();
    qemu_event_destroy(&mis->main_thread_load_event);


static QString *read_line(FILE *file, char *key)

{

    char value[128];

    if (fscanf(file, "%s%s", key, value) == EOF)

        return NULL;

    remove_dots(key);

    return qstring_from_str(value);

}


av_cold void ff_intrax8_common_init(IntraX8Context *w, MpegEncContext *const s)

{

    w->s = s;

    x8_vlc_init();

    assert(s->mb_width > 0);

    // two rows, 2 blocks per cannon mb

    w->prediction_table = av_mallocz(s->mb_width * 2 * 2);

    ff_init_scantable(s->idsp.idct_permutation, &w->scantable[0],

                      ff_wmv1_scantable[0]);

    ff_init_scantable(s->idsp.idct_permutation, &w->scantable[1],

                      ff_wmv1_scantable[2]);

    ff_init_scantable(s->idsp.idct_permutation, &w->scantable[2],

                      ff_wmv1_scantable[3]);

    ff_intrax8dsp_init(&w->dsp);

}


static av_cold int ffat_close_encoder(AVCodecContext *avctx)

{

    ATDecodeContext *at = avctx->priv_data;

    AudioConverterDispose(at->converter);

    av_frame_unref(&at->new_in_frame);

    av_frame_unref(&at->in_frame);

    ff_af_queue_close(&at->afq);

    return 0;

}


static int udp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,

                           uint8_t *buf, int buf_size, int64_t wait_end)

{

    RTSPState *rt = s->priv_data;

    RTSPStream *rtsp_st;

    int n, i, ret, timeout_cnt = 0;

    struct pollfd *p = rt->p;

    int *fds = NULL, fdsnum, fdsidx;

    if (!p) {

        p = rt->p = av_malloc_array(2 * (rt->nb_rtsp_streams + 1), sizeof(struct pollfd));

        if (!p)

            return AVERROR(ENOMEM);

        if (rt->rtsp_hd) {

            p[rt->max_p].fd = ffurl_get_file_handle(rt->rtsp_hd);

            p[rt->max_p++].events = POLLIN;

        }

        for (i = 0; i < rt->nb_rtsp_streams; i++) {

            rtsp_st = rt->rtsp_streams[i];

            if (rtsp_st->rtp_handle) {

                if (ret = ffurl_get_multi_file_handle(rtsp_st->rtp_handle,

                                                      &fds, &fdsnum)) {

                    av_log(s, AV_LOG_ERROR, "Unable to recover rtp ports\n");

                    return ret;

                }

                if (fdsnum != 2) {

                    av_log(s, AV_LOG_ERROR,

                           "Number of fds %d not supported\n", fdsnum);

                    return AVERROR_INVALIDDATA;

                }

                for (fdsidx = 0; fdsidx < fdsnum; fdsidx++) {

                    p[rt->max_p].fd       = fds[fdsidx];

                    p[rt->max_p++].events = POLLIN;

                }

                av_free(fds);

            }

        }

    }

    for (;;) {

        if (ff_check_interrupt(&s->interrupt_callback))

            return AVERROR_EXIT;

        if (wait_end && wait_end - av_gettime_relative() < 0)

            return AVERROR(EAGAIN);

        n = poll(p, rt->max_p, POLL_TIMEOUT_MS);

        if (n > 0) {

            int j = rt->rtsp_hd ? 1 : 0;

            timeout_cnt = 0;

            for (i = 0; i < rt->nb_rtsp_streams; i++) {

                rtsp_st = rt->rtsp_streams[i];

                if (rtsp_st->rtp_handle) {

                    if (p[j].revents & POLLIN || p[j+1].revents & POLLIN) {

                        ret = ffurl_read(rtsp_st->rtp_handle, buf, buf_size);

                        if (ret > 0) {

                            *prtsp_st = rtsp_st;

                            return ret;

                        }

                    }

                    j+=2;

                }

            }

#if CONFIG_RTSP_DEMUXER

            if (rt->rtsp_hd && p[0].revents & POLLIN) {

                return parse_rtsp_message(s);

            }

#endif

        } else if (n == 0 && ++timeout_cnt >= MAX_TIMEOUTS) {

            return AVERROR(ETIMEDOUT);

        } else if (n < 0 && errno != EINTR)

            return AVERROR(errno);

    }

}


static void booke_update_fixed_timer(CPUPPCState         *env,

                                     uint8_t           target_bit,

                                     uint64_t          *next,

                                     struct QEMUTimer *timer)

{

    ppc_tb_t *tb_env = env->tb_env;

    uint64_t lapse;

    uint64_t tb;

    uint64_t period = 1 << (target_bit + 1);

    uint64_t now;

    now = qemu_get_clock_ns(vm_clock);

    tb  = cpu_ppc_get_tb(tb_env, now, tb_env->tb_offset);

    lapse = period - ((tb - (1 << target_bit)) & (period - 1));

    *next = now + muldiv64(lapse, get_ticks_per_sec(), tb_env->tb_freq);

    /* XXX: If expire time is now. We can't run the callback because we don't

     * have access to it. So we just set the timer one nanosecond later.

     */

    if (*next == now) {

        (*next)++;

    }

    qemu_mod_timer(timer, *next);

}


static void spapr_machine_init(MachineState *machine)
{
    sPAPRMachineState *spapr = SPAPR_MACHINE(machine);
    sPAPRMachineClass *smc = SPAPR_MACHINE_GET_CLASS(machine);
    const char *kernel_filename = machine->kernel_filename;
    const char *initrd_filename = machine->initrd_filename;
    PCIHostState *phb;
    int i;
    MemoryRegion *sysmem = get_system_memory();
    MemoryRegion *ram = g_new(MemoryRegion, 1);
    MemoryRegion *rma_region;
    void *rma = NULL;
    hwaddr rma_alloc_size;
    hwaddr node0_size = spapr_node0_size(machine);
    long load_limit, fw_size;
    char *filename;
    Error *resize_hpt_err = NULL;
    msi_nonbroken = true;
    QLIST_INIT(&spapr->phbs);
    QTAILQ_INIT(&spapr->pending_dimm_unplugs);
    /* Check HPT resizing availability */
    kvmppc_check_papr_resize_hpt(&resize_hpt_err);
    if (spapr->resize_hpt == SPAPR_RESIZE_HPT_DEFAULT) {
        /*
         * If the user explicitly requested a mode we should either
         * supply it, or fail completely (which we do below).  But if
         * it's not set explicitly, we reset our mode to something
         * that works
         */
        if (resize_hpt_err) {
            spapr->resize_hpt = SPAPR_RESIZE_HPT_DISABLED;
            error_free(resize_hpt_err);
            resize_hpt_err = NULL;
        } else {
            spapr->resize_hpt = smc->resize_hpt_default;
        }
    }
    assert(spapr->resize_hpt != SPAPR_RESIZE_HPT_DEFAULT);
    if ((spapr->resize_hpt != SPAPR_RESIZE_HPT_DISABLED) && resize_hpt_err) {
        /*
         * User requested HPT resize, but this host can't supply it.  Bail out
         */
        error_report_err(resize_hpt_err);
        exit(1);
    }
    /* Allocate RMA if necessary */
    rma_alloc_size = kvmppc_alloc_rma(&rma);
    if (rma_alloc_size == -1) {
        error_report("Unable to create RMA");
        exit(1);
    }
    if (rma_alloc_size && (rma_alloc_size < node0_size)) {
        spapr->rma_size = rma_alloc_size;
    } else {
        spapr->rma_size = node0_size;
        /* With KVM, we don't actually know whether KVM supports an
         * unbounded RMA (PR KVM) or is limited by the hash table size
         * (HV KVM using VRMA), so we always assume the latter
         *
         * In that case, we also limit the initial allocations for RTAS
         * etc... to 256M since we have no way to know what the VRMA size
         * is going to be as it depends on the size of the hash table
         * isn't determined yet.
         */
        if (kvm_enabled()) {
            spapr->vrma_adjust = 1;
            spapr->rma_size = MIN(spapr->rma_size, 0x10000000);
        }
        /* Actually we don't support unbounded RMA anymore since we
         * added proper emulation of HV mode. The max we can get is
         * 16G which also happens to be what we configure for PAPR
         * mode so make sure we don't do anything bigger than that
         */
        spapr->rma_size = MIN(spapr->rma_size, 0x400000000ull);
    }
    if (spapr->rma_size > node0_size) {
        error_report("Numa node 0 has to span the RMA (%#08"HWADDR_PRIx")",
                     spapr->rma_size);
        exit(1);
    }
    /* Setup a load limit for the ramdisk leaving room for SLOF and FDT */
    load_limit = MIN(spapr->rma_size, RTAS_MAX_ADDR) - FW_OVERHEAD;
    /* Set up Interrupt Controller before we create the VCPUs */
    xics_system_init(machine, XICS_IRQS_SPAPR, &error_fatal);
    /* Set up containers for ibm,client-architecture-support negotiated options
     */
    spapr->ov5 = spapr_ovec_new();
    spapr->ov5_cas = spapr_ovec_new();
    if (smc->dr_lmb_enabled) {
        spapr_ovec_set(spapr->ov5, OV5_DRCONF_MEMORY);
        spapr_validate_node_memory(machine, &error_fatal);
    }
    spapr_ovec_set(spapr->ov5, OV5_FORM1_AFFINITY);
    if (!kvm_enabled() || kvmppc_has_cap_mmu_radix()) {
        /* KVM and TCG always allow GTSE with radix... */
        spapr_ovec_set(spapr->ov5, OV5_MMU_RADIX_GTSE);
    }
    /* ... but not with hash (currently). */
    /* advertise support for dedicated HP event source to guests */
    if (spapr->use_hotplug_event_source) {
        spapr_ovec_set(spapr->ov5, OV5_HP_EVT);
    }
    /* advertise support for HPT resizing */
    if (spapr->resize_hpt != SPAPR_RESIZE_HPT_DISABLED) {
        spapr_ovec_set(spapr->ov5, OV5_HPT_RESIZE);
    }
    /* init CPUs */
    spapr_set_vsmt_mode(spapr, &error_fatal);
    spapr_init_cpus(spapr);
    if (kvm_enabled()) {
        /* Enable H_LOGICAL_CI_* so SLOF can talk to in-kernel devices */
        kvmppc_enable_logical_ci_hcalls();
        kvmppc_enable_set_mode_hcall();
        /* H_CLEAR_MOD/_REF are mandatory in PAPR, but off by default */
        kvmppc_enable_clear_ref_mod_hcalls();
    }
    /* allocate RAM */
    memory_region_allocate_system_memory(ram, NULL, "ppc_spapr.ram",
                                         machine->ram_size);
    memory_region_add_subregion(sysmem, 0, ram);
    if (rma_alloc_size && rma) {
        rma_region = g_new(MemoryRegion, 1);
        memory_region_init_ram_ptr(rma_region, NULL, "ppc_spapr.rma",
                                   rma_alloc_size, rma);
        vmstate_register_ram_global(rma_region);
        memory_region_add_subregion(sysmem, 0, rma_region);
    }
    /* initialize hotplug memory address space */
    if (machine->ram_size < machine->maxram_size) {
        ram_addr_t hotplug_mem_size = machine->maxram_size - machine->ram_size;
        /*
         * Limit the number of hotpluggable memory slots to half the number
         * slots that KVM supports, leaving the other half for PCI and other
         * devices. However ensure that number of slots doesn't drop below 32.
         */
        int max_memslots = kvm_enabled() ? kvm_get_max_memslots() / 2 :
                           SPAPR_MAX_RAM_SLOTS;
        if (max_memslots < SPAPR_MAX_RAM_SLOTS) {
            max_memslots = SPAPR_MAX_RAM_SLOTS;
        }
        if (machine->ram_slots > max_memslots) {
            error_report("Specified number of memory slots %"
                         PRIu64" exceeds max supported %d",
                         machine->ram_slots, max_memslots);
            exit(1);
        }
        spapr->hotplug_memory.base = ROUND_UP(machine->ram_size,
                                              SPAPR_HOTPLUG_MEM_ALIGN);
        memory_region_init(&spapr->hotplug_memory.mr, OBJECT(spapr),
                           "hotplug-memory", hotplug_mem_size);
        memory_region_add_subregion(sysmem, spapr->hotplug_memory.base,
                                    &spapr->hotplug_memory.mr);
    }
    if (smc->dr_lmb_enabled) {
        spapr_create_lmb_dr_connectors(spapr);
    }
    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, "spapr-rtas.bin");
    if (!filename) {
        error_report("Could not find LPAR rtas '%s'", "spapr-rtas.bin");
        exit(1);
    }
    spapr->rtas_size = get_image_size(filename);
    if (spapr->rtas_size < 0) {
        error_report("Could not get size of LPAR rtas '%s'", filename);
        exit(1);
    }
    spapr->rtas_blob = g_malloc(spapr->rtas_size);
    if (load_image_size(filename, spapr->rtas_blob, spapr->rtas_size) < 0) {
        error_report("Could not load LPAR rtas '%s'", filename);
        exit(1);
    }
    if (spapr->rtas_size > RTAS_MAX_SIZE) {
        error_report("RTAS too big ! 0x%zx bytes (max is 0x%x)",
                     (size_t)spapr->rtas_size, RTAS_MAX_SIZE);
        exit(1);
    }
    g_free(filename);
    /* Set up RTAS event infrastructure */
    spapr_events_init(spapr);
    /* Set up the RTC RTAS interfaces */
    spapr_rtc_create(spapr);
    /* Set up VIO bus */
    spapr->vio_bus = spapr_vio_bus_init();
    for (i = 0; i < MAX_SERIAL_PORTS; i++) {
        if (serial_hds[i]) {
            spapr_vty_create(spapr->vio_bus, serial_hds[i]);
        }
    }
    /* We always have at least the nvram device on VIO */
    spapr_create_nvram(spapr);
    /* Set up PCI */
    spapr_pci_rtas_init();
    phb = spapr_create_phb(spapr, 0);
    for (i = 0; i < nb_nics; i++) {
        NICInfo *nd = &nd_table[i];
        if (!nd->model) {
            nd->model = g_strdup("ibmveth");
        }
        if (strcmp(nd->model, "ibmveth") == 0) {
            spapr_vlan_create(spapr->vio_bus, nd);
        } else {
            pci_nic_init_nofail(&nd_table[i], phb->bus, nd->model, NULL);
        }
    }
    for (i = 0; i <= drive_get_max_bus(IF_SCSI); i++) {
        spapr_vscsi_create(spapr->vio_bus);
    }
    /* Graphics */
    if (spapr_vga_init(phb->bus, &error_fatal)) {
        spapr->has_graphics = true;
        machine->usb |= defaults_enabled() && !machine->usb_disabled;
    }
    if (machine->usb) {
        if (smc->use_ohci_by_default) {
            pci_create_simple(phb->bus, -1, "pci-ohci");
        } else {
            pci_create_simple(phb->bus, -1, "nec-usb-xhci");
        }
        if (spapr->has_graphics) {
            USBBus *usb_bus = usb_bus_find(-1);
            usb_create_simple(usb_bus, "usb-kbd");
            usb_create_simple(usb_bus, "usb-mouse");
        }
    }
    if (spapr->rma_size < (MIN_RMA_SLOF << 20)) {
        error_report(
            "pSeries SLOF firmware requires >= %ldM guest RMA (Real Mode Area memory)",
            MIN_RMA_SLOF);
        exit(1);
    }
    if (kernel_filename) {
        uint64_t lowaddr = 0;
        spapr->kernel_size = load_elf(kernel_filename, translate_kernel_address,
                                      NULL, NULL, &lowaddr, NULL, 1,
                                      PPC_ELF_MACHINE, 0, 0);
        if (spapr->kernel_size == ELF_LOAD_WRONG_ENDIAN) {
            spapr->kernel_size = load_elf(kernel_filename,
                                          translate_kernel_address, NULL, NULL,
                                          &lowaddr, NULL, 0, PPC_ELF_MACHINE,
                                          0, 0);
            spapr->kernel_le = spapr->kernel_size > 0;
        }
        if (spapr->kernel_size < 0) {
            error_report("error loading %s: %s", kernel_filename,
                         load_elf_strerror(spapr->kernel_size));
            exit(1);
        }
        /* load initrd */
        if (initrd_filename) {
            /* Try to locate the initrd in the gap between the kernel
             * and the firmware. Add a bit of space just in case
             */
            spapr->initrd_base = (KERNEL_LOAD_ADDR + spapr->kernel_size
                                  + 0x1ffff) & ~0xffff;
            spapr->initrd_size = load_image_targphys(initrd_filename,
                                                     spapr->initrd_base,
                                                     load_limit
                                                     - spapr->initrd_base);
            if (spapr->initrd_size < 0) {
                error_report("could not load initial ram disk '%s'",
                             initrd_filename);
                exit(1);
            }
        }
    }
    if (bios_name == NULL) {
        bios_name = FW_FILE_NAME;
    }
    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);
    if (!filename) {
        error_report("Could not find LPAR firmware '%s'", bios_name);
        exit(1);
    }
    fw_size = load_image_targphys(filename, 0, FW_MAX_SIZE);
    if (fw_size <= 0) {
        error_report("Could not load LPAR firmware '%s'", filename);
        exit(1);
    }
    g_free(filename);
    /* FIXME: Should register things through the MachineState's qdev
     * interface, this is a legacy from the sPAPREnvironment structure
     * which predated MachineState but had a similar function */
    vmstate_register(NULL, 0, &vmstate_spapr, spapr);
    register_savevm_live(NULL, "spapr/htab", -1, 1,
                         &savevm_htab_handlers, spapr);
    qemu_register_boot_set(spapr_boot_set, spapr);
    if (kvm_enabled()) {
        /* to stop and start vmclock */
        qemu_add_vm_change_state_handler(cpu_ppc_clock_vm_state_change,
                                         &spapr->tb);
        kvmppc_spapr_enable_inkernel_multitce();
    }
}


static int append_flv_data(RTMPContext *rt, RTMPPacket *pkt, int skip)

{

    int old_flv_size, ret;

    PutByteContext pbc;

    const uint8_t *data = pkt->data + skip;

    const int size      = pkt->size - skip;

    uint32_t ts         = pkt->timestamp;

    if (pkt->type == RTMP_PT_AUDIO) {

        rt->has_audio = 1;

    } else if (pkt->type == RTMP_PT_VIDEO) {

        rt->has_video = 1;

    }

    old_flv_size = update_offset(rt, size + 15);

    if ((ret = av_reallocp(&rt->flv_data, rt->flv_size)) < 0) {

        rt->flv_size = rt->flv_off = 0;

        return ret;

    }

    bytestream2_init_writer(&pbc, rt->flv_data, rt->flv_size);

    bytestream2_skip_p(&pbc, old_flv_size);

    bytestream2_put_byte(&pbc, pkt->type);

    bytestream2_put_be24(&pbc, size);

    bytestream2_put_be24(&pbc, ts);

    bytestream2_put_byte(&pbc, ts >> 24);

    bytestream2_put_be24(&pbc, 0);

    bytestream2_put_buffer(&pbc, data, size);

    bytestream2_put_be32(&pbc, 0);

    return 0;

}