static int qcow2_do_open(BlockDriverState *bs, QDict *options, int flags,
                         Error **errp)
{
    BDRVQcow2State *s = bs->opaque;
    unsigned int len, i;
    int ret = 0;
    QCowHeader header;
    Error *local_err = NULL;
    uint64_t ext_end;
    uint64_t l1_vm_state_index;
    bool update_header = false;
    ret = bdrv_pread(bs->file, 0, &header, sizeof(header));
    if (ret < 0) {
        error_setg_errno(errp, -ret, "Could not read qcow2 header");
    be32_to_cpus(&header.magic);
    be32_to_cpus(&header.version);
    be64_to_cpus(&header.backing_file_offset);
    be32_to_cpus(&header.backing_file_size);
    be64_to_cpus(&header.size);
    be32_to_cpus(&header.cluster_bits);
    be32_to_cpus(&header.crypt_method);
    be64_to_cpus(&header.l1_table_offset);
    be32_to_cpus(&header.l1_size);
    be64_to_cpus(&header.refcount_table_offset);
    be32_to_cpus(&header.refcount_table_clusters);
    be64_to_cpus(&header.snapshots_offset);
    be32_to_cpus(&header.nb_snapshots);
    if (header.magic != QCOW_MAGIC) {
        error_setg(errp, "Image is not in qcow2 format");
    if (header.version < 2 || header.version > 3) {
        error_setg(errp, "Unsupported qcow2 version %" PRIu32, header.version);
        ret = -ENOTSUP;
    s->qcow_version = header.version;
    /* Initialise cluster size */
    if (header.cluster_bits < MIN_CLUSTER_BITS ||
        header.cluster_bits > MAX_CLUSTER_BITS) {
        error_setg(errp, "Unsupported cluster size: 2^%" PRIu32,
                   header.cluster_bits);
    s->cluster_bits = header.cluster_bits;
    s->cluster_size = 1 << s->cluster_bits;
    s->cluster_sectors = 1 << (s->cluster_bits - BDRV_SECTOR_BITS);
    /* Initialise version 3 header fields */
    if (header.version == 2) {
        header.incompatible_features    = 0;
        header.compatible_features      = 0;
        header.autoclear_features       = 0;
        header.refcount_order           = 4;
        header.header_length            = 72;
    } else {
        be64_to_cpus(&header.incompatible_features);
        be64_to_cpus(&header.compatible_features);
        be64_to_cpus(&header.autoclear_features);
        be32_to_cpus(&header.refcount_order);
        be32_to_cpus(&header.header_length);
        if (header.header_length < 104) {
            error_setg(errp, "qcow2 header too short");
    if (header.header_length > s->cluster_size) {
        error_setg(errp, "qcow2 header exceeds cluster size");
    if (header.header_length > sizeof(header)) {
        s->unknown_header_fields_size = header.header_length - sizeof(header);
        s->unknown_header_fields = g_malloc(s->unknown_header_fields_size);
        ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields,
                         s->unknown_header_fields_size);
        if (ret < 0) {
            error_setg_errno(errp, -ret, "Could not read unknown qcow2 header "
                             "fields");
    if (header.backing_file_offset > s->cluster_size) {
        error_setg(errp, "Invalid backing file offset");
    if (header.backing_file_offset) {
        ext_end = header.backing_file_offset;
    } else {
        ext_end = 1 << header.cluster_bits;
    /* Handle feature bits */
    s->incompatible_features    = header.incompatible_features;
    s->compatible_features      = header.compatible_features;
    s->autoclear_features       = header.autoclear_features;
    if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) {
        void *feature_table = NULL;
        qcow2_read_extensions(bs, header.header_length, ext_end,
                              &feature_table, flags, NULL, NULL);
        report_unsupported_feature(errp, feature_table,
                                   s->incompatible_features &
                                   ~QCOW2_INCOMPAT_MASK);
        ret = -ENOTSUP;
        g_free(feature_table);
    if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) {
        /* Corrupt images may not be written to unless they are being repaired
         */
        if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) {
            error_setg(errp, "qcow2: Image is corrupt; cannot be opened "
                       "read/write");
            ret = -EACCES;
    /* Check support for various header values */
    if (header.refcount_order > 6) {
        error_setg(errp, "Reference count entry width too large; may not "
                   "exceed 64 bits");
    s->refcount_order = header.refcount_order;
    s->refcount_bits = 1 << s->refcount_order;
    s->refcount_max = UINT64_C(1) << (s->refcount_bits - 1);
    s->refcount_max += s->refcount_max - 1;
    s->crypt_method_header = header.crypt_method;
    if (s->crypt_method_header) {
        if (bdrv_uses_whitelist() &&
            s->crypt_method_header == QCOW_CRYPT_AES) {
            error_setg(errp,
                       "Use of AES-CBC encrypted qcow2 images is no longer "
                       "supported in system emulators");
            error_append_hint(errp,
                              "You can use 'qemu-img convert' to convert your "
                              "image to an alternative supported format, such "
                              "as unencrypted qcow2, or raw with the LUKS "
                              "format instead.\n");
            ret = -ENOSYS;
        if (s->crypt_method_header == QCOW_CRYPT_AES) {
            s->crypt_physical_offset = false;
        } else {
            /* Assuming LUKS and any future crypt methods we
             * add will all use physical offsets, due to the
             * fact that the alternative is insecure...  */
            s->crypt_physical_offset = true;
        bs->encrypted = true;
    s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */
    s->l2_size = 1 << s->l2_bits;
    /* 2^(s->refcount_order - 3) is the refcount width in bytes */
    s->refcount_block_bits = s->cluster_bits - (s->refcount_order - 3);
    s->refcount_block_size = 1 << s->refcount_block_bits;
    bs->total_sectors = header.size / 512;
    s->csize_shift = (62 - (s->cluster_bits - 8));
    s->csize_mask = (1 << (s->cluster_bits - 8)) - 1;
    s->cluster_offset_mask = (1LL << s->csize_shift) - 1;
    s->refcount_table_offset = header.refcount_table_offset;
    s->refcount_table_size =
        header.refcount_table_clusters << (s->cluster_bits - 3);
    if (header.refcount_table_clusters > qcow2_max_refcount_clusters(s)) {
        error_setg(errp, "Reference count table too large");
    ret = validate_table_offset(bs, s->refcount_table_offset,
                                s->refcount_table_size, sizeof(uint64_t));
    if (ret < 0) {
        error_setg(errp, "Invalid reference count table offset");
    /* Snapshot table offset/length */
    if (header.nb_snapshots > QCOW_MAX_SNAPSHOTS) {
        error_setg(errp, "Too many snapshots");
    ret = validate_table_offset(bs, header.snapshots_offset,
                                header.nb_snapshots,
                                sizeof(QCowSnapshotHeader));
    if (ret < 0) {
        error_setg(errp, "Invalid snapshot table offset");
    /* read the level 1 table */
    if (header.l1_size > QCOW_MAX_L1_SIZE / sizeof(uint64_t)) {
        error_setg(errp, "Active L1 table too large");
        ret = -EFBIG;
    s->l1_size = header.l1_size;
    l1_vm_state_index = size_to_l1(s, header.size);
    if (l1_vm_state_index > INT_MAX) {
        error_setg(errp, "Image is too big");
        ret = -EFBIG;
    s->l1_vm_state_index = l1_vm_state_index;
    /* the L1 table must contain at least enough entries to put
       header.size bytes */
    if (s->l1_size < s->l1_vm_state_index) {
        error_setg(errp, "L1 table is too small");
    ret = validate_table_offset(bs, header.l1_table_offset,
                                header.l1_size, sizeof(uint64_t));
    if (ret < 0) {
        error_setg(errp, "Invalid L1 table offset");
    s->l1_table_offset = header.l1_table_offset;
    if (s->l1_size > 0) {
        s->l1_table = qemu_try_blockalign(bs->file->bs,
            align_offset(s->l1_size * sizeof(uint64_t), 512));
        if (s->l1_table == NULL) {
            error_setg(errp, "Could not allocate L1 table");
            ret = -ENOMEM;
        ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table,
                         s->l1_size * sizeof(uint64_t));
        if (ret < 0) {
            error_setg_errno(errp, -ret, "Could not read L1 table");
        for(i = 0;i < s->l1_size; i++) {
            be64_to_cpus(&s->l1_table[i]);
    /* Parse driver-specific options */
    ret = qcow2_update_options(bs, options, flags, errp);
    if (ret < 0) {
    s->cluster_cache_offset = -1;
    s->flags = flags;
    ret = qcow2_refcount_init(bs);
    if (ret != 0) {
        error_setg_errno(errp, -ret, "Could not initialize refcount handling");
    QLIST_INIT(&s->cluster_allocs);
    QTAILQ_INIT(&s->discards);
    /* read qcow2 extensions */
    if (qcow2_read_extensions(bs, header.header_length, ext_end, NULL,
                              flags, &update_header, &local_err)) {
        error_propagate(errp, local_err);
    /* qcow2_read_extension may have set up the crypto context
     * if the crypt method needs a header region, some methods
     * don't need header extensions, so must check here
     */
    if (s->crypt_method_header && !s->crypto) {
        if (s->crypt_method_header == QCOW_CRYPT_AES) {
            unsigned int cflags = 0;
            if (flags & BDRV_O_NO_IO) {
                cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;
            s->crypto = qcrypto_block_open(s->crypto_opts, "encrypt.",
                                           NULL, NULL, cflags, errp);
            if (!s->crypto) {
        } else if (!(flags & BDRV_O_NO_IO)) {
            error_setg(errp, "Missing CRYPTO header for crypt method %d",
                       s->crypt_method_header);
    /* read the backing file name */
    if (header.backing_file_offset != 0) {
        len = header.backing_file_size;
        if (len > MIN(1023, s->cluster_size - header.backing_file_offset) ||
            len >= sizeof(bs->backing_file)) {
            error_setg(errp, "Backing file name too long");
        ret = bdrv_pread(bs->file, header.backing_file_offset,
                         bs->backing_file, len);
        if (ret < 0) {
            error_setg_errno(errp, -ret, "Could not read backing file name");
        bs->backing_file[len] = '\0';
        s->image_backing_file = g_strdup(bs->backing_file);
    /* Internal snapshots */
    s->snapshots_offset = header.snapshots_offset;
    s->nb_snapshots = header.nb_snapshots;
    ret = qcow2_read_snapshots(bs);
    if (ret < 0) {
        error_setg_errno(errp, -ret, "Could not read snapshots");
    /* Clear unknown autoclear feature bits */
    update_header |= s->autoclear_features & ~QCOW2_AUTOCLEAR_MASK;
    update_header =
        update_header && !bs->read_only && !(flags & BDRV_O_INACTIVE);
    if (update_header) {
        s->autoclear_features &= QCOW2_AUTOCLEAR_MASK;
    if (qcow2_load_autoloading_dirty_bitmaps(bs, &local_err)) {
        update_header = false;
    if (local_err != NULL) {
        error_propagate(errp, local_err);
    if (update_header) {
        ret = qcow2_update_header(bs);
        if (ret < 0) {
            error_setg_errno(errp, -ret, "Could not update qcow2 header");
    /* Initialise locks */
    qemu_co_mutex_init(&s->lock);
    bs->supported_zero_flags = BDRV_REQ_MAY_UNMAP;
    /* Repair image if dirty */
    if (!(flags & (BDRV_O_CHECK | BDRV_O_INACTIVE)) && !bs->read_only &&
        (s->incompatible_features & QCOW2_INCOMPAT_DIRTY)) {
        BdrvCheckResult result = {0};
        ret = qcow2_check(bs, &result, BDRV_FIX_ERRORS | BDRV_FIX_LEAKS);
        if (ret < 0) {
            error_setg_errno(errp, -ret, "Could not repair dirty image");
#ifdef DEBUG_ALLOC
    {
        BdrvCheckResult result = {0};
        qcow2_check_refcounts(bs, &result, 0);
#endif
    return ret;
 fail:
    g_free(s->unknown_header_fields);
    cleanup_unknown_header_ext(bs);
    qcow2_free_snapshots(bs);
    qcow2_refcount_close(bs);
    qemu_vfree(s->l1_table);
    /* else pre-write overlap checks in cache_destroy may crash */
    s->l1_table = NULL;
    cache_clean_timer_del(bs);
    if (s->l2_table_cache) {
        qcow2_cache_destroy(bs, s->l2_table_cache);
    if (s->refcount_block_cache) {
        qcow2_cache_destroy(bs, s->refcount_block_cache);
    qcrypto_block_free(s->crypto);
    qapi_free_QCryptoBlockOpenOptions(s->crypto_opts);
    return ret;


static void qemu_kvm_init_cpu_signals(CPUState *env)

{

    int r;

    sigset_t set;

    struct sigaction sigact;

    memset(&sigact, 0, sizeof(sigact));

    sigact.sa_handler = dummy_signal;

    sigaction(SIG_IPI, &sigact, NULL);

#ifdef CONFIG_IOTHREAD

    pthread_sigmask(SIG_BLOCK, NULL, &set);

    sigdelset(&set, SIG_IPI);

    sigdelset(&set, SIGBUS);

    r = kvm_set_signal_mask(env, &set);

    if (r) {

        fprintf(stderr, "kvm_set_signal_mask: %s\n", strerror(-r));

        exit(1);

    }

#else

    sigemptyset(&set);

    sigaddset(&set, SIG_IPI);

    sigaddset(&set, SIGIO);

    sigaddset(&set, SIGALRM);

    pthread_sigmask(SIG_BLOCK, &set, NULL);

    pthread_sigmask(SIG_BLOCK, NULL, &set);

    sigdelset(&set, SIGIO);

    sigdelset(&set, SIGALRM);

#endif

    sigdelset(&set, SIG_IPI);

    sigdelset(&set, SIGBUS);

    r = kvm_set_signal_mask(env, &set);

    if (r) {

        fprintf(stderr, "kvm_set_signal_mask: %s\n", strerror(-r));

        exit(1);

    }

}


static inline void vmxnet3_ring_write_curr_cell(Vmxnet3Ring *ring, void *buff)

{

    vmw_shmem_write(vmxnet3_ring_curr_cell_pa(ring), buff, ring->cell_size);

}


static uint16_t roundToInt16(int64_t f){

	int r= (f + (1<<15))>>16;

	     if(r<-0x7FFF) return 0x8000;

	else if(r> 0x7FFF) return 0x7FFF;

	else               return r;

}


static int decode_band_hdr(IVI4DecContext *ctx, IVIBandDesc *band,

                           AVCodecContext *avctx)

{

    int plane, band_num, indx, transform_id, scan_indx;

    int i;

    int quant_mat;

    plane    = get_bits(&ctx->gb, 2);

    band_num = get_bits(&ctx->gb, 4);

    if (band->plane != plane || band->band_num != band_num) {

        av_log(avctx, AV_LOG_ERROR, "Invalid band header sequence!\n");

        return AVERROR_INVALIDDATA;

    }

    band->is_empty = get_bits1(&ctx->gb);

    if (!band->is_empty) {

        /* skip header size

         * If header size is not given, header size is 4 bytes. */

        if (get_bits1(&ctx->gb))

            skip_bits(&ctx->gb, 16);

        band->is_halfpel = get_bits(&ctx->gb, 2);

        if (band->is_halfpel >= 2) {

            av_log(avctx, AV_LOG_ERROR, "Invalid/unsupported mv resolution: %d!\n",

                   band->is_halfpel);

            return AVERROR_INVALIDDATA;

        }

#if IVI4_STREAM_ANALYSER

        if (!band->is_halfpel)

            ctx->uses_fullpel = 1;

#endif

        band->checksum_present = get_bits1(&ctx->gb);

        if (band->checksum_present)

            band->checksum = get_bits(&ctx->gb, 16);

        indx = get_bits(&ctx->gb, 2);

        if (indx == 3) {

            av_log(avctx, AV_LOG_ERROR, "Invalid block size!\n");

            return AVERROR_INVALIDDATA;

        }

        band->mb_size  = 16 >> indx;

        band->blk_size = 8 >> (indx >> 1);

        band->inherit_mv     = get_bits1(&ctx->gb);

        band->inherit_qdelta = get_bits1(&ctx->gb);

        band->glob_quant = get_bits(&ctx->gb, 5);

        if (!get_bits1(&ctx->gb) || ctx->frame_type == FRAMETYPE_INTRA) {

            transform_id = get_bits(&ctx->gb, 5);

            if (transform_id >= FF_ARRAY_ELEMS(transforms) ||

                !transforms[transform_id].inv_trans) {

                av_log_ask_for_sample(avctx, "Unimplemented transform: %d!\n", transform_id);

                return AVERROR_PATCHWELCOME;

            }

            if ((transform_id >= 7 && transform_id <= 9) ||

                 transform_id == 17) {

                av_log_ask_for_sample(avctx, "DCT transform not supported yet!\n");

                return AVERROR_PATCHWELCOME;

            }

            if (transform_id < 10 && band->blk_size < 8) {

                av_log(avctx, AV_LOG_ERROR, "wrong transform size!\n");

                return AVERROR_INVALIDDATA;

            }

#if IVI4_STREAM_ANALYSER

            if ((transform_id >= 0 && transform_id <= 2) || transform_id == 10)

                ctx->uses_haar = 1;

#endif

            band->inv_transform = transforms[transform_id].inv_trans;

            band->dc_transform  = transforms[transform_id].dc_trans;

            band->is_2d_trans   = transforms[transform_id].is_2d_trans;

            band->transform_size= (transform_id < 10) ? 8 : 4;

            scan_indx = get_bits(&ctx->gb, 4);

            if ((scan_indx>4 && scan_indx<10) != (band->blk_size==4)) {

                av_log(avctx, AV_LOG_ERROR, "mismatching scan table!\n");

                return AVERROR_INVALIDDATA;

            }

            if (scan_indx == 15) {

                av_log(avctx, AV_LOG_ERROR, "Custom scan pattern encountered!\n");

                return AVERROR_INVALIDDATA;

            }

            band->scan = scan_index_to_tab[scan_indx];

            quant_mat = get_bits(&ctx->gb, 5);

            if (quant_mat == 31) {

                av_log(avctx, AV_LOG_ERROR, "Custom quant matrix encountered!\n");

                return AVERROR_INVALIDDATA;

            }

            if (quant_mat > 21) {

                av_log(avctx, AV_LOG_ERROR, "Invalid quant matrix encountered!\n");

                return AVERROR_INVALIDDATA;

            }

            band->quant_mat = quant_mat;

        }

        /* decode block huffman codebook */

        if (ff_ivi_dec_huff_desc(&ctx->gb, get_bits1(&ctx->gb), IVI_BLK_HUFF,

                                 &band->blk_vlc, avctx))

            return AVERROR_INVALIDDATA;

        /* select appropriate rvmap table for this band */

        band->rvmap_sel = get_bits1(&ctx->gb) ? get_bits(&ctx->gb, 3) : 8;

        /* decode rvmap probability corrections if any */

        band->num_corr = 0; /* there is no corrections */

        if (get_bits1(&ctx->gb)) {

            band->num_corr = get_bits(&ctx->gb, 8); /* get number of correction pairs */

            if (band->num_corr > 61) {

                av_log(avctx, AV_LOG_ERROR, "Too many corrections: %d\n",

                       band->num_corr);

                return AVERROR_INVALIDDATA;

            }

            /* read correction pairs */

            for (i = 0; i < band->num_corr * 2; i++)

                band->corr[i] = get_bits(&ctx->gb, 8);

        }

    }

    if (band->blk_size == 8) {

        band->intra_base = &ivi4_quant_8x8_intra[quant_index_to_tab[band->quant_mat]][0];

        band->inter_base = &ivi4_quant_8x8_inter[quant_index_to_tab[band->quant_mat]][0];

    } else {

        band->intra_base = &ivi4_quant_4x4_intra[quant_index_to_tab[band->quant_mat]][0];

        band->inter_base = &ivi4_quant_4x4_inter[quant_index_to_tab[band->quant_mat]][0];

    }

    /* Indeo 4 doesn't use scale tables */

    band->intra_scale = NULL;

    band->inter_scale = NULL;

    align_get_bits(&ctx->gb);

    if (!band->scan) {

        av_log(avctx, AV_LOG_ERROR, "band->scan not set\n");

        return AVERROR_INVALIDDATA;

    }

    return 0;

}


static void scale_coefficients(AC3EncodeContext *s)

{

    /* scaling/conversion is obviously not needed for the fixed-point encoder

       since the coefficients are already fixed-point. */

    return;

}


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

                       const uint8_t *src, const uint8_t *src_end)

{

    const uint8_t *frame_start = frame;

    const uint8_t *frame_end   = frame + width * height;

    int mask = 0x10000, bitbuf = 0;

    int i, v, offset, count, segments;

    segments = bytestream_get_le16(&src);

    while (segments--) {

        if (mask == 0x10000) {

            if (src >= src_end)

                return -1;

            bitbuf = bytestream_get_le16(&src);

            mask = 1;

        }

        if (src_end - src < 2 || frame_end - frame < 2)

            return -1;

        if (bitbuf & mask) {

            v = bytestream_get_le16(&src);

            offset = (v & 0x1FFF) << 2;

            count = ((v >> 13) + 2) << 1;

            if (frame - frame_start < offset || frame_end - frame < count*2 + width)

                return -1;

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

                frame[0] = frame[1] =

                frame[width] = frame[width + 1] = frame[-offset];

                frame += 2;

            }

        } else if (bitbuf & (mask << 1)) {

            frame += bytestream_get_le16(&src) * 2;

        } else {

            frame[0] = frame[1] =

            frame[width] = frame[width + 1] =  *src++;

            frame += 2;

            frame[0] = frame[1] =

            frame[width] = frame[width + 1] =  *src++;

            frame += 2;

        }

        mask <<= 2;

    }

    return 0;

}


static void gen_test_cc(int cc, int label)

{

    TCGv tmp;

    TCGv tmp2;

    int inv;

    switch (cc) {

    case 0: /* eq: Z */

        tmp = load_cpu_field(ZF);

        tcg_gen_brcondi_i32(TCG_COND_EQ, tmp, 0, label);

        break;

    case 1: /* ne: !Z */

        tmp = load_cpu_field(ZF);

        tcg_gen_brcondi_i32(TCG_COND_NE, tmp, 0, label);

        break;

    case 2: /* cs: C */

        tmp = load_cpu_field(CF);

        tcg_gen_brcondi_i32(TCG_COND_NE, tmp, 0, label);

        break;

    case 3: /* cc: !C */

        tmp = load_cpu_field(CF);

        tcg_gen_brcondi_i32(TCG_COND_EQ, tmp, 0, label);

        break;

    case 4: /* mi: N */

        tmp = load_cpu_field(NF);

        tcg_gen_brcondi_i32(TCG_COND_LT, tmp, 0, label);

        break;

    case 5: /* pl: !N */

        tmp = load_cpu_field(NF);

        tcg_gen_brcondi_i32(TCG_COND_GE, tmp, 0, label);

        break;

    case 6: /* vs: V */

        tmp = load_cpu_field(VF);

        tcg_gen_brcondi_i32(TCG_COND_LT, tmp, 0, label);

        break;

    case 7: /* vc: !V */

        tmp = load_cpu_field(VF);

        tcg_gen_brcondi_i32(TCG_COND_GE, tmp, 0, label);

        break;

    case 8: /* hi: C && !Z */

        inv = gen_new_label();

        tmp = load_cpu_field(CF);

        tcg_gen_brcondi_i32(TCG_COND_EQ, tmp, 0, inv);

        dead_tmp(tmp);

        tmp = load_cpu_field(ZF);

        tcg_gen_brcondi_i32(TCG_COND_NE, tmp, 0, label);

        gen_set_label(inv);

        break;

    case 9: /* ls: !C || Z */

        tmp = load_cpu_field(CF);

        tcg_gen_brcondi_i32(TCG_COND_EQ, tmp, 0, label);

        dead_tmp(tmp);

        tmp = load_cpu_field(ZF);

        tcg_gen_brcondi_i32(TCG_COND_EQ, tmp, 0, label);

        break;

    case 10: /* ge: N == V -> N ^ V == 0 */

        tmp = load_cpu_field(VF);

        tmp2 = load_cpu_field(NF);

        tcg_gen_xor_i32(tmp, tmp, tmp2);

        dead_tmp(tmp2);

        tcg_gen_brcondi_i32(TCG_COND_GE, tmp, 0, label);

        break;

    case 11: /* lt: N != V -> N ^ V != 0 */

        tmp = load_cpu_field(VF);

        tmp2 = load_cpu_field(NF);

        tcg_gen_xor_i32(tmp, tmp, tmp2);

        dead_tmp(tmp2);

        tcg_gen_brcondi_i32(TCG_COND_LT, tmp, 0, label);

        break;

    case 12: /* gt: !Z && N == V */

        inv = gen_new_label();

        tmp = load_cpu_field(ZF);

        tcg_gen_brcondi_i32(TCG_COND_EQ, tmp, 0, inv);

        dead_tmp(tmp);

        tmp = load_cpu_field(VF);

        tmp2 = load_cpu_field(NF);

        tcg_gen_xor_i32(tmp, tmp, tmp2);

        dead_tmp(tmp2);

        tcg_gen_brcondi_i32(TCG_COND_GE, tmp, 0, label);

        gen_set_label(inv);

        break;

    case 13: /* le: Z || N != V */

        tmp = load_cpu_field(ZF);

        tcg_gen_brcondi_i32(TCG_COND_EQ, tmp, 0, label);

        dead_tmp(tmp);

        tmp = load_cpu_field(VF);

        tmp2 = load_cpu_field(NF);

        tcg_gen_xor_i32(tmp, tmp, tmp2);

        dead_tmp(tmp2);

        tcg_gen_brcondi_i32(TCG_COND_LT, tmp, 0, label);

        break;

    default:

        fprintf(stderr, "Bad condition code 0x%x\n", cc);

        abort();

    }

    dead_tmp(tmp);

}


static int init_input_threads(void)

{

    int i, ret;

    if (nb_input_files == 1)

        return 0;

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

        InputFile *f = input_files[i];

        if (f->ctx->pb ? !f->ctx->pb->seekable :

            strcmp(f->ctx->iformat->name, "lavfi"))

            f->non_blocking = 1;

        ret = av_thread_message_queue_alloc(&f->in_thread_queue,

                                            8, sizeof(AVPacket));

        if (ret < 0)

            return ret;

        if ((ret = pthread_create(&f->thread, NULL, input_thread, f)))

            return AVERROR(ret);

    }

    return 0;

}


static const MXFCodecUL *mxf_get_essence_container_ul(enum CodecID type)

{

    const MXFCodecUL *uls = ff_mxf_essence_container_uls;

    while (uls->id != CODEC_ID_NONE) {

        if (uls->id == type)

            break;

        uls++;

    }

    return uls;

}


static int amovie_request_frame(AVFilterLink *outlink)

{

    MovieContext *movie = outlink->src->priv;

    int ret;

    if (movie->is_done)

        return AVERROR_EOF;

    do {

        if ((ret = amovie_get_samples(outlink)) < 0)

            return ret;

    } while (!movie->samplesref);

    ff_filter_samples(outlink, avfilter_ref_buffer(movie->samplesref, ~0));

    avfilter_unref_buffer(movie->samplesref);

    movie->samplesref = NULL;

    return 0;

}


static av_cold int pcm_decode_init(AVCodecContext *avctx)

{

    PCMDecode *s = avctx->priv_data;

    int i;

    if (avctx->channels <= 0) {

        av_log(avctx, AV_LOG_ERROR, "PCM channels out of bounds\n");

        return AVERROR(EINVAL);

    }

    switch (avctx->codec->id) {

    case AV_CODEC_ID_PCM_ALAW:

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

            s->table[i] = alaw2linear(i);

        break;

    case AV_CODEC_ID_PCM_MULAW:

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

            s->table[i] = ulaw2linear(i);

        break;

    default:

        break;

    }

    avctx->sample_fmt = avctx->codec->sample_fmts[0];

    if (avctx->sample_fmt == AV_SAMPLE_FMT_S32)

        avctx->bits_per_raw_sample = av_get_bits_per_sample(avctx->codec->id);

    avcodec_get_frame_defaults(&s->frame);

    avctx->coded_frame = &s->frame;

    return 0;

}


static av_cold int tta_decode_init(AVCodecContext * avctx)

{

    TTAContext *s = avctx->priv_data;

    int total_frames;

    s->avctx = avctx;

    // 30bytes includes TTA1 header

    if (avctx->extradata_size < 22)

        return AVERROR_INVALIDDATA;

    init_get_bits(&s->gb, avctx->extradata, avctx->extradata_size * 8);

    if (show_bits_long(&s->gb, 32) == AV_RL32("TTA1"))

    {

        if (avctx->err_recognition & AV_EF_CRCCHECK) {

            s->crc_table = av_crc_get_table(AV_CRC_32_IEEE_LE);

            tta_check_crc(s, avctx->extradata, 18);

        }

        /* signature */

        skip_bits_long(&s->gb, 32);

        s->format = get_bits(&s->gb, 16);

        if (s->format > 2) {

            av_log(avctx, AV_LOG_ERROR, "Invalid format\n");

            return AVERROR_INVALIDDATA;

        }

        if (s->format == FORMAT_ENCRYPTED) {

            if (!s->pass) {

                av_log(avctx, AV_LOG_ERROR, "Missing password for encrypted stream. Please use the -password option\n");

                return AVERROR(EINVAL);

            }

            AV_WL64(s->crc_pass, tta_check_crc64(s->pass));

        }

        avctx->channels = s->channels = get_bits(&s->gb, 16);

        if (s->channels > 1 && s->channels < 9)

            avctx->channel_layout = tta_channel_layouts[s->channels-2];

        avctx->bits_per_raw_sample = get_bits(&s->gb, 16);

        s->bps = (avctx->bits_per_raw_sample + 7) / 8;

        avctx->sample_rate = get_bits_long(&s->gb, 32);

        s->data_length = get_bits_long(&s->gb, 32);

        skip_bits_long(&s->gb, 32); // CRC32 of header

        if (s->channels == 0) {

            av_log(avctx, AV_LOG_ERROR, "Invalid number of channels\n");

            return AVERROR_INVALIDDATA;

        } else if (avctx->sample_rate == 0) {

            av_log(avctx, AV_LOG_ERROR, "Invalid samplerate\n");

            return AVERROR_INVALIDDATA;

        }

        switch(s->bps) {

        case 1: avctx->sample_fmt = AV_SAMPLE_FMT_U8; break;

        case 2:

            avctx->sample_fmt = AV_SAMPLE_FMT_S16;

            break;

        case 3:

            avctx->sample_fmt = AV_SAMPLE_FMT_S32;

            break;

        //case 4: avctx->sample_fmt = AV_SAMPLE_FMT_S32; break;

        default:

            av_log(avctx, AV_LOG_ERROR, "Invalid/unsupported sample format.\n");

            return AVERROR_INVALIDDATA;

        }

        // prevent overflow

        if (avctx->sample_rate > 0x7FFFFFu) {

            av_log(avctx, AV_LOG_ERROR, "sample_rate too large\n");

            return AVERROR(EINVAL);

        }

        s->frame_length = 256 * avctx->sample_rate / 245;

        s->last_frame_length = s->data_length % s->frame_length;

        total_frames = s->data_length / s->frame_length +

                       (s->last_frame_length ? 1 : 0);

        av_log(avctx, AV_LOG_DEBUG, "format: %d chans: %d bps: %d rate: %d block: %d\n",

            s->format, avctx->channels, avctx->bits_per_coded_sample, avctx->sample_rate,

            avctx->block_align);

        av_log(avctx, AV_LOG_DEBUG, "data_length: %d frame_length: %d last: %d total: %d\n",

            s->data_length, s->frame_length, s->last_frame_length, total_frames);

        if(s->frame_length >= UINT_MAX / (s->channels * sizeof(int32_t))){

            av_log(avctx, AV_LOG_ERROR, "frame_length too large\n");

            return AVERROR_INVALIDDATA;

        }

        if (s->bps < 3) {

            s->decode_buffer = av_mallocz(sizeof(int32_t)*s->frame_length*s->channels);

            if (!s->decode_buffer)

                return AVERROR(ENOMEM);

        } else

            s->decode_buffer = NULL;

        s->ch_ctx = av_malloc(avctx->channels * sizeof(*s->ch_ctx));

        if (!s->ch_ctx) {

            av_freep(&s->decode_buffer);

            return AVERROR(ENOMEM);

        }

    } else {

        av_log(avctx, AV_LOG_ERROR, "Wrong extradata present\n");

        return AVERROR_INVALIDDATA;

    }

    return 0;

}


static void vda_h264_uninit(AVCodecContext *avctx)

{

    VDAContext *vda = avctx->internal->priv_data;

    av_freep(&vda->bitstream);

}


int vhost_dev_init(struct vhost_dev *hdev, void *opaque,

                   VhostBackendType backend_type, uint32_t busyloop_timeout)

{

    uint64_t features;

    int i, r;

    hdev->migration_blocker = NULL;

    r = vhost_set_backend_type(hdev, backend_type);

    assert(r >= 0);

    r = hdev->vhost_ops->vhost_backend_init(hdev, opaque);

    if (r < 0) {

        goto fail;

    }

    if (used_memslots > hdev->vhost_ops->vhost_backend_memslots_limit(hdev)) {

        fprintf(stderr, "vhost backend memory slots limit is less"

                " than current number of present memory slots\n");

        r = -1;

        goto fail;

    }

    QLIST_INSERT_HEAD(&vhost_devices, hdev, entry);

    r = hdev->vhost_ops->vhost_set_owner(hdev);

    if (r < 0) {

        goto fail;

    }

    r = hdev->vhost_ops->vhost_get_features(hdev, &features);

    if (r < 0) {

        goto fail;

    }

    for (i = 0; i < hdev->nvqs; ++i) {

        r = vhost_virtqueue_init(hdev, hdev->vqs + i, hdev->vq_index + i);

        if (r < 0) {

            goto fail_vq;

        }

    }

    if (busyloop_timeout) {

        for (i = 0; i < hdev->nvqs; ++i) {

            r = vhost_virtqueue_set_busyloop_timeout(hdev, hdev->vq_index + i,

                                                     busyloop_timeout);

            if (r < 0) {

                goto fail_busyloop;

            }

        }

    }

    hdev->features = features;

    hdev->memory_listener = (MemoryListener) {

        .begin = vhost_begin,

        .commit = vhost_commit,

        .region_add = vhost_region_add,

        .region_del = vhost_region_del,

        .region_nop = vhost_region_nop,

        .log_start = vhost_log_start,

        .log_stop = vhost_log_stop,

        .log_sync = vhost_log_sync,

        .log_global_start = vhost_log_global_start,

        .log_global_stop = vhost_log_global_stop,

        .eventfd_add = vhost_eventfd_add,

        .eventfd_del = vhost_eventfd_del,

        .priority = 10

    };

    if (hdev->migration_blocker == NULL) {

        if (!(hdev->features & (0x1ULL << VHOST_F_LOG_ALL))) {

            error_setg(&hdev->migration_blocker,

                       "Migration disabled: vhost lacks VHOST_F_LOG_ALL feature.");

        } else if (!qemu_memfd_check()) {

            error_setg(&hdev->migration_blocker,

                       "Migration disabled: failed to allocate shared memory");

        }

    }

    if (hdev->migration_blocker != NULL) {

        migrate_add_blocker(hdev->migration_blocker);

    }

    hdev->mem = g_malloc0(offsetof(struct vhost_memory, regions));

    hdev->n_mem_sections = 0;

    hdev->mem_sections = NULL;

    hdev->log = NULL;

    hdev->log_size = 0;

    hdev->log_enabled = false;

    hdev->started = false;

    hdev->memory_changed = false;

    memory_listener_register(&hdev->memory_listener, &address_space_memory);

    return 0;

fail_busyloop:

    while (--i >= 0) {

        vhost_virtqueue_set_busyloop_timeout(hdev, hdev->vq_index + i, 0);

    }

    i = hdev->nvqs;

fail_vq:

    while (--i >= 0) {

        vhost_virtqueue_cleanup(hdev->vqs + i);

    }

fail:

    r = -errno;

    hdev->vhost_ops->vhost_backend_cleanup(hdev);

    QLIST_REMOVE(hdev, entry);

    return r;

}


static void cmv_process_header(CmvContext *s, const uint8_t *buf, const uint8_t *buf_end)

{

    int pal_start, pal_count, i;

    if(buf+16>=buf_end) {

        av_log(s->avctx, AV_LOG_WARNING, "truncated header\n");

        return;

    }

    s->width  = AV_RL16(&buf[4]);

    s->height = AV_RL16(&buf[6]);

    if (s->avctx->width!=s->width || s->avctx->height!=s->height)

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

    s->avctx->time_base.num = 1;

    s->avctx->time_base.den = AV_RL16(&buf[10]);

    pal_start = AV_RL16(&buf[12]);

    pal_count = AV_RL16(&buf[14]);

    buf += 16;

    for (i=pal_start; i<pal_start+pal_count && i<AVPALETTE_COUNT && buf+2<buf_end; i++) {

        s->palette[i] = AV_RB24(buf);

        buf += 3;

    }

}


static int usb_serial_initfn(USBDevice *dev)
{
    USBSerialState *s = DO_UPCAST(USBSerialState, dev, dev);
    s->dev.speed = USB_SPEED_FULL;
    qemu_chr_add_handlers(s->cs, usb_serial_can_read, usb_serial_read,
                          usb_serial_event, s);
    usb_serial_handle_reset(dev);
    return 0;


static ssize_t vnc_client_write_tls(gnutls_session_t *session,

                                    const uint8_t *data,

                                    size_t datalen)

{

    ssize_t ret = gnutls_write(*session, data, datalen);

    if (ret < 0) {

        if (ret == GNUTLS_E_AGAIN) {

            errno = EAGAIN;

        } else {

            errno = EIO;

        }

        ret = -1;

    }

    return ret;

}


ivshmem_client_handle_server_msg(IvshmemClient *client)
{
    IvshmemClientPeer *peer;
    long peer_id;
    int ret, fd;
    ret = ivshmem_client_read_one_msg(client, &peer_id, &fd);
    if (ret < 0) {
    /* can return a peer or the local client */
    peer = ivshmem_client_search_peer(client, peer_id);
    /* delete peer */
    if (fd == -1) {
        if (peer == NULL || peer == &client->local) {
            IVSHMEM_CLIENT_DEBUG(client, "receive delete for invalid "
                                 "peer %ld\n", peer_id);
        IVSHMEM_CLIENT_DEBUG(client, "delete peer id = %ld\n", peer_id);
        ivshmem_client_free_peer(client, peer);
        return 0;
    /* new peer */
    if (peer == NULL) {
        peer = g_malloc0(sizeof(*peer));
        peer->id = peer_id;
        peer->vectors_count = 0;
        QTAILQ_INSERT_TAIL(&client->peer_list, peer, next);
        IVSHMEM_CLIENT_DEBUG(client, "new peer id = %ld\n", peer_id);
    /* new vector */
    IVSHMEM_CLIENT_DEBUG(client, "  new vector %d (fd=%d) for peer id %ld\n",
                         peer->vectors_count, fd, peer->id);
    peer->vectors[peer->vectors_count] = fd;
    peer->vectors_count++;
    return 0;


yuv2422_2_c_template(SwsContext *c, const int16_t *buf[2],
                     const int16_t *ubuf[2], const int16_t *vbuf[2],
                     const int16_t *abuf[2], uint8_t *dest, int dstW,
                     int yalpha, int uvalpha, int y,
                     enum PixelFormat target)
{
    const int16_t *buf0  = buf[0],  *buf1  = buf[1],
                  *ubuf0 = ubuf[0], *ubuf1 = ubuf[1],
                  *vbuf0 = vbuf[0], *vbuf1 = vbuf[1];
    int  yalpha1 = 4095 - yalpha;
    int uvalpha1 = 4095 - uvalpha;
    int i;
    for (i = 0; i < (dstW >> 1); i++) {
        int Y1 = (buf0[i * 2]     * yalpha1  + buf1[i * 2]     * yalpha)  >> 19;
        int Y2 = (buf0[i * 2 + 1] * yalpha1  + buf1[i * 2 + 1] * yalpha)  >> 19;
        int U  = (ubuf0[i]        * uvalpha1 + ubuf1[i]        * uvalpha) >> 19;
        int V  = (vbuf0[i]        * uvalpha1 + vbuf1[i]        * uvalpha) >> 19;
        output_pixels(i * 4, Y1, U, Y2, V);
    }
}


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

{

    MpegDemuxContext *vobsub = s->priv_data;

    FFDemuxSubtitlesQueue *q;

    AVIOContext *pb = vobsub->sub_ctx->pb;

    int ret, psize, total_read = 0, i;

    AVPacket idx_pkt;

    int64_t min_ts = INT64_MAX;

    int sid = 0;

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

        FFDemuxSubtitlesQueue *tmpq = &vobsub->q[i];

        int64_t ts = tmpq->subs[tmpq->current_sub_idx].pts;

        if (ts < min_ts) {

            min_ts = ts;

            sid = i;

        }

    }

    q = &vobsub->q[sid];

    ret = ff_subtitles_queue_read_packet(q, &idx_pkt);

    if (ret < 0)

        return ret;

    /* compute maximum packet size using the next packet position. This is

     * useful when the len in the header is non-sense */

    if (q->current_sub_idx < q->nb_subs) {

        psize = q->subs[q->current_sub_idx].pos - idx_pkt.pos;

    } else {

        int64_t fsize = avio_size(pb);

        psize = fsize < 0 ? 0xffff : fsize - idx_pkt.pos;

    }

    avio_seek(pb, idx_pkt.pos, SEEK_SET);

    av_init_packet(pkt);

    pkt->size = 0;

    pkt->data = NULL;

    do {

        int n, to_read, startcode;

        int64_t pts, dts;

        int64_t old_pos = avio_tell(pb), new_pos;

        int pkt_size;

        ret = mpegps_read_pes_header(vobsub->sub_ctx, NULL, &startcode, &pts, &dts);

        if (ret < 0) {

            if (pkt->size) // raise packet even if incomplete

                break;

            goto fail;

        }

        to_read = ret & 0xffff;

        new_pos = avio_tell(pb);

        pkt_size = ret + (new_pos - old_pos);

        /* this prevents reads above the current packet */

        if (total_read + pkt_size > psize)

            break;

        total_read += pkt_size;

        /* the current chunk doesn't match the stream index (unlikely) */

        if ((startcode & 0x1f) != idx_pkt.stream_index)

            break;

        ret = av_grow_packet(pkt, to_read);

        if (ret < 0)

            goto fail;

        n = avio_read(pb, pkt->data + (pkt->size - to_read), to_read);

        if (n < to_read)

            pkt->size -= to_read - n;

    } while (total_read < psize);

    pkt->pts = pkt->dts = idx_pkt.pts;

    pkt->pos = idx_pkt.pos;

    pkt->stream_index = idx_pkt.stream_index;

    av_free_packet(&idx_pkt);

    return 0;

fail:

    av_free_packet(pkt);

    av_free_packet(&idx_pkt);

    return ret;

}


static int dxtory_decode_v1_410(AVCodecContext *avctx, AVFrame *pic,

                                const uint8_t *src, int src_size)

{

    int h, w;

    uint8_t *Y1, *Y2, *Y3, *Y4, *U, *V;

    int ret;

    if (src_size < avctx->width * avctx->height * 9L / 8) {

        av_log(avctx, AV_LOG_ERROR, "packet too small\n");

        return AVERROR_INVALIDDATA;

    }

    avctx->pix_fmt = AV_PIX_FMT_YUV410P;

    if ((ret = ff_get_buffer(avctx, pic, 0)) < 0)

        return ret;

    Y1 = pic->data[0];

    Y2 = pic->data[0] + pic->linesize[0];

    Y3 = pic->data[0] + pic->linesize[0] * 2;

    Y4 = pic->data[0] + pic->linesize[0] * 3;

    U  = pic->data[1];

    V  = pic->data[2];

    for (h = 0; h < avctx->height; h += 4) {

        for (w = 0; w < avctx->width; w += 4) {

            AV_COPY32(Y1 + w, src);

            AV_COPY32(Y2 + w, src + 4);

            AV_COPY32(Y3 + w, src + 8);

            AV_COPY32(Y4 + w, src + 12);

            U[w >> 2] = src[16] + 0x80;

            V[w >> 2] = src[17] + 0x80;

            src += 18;

        }

        Y1 += pic->linesize[0] << 2;

        Y2 += pic->linesize[0] << 2;

        Y3 += pic->linesize[0] << 2;

        Y4 += pic->linesize[0] << 2;

        U  += pic->linesize[1];

        V  += pic->linesize[2];

    }

    return 0;

}


static void dnxhd_decode_dct_block(DNXHDContext *ctx, DCTELEM *block, int n, int qscale)

{

    int i, j, index, index2;

    int level, component, sign;

    const uint8_t *weigth_matrix;

    if (n&2) {

        component = 1 + (n&1);

        weigth_matrix = ctx->cid_table->chroma_weigth;

    } else {

        component = 0;

        weigth_matrix = ctx->cid_table->luma_weigth;

    }

    ctx->last_dc[component] += dnxhd_decode_dc(ctx);

    block[0] = ctx->last_dc[component];

    //av_log(ctx->avctx, AV_LOG_DEBUG, "dc %d\n", block[0]);

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

        index = get_vlc2(&ctx->gb, ctx->ac_vlc.table, DNXHD_VLC_BITS, 2);

        //av_log(ctx->avctx, AV_LOG_DEBUG, "index %d\n", index);

        level = ctx->cid_table->ac_level[index];

        if (!level) { /* EOB */

            //av_log(ctx->avctx, AV_LOG_DEBUG, "EOB\n");

            return;

        }

        sign = get_sbits(&ctx->gb, 1);

        if (ctx->cid_table->ac_index_flag[index]) {

            level += get_bits(&ctx->gb, ctx->cid_table->index_bits)<<6;

        }

        if (ctx->cid_table->ac_run_flag[index]) {

            index2 = get_vlc2(&ctx->gb, ctx->run_vlc.table, DNXHD_VLC_BITS, 2);

            i += ctx->cid_table->run[index2];

        }

        j = ctx->scantable.permutated[i];

        //av_log(ctx->avctx, AV_LOG_DEBUG, "j %d\n", j);

        //av_log(ctx->avctx, AV_LOG_DEBUG, "level %d, weigth %d\n", level, weigth_matrix[i]);

        level = (2*level+1) * qscale * weigth_matrix[i];

        if (weigth_matrix[i] != 32) // FIXME 10bit

            level += 32;

        level >>= 6;

        level = (level^sign) - sign;

        if (i > 63) {

            av_log(ctx->avctx, AV_LOG_ERROR, "ac tex damaged %d, %d\n", n, i);

            return;

        }

        //av_log(NULL, AV_LOG_DEBUG, "i %d, j %d, end level %d\n", i, j, level);

        block[j] = level;

    }

}


const char *avutil_configuration(void)

{

    return FFMPEG_CONFIGURATION;

}


static void i8042_class_initfn(ObjectClass *klass, void *data)

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    dc->realize = i8042_realizefn;

    dc->no_user = 1;

    dc->vmsd = &vmstate_kbd_isa;

}


int vp78_decode_frame(AVCodecContext *avctx, void *data, int *got_frame,

                      AVPacket *avpkt, int is_vp7)

{

    VP8Context *s = avctx->priv_data;

    int ret, i, referenced, num_jobs;

    enum AVDiscard skip_thresh;

    VP8Frame *av_uninit(curframe), *prev_frame;

    if (is_vp7)

        ret = vp7_decode_frame_header(s, avpkt->data, avpkt->size);

    else

        ret = vp8_decode_frame_header(s, avpkt->data, avpkt->size);

    if (ret < 0)

        goto err;

    prev_frame = s->framep[VP56_FRAME_CURRENT];

    referenced = s->update_last || s->update_golden == VP56_FRAME_CURRENT ||

                 s->update_altref == VP56_FRAME_CURRENT;

    skip_thresh = !referenced ? AVDISCARD_NONREF

                              : !s->keyframe ? AVDISCARD_NONKEY

                                             : AVDISCARD_ALL;

    if (avctx->skip_frame >= skip_thresh) {

        s->invisible = 1;

        memcpy(&s->next_framep[0], &s->framep[0], sizeof(s->framep[0]) * 4);

        goto skip_decode;

    }

    s->deblock_filter = s->filter.level && avctx->skip_loop_filter < skip_thresh;

    // release no longer referenced frames

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

        if (s->frames[i].tf.f->data[0] &&

            &s->frames[i] != prev_frame &&

            &s->frames[i] != s->framep[VP56_FRAME_PREVIOUS] &&

            &s->frames[i] != s->framep[VP56_FRAME_GOLDEN]   &&

            &s->frames[i] != s->framep[VP56_FRAME_GOLDEN2])

            vp8_release_frame(s, &s->frames[i]);

    curframe = s->framep[VP56_FRAME_CURRENT] = vp8_find_free_buffer(s);

    if (!s->colorspace)

        avctx->colorspace = AVCOL_SPC_BT470BG;

    if (s->fullrange)

        avctx->color_range = AVCOL_RANGE_JPEG;

    else

        avctx->color_range = AVCOL_RANGE_MPEG;

    /* Given that arithmetic probabilities are updated every frame, it's quite

     * likely that the values we have on a random interframe are complete

     * junk if we didn't start decode on a keyframe. So just don't display

     * anything rather than junk. */

    if (!s->keyframe && (!s->framep[VP56_FRAME_PREVIOUS] ||

                         !s->framep[VP56_FRAME_GOLDEN]   ||

                         !s->framep[VP56_FRAME_GOLDEN2])) {

        av_log(avctx, AV_LOG_WARNING,

               "Discarding interframe without a prior keyframe!\n");

        ret = AVERROR_INVALIDDATA;

        goto err;

    }

    curframe->tf.f->key_frame = s->keyframe;

    curframe->tf.f->pict_type = s->keyframe ? AV_PICTURE_TYPE_I

                                            : AV_PICTURE_TYPE_P;

    if ((ret = vp8_alloc_frame(s, curframe, referenced)) < 0)

        goto err;

    // check if golden and altref are swapped

    if (s->update_altref != VP56_FRAME_NONE)

        s->next_framep[VP56_FRAME_GOLDEN2] = s->framep[s->update_altref];

    else

        s->next_framep[VP56_FRAME_GOLDEN2] = s->framep[VP56_FRAME_GOLDEN2];

    if (s->update_golden != VP56_FRAME_NONE)

        s->next_framep[VP56_FRAME_GOLDEN] = s->framep[s->update_golden];

    else

        s->next_framep[VP56_FRAME_GOLDEN] = s->framep[VP56_FRAME_GOLDEN];

    if (s->update_last)

        s->next_framep[VP56_FRAME_PREVIOUS] = curframe;

    else

        s->next_framep[VP56_FRAME_PREVIOUS] = s->framep[VP56_FRAME_PREVIOUS];

    s->next_framep[VP56_FRAME_CURRENT] = curframe;

    if (avctx->codec->update_thread_context)

        ff_thread_finish_setup(avctx);

    s->linesize   = curframe->tf.f->linesize[0];

    s->uvlinesize = curframe->tf.f->linesize[1];

    memset(s->top_nnz, 0, s->mb_width * sizeof(*s->top_nnz));

    /* Zero macroblock structures for top/top-left prediction

     * from outside the frame. */

    if (!s->mb_layout)

        memset(s->macroblocks + s->mb_height * 2 - 1, 0,

               (s->mb_width + 1) * sizeof(*s->macroblocks));

    if (!s->mb_layout && s->keyframe)

        memset(s->intra4x4_pred_mode_top, DC_PRED, s->mb_width * 4);

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

    if (s->mb_layout == 1) {

        // Make sure the previous frame has read its segmentation map,

        // if we re-use the same map.

        if (prev_frame && s->segmentation.enabled &&

            !s->segmentation.update_map)

            ff_thread_await_progress(&prev_frame->tf, 1, 0);

        if (is_vp7)

            vp7_decode_mv_mb_modes(avctx, curframe, prev_frame);

        else

            vp8_decode_mv_mb_modes(avctx, curframe, prev_frame);

    }

    if (avctx->active_thread_type == FF_THREAD_FRAME)

        num_jobs = 1;

    else

        num_jobs = FFMIN(s->num_coeff_partitions, avctx->thread_count);

    s->num_jobs   = num_jobs;

    s->curframe   = curframe;

    s->prev_frame = prev_frame;

    s->mv_min.y   = -MARGIN;

    s->mv_max.y   = ((s->mb_height - 1) << 6) + MARGIN;

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

        VP8ThreadData *td = &s->thread_data[i];

        atomic_init(&td->thread_mb_pos, 0);

        atomic_init(&td->wait_mb_pos, INT_MAX);

    }

    if (is_vp7)

        avctx->execute2(avctx, vp7_decode_mb_row_sliced, s->thread_data, NULL,

                        num_jobs);

    else

        avctx->execute2(avctx, vp8_decode_mb_row_sliced, s->thread_data, NULL,

                        num_jobs);

    ff_thread_report_progress(&curframe->tf, INT_MAX, 0);

    memcpy(&s->framep[0], &s->next_framep[0], sizeof(s->framep[0]) * 4);

skip_decode:

    // if future frames don't use the updated probabilities,

    // reset them to the values we saved

    if (!s->update_probabilities)

        s->prob[0] = s->prob[1];

    if (!s->invisible) {

        if ((ret = av_frame_ref(data, curframe->tf.f)) < 0)

            return ret;

        *got_frame = 1;

    }

    return avpkt->size;

err:

    memcpy(&s->next_framep[0], &s->framep[0], sizeof(s->framep[0]) * 4);

    return ret;

}


void ff_bink_idct_put_c(uint8_t *dest, int linesize, DCTELEM *block)

{

    int i;

    DCTELEM temp[64];

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

        bink_idct_col(&temp[i], &block[i]);

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

        IDCT_ROW( (&dest[i*linesize]), (&temp[8*i]) );

    }

}


static void qemu_rdma_signal_unregister(RDMAContext *rdma, uint64_t index,

                                        uint64_t chunk, uint64_t wr_id)

{

    if (rdma->unregistrations[rdma->unregister_next] != 0) {

        fprintf(stderr, "rdma migration: queue is full!\n");

    } else {

        RDMALocalBlock *block = &(rdma->local_ram_blocks.block[index]);

        if (!test_and_set_bit(chunk, block->unregister_bitmap)) {

            DDPRINTF("Appending unregister chunk %" PRIu64

                    " at position %d\n", chunk, rdma->unregister_next);

            rdma->unregistrations[rdma->unregister_next++] =

                    qemu_rdma_make_wrid(wr_id, index, chunk);

            if (rdma->unregister_next == RDMA_SIGNALED_SEND_MAX) {

                rdma->unregister_next = 0;

            }

        } else {

            DDPRINTF("Unregister chunk %" PRIu64 " already in queue.\n",

                    chunk);

        }

    }

}


static void v9fs_unlinkat(void *opaque)
{
    int err = 0;
    V9fsString name;
    int32_t dfid, flags;
    size_t offset = 7;
    V9fsPath path;
    V9fsFidState *dfidp;
    V9fsPDU *pdu = opaque;
    v9fs_string_init(&name);
    err = pdu_unmarshal(pdu, offset, "dsd", &dfid, &name, &flags);
    if (err < 0) {
    dfidp = get_fid(pdu, dfid);
    if (dfidp == NULL) {
        err = -EINVAL;
    /*
     * IF the file is unlinked, we cannot reopen
     * the file later. So don't reclaim fd
     */
    v9fs_path_init(&path);
    err = v9fs_co_name_to_path(pdu, &dfidp->path, name.data, &path);
    if (err < 0) {
        goto out_err;
    err = v9fs_mark_fids_unreclaim(pdu, &path);
    if (err < 0) {
        goto out_err;
    err = v9fs_co_unlinkat(pdu, &dfidp->path, &name, flags);
    if (!err) {
        err = offset;
out_err:
    put_fid(pdu, dfidp);
    v9fs_path_free(&path);
out_nofid:
    pdu_complete(pdu, err);
    v9fs_string_free(&name);


static int parse_pci_devfn(DeviceState *dev, Property *prop, const char *str)

{

    uint32_t *ptr = qdev_get_prop_ptr(dev, prop);

    unsigned int slot, fn, n;

    if (sscanf(str, "%x.%x%n", &slot, &fn, &n) != 2) {

        fn = 0;

        if (sscanf(str, "%x%n", &slot, &n) != 1) {

            return -EINVAL;

        }

    }

    if (str[n] != '\0')

        return -EINVAL;

    if (fn > 7)

        return -EINVAL;

    if (slot > 31)

        return -EINVAL;

    *ptr = slot << 3 | fn;

    return 0;

}


static int nsv_read_header(AVFormatContext *s)

{

    NSVContext *nsv = s->priv_data;

    int i, err;

    av_dlog(s, "%s()\n", __FUNCTION__);

    av_dlog(s, "filename '%s'\n", s->filename);

    nsv->state = NSV_UNSYNC;

    nsv->ahead[0].data = nsv->ahead[1].data = NULL;

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

        if (nsv_resync(s) < 0)

            return -1;

        if (nsv->state == NSV_FOUND_NSVF)

            err = nsv_parse_NSVf_header(s);

            /* we need the first NSVs also... */

        if (nsv->state == NSV_FOUND_NSVS) {

            err = nsv_parse_NSVs_header(s);

            break; /* we just want the first one */

        }

    }

    if (s->nb_streams < 1) /* no luck so far */

        return -1;

    /* now read the first chunk, so we can attempt to decode more info */

    err = nsv_read_chunk(s, 1);

    av_dlog(s, "parsed header\n");

    return err;

}


static void cd_read_sector_cb(void *opaque, int ret)

{

    IDEState *s = opaque;

    block_acct_done(blk_get_stats(s->blk), &s->acct);

#ifdef DEBUG_IDE_ATAPI

    printf("cd_read_sector_cb: lba=%d ret=%d\n", s->lba, ret);

#endif

    if (ret < 0) {

        ide_atapi_io_error(s, ret);

        return;

    }

    if (s->cd_sector_size == 2352) {

        cd_data_to_raw(s->io_buffer, s->lba);

    }

    s->lba++;

    s->io_buffer_index = 0;

    s->status &= ~BUSY_STAT;

    ide_atapi_cmd_reply_end(s);

}


static void vnc_tls_handshake_done(QIOTask *task,

                                   gpointer user_data)

{

    VncState *vs = user_data;

    Error *err = NULL;

    if (qio_task_propagate_error(task, &err)) {

        VNC_DEBUG("Handshake failed %s\n",

                  error_get_pretty(err));

        vnc_client_error(vs);

        error_free(err);

    } else {

        vs->ioc_tag = qio_channel_add_watch(

            vs->ioc, G_IO_IN | G_IO_OUT, vnc_client_io, vs, NULL);

        start_auth_vencrypt_subauth(vs);

    }

}


static int get_best_header(FLACParseContext* fpc, const uint8_t **poutbuf,

                           int *poutbuf_size)

{

    FLACHeaderMarker *header = fpc->best_header;

    FLACHeaderMarker *child  = header->best_child;

    if (!child) {

        *poutbuf_size = av_fifo_size(fpc->fifo_buf) - header->offset;

    } else {

        *poutbuf_size = child->offset - header->offset;

        /* If the child has suspicious changes, log them */

        check_header_mismatch(fpc, header, child, 0);

    }

    if (header->fi.channels != fpc->avctx->channels ||

        (!fpc->avctx->channel_layout && header->fi.channels <= 6)) {

        fpc->avctx->channels = header->fi.channels;

        ff_flac_set_channel_layout(fpc->avctx);

    }

    fpc->avctx->sample_rate = header->fi.samplerate;

    fpc->pc->duration       = header->fi.blocksize;

    *poutbuf = flac_fifo_read_wrap(fpc, header->offset, *poutbuf_size,

                                        &fpc->wrap_buf,

                                        &fpc->wrap_buf_allocated_size);

    fpc->best_header_valid = 0;

    /* Return the negative overread index so the client can compute pos.

       This should be the amount overread to the beginning of the child */

    if (child)

        return child->offset - av_fifo_size(fpc->fifo_buf);

    return 0;

}


static int decode_packet(int *got_frame, int cached)

{

    int ret = 0;

    int decoded = pkt.size;

    *got_frame = 0;

    if (pkt.stream_index == video_stream_idx) {

        /* decode video frame */

        ret = avcodec_decode_video2(video_dec_ctx, frame, got_frame, &pkt);

        if (ret < 0) {

            fprintf(stderr, "Error decoding video frame (%s)\n", av_err2str(ret));

            return ret;

        }

        if (video_dec_ctx->width != width || video_dec_ctx->height != height ||

            video_dec_ctx->pix_fmt != pix_fmt) {

            /* To handle this change, one could call av_image_alloc again and

             * decode the following frames into another rawvideo file. */

            fprintf(stderr, "Error: Width, height and pixel format have to be "

                    "constant in a rawvideo file, but the width, height or "

                    "pixel format of the input video changed:\n"

                    "old: width = %d, height = %d, format = %s\n"

                    "new: width = %d, height = %d, format = %s\n",

                    width, height, av_get_pix_fmt_name(pix_fmt),

                    video_dec_ctx->width, video_dec_ctx->height,

                    av_get_pix_fmt_name(video_dec_ctx->pix_fmt));

            return -1;

        }

        if (*got_frame) {

            printf("video_frame%s n:%d coded_n:%d pts:%s\n",

                   cached ? "(cached)" : "",

                   video_frame_count++, frame->coded_picture_number,

                   av_ts2timestr(frame->pts, &video_dec_ctx->time_base));

            /* copy decoded frame to destination buffer:

             * this is required since rawvideo expects non aligned data */

            av_image_copy(video_dst_data, video_dst_linesize,

                          (const uint8_t **)(frame->data), frame->linesize,

                          pix_fmt, width, height);

            /* write to rawvideo file */

            fwrite(video_dst_data[0], 1, video_dst_bufsize, video_dst_file);

        }

    } else if (pkt.stream_index == audio_stream_idx) {

        /* decode audio frame */

        ret = avcodec_decode_audio4(audio_dec_ctx, frame, got_frame, &pkt);

        if (ret < 0) {

            fprintf(stderr, "Error decoding audio frame (%s)\n", av_err2str(ret));

            return ret;

        }

        /* Some audio decoders decode only part of the packet, and have to be

         * called again with the remainder of the packet data.

         * Sample: fate-suite/lossless-audio/luckynight-partial.shn

         * Also, some decoders might over-read the packet. */

        decoded = FFMIN(ret, pkt.size);

        if (*got_frame) {

            size_t unpadded_linesize = frame->nb_samples * av_get_bytes_per_sample(frame->format);

            printf("audio_frame%s n:%d nb_samples:%d pts:%s\n",

                   cached ? "(cached)" : "",

                   audio_frame_count++, frame->nb_samples,

                   av_ts2timestr(frame->pts, &audio_dec_ctx->time_base));

            /* Write the raw audio data samples of the first plane. This works

             * fine for packed formats (e.g. AV_SAMPLE_FMT_S16). However,

             * most audio decoders output planar audio, which uses a separate

             * plane of audio samples for each channel (e.g. AV_SAMPLE_FMT_S16P).

             * In other words, this code will write only the first audio channel

             * in these cases.

             * You should use libswresample or libavfilter to convert the frame

             * to packed data. */

            fwrite(frame->extended_data[0], 1, unpadded_linesize, audio_dst_file);

        }

    }

    /* If we use the new API with reference counting, we own the data and need

     * to de-reference it when we don't use it anymore */

    if (*got_frame && api_mode == API_MODE_NEW_API_REF_COUNT)

        av_frame_unref(frame);

    return decoded;

}


void ff_avg_h264_qpel16_mc00_msa(uint8_t *dst, const uint8_t *src,

                                 ptrdiff_t stride)

{

    avg_width16_msa(src, stride, dst, stride, 16);

}


static inline int init_pfa_reindex_tabs(MDCT15Context *s)

{

    int i, j;

    const int b_ptwo = s->ptwo_fft.nbits; /* Bits for the power of two FFTs */

    const int l_ptwo = 1 << b_ptwo; /* Total length for the power of two FFTs */

    const int inv_1 = l_ptwo << ((4 - b_ptwo) & 3); /* (2^b_ptwo)^-1 mod 15 */

    const int inv_2 = 0xeeeeeeef & ((1U << b_ptwo) - 1); /* 15^-1 mod 2^b_ptwo */

    s->pfa_prereindex = av_malloc(15 * l_ptwo * sizeof(*s->pfa_prereindex));

    if (!s->pfa_prereindex)

        return 1;

    s->pfa_postreindex = av_malloc(15 * l_ptwo * sizeof(*s->pfa_postreindex));

    if (!s->pfa_postreindex)

        return 1;

    /* Pre/Post-reindex */

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

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

            const int q_pre = ((l_ptwo * j)/15 + i) >> b_ptwo;

            const int q_post = (((j*inv_1)/15) + (i*inv_2)) >> b_ptwo;

            const int k_pre = 15*i + ((j - q_pre*15) << b_ptwo);

            const int k_post = i*inv_2*15 + j*inv_1 - 15*q_post*l_ptwo;

            s->pfa_prereindex[i*15 + j] = k_pre;

            s->pfa_postreindex[k_post] = l_ptwo*j + i;

        }

    }

    return 0;

}


static void mxf_write_identification(AVFormatContext *s)

{

    MXFContext *mxf = s->priv_data;

    AVIOContext *pb = s->pb;

    const char *company = "Libav";

    const char *product = "OP1a Muxer";

    const char *version;

    int length;

    mxf_write_metadata_key(pb, 0x013000);

    PRINT_KEY(s, "identification key", pb->buf_ptr - 16);

    version = s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT ?

        "0.0.0" : AV_STRINGIFY(LIBAVFORMAT_VERSION);

    length = 84 + (strlen(company)+strlen(product)+strlen(version))*2; // utf-16

    klv_encode_ber_length(pb, length);

    // write uid

    mxf_write_local_tag(pb, 16, 0x3C0A);

    mxf_write_uuid(pb, Identification, 0);

    PRINT_KEY(s, "identification uid", pb->buf_ptr - 16);

    // write generation uid

    mxf_write_local_tag(pb, 16, 0x3C09);

    mxf_write_uuid(pb, Identification, 1);

    mxf_write_local_tag_utf16(pb, 0x3C01, company); // Company Name

    mxf_write_local_tag_utf16(pb, 0x3C02, product); // Product Name

    mxf_write_local_tag_utf16(pb, 0x3C04, version); // Version String

    // write product uid

    mxf_write_local_tag(pb, 16, 0x3C05);

    mxf_write_uuid(pb, Identification, 2);

    // modification date

    mxf_write_local_tag(pb, 8, 0x3C06);

    avio_wb64(pb, mxf->timestamp);

}


static void test_visitor_out_native_list_uint32(TestOutputVisitorData *data,

                                                const void *unused)

{

    test_native_list(data, unused, USER_DEF_NATIVE_LIST_UNION_KIND_U32);

}


static void ahci_test_identify(AHCIQState *ahci)

{

    RegD2HFIS *d2h = g_malloc0(0x20);

    RegD2HFIS *pio = g_malloc0(0x20);

    RegH2DFIS fis;

    AHCICommandHeader cmd;

    PRD prd;

    uint32_t reg, data_ptr;

    uint16_t buff[256];

    unsigned i;

    int rc;

    uint8_t cx;

    uint64_t table;

    g_assert(ahci != NULL);

    /* We need to:

     * (1) Create a Command Table Buffer and update the Command List Slot #0

     *     to point to this buffer.

     * (2) Construct an FIS host-to-device command structure, and write it to

     *     the top of the command table buffer.

     * (3) Create a data buffer for the IDENTIFY response to be sent to

     * (4) Create a Physical Region Descriptor that points to the data buffer,

     *     and write it to the bottom (offset 0x80) of the command table.

     * (5) Now, PxCLB points to the command list, command 0 points to

     *     our table, and our table contains an FIS instruction and a

     *     PRD that points to our rx buffer.

     * (6) We inform the HBA via PxCI that there is a command ready in slot #0.

     */

    /* Pick the first implemented and running port */

    i = ahci_port_select(ahci);

    g_test_message("Selected port %u for test", i);

    /* Clear out the FIS Receive area and any pending interrupts. */

    ahci_port_clear(ahci, i);

    /* Create a Command Table buffer. 0x80 is the smallest with a PRDTL of 0. */

    /* We need at least one PRD, so round up to the nearest 0x80 multiple.    */

    table = ahci_alloc(ahci, CMD_TBL_SIZ(1));

    g_assert(table);

    ASSERT_BIT_CLEAR(table, 0x7F);

    /* Create a data buffer ... where we will dump the IDENTIFY data to. */

    data_ptr = ahci_alloc(ahci, 512);

    g_assert(data_ptr);

    /* pick a command slot (should be 0!) */

    cx = ahci_pick_cmd(ahci, i);

    /* Construct our Command Header (set_command_header handles endianness.) */

    memset(&cmd, 0x00, sizeof(cmd));

    cmd.flags = 5;      /* reg_h2d_fis is 5 double-words long */

    cmd.flags |= 0x400; /* clear PxTFD.STS.BSY when done */

    cmd.prdtl = 1;      /* One PRD table entry. */

    cmd.prdbc = 0;

    cmd.ctba = table;

    /* Construct our PRD, noting that DBC is 0-indexed. */

    prd.dba = cpu_to_le64(data_ptr);

    prd.res = 0;

    /* 511+1 bytes, request DPS interrupt */

    prd.dbc = cpu_to_le32(511 | 0x80000000);

    /* Construct our Command FIS, Based on http://wiki.osdev.org/AHCI */

    memset(&fis, 0x00, sizeof(fis));

    fis.fis_type = 0x27; /* Register Host-to-Device FIS */

    fis.command = 0xEC;  /* IDENTIFY */

    fis.device = 0;

    fis.flags = 0x80;    /* Indicate this is a command FIS */

    /* We've committed nothing yet, no interrupts should be posted yet. */

    g_assert_cmphex(ahci_px_rreg(ahci, i, AHCI_PX_IS), ==, 0);

    /* Commit the Command FIS to the Command Table */

    memwrite(table, &fis, sizeof(fis));

    /* Commit the PRD entry to the Command Table */

    memwrite(table + 0x80, &prd, sizeof(prd));

    /* Commit Command #cx, pointing to the Table, to the Command List Buffer. */

    ahci_set_command_header(ahci, i, cx, &cmd);

    /* Everything is in place, but we haven't given the go-ahead yet,

     * so we should find that there are no pending interrupts yet. */

    g_assert_cmphex(ahci_px_rreg(ahci, i, AHCI_PX_IS), ==, 0);

    /* Issue Command #cx via PxCI */

    ahci_px_wreg(ahci, i, AHCI_PX_CI, (1 << cx));

    while (BITSET(ahci_px_rreg(ahci, i, AHCI_PX_TFD), AHCI_PX_TFD_STS_BSY)) {

        usleep(50);

    }

    /* Check for expected interrupts */

    reg = ahci_px_rreg(ahci, i, AHCI_PX_IS);

    ASSERT_BIT_SET(reg, AHCI_PX_IS_DHRS);

    ASSERT_BIT_SET(reg, AHCI_PX_IS_PSS);

    /* BUG: we expect AHCI_PX_IS_DPS to be set. */

    ASSERT_BIT_CLEAR(reg, AHCI_PX_IS_DPS);

    /* Clear expected interrupts and assert all interrupts now cleared. */

    ahci_px_wreg(ahci, i, AHCI_PX_IS,

                 AHCI_PX_IS_DHRS | AHCI_PX_IS_PSS | AHCI_PX_IS_DPS);

    g_assert_cmphex(ahci_px_rreg(ahci, i, AHCI_PX_IS), ==, 0);

    /* Check for errors. */

    reg = ahci_px_rreg(ahci, i, AHCI_PX_SERR);

    g_assert_cmphex(reg, ==, 0);

    reg = ahci_px_rreg(ahci, i, AHCI_PX_TFD);

    ASSERT_BIT_CLEAR(reg, AHCI_PX_TFD_STS_ERR);

    ASSERT_BIT_CLEAR(reg, AHCI_PX_TFD_ERR);

    /* Investigate the CMD, assert that we read 512 bytes */

    ahci_get_command_header(ahci, i, cx, &cmd);

    g_assert_cmphex(512, ==, cmd.prdbc);

    /* Investigate FIS responses */

    memread(ahci->port[i].fb + 0x20, pio, 0x20);

    memread(ahci->port[i].fb + 0x40, d2h, 0x20);

    g_assert_cmphex(pio->fis_type, ==, 0x5f);

    g_assert_cmphex(d2h->fis_type, ==, 0x34);

    g_assert_cmphex(pio->flags, ==, d2h->flags);

    g_assert_cmphex(pio->status, ==, d2h->status);

    g_assert_cmphex(pio->error, ==, d2h->error);

    reg = ahci_px_rreg(ahci, i, AHCI_PX_TFD);

    g_assert_cmphex((reg & AHCI_PX_TFD_ERR), ==, pio->error);

    g_assert_cmphex((reg & AHCI_PX_TFD_STS), ==, pio->status);

    /* The PIO Setup FIS contains a "bytes read" field, which is a

     * 16-bit value. The Physical Region Descriptor Byte Count is

     * 32-bit, but for small transfers using one PRD, it should match. */

    g_assert_cmphex(le16_to_cpu(pio->res4), ==, cmd.prdbc);

    /* Last, but not least: Investigate the IDENTIFY response data. */

    memread(data_ptr, &buff, 512);

    /* Check serial number/version in the buffer */

    /* NB: IDENTIFY strings are packed in 16bit little endian chunks.

     * Since we copy byte-for-byte in ahci-test, on both LE and BE, we need to

     * unchunk this data. By contrast, ide-test copies 2 bytes at a time, and

     * as a consequence, only needs to unchunk the data on LE machines. */

    string_bswap16(&buff[10], 20);

    rc = memcmp(&buff[10], "testdisk            ", 20);

    g_assert_cmphex(rc, ==, 0);

    string_bswap16(&buff[23], 8);

    rc = memcmp(&buff[23], "version ", 8);

    g_assert_cmphex(rc, ==, 0);

    g_free(d2h);

    g_free(pio);

}


void opt_output_file(const char *filename)

{

    AVStream *st;

    AVFormatContext *oc;

    int use_video, use_audio, nb_streams, input_has_video, input_has_audio;

    int codec_id;

    if (!strcmp(filename, "-"))

        filename = "pipe:";

    oc = av_mallocz(sizeof(AVFormatContext));

    if (!file_format) {

        file_format = guess_format(NULL, filename, NULL);

        if (!file_format)

            file_format = &mpeg_mux_format;

    }

    oc->format = file_format;

    if (!strcmp(file_format->name, "ffm") &&

        strstart(filename, "http:", NULL)) {

        /* special case for files sent to ffserver: we get the stream

           parameters from ffserver */

        if (read_ffserver_streams(oc, filename) < 0) {

            fprintf(stderr, "Could not read stream parameters from '%s'\n", filename);

            exit(1);

        }

    } else {

        use_video = file_format->video_codec != CODEC_ID_NONE;

        use_audio = file_format->audio_codec != CODEC_ID_NONE;

        /* disable if no corresponding type found */

        check_audio_video_inputs(&input_has_video, &input_has_audio);

        if (!input_has_video)

            use_video = 0;

        if (!input_has_audio)

            use_audio = 0;

        /* manual disable */

        if (audio_disable) {

            use_audio = 0;

        }

        if (video_disable) {

            use_video = 0;

        }

        nb_streams = 0;

        if (use_video) {

            AVCodecContext *video_enc;

            st = av_mallocz(sizeof(AVStream));

            if (!st) {

                fprintf(stderr, "Could not alloc stream\n");

                exit(1);

            }

            video_enc = &st->codec;

            codec_id = file_format->video_codec;

            if (video_codec_id != CODEC_ID_NONE)

                codec_id = video_codec_id;

            video_enc->codec_id = codec_id;

            video_enc->codec_type = CODEC_TYPE_VIDEO;

            video_enc->bit_rate = video_bit_rate;

            video_enc->frame_rate = frame_rate;

            video_enc->width = frame_width;

            video_enc->height = frame_height;

            if (!intra_only)

                video_enc->gop_size = gop_size;

            else

                video_enc->gop_size = 0;

            if (video_qscale || same_quality) {

                video_enc->flags |= CODEC_FLAG_QSCALE;

                video_enc->quality = video_qscale;

            }

            /* XXX: need to find a way to set codec parameters */

            if (oc->format == &ppm_format ||

                oc->format == &ppmpipe_format) {

                video_enc->pix_fmt = PIX_FMT_RGB24;

            }

            oc->streams[nb_streams] = st;

            nb_streams++;

        }

        if (use_audio) {

            AVCodecContext *audio_enc;

            st = av_mallocz(sizeof(AVStream));

            if (!st) {

                fprintf(stderr, "Could not alloc stream\n");

                exit(1);

            }

            audio_enc = &st->codec;

            codec_id = file_format->audio_codec;

            if (audio_codec_id != CODEC_ID_NONE)

                codec_id = audio_codec_id;

            audio_enc->codec_id = codec_id;

            audio_enc->codec_type = CODEC_TYPE_AUDIO;

            audio_enc->bit_rate = audio_bit_rate;

            audio_enc->sample_rate = audio_sample_rate;

            audio_enc->channels = audio_channels;

            oc->streams[nb_streams] = st;

            nb_streams++;

        }

        oc->nb_streams = nb_streams;

        if (!nb_streams) {

            fprintf(stderr, "No audio or video streams available\n");

            exit(1);

        }

        if (str_title)

            nstrcpy(oc->title, sizeof(oc->title), str_title);

        if (str_author)

            nstrcpy(oc->author, sizeof(oc->author), str_author);

        if (str_copyright)

            nstrcpy(oc->copyright, sizeof(oc->copyright), str_copyright);

        if (str_comment)

            nstrcpy(oc->comment, sizeof(oc->comment), str_comment);

    }

    output_files[nb_output_files] = oc;

    /* dump the file content */

    dump_format(oc, nb_output_files, filename, 1);

    nb_output_files++;

    strcpy(oc->filename, filename);

    /* check filename in case of an image number is expected */

    if (oc->format->flags & AVFMT_NEEDNUMBER) {

        if (filename_number_test(oc->filename) < 0)

            exit(1);

    }

    if (!(oc->format->flags & AVFMT_NOFILE)) {

        /* test if it already exists to avoid loosing precious files */

        if (!file_overwrite &&

            (strchr(filename, ':') == NULL ||

             strstart(filename, "file:", NULL))) {

            if (url_exist(filename)) {

                int c;

                printf("File '%s' already exists. Overwrite ? [y/N] ", filename);

                fflush(stdout);

                c = getchar();

                if (toupper(c) != 'Y') {

                    fprintf(stderr, "Not overwriting - exiting\n");

                    exit(1);

                }

            }

        }

        /* open the file */

        if (url_fopen(&oc->pb, filename, URL_WRONLY) < 0) {

            fprintf(stderr, "Could not open '%s'\n", filename);

            exit(1);

        }

    }

    /* reset some options */

    file_format = NULL;

    audio_disable = 0;

    video_disable = 0;

    audio_codec_id = CODEC_ID_NONE;

    video_codec_id = CODEC_ID_NONE;

}


int xen_hvm_init(void)

{

    int i, rc;

    unsigned long ioreq_pfn;

    XenIOState *state;

    state = g_malloc0(sizeof (XenIOState));

    state->xce_handle = xen_xc_evtchn_open(NULL, 0);

    if (state->xce_handle == XC_HANDLER_INITIAL_VALUE) {

        perror("xen: event channel open");

        return -errno;

    }

    state->xenstore = xs_daemon_open();

    if (state->xenstore == NULL) {

        perror("xen: xenstore open");

        return -errno;

    }

    state->exit.notify = xen_exit_notifier;

    qemu_add_exit_notifier(&state->exit);

    state->suspend.notify = xen_suspend_notifier;

    qemu_register_suspend_notifier(&state->suspend);

    xc_get_hvm_param(xen_xc, xen_domid, HVM_PARAM_IOREQ_PFN, &ioreq_pfn);

    DPRINTF("shared page at pfn %lx\n", ioreq_pfn);

    state->shared_page = xc_map_foreign_range(xen_xc, xen_domid, XC_PAGE_SIZE,

                                              PROT_READ|PROT_WRITE, ioreq_pfn);

    if (state->shared_page == NULL) {

        hw_error("map shared IO page returned error %d handle=" XC_INTERFACE_FMT,

                 errno, xen_xc);

    }

    xc_get_hvm_param(xen_xc, xen_domid, HVM_PARAM_BUFIOREQ_PFN, &ioreq_pfn);

    DPRINTF("buffered io page at pfn %lx\n", ioreq_pfn);

    state->buffered_io_page = xc_map_foreign_range(xen_xc, xen_domid, XC_PAGE_SIZE,

                                                   PROT_READ|PROT_WRITE, ioreq_pfn);

    if (state->buffered_io_page == NULL) {

        hw_error("map buffered IO page returned error %d", errno);

    }

    state->ioreq_local_port = g_malloc0(smp_cpus * sizeof (evtchn_port_t));

    /* FIXME: how about if we overflow the page here? */

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

        rc = xc_evtchn_bind_interdomain(state->xce_handle, xen_domid,

                                        xen_vcpu_eport(state->shared_page, i));

        if (rc == -1) {

            fprintf(stderr, "bind interdomain ioctl error %d\n", errno);

            return -1;

        }

        state->ioreq_local_port[i] = rc;

    }

    /* Init RAM management */

    xen_map_cache_init();

    xen_ram_init(ram_size);

    qemu_add_vm_change_state_handler(xen_hvm_change_state_handler, state);

    state->memory_listener = xen_memory_listener;

    QLIST_INIT(&state->physmap);

    memory_listener_register(&state->memory_listener);

    state->log_for_dirtybit = NULL;

    /* Initialize backend core & drivers */

    if (xen_be_init() != 0) {

        fprintf(stderr, "%s: xen backend core setup failed\n", __FUNCTION__);

        exit(1);

    }

    xen_be_register("console", &xen_console_ops);

    xen_be_register("vkbd", &xen_kbdmouse_ops);

    xen_be_register("qdisk", &xen_blkdev_ops);

    xen_read_physmap(state);

    return 0;

}


static void nic_receive(void *opaque, const uint8_t * buf, size_t size)

{

    /* TODO:

     * - Magic packets should set bit 30 in power management driver register.

     * - Interesting packets should set bit 29 in power management driver register.

     */

    EEPRO100State *s = opaque;

    uint16_t rfd_status = 0xa000;

    static const uint8_t broadcast_macaddr[6] =

        { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };

    /* TODO: check multiple IA bit. */

    assert(!(s->configuration[20] & BIT(6)));

    if (s->configuration[8] & 0x80) {

        /* CSMA is disabled. */

        logout("%p received while CSMA is disabled\n", s);

        return;

    } else if (size < 64 && (s->configuration[7] & 1)) {

        /* Short frame and configuration byte 7/0 (discard short receive) set:

         * Short frame is discarded */

        logout("%p received short frame (%d byte)\n", s, size);

        s->statistics.rx_short_frame_errors++;

        //~ return;

    } else if ((size > MAX_ETH_FRAME_SIZE + 4) && !(s->configuration[18] & 8)) {

        /* Long frame and configuration byte 18/3 (long receive ok) not set:

         * Long frames are discarded. */

        logout("%p received long frame (%d byte), ignored\n", s, size);

        return;

    } else if (memcmp(buf, s->macaddr, 6) == 0) {       // !!!

        /* Frame matches individual address. */

        /* TODO: check configuration byte 15/4 (ignore U/L). */

        logout("%p received frame for me, len=%d\n", s, size);

    } else if (memcmp(buf, broadcast_macaddr, 6) == 0) {

        /* Broadcast frame. */

        logout("%p received broadcast, len=%d\n", s, size);

        rfd_status |= 0x0002;

    } else if (buf[0] & 0x01) { // !!!

        /* Multicast frame. */

        logout("%p received multicast, len=%d\n", s, size);

        /* TODO: check multicast all bit. */

        assert(!(s->configuration[21] & BIT(3)));

        int mcast_idx = compute_mcast_idx(buf);

        if (!(s->mult[mcast_idx >> 3] & (1 << (mcast_idx & 7)))) {

            return;

        }

        rfd_status |= 0x0002;

    } else if (s->configuration[15] & 1) {

        /* Promiscuous: receive all. */

        logout("%p received frame in promiscuous mode, len=%d\n", s, size);

        rfd_status |= 0x0004;

    } else {

        logout("%p received frame, ignored, len=%d,%s\n", s, size,

               nic_dump(buf, size));

        return;

    }

    if (get_ru_state(s) != ru_ready) {

        /* No ressources available. */

        logout("no ressources, state=%u\n", get_ru_state(s));

        s->statistics.rx_resource_errors++;

        //~ assert(!"no ressources");

        return;

    }

    //~ !!!

//~ $3 = {status = 0x0, command = 0xc000, link = 0x2d220, rx_buf_addr = 0x207dc, count = 0x0, size = 0x5f8, packet = {0x0 <repeats 1518 times>}}

    eepro100_rx_t rx;

    cpu_physical_memory_read(s->ru_base + s->ru_offset, (uint8_t *) & rx,

                             offsetof(eepro100_rx_t, packet));

    uint16_t rfd_command = le16_to_cpu(rx.command);

    uint16_t rfd_size = le16_to_cpu(rx.size);

    assert(size <= rfd_size);

    if (size < 64) {

        rfd_status |= 0x0080;

    }

    logout("command 0x%04x, link 0x%08x, addr 0x%08x, size %u\n", rfd_command,

           rx.link, rx.rx_buf_addr, rfd_size);

    stw_phys(s->ru_base + s->ru_offset + offsetof(eepro100_rx_t, status),

             rfd_status);

    stw_phys(s->ru_base + s->ru_offset + offsetof(eepro100_rx_t, count), size);

    /* Early receive interrupt not supported. */

    //~ eepro100_er_interrupt(s);

    /* Receive CRC Transfer not supported. */

    assert(!(s->configuration[18] & 4));

    /* TODO: check stripping enable bit. */

    //~ assert(!(s->configuration[17] & 1));

    cpu_physical_memory_write(s->ru_base + s->ru_offset +

                              offsetof(eepro100_rx_t, packet), buf, size);

    s->statistics.rx_good_frames++;

    eepro100_fr_interrupt(s);

    s->ru_offset = le32_to_cpu(rx.link);

    if (rfd_command & 0x8000) {

        /* EL bit is set, so this was the last frame. */

        assert(0);

    }

    if (rfd_command & 0x4000) {

        /* S bit is set. */

        set_ru_state(s, ru_suspended);

    }

}


static inline void tcg_out_brcond(TCGContext *s, TCGCond cond, TCGReg arg1,

                                  TCGReg arg2, int label_index, int cmp4)

{

    TCGLabel *l = &s->labels[label_index];

    uint64_t imm;

    /* We pay attention here to not modify the branch target by reading

       the existing value and using it again. This ensure that caches and

       memory are kept coherent during retranslation. */

    if (l->has_value) {

        imm = l->u.value_ptr - s->code_ptr;

    } else {

        imm = get_reloc_pcrel21b_slot2(s->code_ptr);

        tcg_out_reloc(s, s->code_ptr, R_IA64_PCREL21B, label_index, 0);

    }

    tcg_out_bundle(s, miB,

                   INSN_NOP_M,

                   tcg_opc_cmp_a(TCG_REG_P0, cond, arg1, arg2, cmp4),

                   tcg_opc_b1(TCG_REG_P6, OPC_BR_DPTK_FEW_B1, imm));

}


static int handle_buffered_iopage(XenIOState *state)

{

    buffered_iopage_t *buf_page = state->buffered_io_page;

    buf_ioreq_t *buf_req = NULL;

    ioreq_t req;

    int qw;

    if (!buf_page) {

        return 0;

    }

    memset(&req, 0x00, sizeof(req));

    for (;;) {

        uint32_t rdptr = buf_page->read_pointer, wrptr;

        xen_rmb();

        wrptr = buf_page->write_pointer;

        xen_rmb();

        if (rdptr != buf_page->read_pointer) {

            continue;

        }

        if (rdptr == wrptr) {

            break;

        }

        buf_req = &buf_page->buf_ioreq[rdptr % IOREQ_BUFFER_SLOT_NUM];

        req.size = 1UL << buf_req->size;

        req.count = 1;

        req.addr = buf_req->addr;

        req.data = buf_req->data;

        req.state = STATE_IOREQ_READY;

        req.dir = buf_req->dir;

        req.df = 1;

        req.type = buf_req->type;

        req.data_is_ptr = 0;

        xen_rmb();

        qw = (req.size == 8);

        if (qw) {

            if (rdptr + 1 == wrptr) {

                hw_error("Incomplete quad word buffered ioreq");

            }

            buf_req = &buf_page->buf_ioreq[(rdptr + 1) %

                                           IOREQ_BUFFER_SLOT_NUM];

            req.data |= ((uint64_t)buf_req->data) << 32;

            xen_rmb();

        }

        handle_ioreq(state, &req);

        atomic_add(&buf_page->read_pointer, qw + 1);

    }

    return req.count;

}


void virtio_bus_device_plugged(VirtIODevice *vdev, Error **errp)

{

    DeviceState *qdev = DEVICE(vdev);

    BusState *qbus = BUS(qdev_get_parent_bus(qdev));

    VirtioBusState *bus = VIRTIO_BUS(qbus);

    VirtioBusClass *klass = VIRTIO_BUS_GET_CLASS(bus);

    VirtioDeviceClass *vdc = VIRTIO_DEVICE_GET_CLASS(vdev);

    DPRINTF("%s: plug device.\n", qbus->name);

    if (klass->device_plugged != NULL) {

        klass->device_plugged(qbus->parent, errp);

    }

    /* Get the features of the plugged device. */

    assert(vdc->get_features != NULL);

    vdev->host_features = vdc->get_features(vdev, vdev->host_features,

                                            errp);

    if (klass->post_plugged != NULL) {

        klass->post_plugged(qbus->parent, errp);

    }

}


GSource *aio_get_g_source(AioContext *ctx)

{

    g_source_ref(&ctx->source);

    return &ctx->source;

}


static int decode_frame_mp3on4(AVCodecContext * avctx,

                        void *data, int *data_size,

                        const uint8_t * buf, int buf_size)

{

    MP3On4DecodeContext *s = avctx->priv_data;

    MPADecodeContext *m;

    int len, out_size = 0;

    uint32_t header;

    OUT_INT *out_samples = data;

    OUT_INT decoded_buf[MPA_FRAME_SIZE * MPA_MAX_CHANNELS];

    OUT_INT *outptr, *bp;

    int fsize;

    int fr, i, j, n;

    len = buf_size;

    *data_size = 0;

    // Discard too short frames

    if (buf_size < HEADER_SIZE)

        return -1;

    // If only one decoder interleave is not needed

    outptr = s->frames == 1 ? out_samples : decoded_buf;

    for (fr = 0; fr < s->frames; fr++) {

        fsize = AV_RB16(buf) >> 4;

        fsize = FFMIN3(fsize, len, MPA_MAX_CODED_FRAME_SIZE);

        m = s->mp3decctx[fr];

        assert (m != NULL);

        header = (AV_RB32(buf) & 0x000fffff) | s->syncword; // patch header

        if (ff_mpa_check_header(header) < 0) { // Bad header, discard block

            *data_size = 0;

            return buf_size;

        }

        ff_mpegaudio_decode_header(m, header);

        out_size += mp_decode_frame(m, outptr, buf, fsize);

        buf += fsize;

        len -= fsize;

        if(s->frames > 1) {

            n = m->avctx->frame_size*m->nb_channels;

            /* interleave output data */

            bp = out_samples + s->coff[fr];

            if(m->nb_channels == 1) {

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

                    *bp = decoded_buf[j];

                    bp += avctx->channels;

                }

            } else {

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

                    bp[0] = decoded_buf[j++];

                    bp[1] = decoded_buf[j];

                    bp += avctx->channels;

                }

            }

        }

    }

    /* update codec info */

    avctx->sample_rate = s->mp3decctx[0]->sample_rate;

    avctx->bit_rate = 0;

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

        avctx->bit_rate += s->mp3decctx[i]->bit_rate;

    *data_size = out_size;

    return buf_size;

}


int rom_add_option(const char *file)

{

    if (!rom_enable_driver_roms)

        return 0;

    return rom_add_file(file, "genroms", file, 0);

}


static target_ulong h_client_architecture_support(PowerPCCPU *cpu_,

                                                  sPAPRMachineState *spapr,

                                                  target_ulong opcode,

                                                  target_ulong *args)

{

    target_ulong list = ppc64_phys_to_real(args[0]);

    target_ulong ov_table;

    PowerPCCPUClass *pcc = POWERPC_CPU_GET_CLASS(cpu_);

    CPUState *cs;

    bool cpu_match = false, cpu_update = true;

    unsigned old_cpu_version = cpu_->cpu_version;

    unsigned compat_lvl = 0, cpu_version = 0;

    unsigned max_lvl = get_compat_level(cpu_->max_compat);

    int counter;

    sPAPROptionVector *ov5_guest, *ov5_cas_old, *ov5_updates;

    /* Parse PVR list */

    for (counter = 0; counter < 512; ++counter) {

        uint32_t pvr, pvr_mask;

        pvr_mask = ldl_be_phys(&address_space_memory, list);

        list += 4;

        pvr = ldl_be_phys(&address_space_memory, list);

        list += 4;

        trace_spapr_cas_pvr_try(pvr);

        if (!max_lvl &&

            ((cpu_->env.spr[SPR_PVR] & pvr_mask) == (pvr & pvr_mask))) {

            cpu_match = true;

            cpu_version = 0;

        } else if (pvr == cpu_->cpu_version) {

            cpu_match = true;

            cpu_version = cpu_->cpu_version;

        } else if (!cpu_match) {

            cas_handle_compat_cpu(pcc, pvr, max_lvl, &compat_lvl, &cpu_version);

        }

        /* Terminator record */

        if (~pvr_mask & pvr) {

            break;

        }

    }

    /* Parsing finished */

    trace_spapr_cas_pvr(cpu_->cpu_version, cpu_match,

                        cpu_version, pcc->pcr_mask);

    /* Update CPUs */

    if (old_cpu_version != cpu_version) {

        CPU_FOREACH(cs) {

            SetCompatState s = {

                .cpu_version = cpu_version,

                .err = NULL,

            };

            run_on_cpu(cs, do_set_compat, RUN_ON_CPU_HOST_PTR(&s));

            if (s.err) {

                error_report_err(s.err);

                return H_HARDWARE;

            }

        }

    }

    if (!cpu_version) {

        cpu_update = false;

    }

    /* For the future use: here @ov_table points to the first option vector */

    ov_table = list;

    ov5_guest = spapr_ovec_parse_vector(ov_table, 5);

    /* NOTE: there are actually a number of ov5 bits where input from the

     * guest is always zero, and the platform/QEMU enables them independently

     * of guest input. To model these properly we'd want some sort of mask,

     * but since they only currently apply to memory migration as defined

     * by LoPAPR 1.1, 14.5.4.8, which QEMU doesn't implement, we don't need

     * to worry about this for now.

     */

    ov5_cas_old = spapr_ovec_clone(spapr->ov5_cas);

    /* full range of negotiated ov5 capabilities */

    spapr_ovec_intersect(spapr->ov5_cas, spapr->ov5, ov5_guest);

    spapr_ovec_cleanup(ov5_guest);

    /* capabilities that have been added since CAS-generated guest reset.

     * if capabilities have since been removed, generate another reset

     */

    ov5_updates = spapr_ovec_new();

    spapr->cas_reboot = spapr_ovec_diff(ov5_updates,

                                        ov5_cas_old, spapr->ov5_cas);

    if (!spapr->cas_reboot) {

        spapr->cas_reboot =

            (spapr_h_cas_compose_response(spapr, args[1], args[2], cpu_update,

                                          ov5_updates) != 0);

    }

    spapr_ovec_cleanup(ov5_updates);

    if (spapr->cas_reboot) {

        qemu_system_reset_request();

    }

    return H_SUCCESS;

}


static void rtas_ibm_configure_connector(PowerPCCPU *cpu,

                                         sPAPRMachineState *spapr,

                                         uint32_t token, uint32_t nargs,

                                         target_ulong args, uint32_t nret,

                                         target_ulong rets)

{

    uint64_t wa_addr;

    uint64_t wa_offset;

    uint32_t drc_index;

    sPAPRDRConnector *drc;

    sPAPRDRConnectorClass *drck;

    sPAPRConfigureConnectorState *ccs;

    sPAPRDRCCResponse resp = SPAPR_DR_CC_RESPONSE_CONTINUE;

    int rc;

    if (nargs != 2 || nret != 1) {

        rtas_st(rets, 0, RTAS_OUT_PARAM_ERROR);

        return;

    }

    wa_addr = ((uint64_t)rtas_ld(args, 1) << 32) | rtas_ld(args, 0);

    drc_index = rtas_ld(wa_addr, 0);

    drc = spapr_drc_by_index(drc_index);

    if (!drc) {

        trace_spapr_rtas_ibm_configure_connector_invalid(drc_index);

        rc = RTAS_OUT_PARAM_ERROR;

        goto out;

    }

    if ((drc->state != SPAPR_DRC_STATE_LOGICAL_UNISOLATE)

        && (drc->state != SPAPR_DRC_STATE_PHYSICAL_UNISOLATE)) {

        /* Need to unisolate the device before configuring */

        rc = SPAPR_DR_CC_RESPONSE_NOT_CONFIGURABLE;

        goto out;

    }

    g_assert(drc->fdt);

    drck = SPAPR_DR_CONNECTOR_GET_CLASS(drc);

    ccs = drc->ccs;

    if (!ccs) {

        ccs = g_new0(sPAPRConfigureConnectorState, 1);

        ccs->fdt_offset = drc->fdt_start_offset;

        drc->ccs = ccs;

    }

    do {

        uint32_t tag;

        const char *name;

        const struct fdt_property *prop;

        int fdt_offset_next, prop_len;

        tag = fdt_next_tag(drc->fdt, ccs->fdt_offset, &fdt_offset_next);

        switch (tag) {

        case FDT_BEGIN_NODE:

            ccs->fdt_depth++;

            name = fdt_get_name(drc->fdt, ccs->fdt_offset, NULL);

            /* provide the name of the next OF node */

            wa_offset = CC_VAL_DATA_OFFSET;

            rtas_st(wa_addr, CC_IDX_NODE_NAME_OFFSET, wa_offset);

            configure_connector_st(wa_addr, wa_offset, name, strlen(name) + 1);

            resp = SPAPR_DR_CC_RESPONSE_NEXT_CHILD;

            break;

        case FDT_END_NODE:

            ccs->fdt_depth--;

            if (ccs->fdt_depth == 0) {

                uint32_t drc_index = spapr_drc_index(drc);

                /* done sending the device tree, move to configured state */

                trace_spapr_drc_set_configured(drc_index);

                drc->state = drck->ready_state;

                g_free(ccs);

                drc->ccs = NULL;

                ccs = NULL;

                resp = SPAPR_DR_CC_RESPONSE_SUCCESS;

            } else {

                resp = SPAPR_DR_CC_RESPONSE_PREV_PARENT;

            }

            break;

        case FDT_PROP:

            prop = fdt_get_property_by_offset(drc->fdt, ccs->fdt_offset,

                                              &prop_len);

            name = fdt_string(drc->fdt, fdt32_to_cpu(prop->nameoff));

            /* provide the name of the next OF property */

            wa_offset = CC_VAL_DATA_OFFSET;

            rtas_st(wa_addr, CC_IDX_PROP_NAME_OFFSET, wa_offset);

            configure_connector_st(wa_addr, wa_offset, name, strlen(name) + 1);

            /* provide the length and value of the OF property. data gets

             * placed immediately after NULL terminator of the OF property's

             * name string

             */

            wa_offset += strlen(name) + 1,

            rtas_st(wa_addr, CC_IDX_PROP_LEN, prop_len);

            rtas_st(wa_addr, CC_IDX_PROP_DATA_OFFSET, wa_offset);

            configure_connector_st(wa_addr, wa_offset, prop->data, prop_len);

            resp = SPAPR_DR_CC_RESPONSE_NEXT_PROPERTY;

            break;

        case FDT_END:

            resp = SPAPR_DR_CC_RESPONSE_ERROR;

        default:

            /* keep seeking for an actionable tag */

            break;

        }

        if (ccs) {

            ccs->fdt_offset = fdt_offset_next;

        }

    } while (resp == SPAPR_DR_CC_RESPONSE_CONTINUE);

    rc = resp;

out:

    rtas_st(rets, 0, rc);

}


static void term_show_prompt2(void)

{

    term_printf("(qemu) ");

    fflush(stdout);

    term_last_cmd_buf_index = 0;

    term_last_cmd_buf_size = 0;

    term_esc_state = IS_NORM;

}


static void pxa2xx_lcdc_write(void *opaque, hwaddr offset,

                              uint64_t value, unsigned size)

{

    PXA2xxLCDState *s = (PXA2xxLCDState *) opaque;

    int ch;

    switch (offset) {

    case LCCR0:

        /* ACK Quick Disable done */

        if ((s->control[0] & LCCR0_ENB) && !(value & LCCR0_ENB))

            s->status[0] |= LCSR0_QD;

        if (!(s->control[0] & LCCR0_LCDT) && (value & LCCR0_LCDT))

            printf("%s: internal frame buffer unsupported\n", __FUNCTION__);

        if ((s->control[3] & LCCR3_API) &&

                (value & LCCR0_ENB) && !(value & LCCR0_LCDT))

            s->status[0] |= LCSR0_ABC;

        s->control[0] = value & 0x07ffffff;

        pxa2xx_lcdc_int_update(s);

        s->dma_ch[0].up = !!(value & LCCR0_ENB);

        s->dma_ch[1].up = (s->ovl1c[0] & OVLC1_EN) || (value & LCCR0_SDS);

        break;

    case LCCR1:

        s->control[1] = value;

        break;

    case LCCR2:

        s->control[2] = value;

        break;

    case LCCR3:

        s->control[3] = value & 0xefffffff;

        s->bpp = LCCR3_BPP(value);

        break;

    case LCCR4:

        s->control[4] = value & 0x83ff81ff;

        break;

    case LCCR5:

        s->control[5] = value & 0x3f3f3f3f;

        break;

    case OVL1C1:

        if (!(s->ovl1c[0] & OVLC1_EN) && (value & OVLC1_EN))

            printf("%s: Overlay 1 not supported\n", __FUNCTION__);

        s->ovl1c[0] = value & 0x80ffffff;

        s->dma_ch[1].up = (value & OVLC1_EN) || (s->control[0] & LCCR0_SDS);

        break;

    case OVL1C2:

        s->ovl1c[1] = value & 0x000fffff;

        break;

    case OVL2C1:

        if (!(s->ovl2c[0] & OVLC1_EN) && (value & OVLC1_EN))

            printf("%s: Overlay 2 not supported\n", __FUNCTION__);

        s->ovl2c[0] = value & 0x80ffffff;

        s->dma_ch[2].up = !!(value & OVLC1_EN);

        s->dma_ch[3].up = !!(value & OVLC1_EN);

        s->dma_ch[4].up = !!(value & OVLC1_EN);

        break;

    case OVL2C2:

        s->ovl2c[1] = value & 0x007fffff;

        break;

    case CCR:

        if (!(s->ccr & CCR_CEN) && (value & CCR_CEN))

            printf("%s: Hardware cursor unimplemented\n", __FUNCTION__);

        s->ccr = value & 0x81ffffe7;

        s->dma_ch[5].up = !!(value & CCR_CEN);

        break;

    case CMDCR:

        s->cmdcr = value & 0xff;

        break;

    case TRGBR:

        s->trgbr = value & 0x00ffffff;

        break;

    case TCR:

        s->tcr = value & 0x7fff;

        break;

    case 0x200 ... 0x1000:	/* DMA per-channel registers */

        ch = (offset - 0x200) >> 4;

        if (!(ch >= 0 && ch < PXA_LCDDMA_CHANS))

            goto fail;

        switch (offset & 0xf) {

        case DMA_FDADR:

            s->dma_ch[ch].descriptor = value & 0xfffffff0;

            break;

        default:

            goto fail;

        }

        break;

    case FBR0:

        s->dma_ch[0].branch = value & 0xfffffff3;

        break;

    case FBR1:

        s->dma_ch[1].branch = value & 0xfffffff3;

        break;

    case FBR2:

        s->dma_ch[2].branch = value & 0xfffffff3;

        break;

    case FBR3:

        s->dma_ch[3].branch = value & 0xfffffff3;

        break;

    case FBR4:

        s->dma_ch[4].branch = value & 0xfffffff3;

        break;

    case FBR5:

        s->dma_ch[5].branch = value & 0xfffffff3;

        break;

    case FBR6:

        s->dma_ch[6].branch = value & 0xfffffff3;

        break;

    case BSCNTR:

        s->bscntr = value & 0xf;

        break;

    case PRSR:

        break;

    case LCSR0:

        s->status[0] &= ~(value & 0xfff);

        if (value & LCSR0_BER)

            s->status[0] &= ~LCSR0_BERCH(7);

        break;

    case LCSR1:

        s->status[1] &= ~(value & 0x3e3f3f);

        break;

    default:

    fail:

        hw_error("%s: Bad offset " REG_FMT "\n", __FUNCTION__, offset);

    }

}


static void v9fs_clunk(void *opaque)

{

    int err;

    int32_t fid;

    size_t offset = 7;

    V9fsFidState *fidp;

    V9fsPDU *pdu = opaque;

    V9fsState *s = pdu->s;

    pdu_unmarshal(pdu, offset, "d", &fid);

    trace_v9fs_clunk(pdu->tag, pdu->id, fid);

    fidp = clunk_fid(s, fid);

    if (fidp == NULL) {

        err = -ENOENT;

        goto out_nofid;

    }

    /*

     * Bump the ref so that put_fid will

     * free the fid.

     */

    fidp->ref++;

    err = offset;

    put_fid(pdu, fidp);

out_nofid:

    complete_pdu(s, pdu, err);

}