static void x86_cpu_parse_featurestr(CPUState *cs, char *features,

                                     Error **errp)

{

    X86CPU *cpu = X86_CPU(cs);

    char *featurestr; /* Single 'key=value" string being parsed */

    FeatureWord w;

    /* Features to be added */

    FeatureWordArray plus_features = { 0 };

    /* Features to be removed */

    FeatureWordArray minus_features = { 0 };

    CPUX86State *env = &cpu->env;

    Error *local_err = NULL;

    featurestr = features ? strtok(features, ",") : NULL;

    while (featurestr) {

        char *val;

        if (featurestr[0] == '+') {

            add_flagname_to_bitmaps(featurestr + 1, plus_features, &local_err);

        } else if (featurestr[0] == '-') {

            add_flagname_to_bitmaps(featurestr + 1, minus_features, &local_err);

        } else if ((val = strchr(featurestr, '='))) {

            *val = 0; val++;

            feat2prop(featurestr);

            if (!strcmp(featurestr, "tsc-freq")) {

                int64_t tsc_freq;

                char *err;

                char num[32];

                tsc_freq = qemu_strtosz_suffix_unit(val, &err,

                                               QEMU_STRTOSZ_DEFSUFFIX_B, 1000);

                if (tsc_freq < 0 || *err) {

                    error_setg(errp, "bad numerical value %s", val);

                    return;

                }

                snprintf(num, sizeof(num), "%" PRId64, tsc_freq);

                object_property_parse(OBJECT(cpu), num, "tsc-frequency",

                                      &local_err);

            } else {

                object_property_parse(OBJECT(cpu), val, featurestr, &local_err);

            }

        } else {

            feat2prop(featurestr);

            object_property_parse(OBJECT(cpu), "on", featurestr, &local_err);

        }

        if (local_err) {

            error_propagate(errp, local_err);

            return;

        }

        featurestr = strtok(NULL, ",");

    }

    if (cpu->host_features) {

        for (w = 0; w < FEATURE_WORDS; w++) {

            env->features[w] =

                x86_cpu_get_supported_feature_word(w, cpu->migratable);

        }

    }

    for (w = 0; w < FEATURE_WORDS; w++) {

        env->features[w] |= plus_features[w];

        env->features[w] &= ~minus_features[w];

    }

}


static void do_sendkey(const char *string)

{

    uint8_t keycodes[16];

    int nb_keycodes = 0;

    char keyname_buf[16];

    char *separator;

    int keyname_len, keycode, i;

    while (1) {

        separator = strchr(string, '-');

        keyname_len = separator ? separator - string : strlen(string);

        if (keyname_len > 0) {

            pstrcpy(keyname_buf, sizeof(keyname_buf), string);

            if (keyname_len > sizeof(keyname_buf) - 1) {

                term_printf("invalid key: '%s...'\n", keyname_buf);

                return;

            }

            if (nb_keycodes == sizeof(keycodes)) {

                term_printf("too many keys\n");

                return;

            }

            keyname_buf[keyname_len] = 0;

            keycode = get_keycode(keyname_buf);

            if (keycode < 0) {

                term_printf("unknown key: '%s'\n", keyname_buf);

                return;

            }

            keycodes[nb_keycodes++] = keycode;

        }

        if (!separator)

            break;

        string = separator + 1;

    }

    /* key down events */

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

        keycode = keycodes[i];

        if (keycode & 0x80)

            kbd_put_keycode(0xe0);

        kbd_put_keycode(keycode & 0x7f);

    }

    /* key up events */

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

        keycode = keycodes[i];

        if (keycode & 0x80)

            kbd_put_keycode(0xe0);

        kbd_put_keycode(keycode | 0x80);

    }

}


static int nbd_co_receive_request(NBDRequestData *req, NBDRequest *request,

                                  Error **errp)

{

    NBDClient *client = req->client;

    g_assert(qemu_in_coroutine());

    assert(client->recv_coroutine == qemu_coroutine_self());

    if (nbd_receive_request(client->ioc, request, errp) < 0) {

        return -EIO;

    }

    trace_nbd_co_receive_request_decode_type(request->handle, request->type);

    if (request->type != NBD_CMD_WRITE) {

        /* No payload, we are ready to read the next request.  */

        req->complete = true;

    }

    if (request->type == NBD_CMD_DISC) {

        /* Special case: we're going to disconnect without a reply,

         * whether or not flags, from, or len are bogus */

        return -EIO;

    }

    /* Check for sanity in the parameters, part 1.  Defer as many

     * checks as possible until after reading any NBD_CMD_WRITE

     * payload, so we can try and keep the connection alive.  */

    if ((request->from + request->len) < request->from) {

        error_setg(errp,

                   "integer overflow detected, you're probably being attacked");

        return -EINVAL;

    }

    if (request->type == NBD_CMD_READ || request->type == NBD_CMD_WRITE) {

        if (request->len > NBD_MAX_BUFFER_SIZE) {

            error_setg(errp, "len (%" PRIu32" ) is larger than max len (%u)",

                       request->len, NBD_MAX_BUFFER_SIZE);

            return -EINVAL;

        }

        req->data = blk_try_blockalign(client->exp->blk, request->len);

        if (req->data == NULL) {

            error_setg(errp, "No memory");

            return -ENOMEM;

        }

    }

    if (request->type == NBD_CMD_WRITE) {

        if (nbd_read(client->ioc, req->data, request->len, errp) < 0) {

            error_prepend(errp, "reading from socket failed: ");

            return -EIO;

        }

        req->complete = true;

        trace_nbd_co_receive_request_payload_received(request->handle,

                                                      request->len);

    }

    /* Sanity checks, part 2. */

    if (request->from + request->len > client->exp->size) {

        error_setg(errp, "operation past EOF; From: %" PRIu64 ", Len: %" PRIu32

                   ", Size: %" PRIu64, request->from, request->len,

                   (uint64_t)client->exp->size);

        return request->type == NBD_CMD_WRITE ? -ENOSPC : -EINVAL;

    }

    if (request->flags & ~(NBD_CMD_FLAG_FUA | NBD_CMD_FLAG_NO_HOLE)) {

        error_setg(errp, "unsupported flags (got 0x%x)", request->flags);

        return -EINVAL;

    }

    if (request->type != NBD_CMD_WRITE_ZEROES &&

        (request->flags & NBD_CMD_FLAG_NO_HOLE)) {

        error_setg(errp, "unexpected flags (got 0x%x)", request->flags);

        return -EINVAL;

    }

    return 0;

}


int qio_channel_writev_all(QIOChannel *ioc,

                           const struct iovec *iov,

                           size_t niov,

                           Error **errp)

{

    int ret = -1;

    struct iovec *local_iov = g_new(struct iovec, niov);

    struct iovec *local_iov_head = local_iov;

    unsigned int nlocal_iov = niov;

    nlocal_iov = iov_copy(local_iov, nlocal_iov,

                          iov, niov,

                          0, iov_size(iov, niov));

    while (nlocal_iov > 0) {

        ssize_t len;

        len = qio_channel_writev(ioc, local_iov, nlocal_iov, errp);

        if (len == QIO_CHANNEL_ERR_BLOCK) {

            qio_channel_wait(ioc, G_IO_OUT);

            continue;

        }

        if (len < 0) {

            goto cleanup;

        }

        iov_discard_front(&local_iov, &nlocal_iov, len);

    }

    ret = 0;

 cleanup:

    g_free(local_iov_head);

    return ret;

}


static int spapr_vio_busdev_init(DeviceState *qdev)

{

    VIOsPAPRDevice *dev = (VIOsPAPRDevice *)qdev;

    VIOsPAPRDeviceClass *pc = VIO_SPAPR_DEVICE_GET_CLASS(dev);

    uint32_t liobn;

    char *id;

    if (dev->reg != -1) {

        /*

         * Explicitly assigned address, just verify that no-one else

         * is using it.  other mechanism). We have to open code this

         * rather than using spapr_vio_find_by_reg() because sdev

         * itself is already in the list.

         */

        VIOsPAPRDevice *other = reg_conflict(dev);

        if (other) {

            fprintf(stderr, "vio: %s and %s devices conflict at address %#x\n",

                    object_get_typename(OBJECT(qdev)),

                    object_get_typename(OBJECT(&other->qdev)),

                    dev->reg);

            return -1;

        }

    } else {

        /* Need to assign an address */

        VIOsPAPRBus *bus = DO_UPCAST(VIOsPAPRBus, bus, dev->qdev.parent_bus);

        do {

            dev->reg = bus->next_reg++;

        } while (reg_conflict(dev));

    }

    /* Don't overwrite ids assigned on the command line */

    if (!dev->qdev.id) {

        id = vio_format_dev_name(dev);

        if (!id) {

            return -1;

        }

        dev->qdev.id = id;

    }

    dev->qirq = spapr_allocate_msi(dev->vio_irq_num, &dev->vio_irq_num);

    if (!dev->qirq) {

        return -1;

    }

    liobn = SPAPR_VIO_BASE_LIOBN | dev->reg;

    dev->dma = spapr_tce_new_dma_context(liobn, pc->rtce_window_size);

    return pc->init(dev);

}


static unsigned int dec_subs_r(DisasContext *dc)

{

	TCGv t0;

	int size = memsize_z(dc);

	DIS(fprintf (logfile, "subs.%c $r%u, $r%u\n",

		    memsize_char(size),

		    dc->op1, dc->op2));

	cris_cc_mask(dc, CC_MASK_NZVC);

	t0 = tcg_temp_new(TCG_TYPE_TL);

	/* Size can only be qi or hi.  */

	t_gen_sext(t0, cpu_R[dc->op1], size);

	cris_alu(dc, CC_OP_SUB,

		    cpu_R[dc->op2], cpu_R[dc->op2], t0, 4);

	tcg_temp_free(t0);

	return 2;

}


blkdebug_co_preadv(BlockDriverState *bs, uint64_t offset, uint64_t bytes,

                   QEMUIOVector *qiov, int flags)

{

    BDRVBlkdebugState *s = bs->opaque;

    BlkdebugRule *rule = NULL;

    /* Sanity check block layer guarantees */

    assert(QEMU_IS_ALIGNED(offset, bs->bl.request_alignment));

    assert(QEMU_IS_ALIGNED(bytes, bs->bl.request_alignment));

    if (bs->bl.max_transfer) {

        assert(bytes <= bs->bl.max_transfer);

    }

    QSIMPLEQ_FOREACH(rule, &s->active_rules, active_next) {

        uint64_t inject_offset = rule->options.inject.offset;

        if (inject_offset == -1 ||

            (inject_offset >= offset && inject_offset < offset + bytes))

        {

            break;

        }

    }

    if (rule && rule->options.inject.error) {

        return inject_error(bs, rule);

    }

    return bdrv_co_preadv(bs->file, offset, bytes, qiov, flags);

}


static int vmdk_open(BlockDriverState *bs, QDict *options, int flags,

                     Error **errp)

{

    char *buf;

    int ret;

    BDRVVmdkState *s = bs->opaque;

    uint32_t magic;

    buf = vmdk_read_desc(bs->file, 0, errp);

    if (!buf) {

        return -EINVAL;

    }

    magic = ldl_be_p(buf);

    switch (magic) {

        case VMDK3_MAGIC:

        case VMDK4_MAGIC:

            ret = vmdk_open_sparse(bs, bs->file, flags, buf, errp);

            s->desc_offset = 0x200;

            break;

        default:

            ret = vmdk_open_desc_file(bs, flags, buf, errp);

            break;

    }

    if (ret) {

        goto fail;

    }

    /* try to open parent images, if exist */

    ret = vmdk_parent_open(bs);

    if (ret) {

        goto fail;

    }

    s->cid = vmdk_read_cid(bs, 0);

    s->parent_cid = vmdk_read_cid(bs, 1);

    qemu_co_mutex_init(&s->lock);

    /* Disable migration when VMDK images are used */

    error_setg(&s->migration_blocker, "The vmdk format used by node '%s' "

               "does not support live migration",

               bdrv_get_device_or_node_name(bs));

    migrate_add_blocker(s->migration_blocker);

    g_free(buf);

    return 0;

fail:

    g_free(buf);

    g_free(s->create_type);

    s->create_type = NULL;

    vmdk_free_extents(bs);

    return ret;

}


void visit_type_size(Visitor *v, uint64_t *obj, const char *name, Error **errp)

{

    int64_t value;

    if (v->type_size) {

        v->type_size(v, obj, name, errp);

    } else if (v->type_uint64) {

        v->type_uint64(v, obj, name, errp);

    } else {

        value = *obj;

        v->type_int64(v, &value, name, errp);

        *obj = value;

    }

}


void *virtqueue_pop(VirtQueue *vq, size_t sz)

{

    unsigned int i, head, max;

    hwaddr desc_pa = vq->vring.desc;

    VirtIODevice *vdev = vq->vdev;

    VirtQueueElement *elem;

    unsigned out_num, in_num;

    hwaddr addr[VIRTQUEUE_MAX_SIZE];

    struct iovec iov[VIRTQUEUE_MAX_SIZE];

    VRingDesc desc;

    if (!virtqueue_num_heads(vq, vq->last_avail_idx)) {

        return NULL;

    }

    /* When we start there are none of either input nor output. */

    out_num = in_num = 0;

    max = vq->vring.num;

    i = head = virtqueue_get_head(vq, vq->last_avail_idx++);

    if (virtio_vdev_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX)) {

        vring_set_avail_event(vq, vq->last_avail_idx);

    }

    vring_desc_read(vdev, &desc, desc_pa, i);

    if (desc.flags & VRING_DESC_F_INDIRECT) {

        if (desc.len % sizeof(VRingDesc)) {

            error_report("Invalid size for indirect buffer table");

            exit(1);

        }

        /* loop over the indirect descriptor table */

        max = desc.len / sizeof(VRingDesc);

        desc_pa = desc.addr;

        i = 0;

        vring_desc_read(vdev, &desc, desc_pa, i);

    }

    /* Collect all the descriptors */

    do {

        if (desc.flags & VRING_DESC_F_WRITE) {

            virtqueue_map_desc(&in_num, addr + out_num, iov + out_num,

                               VIRTQUEUE_MAX_SIZE - out_num, true, desc.addr, desc.len);

        } else {

            if (in_num) {

                error_report("Incorrect order for descriptors");

                exit(1);

            }

            virtqueue_map_desc(&out_num, addr, iov,

                               VIRTQUEUE_MAX_SIZE, false, desc.addr, desc.len);

        }

        /* If we've got too many, that implies a descriptor loop. */

        if ((in_num + out_num) > max) {

            error_report("Looped descriptor");

            exit(1);

        }

    } while ((i = virtqueue_read_next_desc(vdev, &desc, desc_pa, max)) != max);

    /* Now copy what we have collected and mapped */

    elem = virtqueue_alloc_element(sz, out_num, in_num);

    elem->index = head;

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

        elem->out_addr[i] = addr[i];

        elem->out_sg[i] = iov[i];

    }

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

        elem->in_addr[i] = addr[out_num + i];

        elem->in_sg[i] = iov[out_num + i];

    }

    vq->inuse++;

    trace_virtqueue_pop(vq, elem, elem->in_num, elem->out_num);

    return elem;

}


static void tgen_ext8s(TCGContext *s, TCGType type, TCGReg dest, TCGReg src)

{

    if (facilities & FACILITY_EXT_IMM) {

        tcg_out_insn(s, RRE, LGBR, dest, src);

        return;

    }

    if (type == TCG_TYPE_I32) {

        if (dest == src) {

            tcg_out_sh32(s, RS_SLL, dest, TCG_REG_NONE, 24);

        } else {

            tcg_out_sh64(s, RSY_SLLG, dest, src, TCG_REG_NONE, 24);

        }

        tcg_out_sh32(s, RS_SRA, dest, TCG_REG_NONE, 24);

    } else {

        tcg_out_sh64(s, RSY_SLLG, dest, src, TCG_REG_NONE, 56);

        tcg_out_sh64(s, RSY_SRAG, dest, dest, TCG_REG_NONE, 56);

    }

}


void mips_cpu_list (FILE *f, int (*cpu_fprintf)(FILE *f, const char *fmt, ...))

{

    int i;

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

        (*cpu_fprintf)(f, "MIPS '%s'\n",

                       mips_defs[i].name);

    }

}


static int tpm_passthrough_handle_device_opts(QemuOpts *opts, TPMBackend *tb)

{

    TPMPassthruState *tpm_pt = TPM_PASSTHROUGH(tb);

    const char *value;

    value = qemu_opt_get(opts, "cancel-path");

    tb->cancel_path = g_strdup(value);

    value = qemu_opt_get(opts, "path");

    if (!value) {

        value = TPM_PASSTHROUGH_DEFAULT_DEVICE;

    }

    tpm_pt->tpm_dev = g_strdup(value);

    tb->path = g_strdup(tpm_pt->tpm_dev);

    tpm_pt->tpm_fd = qemu_open(tpm_pt->tpm_dev, O_RDWR);

    if (tpm_pt->tpm_fd < 0) {

        error_report("Cannot access TPM device using '%s': %s",

                     tpm_pt->tpm_dev, strerror(errno));

        goto err_free_parameters;

    }

    if (tpm_passthrough_test_tpmdev(tpm_pt->tpm_fd)) {

        error_report("'%s' is not a TPM device.",

                     tpm_pt->tpm_dev);

        goto err_close_tpmdev;

    }

    return 0;

 err_close_tpmdev:

    qemu_close(tpm_pt->tpm_fd);

    tpm_pt->tpm_fd = -1;

 err_free_parameters:

    g_free(tb->path);

    tb->path = NULL;

    g_free(tpm_pt->tpm_dev);

    tpm_pt->tpm_dev = NULL;

    return 1;

}


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

                                ptrdiff_t stride)

{

    avc_luma_vt_4w_msa(src - (stride * 2), stride, dst, stride, 4);

}


static int nbd_co_writev_1(BlockDriverState *bs, int64_t sector_num,

                           int nb_sectors, QEMUIOVector *qiov,

                           int offset)

{

    BDRVNBDState *s = bs->opaque;

    struct nbd_request request;

    struct nbd_reply reply;

    request.type = NBD_CMD_WRITE;

    if (!bdrv_enable_write_cache(bs) && (s->nbdflags & NBD_FLAG_SEND_FUA)) {

        request.type |= NBD_CMD_FLAG_FUA;

    }

    request.from = sector_num * 512;

    request.len = nb_sectors * 512;

    nbd_coroutine_start(s, &request);

    if (nbd_co_send_request(s, &request, qiov->iov, offset) == -1) {

        reply.error = errno;

    } else {

        nbd_co_receive_reply(s, &request, &reply, NULL, 0);

    }

    nbd_coroutine_end(s, &request);

    return -reply.error;

}


void mtree_info(fprintf_function mon_printf, void *f)

{

    MemoryRegionListHead ml_head;

    MemoryRegionList *ml, *ml2;

    QTAILQ_INIT(&ml_head);

    mon_printf(f, "memory\n");

    mtree_print_mr(mon_printf, f, address_space_memory.root, 0, 0, &ml_head);

    /* print aliased regions */

    QTAILQ_FOREACH(ml, &ml_head, queue) {

        if (!ml->printed) {

            mon_printf(f, "%s\n", ml->mr->name);

            mtree_print_mr(mon_printf, f, ml->mr, 0, 0, &ml_head);

        }

    }

    QTAILQ_FOREACH_SAFE(ml, &ml_head, queue, ml2) {

        g_free(ml2);

    }

    if (address_space_io.root &&

        !QTAILQ_EMPTY(&address_space_io.root->subregions)) {

        QTAILQ_INIT(&ml_head);

        mon_printf(f, "I/O\n");

        mtree_print_mr(mon_printf, f, address_space_io.root, 0, 0, &ml_head);

    }

}


static int tm2_read_deltas(TM2Context *ctx, int stream_id)

{

    int d, mb;

    int i, v;

    d  = get_bits(&ctx->gb, 9);

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

    av_assert2(mb < 32);

    if ((d < 1) || (d > TM2_DELTAS) || (mb < 1)) {

        av_log(ctx->avctx, AV_LOG_ERROR, "Incorrect delta table: %i deltas x %i bits\n", d, mb);

        return AVERROR_INVALIDDATA;

    }

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

        v = get_bits_long(&ctx->gb, mb);

        if (v & (1 << (mb - 1)))

            ctx->deltas[stream_id][i] = v - (1 << mb);

        else

            ctx->deltas[stream_id][i] = v;

    }

    for (; i < TM2_DELTAS; i++)

        ctx->deltas[stream_id][i] = 0;

    return 0;

}


static void decode_delta_j(uint8_t *dst,

                           const uint8_t *buf, const uint8_t *buf_end,

                           int w, int h, int bpp, int dst_size)

{

    int32_t pitch;

    uint8_t *end = dst + dst_size, *ptr;

    uint32_t type, flag, cols, groups, rows, bytes;

    uint32_t offset;

    int planepitch_byte = (w + 7) / 8;

    int planepitch = ((w + 15) / 16) * 2;

    int kludge_j, b, g, r, d;

    GetByteContext gb;

    pitch = planepitch * bpp;

    kludge_j = w < 320 ? (320 - w) / 8 / 2 : 0;

    bytestream2_init(&gb, buf, buf_end - buf);

    while (bytestream2_get_bytes_left(&gb) >= 2) {

        type = bytestream2_get_be16(&gb);

        switch (type) {

        case 0:

            return;

        case 1:

            flag   = bytestream2_get_be16(&gb);

            cols   = bytestream2_get_be16(&gb);

            groups = bytestream2_get_be16(&gb);

            for (g = 0; g < groups; g++) {

                offset = bytestream2_get_be16(&gb);

                if (kludge_j)

                    offset = ((offset / (320 / 8)) * pitch) + (offset % (320 / 8)) - kludge_j;

                else

                    offset = ((offset / planepitch_byte) * pitch) + (offset % planepitch_byte);

                ptr = dst + offset;

                if (ptr >= end)

                    return;

                for (b = 0; b < cols; b++) {

                    for (d = 0; d < bpp; d++) {

                        uint8_t value = bytestream2_get_byte(&gb);

                        if (flag)

                            ptr[0] ^= value;

                        else

                            ptr[0]  = value;

                        ptr += planepitch;

                        if (ptr >= end)

                            return;

                    }

                }

                if ((cols * bpp) & 1)

                    bytestream2_skip(&gb, 1);

            }

            break;

        case 2:

            flag   = bytestream2_get_be16(&gb);

            rows   = bytestream2_get_be16(&gb);

            bytes  = bytestream2_get_be16(&gb);

            groups = bytestream2_get_be16(&gb);

            for (g = 0; g < groups; g++) {

                offset = bytestream2_get_be16(&gb);

                if (kludge_j)

                    offset = ((offset / (320 / 8)) * pitch) + (offset % (320/ 8)) - kludge_j;

                else

                    offset = ((offset / planepitch_byte) * pitch) + (offset % planepitch_byte);

                for (r = 0; r < rows; r++) {

                    for (d = 0; d < bpp; d++) {

                        ptr = dst + offset + (r * pitch) + d * planepitch;

                        if (ptr >= end)

                            return;

                        for (b = 0; b < bytes; b++) {

                            uint8_t value = bytestream2_get_byte(&gb);

                            if (flag)

                                ptr[0] ^= value;

                            else

                                ptr[0]  = value;

                            ptr++;

                            if (ptr >= end)

                                return;

                        }

                    }

                }

                if ((rows * bytes * bpp) & 1)

                    bytestream2_skip(&gb, 1);

            }

            break;

        default:

            return;

        }

    }

}


static int libshine_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,

                                 const AVFrame *frame, int *got_packet_ptr)

{

    SHINEContext *s = avctx->priv_data;

    MPADecodeHeader hdr;

    unsigned char *data;

    long written;

    int ret, len;

    if (frame)

        data = shine_encode_buffer(s->shine, (int16_t **)frame->data, &written);

    else

        data = shine_flush(s->shine, &written);

    if (written < 0)

        return -1;

    if (written > 0) {

        if (s->buffer_index + written > BUFFER_SIZE) {

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

            return AVERROR_BUG;

        }

        memcpy(s->buffer + s->buffer_index, data, written);

        s->buffer_index += written;

    }

    if (frame) {

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

            return ret;

    }

    if (s->buffer_index < 4 || !s->afq.frame_count)

        return 0;

    if (avpriv_mpegaudio_decode_header(&hdr, AV_RB32(s->buffer))) {

        av_log(avctx, AV_LOG_ERROR, "free format output not supported\n");

        return -1;

    }

    len = hdr.frame_size;

    if (len <= s->buffer_index) {

        if ((ret = ff_alloc_packet2(avctx, avpkt, len)))

            return ret;

        memcpy(avpkt->data, s->buffer, len);

        s->buffer_index -= len;

        memmove(s->buffer, s->buffer + len, s->buffer_index);

        ff_af_queue_remove(&s->afq, avctx->frame_size, &avpkt->pts,

                           &avpkt->duration);

        avpkt->size = len;

        *got_packet_ptr = 1;

    }

    return 0;

}


static int flac_write_trailer(struct AVFormatContext *s)

{

    ByteIOContext *pb = s->pb;

    uint8_t *streaminfo = s->streams[0]->codec->extradata;

    int len = s->streams[0]->codec->extradata_size;

    int64_t file_size;

    if (streaminfo && len > 0 && !url_is_streamed(s->pb)) {

        file_size = url_ftell(pb);

        url_fseek(pb, 8, SEEK_SET);

        put_buffer(pb, streaminfo, len);

        url_fseek(pb, file_size, SEEK_SET);

        put_flush_packet(pb);

    }

    return 0;

}


int egl_rendernode_init(const char *rendernode)

{

    qemu_egl_rn_fd = -1;

    qemu_egl_rn_fd = qemu_egl_rendernode_open(rendernode);

    if (qemu_egl_rn_fd == -1) {

        error_report("egl: no drm render node available");

        goto err;

    }

    qemu_egl_rn_gbm_dev = gbm_create_device(qemu_egl_rn_fd);

    if (!qemu_egl_rn_gbm_dev) {

        error_report("egl: gbm_create_device failed");

        goto err;

    }

    qemu_egl_init_dpy_mesa((EGLNativeDisplayType)qemu_egl_rn_gbm_dev);

    if (!epoxy_has_egl_extension(qemu_egl_display,

                                 "EGL_KHR_surfaceless_context")) {

        error_report("egl: EGL_KHR_surfaceless_context not supported");

        goto err;

    }

    if (!epoxy_has_egl_extension(qemu_egl_display,

                                 "EGL_MESA_image_dma_buf_export")) {

        error_report("egl: EGL_MESA_image_dma_buf_export not supported");

        goto err;

    }

    qemu_egl_rn_ctx = qemu_egl_init_ctx();

    if (!qemu_egl_rn_ctx) {

        error_report("egl: egl_init_ctx failed");

        goto err;

    }

    return 0;

err:

    if (qemu_egl_rn_gbm_dev) {

        gbm_device_destroy(qemu_egl_rn_gbm_dev);

    }

    if (qemu_egl_rn_fd != -1) {

        close(qemu_egl_rn_fd);

    }

    return -1;

}


static inline int read_line(AVFormatContext *s, char *rbuf, const int rbufsize,

                            int *rbuflen)

{

    RTSPState *rt = s->priv_data;

    int idx       = 0;

    int ret       = 0;

    *rbuflen      = 0;

    do {

        ret = ffurl_read_complete(rt->rtsp_hd, rbuf + idx, 1);

        if (ret < 0)

            return ret;

        if (rbuf[idx] == '\r') {

            /* Ignore */

        } else if (rbuf[idx] == '\n') {

            rbuf[idx] = '\0';

            *rbuflen  = idx;

            return 0;

        } else

            idx++;

    } while (idx < rbufsize);

    av_log(s, AV_LOG_ERROR, "Message too long\n");

    return AVERROR(EIO);

}


static void pc_cpu_unplug_request_cb(HotplugHandler *hotplug_dev,
                                     DeviceState *dev, Error **errp)
{
    int idx = -1;
    HotplugHandlerClass *hhc;
    Error *local_err = NULL;
    X86CPU *cpu = X86_CPU(dev);
    PCMachineState *pcms = PC_MACHINE(hotplug_dev);
    pc_find_cpu_slot(MACHINE(pcms), cpu->apic_id, &idx);
    assert(idx != -1);
    if (idx == 0) {
        error_setg(&local_err, "Boot CPU is unpluggable");
    hhc = HOTPLUG_HANDLER_GET_CLASS(pcms->acpi_dev);
    hhc->unplug_request(HOTPLUG_HANDLER(pcms->acpi_dev), dev, &local_err);
    if (local_err) {
 out:
    error_propagate(errp, local_err);


static void lm32_evr_init(QEMUMachineInitArgs *args)
{
    const char *cpu_model = args->cpu_model;
    const char *kernel_filename = args->kernel_filename;
    LM32CPU *cpu;
    CPULM32State *env;
    DriveInfo *dinfo;
    MemoryRegion *address_space_mem =  get_system_memory();
    MemoryRegion *phys_ram = g_new(MemoryRegion, 1);
    qemu_irq *cpu_irq, irq[32];
    ResetInfo *reset_info;
    int i;
    /* memory map */
    hwaddr flash_base  = 0x04000000;
    size_t flash_sector_size       = 256 * 1024;
    size_t flash_size              = 32 * 1024 * 1024;
    hwaddr ram_base    = 0x08000000;
    size_t ram_size                = 64 * 1024 * 1024;
    hwaddr timer0_base = 0x80002000;
    hwaddr uart0_base  = 0x80006000;
    hwaddr timer1_base = 0x8000a000;
    int uart0_irq                  = 0;
    int timer0_irq                 = 1;
    int timer1_irq                 = 3;
    reset_info = g_malloc0(sizeof(ResetInfo));
    if (cpu_model == NULL) {
        cpu_model = "lm32-full";
    cpu = cpu_lm32_init(cpu_model);
    env = &cpu->env;
    reset_info->cpu = cpu;
    reset_info->flash_base = flash_base;
    memory_region_init_ram(phys_ram, NULL, "lm32_evr.sdram", ram_size);
    vmstate_register_ram_global(phys_ram);
    memory_region_add_subregion(address_space_mem, ram_base, phys_ram);
    dinfo = drive_get(IF_PFLASH, 0, 0);
    /* Spansion S29NS128P */
    pflash_cfi02_register(flash_base, NULL, "lm32_evr.flash", flash_size,
                          dinfo ? dinfo->bdrv : NULL, flash_sector_size,
                          flash_size / flash_sector_size, 1, 2,
                          0x01, 0x7e, 0x43, 0x00, 0x555, 0x2aa, 1);
    /* create irq lines */
    cpu_irq = qemu_allocate_irqs(cpu_irq_handler, cpu, 1);
    env->pic_state = lm32_pic_init(*cpu_irq);
    for (i = 0; i < 32; i++) {
        irq[i] = qdev_get_gpio_in(env->pic_state, i);
    sysbus_create_simple("lm32-uart", uart0_base, irq[uart0_irq]);
    sysbus_create_simple("lm32-timer", timer0_base, irq[timer0_irq]);
    sysbus_create_simple("lm32-timer", timer1_base, irq[timer1_irq]);
    /* make sure juart isn't the first chardev */
    env->juart_state = lm32_juart_init();
    reset_info->bootstrap_pc = flash_base;
    if (kernel_filename) {
        uint64_t entry;
        int kernel_size;
        kernel_size = load_elf(kernel_filename, NULL, NULL, &entry, NULL, NULL,
                               1, ELF_MACHINE, 0);
        reset_info->bootstrap_pc = entry;
        if (kernel_size < 0) {
            kernel_size = load_image_targphys(kernel_filename, ram_base,
                                              ram_size);
            reset_info->bootstrap_pc = ram_base;
        if (kernel_size < 0) {
            fprintf(stderr, "qemu: could not load kernel '%s'\n",
                    kernel_filename);
    qemu_register_reset(main_cpu_reset, reset_info);


static void nam_writel (void *opaque, uint32_t addr, uint32_t val)

{

    PCIAC97LinkState *d = opaque;

    AC97LinkState *s = &d->ac97;

    dolog ("U nam writel %#x <- %#x\n", addr, val);

    s->cas = 0;

}


static void smbios_check_collision(int type, int entry)

{

    if (type < ARRAY_SIZE(first_opt)) {

        if (first_opt[type].seen) {

            if (first_opt[type].headertype != entry) {

                error_report("Can't mix file= and type= for same type");

                loc_push_restore(&first_opt[type].loc);

                error_report("This is the conflicting setting");

                loc_pop(&first_opt[type].loc);

                exit(1);

            }

        } else {

            first_opt[type].seen = true;

            first_opt[type].headertype = entry;

            loc_save(&first_opt[type].loc);

        }

    }

}


static void monitor_read_command(Monitor *mon, int show_prompt)

{

    if (!mon->rs)

        return;

    readline_start(mon->rs, "(qemu) ", 0, monitor_command_cb, NULL);

    if (show_prompt)

        readline_show_prompt(mon->rs);

}


DriveInfo *drive_init(QemuOpts *opts, int default_to_scsi)

{

    const char *buf;

    const char *file = NULL;

    char devname[128];

    const char *serial;

    const char *mediastr = "";

    BlockInterfaceType type;

    enum { MEDIA_DISK, MEDIA_CDROM } media;

    int bus_id, unit_id;

    int cyls, heads, secs, translation;

    BlockDriver *drv = NULL;

    int max_devs;

    int index;

    int ro = 0;

    int bdrv_flags = 0;

    int on_read_error, on_write_error;

    const char *devaddr;

    DriveInfo *dinfo;

    int snapshot = 0;

    int ret;

    translation = BIOS_ATA_TRANSLATION_AUTO;

    if (default_to_scsi) {

        type = IF_SCSI;

        pstrcpy(devname, sizeof(devname), "scsi");

    } else {

        type = IF_IDE;

        pstrcpy(devname, sizeof(devname), "ide");

    }

    media = MEDIA_DISK;

    /* extract parameters */

    bus_id  = qemu_opt_get_number(opts, "bus", 0);

    unit_id = qemu_opt_get_number(opts, "unit", -1);

    index   = qemu_opt_get_number(opts, "index", -1);

    cyls  = qemu_opt_get_number(opts, "cyls", 0);

    heads = qemu_opt_get_number(opts, "heads", 0);

    secs  = qemu_opt_get_number(opts, "secs", 0);

    snapshot = qemu_opt_get_bool(opts, "snapshot", 0);

    ro = qemu_opt_get_bool(opts, "readonly", 0);

    file = qemu_opt_get(opts, "file");

    serial = qemu_opt_get(opts, "serial");

    if ((buf = qemu_opt_get(opts, "if")) != NULL) {

        pstrcpy(devname, sizeof(devname), buf);

        for (type = 0; type < IF_COUNT && strcmp(buf, if_name[type]); type++)

            ;

        if (type == IF_COUNT) {

            error_report("unsupported bus type '%s'", buf);

            return NULL;

	}

    }

    max_devs = if_max_devs[type];

    if (cyls || heads || secs) {

        if (cyls < 1 || (type == IF_IDE && cyls > 16383)) {

            error_report("invalid physical cyls number");

	    return NULL;

	}

        if (heads < 1 || (type == IF_IDE && heads > 16)) {

            error_report("invalid physical heads number");

	    return NULL;

	}

        if (secs < 1 || (type == IF_IDE && secs > 63)) {

            error_report("invalid physical secs number");

	    return NULL;

	}

    }

    if ((buf = qemu_opt_get(opts, "trans")) != NULL) {

        if (!cyls) {

            error_report("'%s' trans must be used with cyls,heads and secs",

                         buf);

            return NULL;

        }

        if (!strcmp(buf, "none"))

            translation = BIOS_ATA_TRANSLATION_NONE;

        else if (!strcmp(buf, "lba"))

            translation = BIOS_ATA_TRANSLATION_LBA;

        else if (!strcmp(buf, "auto"))

            translation = BIOS_ATA_TRANSLATION_AUTO;

	else {

            error_report("'%s' invalid translation type", buf);

	    return NULL;

	}

    }

    if ((buf = qemu_opt_get(opts, "media")) != NULL) {

        if (!strcmp(buf, "disk")) {

	    media = MEDIA_DISK;

	} else if (!strcmp(buf, "cdrom")) {

            if (cyls || secs || heads) {

                error_report("'%s' invalid physical CHS format", buf);

	        return NULL;

            }

	    media = MEDIA_CDROM;

	} else {

	    error_report("'%s' invalid media", buf);

	    return NULL;

	}

    }

    if ((buf = qemu_opt_get(opts, "cache")) != NULL) {

        if (!strcmp(buf, "off") || !strcmp(buf, "none")) {

            bdrv_flags |= BDRV_O_NOCACHE;

        } else if (!strcmp(buf, "writeback")) {

            bdrv_flags |= BDRV_O_CACHE_WB;

        } else if (!strcmp(buf, "unsafe")) {

            bdrv_flags |= BDRV_O_CACHE_WB;

            bdrv_flags |= BDRV_O_NO_FLUSH;

        } else if (!strcmp(buf, "writethrough")) {

            /* this is the default */

        } else {

           error_report("invalid cache option");

           return NULL;

        }

    }

#ifdef CONFIG_LINUX_AIO

    if ((buf = qemu_opt_get(opts, "aio")) != NULL) {

        if (!strcmp(buf, "native")) {

            bdrv_flags |= BDRV_O_NATIVE_AIO;

        } else if (!strcmp(buf, "threads")) {

            /* this is the default */

        } else {

           error_report("invalid aio option");

           return NULL;

        }

    }

#endif

    if ((buf = qemu_opt_get(opts, "format")) != NULL) {

       if (strcmp(buf, "?") == 0) {

           error_printf("Supported formats:");

           bdrv_iterate_format(bdrv_format_print, NULL);

           error_printf("\n");

           return NULL;

        }

        drv = bdrv_find_whitelisted_format(buf);

        if (!drv) {

            error_report("'%s' invalid format", buf);

            return NULL;

        }

    }

    on_write_error = BLOCK_ERR_STOP_ENOSPC;

    if ((buf = qemu_opt_get(opts, "werror")) != NULL) {

        if (type != IF_IDE && type != IF_SCSI && type != IF_VIRTIO && type != IF_NONE) {

            error_report("werror is not supported by this bus type");

            return NULL;

        }

        on_write_error = parse_block_error_action(buf, 0);

        if (on_write_error < 0) {

            return NULL;

        }

    }

    on_read_error = BLOCK_ERR_REPORT;

    if ((buf = qemu_opt_get(opts, "rerror")) != NULL) {

        if (type != IF_IDE && type != IF_VIRTIO && type != IF_SCSI && type != IF_NONE) {

            error_report("rerror is not supported by this bus type");

            return NULL;

        }

        on_read_error = parse_block_error_action(buf, 1);

        if (on_read_error < 0) {

            return NULL;

        }

    }

    if ((devaddr = qemu_opt_get(opts, "addr")) != NULL) {

        if (type != IF_VIRTIO) {

            error_report("addr is not supported by this bus type");

            return NULL;

        }

    }

    /* compute bus and unit according index */

    if (index != -1) {

        if (bus_id != 0 || unit_id != -1) {

            error_report("index cannot be used with bus and unit");

            return NULL;

        }

        bus_id = drive_index_to_bus_id(type, index);

        unit_id = drive_index_to_unit_id(type, index);

    }

    /* if user doesn't specify a unit_id,

     * try to find the first free

     */

    if (unit_id == -1) {

       unit_id = 0;

       while (drive_get(type, bus_id, unit_id) != NULL) {

           unit_id++;

           if (max_devs && unit_id >= max_devs) {

               unit_id -= max_devs;

               bus_id++;

           }

       }

    }

    /* check unit id */

    if (max_devs && unit_id >= max_devs) {

        error_report("unit %d too big (max is %d)",

                     unit_id, max_devs - 1);

        return NULL;

    }

    /*

     * catch multiple definitions

     */

    if (drive_get(type, bus_id, unit_id) != NULL) {

        error_report("drive with bus=%d, unit=%d (index=%d) exists",

                     bus_id, unit_id, index);

        return NULL;

    }

    /* init */

    dinfo = qemu_mallocz(sizeof(*dinfo));

    if ((buf = qemu_opts_id(opts)) != NULL) {

        dinfo->id = qemu_strdup(buf);

    } else {

        /* no id supplied -> create one */

        dinfo->id = qemu_mallocz(32);

        if (type == IF_IDE || type == IF_SCSI)

            mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";

        if (max_devs)

            snprintf(dinfo->id, 32, "%s%i%s%i",

                     devname, bus_id, mediastr, unit_id);

        else

            snprintf(dinfo->id, 32, "%s%s%i",

                     devname, mediastr, unit_id);

    }

    dinfo->bdrv = bdrv_new(dinfo->id);

    dinfo->devaddr = devaddr;

    dinfo->type = type;

    dinfo->bus = bus_id;

    dinfo->unit = unit_id;

    dinfo->opts = opts;

    dinfo->refcount = 1;

    if (serial)

        strncpy(dinfo->serial, serial, sizeof(dinfo->serial) - 1);

    QTAILQ_INSERT_TAIL(&drives, dinfo, next);

    bdrv_set_on_error(dinfo->bdrv, on_read_error, on_write_error);

    switch(type) {

    case IF_IDE:

    case IF_SCSI:

    case IF_XEN:

    case IF_NONE:

        switch(media) {

	case MEDIA_DISK:

            if (cyls != 0) {

                bdrv_set_geometry_hint(dinfo->bdrv, cyls, heads, secs);

                bdrv_set_translation_hint(dinfo->bdrv, translation);

            }

	    break;

	case MEDIA_CDROM:

            bdrv_set_removable(dinfo->bdrv, 1);

            dinfo->media_cd = 1;

	    break;

	}

        break;

    case IF_SD:

        /* FIXME: This isn't really a floppy, but it's a reasonable

           approximation.  */

    case IF_FLOPPY:

        bdrv_set_removable(dinfo->bdrv, 1);

        break;

    case IF_PFLASH:

    case IF_MTD:

        break;

    case IF_VIRTIO:

        /* add virtio block device */

        opts = qemu_opts_create(qemu_find_opts("device"), NULL, 0);

        qemu_opt_set(opts, "driver", "virtio-blk");

        qemu_opt_set(opts, "drive", dinfo->id);

        if (devaddr)

            qemu_opt_set(opts, "addr", devaddr);

        break;

    default:

        abort();

    }

    if (!file || !*file) {

        return dinfo;

    }

    if (snapshot) {

        /* always use cache=unsafe with snapshot */

        bdrv_flags &= ~BDRV_O_CACHE_MASK;

        bdrv_flags |= (BDRV_O_SNAPSHOT|BDRV_O_CACHE_WB|BDRV_O_NO_FLUSH);

    }

    if (media == MEDIA_CDROM) {

        /* CDROM is fine for any interface, don't check.  */

        ro = 1;

    } else if (ro == 1) {

        if (type != IF_SCSI && type != IF_VIRTIO && type != IF_FLOPPY && type != IF_NONE) {

            error_report("readonly not supported by this bus type");

            goto err;

        }

    }

    bdrv_flags |= ro ? 0 : BDRV_O_RDWR;

    ret = bdrv_open(dinfo->bdrv, file, bdrv_flags, drv);

    if (ret < 0) {

        error_report("could not open disk image %s: %s",

                     file, strerror(-ret));

        goto err;

    }

    if (bdrv_key_required(dinfo->bdrv))

        autostart = 0;

    return dinfo;

err:

    bdrv_delete(dinfo->bdrv);

    qemu_free(dinfo->id);

    QTAILQ_REMOVE(&drives, dinfo, next);

    qemu_free(dinfo);

    return NULL;

}


static void sx1_init(MachineState *machine, const int version)

{

    struct omap_mpu_state_s *mpu;

    MemoryRegion *address_space = get_system_memory();

    MemoryRegion *flash = g_new(MemoryRegion, 1);

    MemoryRegion *flash_1 = g_new(MemoryRegion, 1);

    MemoryRegion *cs = g_new(MemoryRegion, 4);

    static uint32_t cs0val = 0x00213090;

    static uint32_t cs1val = 0x00215070;

    static uint32_t cs2val = 0x00001139;

    static uint32_t cs3val = 0x00001139;

    DriveInfo *dinfo;

    int fl_idx;

    uint32_t flash_size = flash0_size;

    int be;

    if (version == 2) {

        flash_size = flash2_size;

    }

    mpu = omap310_mpu_init(address_space, sx1_binfo.ram_size,

                           machine->cpu_model);

    /* External Flash (EMIFS) */

    memory_region_init_ram(flash, NULL, "omap_sx1.flash0-0", flash_size,

                           &error_abort);

    vmstate_register_ram_global(flash);

    memory_region_set_readonly(flash, true);

    memory_region_add_subregion(address_space, OMAP_CS0_BASE, flash);

    memory_region_init_io(&cs[0], NULL, &static_ops, &cs0val,

                          "sx1.cs0", OMAP_CS0_SIZE - flash_size);

    memory_region_add_subregion(address_space,

                                OMAP_CS0_BASE + flash_size, &cs[0]);

    memory_region_init_io(&cs[2], NULL, &static_ops, &cs2val,

                          "sx1.cs2", OMAP_CS2_SIZE);

    memory_region_add_subregion(address_space,

                                OMAP_CS2_BASE, &cs[2]);

    memory_region_init_io(&cs[3], NULL, &static_ops, &cs3val,

                          "sx1.cs3", OMAP_CS3_SIZE);

    memory_region_add_subregion(address_space,

                                OMAP_CS2_BASE, &cs[3]);

    fl_idx = 0;

#ifdef TARGET_WORDS_BIGENDIAN

    be = 1;

#else

    be = 0;

#endif

    if ((dinfo = drive_get(IF_PFLASH, 0, fl_idx)) != NULL) {

        if (!pflash_cfi01_register(OMAP_CS0_BASE, NULL,

                                   "omap_sx1.flash0-1", flash_size,

                                   blk_bs(blk_by_legacy_dinfo(dinfo)),

                                   sector_size, flash_size / sector_size,

                                   4, 0, 0, 0, 0, be)) {

            fprintf(stderr, "qemu: Error registering flash memory %d.\n",

                           fl_idx);

        }

        fl_idx++;

    }

    if ((version == 1) &&

            (dinfo = drive_get(IF_PFLASH, 0, fl_idx)) != NULL) {

        memory_region_init_ram(flash_1, NULL, "omap_sx1.flash1-0", flash1_size,

                               &error_abort);

        vmstate_register_ram_global(flash_1);

        memory_region_set_readonly(flash_1, true);

        memory_region_add_subregion(address_space, OMAP_CS1_BASE, flash_1);

        memory_region_init_io(&cs[1], NULL, &static_ops, &cs1val,

                              "sx1.cs1", OMAP_CS1_SIZE - flash1_size);

        memory_region_add_subregion(address_space,

                                OMAP_CS1_BASE + flash1_size, &cs[1]);

        if (!pflash_cfi01_register(OMAP_CS1_BASE, NULL,

                                   "omap_sx1.flash1-1", flash1_size,

                                   blk_bs(blk_by_legacy_dinfo(dinfo)),

                                   sector_size, flash1_size / sector_size,

                                   4, 0, 0, 0, 0, be)) {

            fprintf(stderr, "qemu: Error registering flash memory %d.\n",

                           fl_idx);

        }

        fl_idx++;

    } else {

        memory_region_init_io(&cs[1], NULL, &static_ops, &cs1val,

                              "sx1.cs1", OMAP_CS1_SIZE);

        memory_region_add_subregion(address_space,

                                OMAP_CS1_BASE, &cs[1]);

    }

    if (!machine->kernel_filename && !fl_idx && !qtest_enabled()) {

        fprintf(stderr, "Kernel or Flash image must be specified\n");

        exit(1);

    }

    /* Load the kernel.  */

    sx1_binfo.kernel_filename = machine->kernel_filename;

    sx1_binfo.kernel_cmdline = machine->kernel_cmdline;

    sx1_binfo.initrd_filename = machine->initrd_filename;

    arm_load_kernel(mpu->cpu, &sx1_binfo);

    /* TODO: fix next line */

    //~ qemu_console_resize(ds, 640, 480);

}


qcrypto_block_luks_load_key(QCryptoBlock *block,

                            QCryptoBlockLUKSKeySlot *slot,

                            const char *password,

                            QCryptoCipherAlgorithm cipheralg,

                            QCryptoCipherMode ciphermode,

                            QCryptoHashAlgorithm hash,

                            QCryptoIVGenAlgorithm ivalg,

                            QCryptoCipherAlgorithm ivcipheralg,

                            QCryptoHashAlgorithm ivhash,

                            uint8_t *masterkey,

                            size_t masterkeylen,

                            QCryptoBlockReadFunc readfunc,

                            void *opaque,

                            Error **errp)

{

    QCryptoBlockLUKS *luks = block->opaque;

    uint8_t *splitkey;

    size_t splitkeylen;

    uint8_t *possiblekey;

    int ret = -1;

    ssize_t rv;

    QCryptoCipher *cipher = NULL;

    uint8_t keydigest[QCRYPTO_BLOCK_LUKS_DIGEST_LEN];

    QCryptoIVGen *ivgen = NULL;

    size_t niv;

    if (slot->active != QCRYPTO_BLOCK_LUKS_KEY_SLOT_ENABLED) {

        return 0;

    }

    splitkeylen = masterkeylen * slot->stripes;

    splitkey = g_new0(uint8_t, splitkeylen);

    possiblekey = g_new0(uint8_t, masterkeylen);

    /*

     * The user password is used to generate a (possible)

     * decryption key. This may or may not successfully

     * decrypt the master key - we just blindly assume

     * the key is correct and validate the results of

     * decryption later.

     */

    if (qcrypto_pbkdf2(hash,

                       (const uint8_t *)password, strlen(password),

                       slot->salt, QCRYPTO_BLOCK_LUKS_SALT_LEN,

                       slot->iterations,

                       possiblekey, masterkeylen,

                       errp) < 0) {

        goto cleanup;

    }

    /*

     * We need to read the master key material from the

     * LUKS key material header. What we're reading is

     * not the raw master key, but rather the data after

     * it has been passed through AFSplit and the result

     * then encrypted.

     */

    rv = readfunc(block,

                  slot->key_offset * QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,

                  splitkey, splitkeylen,

                  errp,

                  opaque);

    if (rv < 0) {

        goto cleanup;

    }

    /* Setup the cipher/ivgen that we'll use to try to decrypt

     * the split master key material */

    cipher = qcrypto_cipher_new(cipheralg, ciphermode,

                                possiblekey, masterkeylen,

                                errp);

    if (!cipher) {

        goto cleanup;

    }

    niv = qcrypto_cipher_get_iv_len(cipheralg,

                                    ciphermode);

    ivgen = qcrypto_ivgen_new(ivalg,

                              ivcipheralg,

                              ivhash,

                              possiblekey, masterkeylen,

                              errp);

    if (!ivgen) {

        goto cleanup;

    }

    /*

     * The master key needs to be decrypted in the same

     * way that the block device payload will be decrypted

     * later. In particular we'll be using the IV generator

     * to reset the encryption cipher every time the master

     * key crosses a sector boundary.

     */

    if (qcrypto_block_decrypt_helper(cipher,

                                     niv,

                                     ivgen,

                                     QCRYPTO_BLOCK_LUKS_SECTOR_SIZE,

                                     0,

                                     splitkey,

                                     splitkeylen,

                                     errp) < 0) {

        goto cleanup;

    }

    /*

     * Now we've decrypted the split master key, join

     * it back together to get the actual master key.

     */

    if (qcrypto_afsplit_decode(hash,

                               masterkeylen,

                               slot->stripes,

                               splitkey,

                               masterkey,

                               errp) < 0) {

        goto cleanup;

    }

    /*

     * We still don't know that the masterkey we got is valid,

     * because we just blindly assumed the user's password

     * was correct. This is where we now verify it. We are

     * creating a hash of the master key using PBKDF and

     * then comparing that to the hash stored in the key slot

     * header

     */

    if (qcrypto_pbkdf2(hash,

                       masterkey, masterkeylen,

                       luks->header.master_key_salt,

                       QCRYPTO_BLOCK_LUKS_SALT_LEN,

                       luks->header.master_key_iterations,

                       keydigest, G_N_ELEMENTS(keydigest),

                       errp) < 0) {

        goto cleanup;

    }

    if (memcmp(keydigest, luks->header.master_key_digest,

               QCRYPTO_BLOCK_LUKS_DIGEST_LEN) == 0) {

        /* Success, we got the right master key */

        ret = 1;

        goto cleanup;

    }

    /* Fail, user's password was not valid for this key slot,

     * tell caller to try another slot */

    ret = 0;

 cleanup:

    qcrypto_ivgen_free(ivgen);

    qcrypto_cipher_free(cipher);

    g_free(splitkey);

    g_free(possiblekey);

    return ret;

}


static uint64_t gem_read(void *opaque, target_phys_addr_t offset, unsigned size)

{

    GemState *s;

    uint32_t retval;

    s = (GemState *)opaque;

    offset >>= 2;

    retval = s->regs[offset];

    DB_PRINT("offset: 0x%04x read: 0x%08x\n", offset*4, retval);

    switch (offset) {

    case GEM_ISR:

        qemu_set_irq(s->irq, 0);

        break;

    case GEM_PHYMNTNC:

        if (retval & GEM_PHYMNTNC_OP_R) {

            uint32_t phy_addr, reg_num;

            phy_addr = (retval & GEM_PHYMNTNC_ADDR) >> GEM_PHYMNTNC_ADDR_SHFT;

            if (phy_addr == BOARD_PHY_ADDRESS) {

                reg_num = (retval & GEM_PHYMNTNC_REG) >> GEM_PHYMNTNC_REG_SHIFT;

                retval &= 0xFFFF0000;

                retval |= gem_phy_read(s, reg_num);

            } else {

                retval |= 0xFFFF; /* No device at this address */

            }

        }

        break;

    }

    /* Squash read to clear bits */

    s->regs[offset] &= ~(s->regs_rtc[offset]);

    /* Do not provide write only bits */

    retval &= ~(s->regs_wo[offset]);

    DB_PRINT("0x%08x\n", retval);

    return retval;

}


static void musicpal_lcd_init(DisplayState *ds, uint32_t base)

{

    musicpal_lcd_state *s;

    int iomemtype;

    s = qemu_mallocz(sizeof(musicpal_lcd_state));

    if (!s)

        return;

    s->base = base;

    s->ds = ds;

    iomemtype = cpu_register_io_memory(0, musicpal_lcd_readfn,

                                       musicpal_lcd_writefn, s);

    cpu_register_physical_memory(base, MP_LCD_SIZE, iomemtype);

    graphic_console_init(ds, lcd_refresh, NULL, NULL, NULL, s);

    dpy_resize(ds, 128*3, 64*3);

}


void virtqueue_get_avail_bytes(VirtQueue *vq, unsigned int *in_bytes,

                               unsigned int *out_bytes)

{

    unsigned int idx;

    unsigned int total_bufs, in_total, out_total;

    idx = vq->last_avail_idx;

    total_bufs = in_total = out_total = 0;

    while (virtqueue_num_heads(vq, idx)) {

        unsigned int max, num_bufs, indirect = 0;

        hwaddr desc_pa;

        int i;

        max = vq->vring.num;

        num_bufs = total_bufs;

        i = virtqueue_get_head(vq, idx++);

        desc_pa = vq->vring.desc;

        if (vring_desc_flags(desc_pa, i) & VRING_DESC_F_INDIRECT) {

            if (vring_desc_len(desc_pa, i) % sizeof(VRingDesc)) {

                error_report("Invalid size for indirect buffer table");

                exit(1);

            }

            /* If we've got too many, that implies a descriptor loop. */

            if (num_bufs >= max) {

                error_report("Looped descriptor");

                exit(1);

            }

            /* loop over the indirect descriptor table */

            indirect = 1;

            max = vring_desc_len(desc_pa, i) / sizeof(VRingDesc);

            num_bufs = i = 0;

            desc_pa = vring_desc_addr(desc_pa, i);

        }

        do {

            /* If we've got too many, that implies a descriptor loop. */

            if (++num_bufs > max) {

                error_report("Looped descriptor");

                exit(1);

            }

            if (vring_desc_flags(desc_pa, i) & VRING_DESC_F_WRITE) {

                in_total += vring_desc_len(desc_pa, i);

            } else {

                out_total += vring_desc_len(desc_pa, i);

            }

        } while ((i = virtqueue_next_desc(desc_pa, i, max)) != max);

        if (!indirect)

            total_bufs = num_bufs;

        else

            total_bufs++;

    }

    if (in_bytes) {

        *in_bytes = in_total;

    }

    if (out_bytes) {

        *out_bytes = out_total;

    }

}


static int xen_pt_cmd_reg_write(XenPCIPassthroughState *s, XenPTReg *cfg_entry,

                                uint16_t *val, uint16_t dev_value,

                                uint16_t valid_mask)

{

    XenPTRegInfo *reg = cfg_entry->reg;

    uint16_t writable_mask = 0;

    uint16_t throughable_mask = get_throughable_mask(s, reg, valid_mask);

    /* modify emulate register */

    writable_mask = ~reg->ro_mask & valid_mask;

    cfg_entry->data = XEN_PT_MERGE_VALUE(*val, cfg_entry->data, writable_mask);

    /* create value for writing to I/O device register */

    if (*val & PCI_COMMAND_INTX_DISABLE) {

        throughable_mask |= PCI_COMMAND_INTX_DISABLE;

    } else {

        if (s->machine_irq) {

            throughable_mask |= PCI_COMMAND_INTX_DISABLE;

        }

    }

    *val = XEN_PT_MERGE_VALUE(*val, dev_value, throughable_mask);

    return 0;

}


static void v9fs_remove(void *opaque)

{

    int32_t fid;

    int err = 0;

    size_t offset = 7;

    V9fsFidState *fidp;

    V9fsPDU *pdu = opaque;

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

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

    fidp = get_fid(pdu, fid);

    if (fidp == NULL) {

        err = -EINVAL;

        goto out_nofid;

    }

    /* if fs driver is not path based, return EOPNOTSUPP */

    if (!(pdu->s->ctx.export_flags & V9FS_PATHNAME_FSCONTEXT)) {

        err = -EOPNOTSUPP;

        goto out_err;

    }

    /*

     * IF the file is unlinked, we cannot reopen

     * the file later. So don't reclaim fd

     */

    err = v9fs_mark_fids_unreclaim(pdu, &fidp->path);

    if (err < 0) {

        goto out_err;

    }

    err = v9fs_co_remove(pdu, &fidp->path);

    if (!err) {

        err = offset;

    }

out_err:

    /* For TREMOVE we need to clunk the fid even on failed remove */

    clunk_fid(pdu->s, fidp->fid);

    put_fid(pdu, fidp);

out_nofid:

    complete_pdu(pdu->s, pdu, err);

}


static void mips_qemu_write (void *opaque, target_phys_addr_t addr,

                             uint64_t val, unsigned size)

{

    if ((addr & 0xffff) == 0 && val == 42)

        qemu_system_reset_request ();

    else if ((addr & 0xffff) == 4 && val == 42)

        qemu_system_shutdown_request ();

}


SocketAddress *socket_remote_address(int fd, Error **errp)

{

    struct sockaddr_storage ss;

    socklen_t sslen = sizeof(ss);

    if (getpeername(fd, (struct sockaddr *)&ss, &sslen) < 0) {

        error_setg_errno(errp, errno, "%s",

                         "Unable to query remote socket address");

        return NULL;

    }

    return socket_sockaddr_to_address(&ss, sslen, errp);

}


static int mov_read_wave(MOVContext *c, ByteIOContext *pb, MOVAtom atom)

{

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

    if((uint64_t)atom.size > (1<<30))

        return -1;

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

        // pass all frma atom to codec, needed at least for QDM2

        av_free(st->codec->extradata);

        st->codec->extradata = av_mallocz(atom.size + FF_INPUT_BUFFER_PADDING_SIZE);

        if (!st->codec->extradata)

            return AVERROR(ENOMEM);

        st->codec->extradata_size = atom.size;

        get_buffer(pb, st->codec->extradata, atom.size);

    } else if (atom.size > 8) { /* to read frma, esds atoms */

        if (mov_read_default(c, pb, atom) < 0)

            return -1;

    } else

        url_fskip(pb, atom.size);

    return 0;

}


fetchline(void)

{

	char	*p, *line = malloc(MAXREADLINESZ);

	if (!line)

		return NULL;

	printf("%s", get_prompt());

	fflush(stdout);

	if (!fgets(line, MAXREADLINESZ, stdin)) {

		free(line);

		return NULL;

	}

	p = line + strlen(line);

	if (p != line && p[-1] == '\n')

		p[-1] = '\0';

	return line;

}


static void kvmclock_vm_state_change(void *opaque, int running,

                                     RunState state)

{

    KVMClockState *s = opaque;

    CPUState *cpu;

    int cap_clock_ctrl = kvm_check_extension(kvm_state, KVM_CAP_KVMCLOCK_CTRL);

    int ret;

    if (running) {

        struct kvm_clock_data data = {};

        uint64_t time_at_migration = kvmclock_current_nsec(s);

        s->clock_valid = false;

        /* We can't rely on the migrated clock value, just discard it */

        if (time_at_migration) {

            s->clock = time_at_migration;

        }

        data.clock = s->clock;

        ret = kvm_vm_ioctl(kvm_state, KVM_SET_CLOCK, &data);

        if (ret < 0) {

            fprintf(stderr, "KVM_SET_CLOCK failed: %s\n", strerror(ret));

            abort();

        }

        if (!cap_clock_ctrl) {

            return;

        }

        CPU_FOREACH(cpu) {

            ret = kvm_vcpu_ioctl(cpu, KVM_KVMCLOCK_CTRL, 0);

            if (ret) {

                if (ret != -EINVAL) {

                    fprintf(stderr, "%s: %s\n", __func__, strerror(-ret));

                }

                return;

            }

        }

    } else {

        struct kvm_clock_data data;

        int ret;

        if (s->clock_valid) {

            return;

        }

        kvm_synchronize_all_tsc();

        ret = kvm_vm_ioctl(kvm_state, KVM_GET_CLOCK, &data);

        if (ret < 0) {

            fprintf(stderr, "KVM_GET_CLOCK failed: %s\n", strerror(ret));

            abort();

        }

        s->clock = data.clock;

        /*

         * If the VM is stopped, declare the clock state valid to

         * avoid re-reading it on next vmsave (which would return

         * a different value). Will be reset when the VM is continued.

         */

        s->clock_valid = true;

    }

}


static void nvenc_setup_rate_control(AVCodecContext *avctx)

{

    NVENCContext *ctx    = avctx->priv_data;

    NV_ENC_RC_PARAMS *rc = &ctx->config.rcParams;

    if (avctx->bit_rate > 0)

        rc->averageBitRate = avctx->bit_rate;

    if (avctx->rc_max_rate > 0)

        rc->maxBitRate = avctx->rc_max_rate;

    if (ctx->rc > 0) {

        nvenc_override_rate_control(avctx, rc);

    } else if (ctx->flags & NVENC_LOSSLESS) {

        set_lossless(avctx, rc);

    } else if (avctx->global_quality > 0) {

        set_constqp(avctx, rc);

    } else if (avctx->qmin >= 0 && avctx->qmax >= 0) {

        rc->rateControlMode = NV_ENC_PARAMS_RC_VBR;

        set_vbr(avctx, rc);

    }

    if (avctx->rc_buffer_size > 0)

        rc->vbvBufferSize = avctx->rc_buffer_size;

    if (rc->averageBitRate > 0)

        avctx->bit_rate = rc->averageBitRate;

#if NVENCAPI_MAJOR_VERSION >= 7

    if (ctx->aq) {

        ctx->config.rcParams.enableAQ   = 1;

        ctx->config.rcParams.aqStrength = ctx->aq_strength;

        av_log(avctx, AV_LOG_VERBOSE, "AQ enabled.\n");

    }

    if (ctx->temporal_aq) {

        ctx->config.rcParams.enableTemporalAQ = 1;

        av_log(avctx, AV_LOG_VERBOSE, "Temporal AQ enabled.\n");

    }

    if (ctx->rc_lookahead) {

        int lkd_bound = FFMIN(ctx->nb_surfaces, ctx->async_depth) -

                        ctx->config.frameIntervalP - 4;

        if (lkd_bound < 0) {

            av_log(avctx, AV_LOG_WARNING,

                   "Lookahead not enabled. Increase buffer delay (-delay).\n");

        } else {

            ctx->config.rcParams.enableLookahead = 1;

            ctx->config.rcParams.lookaheadDepth  = av_clip(ctx->rc_lookahead, 0, lkd_bound);

            ctx->config.rcParams.disableIadapt   = ctx->no_scenecut;

            ctx->config.rcParams.disableBadapt   = !ctx->b_adapt;

            av_log(avctx, AV_LOG_VERBOSE,

                   "Lookahead enabled: depth %d, scenecut %s, B-adapt %s.\n",

                   ctx->config.rcParams.lookaheadDepth,

                   ctx->config.rcParams.disableIadapt ? "disabled" : "enabled",

                   ctx->config.rcParams.disableBadapt ? "disabled" : "enabled");

        }

    }

    if (ctx->strict_gop) {

        ctx->config.rcParams.strictGOPTarget = 1;

        av_log(avctx, AV_LOG_VERBOSE, "Strict GOP target enabled.\n");

    }

    if (ctx->nonref_p)

        ctx->config.rcParams.enableNonRefP = 1;

    if (ctx->zerolatency)

        ctx->config.rcParams.zeroReorderDelay = 1;

    if (ctx->quality)

        ctx->config.rcParams.targetQuality = ctx->quality;

#endif /* NVENCAPI_MAJOR_VERSION >= 7 */

}


static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *insamples)

{

    AVFilterContext *ctx = inlink->dst;

    AVFilterLink *outlink = ctx->outputs[0];

    ShowWavesContext *showwaves = ctx->priv;

    const int nb_samples = insamples->audio->nb_samples;

    AVFilterBufferRef *outpicref = showwaves->outpicref;

    int linesize = outpicref ? outpicref->linesize[0] : 0;

    int16_t *p = (int16_t *)insamples->data[0];

    int nb_channels = av_get_channel_layout_nb_channels(insamples->audio->channel_layout);

    int i, j, h;

    const int n = showwaves->n;

    const int x = 255 / (nb_channels * n); /* multiplication factor, pre-computed to avoid in-loop divisions */

    /* draw data in the buffer */

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

        if (!outpicref) {

            showwaves->outpicref = outpicref =

                ff_get_video_buffer(outlink, AV_PERM_WRITE|AV_PERM_ALIGN,

                                    outlink->w, outlink->h);

            if (!outpicref)

                return AVERROR(ENOMEM);

            outpicref->video->w = outlink->w;

            outpicref->video->h = outlink->h;

            outpicref->pts = insamples->pts +

                             av_rescale_q((p - (int16_t *)insamples->data[0]) / nb_channels,

                                          (AVRational){ 1, inlink->sample_rate },

                                          outlink->time_base);

            linesize = outpicref->linesize[0];

            memset(outpicref->data[0], 0, showwaves->h*linesize);

        }

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

            h = showwaves->h/2 - av_rescale(*p++, showwaves->h/2, MAX_INT16);

            if (h >= 0 && h < outlink->h)

                *(outpicref->data[0] + showwaves->buf_idx + h * linesize) += x;

        }

        showwaves->sample_count_mod++;

        if (showwaves->sample_count_mod == n) {

            showwaves->sample_count_mod = 0;

            showwaves->buf_idx++;

        }

        if (showwaves->buf_idx == showwaves->w)

            push_frame(outlink);

        outpicref = showwaves->outpicref;

    }

    avfilter_unref_buffer(insamples);

    return 0;

}


static void filter_mb_edgev( H264Context *h, uint8_t *pix, int stride, int bS[4], int qp ) {

    int i, d;

    const int index_a = clip( qp + h->slice_alpha_c0_offset, 0, 51 );

    const int alpha = alpha_table[index_a];

    const int beta  = beta_table[clip( qp + h->slice_beta_offset, 0, 51 )];

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

        if( bS[i] == 0 ) {

            pix += 4 * stride;

            continue;

        }

        /* 4px edge length */

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

            const uint8_t p0 = pix[-1];

            const uint8_t p1 = pix[-2];

            const uint8_t p2 = pix[-3];

            const uint8_t q0 = pix[0];

            const uint8_t q1 = pix[1];

            const uint8_t q2 = pix[2];

            if( abs( p0 - q0 ) >= alpha ||

                abs( p1 - p0 ) >= beta ||

                abs( q1 - q0 ) >= beta ) {

                pix += stride;

                continue;

            }

            if( bS[i] < 4 ) {

                const int tc0 = tc0_table[index_a][bS[i] - 1];

                int tc = tc0;

                int i_delta;

                if( abs( p2 - p0 ) < beta ) {

                    pix[-2] = p1 + clip( ( p2 + ( ( p0 + q0 + 1 ) >> 1 ) - ( p1 << 1 ) ) >> 1, -tc0, tc0 );

                    tc++;

                }

                if( abs( q2 - q0 ) < beta ) {

                    pix[1] = q1 + clip( ( q2 + ( ( p0 + q0 + 1 ) >> 1 ) - ( q1 << 1 ) ) >> 1, -tc0, tc0 );

                    tc++;

                }

                i_delta = clip( (((q0 - p0 ) << 2) + (p1 - q1) + 4) >> 3, -tc, tc );

                pix[-1] = clip( p0 + i_delta, 0, 255 );    /* p0' */

                pix[0]  = clip( q0 - i_delta, 0, 255 );    /* q0' */

            }

            else

            {

                const int c  = abs( p0 - q0 ) < (( alpha >> 2 ) + 2 );

                if( abs( p2 - p0 ) < beta && c )

                {

                    const uint8_t p3 = pix[-4];

                    /* p0', p1', p2' */

                    pix[-1] = ( p2 + 2*p1 + 2*p0 + 2*q0 + q1 + 4 ) >> 3;

                    pix[-2] = ( p2 + p1 + p0 + q0 + 2 ) >> 2;

                    pix[-3] = ( 2*p3 + 3*p2 + p1 + p0 + q0 + 4 ) >> 3;

                } else {

                    /* p0' */

                    pix[-1] = ( 2*p1 + p0 + q1 + 2 ) >> 2;

                }

                if( abs( q2 - q0 ) < beta && c )

                {

                    const uint8_t q3 = pix[3];

                    /* q0', q1', q2' */

                    pix[0] = ( p1 + 2*p0 + 2*q0 + 2*q1 + q2 + 4 ) >> 3;

                    pix[1] = ( p0 + q0 + q1 + q2 + 2 ) >> 2;

                    pix[2] = ( 2*q3 + 3*q2 + q1 + q0 + p0 + 4 ) >> 3;

                } else {

                    /* q0' */

                    pix[0] = ( 2*q1 + q0 + p1 + 2 ) >> 2;

                }

            }

            pix += stride;

        }

    }

}


static void report_config_error(const char *filename, int line_num, int log_level, int *errors, const char *fmt, ...)

{

    va_list vl;

    va_start(vl, fmt);

    av_log(NULL, log_level, "%s:%d: ", filename, line_num);

    av_vlog(NULL, log_level, fmt, vl);

    va_end(vl);

    (*errors)++;

}


static int test_vector_fmul_add(AVFloatDSPContext *fdsp, AVFloatDSPContext *cdsp,

                                const float *v1, const float *v2, const float *v3)

{

    LOCAL_ALIGNED(32, float, cdst, [LEN]);

    LOCAL_ALIGNED(32, float, odst, [LEN]);

    int ret;

    cdsp->vector_fmul_add(cdst, v1, v2, v3, LEN);

    fdsp->vector_fmul_add(odst, v1, v2, v3, LEN);

    if (ret = compare_floats(cdst, odst, LEN, ARBITRARY_FMUL_ADD_CONST))

        av_log(NULL, AV_LOG_ERROR, "vector_fmul_add failed\n");

    return ret;

}


static inline int bidir_refine(MpegEncContext * s, int mb_x, int mb_y)

{

    MotionEstContext * const c= &s->me;

    const int mot_stride = s->mb_stride;

    const int xy = mb_y *mot_stride + mb_x;

    int fbmin;

    int pred_fx= s->b_bidir_forw_mv_table[xy-1][0];

    int pred_fy= s->b_bidir_forw_mv_table[xy-1][1];

    int pred_bx= s->b_bidir_back_mv_table[xy-1][0];

    int pred_by= s->b_bidir_back_mv_table[xy-1][1];

    int motion_fx= s->b_bidir_forw_mv_table[xy][0]= s->b_forw_mv_table[xy][0];

    int motion_fy= s->b_bidir_forw_mv_table[xy][1]= s->b_forw_mv_table[xy][1];

    int motion_bx= s->b_bidir_back_mv_table[xy][0]= s->b_back_mv_table[xy][0];

    int motion_by= s->b_bidir_back_mv_table[xy][1]= s->b_back_mv_table[xy][1];

    const int flags= c->sub_flags;

    const int qpel= flags&FLAG_QPEL;

    const int shift= 1+qpel;

    const int xmin= c->xmin<<shift;

    const int ymin= c->ymin<<shift;

    const int xmax= c->xmax<<shift;

    const int ymax= c->ymax<<shift;

    uint8_t map[8][8][8][8];

    memset(map,0,sizeof(map));

#define BIDIR_MAP(fx,fy,bx,by) \

    map[(motion_fx+fx)&7][(motion_fy+fy)&7][(motion_bx+bx)&7][(motion_by+by)&7]

    BIDIR_MAP(0,0,0,0) = 1;

    fbmin= check_bidir_mv(s, motion_fx, motion_fy,

                          motion_bx, motion_by,

                          pred_fx, pred_fy,

                          pred_bx, pred_by,

                          0, 16);

    if(s->avctx->bidir_refine){

        int score, end;

#define CHECK_BIDIR(fx,fy,bx,by)\

    if( !BIDIR_MAP(fx,fy,bx,by)\

       &&(fx<=0 || motion_fx+fx<=xmax) && (fy<=0 || motion_fy+fy<=ymax) && (bx<=0 || motion_bx+bx<=xmax) && (by<=0 || motion_by+by<=ymax)\

       &&(fx>=0 || motion_fx+fx>=xmin) && (fy>=0 || motion_fy+fy>=ymin) && (bx>=0 || motion_bx+bx>=xmin) && (by>=0 || motion_by+by>=ymin)){\

        BIDIR_MAP(fx,fy,bx,by) = 1;\

        score= check_bidir_mv(s, motion_fx+fx, motion_fy+fy, motion_bx+bx, motion_by+by, pred_fx, pred_fy, pred_bx, pred_by, 0, 16);\

        if(score < fbmin){\

            fbmin= score;\

            motion_fx+=fx;\

            motion_fy+=fy;\

            motion_bx+=bx;\

            motion_by+=by;\

            end=0;\

        }\

    }

#define CHECK_BIDIR2(a,b,c,d)\

CHECK_BIDIR(a,b,c,d)\

CHECK_BIDIR(-a,-b,-c,-d)

#define CHECK_BIDIRR(a,b,c,d)\

CHECK_BIDIR2(a,b,c,d)\

CHECK_BIDIR2(b,c,d,a)\

CHECK_BIDIR2(c,d,a,b)\

CHECK_BIDIR2(d,a,b,c)

        do{

            end=1;

            CHECK_BIDIRR( 0, 0, 0, 1)

            if(s->avctx->bidir_refine > 1){

                CHECK_BIDIRR( 0, 0, 1, 1)

                CHECK_BIDIR2( 0, 1, 0, 1)

                CHECK_BIDIR2( 1, 0, 1, 0)

                CHECK_BIDIRR( 0, 0,-1, 1)

                CHECK_BIDIR2( 0,-1, 0, 1)

                CHECK_BIDIR2(-1, 0, 1, 0)

                if(s->avctx->bidir_refine > 2){

                    CHECK_BIDIRR( 0, 1, 1, 1)

                    CHECK_BIDIRR( 0,-1, 1, 1)

                    CHECK_BIDIRR( 0, 1,-1, 1)

                    CHECK_BIDIRR( 0, 1, 1,-1)

                    if(s->avctx->bidir_refine > 3){

                        CHECK_BIDIR2( 1, 1, 1, 1)

                        CHECK_BIDIRR( 1, 1, 1,-1)

                        CHECK_BIDIR2( 1, 1,-1,-1)

                        CHECK_BIDIR2( 1,-1,-1, 1)

                        CHECK_BIDIR2( 1,-1, 1,-1)

                    }

                }

            }

        }while(!end);

    }

    s->b_bidir_forw_mv_table[xy][0]= motion_fx;

    s->b_bidir_forw_mv_table[xy][1]= motion_fy;

    s->b_bidir_back_mv_table[xy][0]= motion_bx;

    s->b_bidir_back_mv_table[xy][1]= motion_by;

    return fbmin;

}


int ff_h264_execute_decode_slices(H264Context *h, unsigned context_count)

{

    AVCodecContext *const avctx = h->avctx;

    H264Context *hx;

    int i;

    if (h->mb_y >= h->mb_height) {

        av_log(h->avctx, AV_LOG_ERROR,

               "Input contains more MB rows than the frame height.\n");

        return AVERROR_INVALIDDATA;

    }

    if (h->avctx->hwaccel)

        return 0;

    if (context_count == 1) {

        return decode_slice(avctx, &h);

    } else {

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

            hx                 = h->thread_context[i];

            hx->er.error_count = 0;

        }

        avctx->execute(avctx, decode_slice, h->thread_context,

                       NULL, context_count, sizeof(void *));

        /* pull back stuff from slices to master context */

        hx                   = h->thread_context[context_count - 1];

        h->mb_x              = hx->mb_x;

        h->mb_y              = hx->mb_y;

        h->droppable         = hx->droppable;

        h->picture_structure = hx->picture_structure;

        for (i = 1; i < context_count; i++)

            h->er.error_count += h->thread_context[i]->er.error_count;

    }

    return 0;

}


static int open_next_file(AVFormatContext *avf)

{

    ConcatContext *cat = avf->priv_data;

    unsigned fileno = cat->cur_file - cat->files;

    if (cat->cur_file->duration == AV_NOPTS_VALUE)

        cat->cur_file->duration = cat->avf->duration - (cat->cur_file->file_inpoint - cat->cur_file->file_start_time);

    if (++fileno >= cat->nb_files) {

        cat->eof = 1;

        return AVERROR_EOF;

    }

    return open_file(avf, fileno);

}


static void set_signalled(sPAPRDRConnector *drc)

{

    drc->signalled = true;

}


static int mig_save_device_dirty(Monitor *mon, QEMUFile *f,

                                 BlkMigDevState *bmds, int is_async)

{

    BlkMigBlock *blk;

    int64_t total_sectors = bmds->total_sectors;

    int64_t sector;

    int nr_sectors;

    int ret = -EIO;

    for (sector = bmds->cur_dirty; sector < bmds->total_sectors;) {

        if (bmds_aio_inflight(bmds, sector)) {

            qemu_aio_flush();

        }

        if (bdrv_get_dirty(bmds->bs, sector)) {

            if (total_sectors - sector < BDRV_SECTORS_PER_DIRTY_CHUNK) {

                nr_sectors = total_sectors - sector;

            } else {

                nr_sectors = BDRV_SECTORS_PER_DIRTY_CHUNK;

            }

            blk = g_malloc(sizeof(BlkMigBlock));

            blk->buf = g_malloc(BLOCK_SIZE);

            blk->bmds = bmds;

            blk->sector = sector;

            blk->nr_sectors = nr_sectors;

            if (is_async) {

                blk->iov.iov_base = blk->buf;

                blk->iov.iov_len = nr_sectors * BDRV_SECTOR_SIZE;

                qemu_iovec_init_external(&blk->qiov, &blk->iov, 1);

                if (block_mig_state.submitted == 0) {

                    block_mig_state.prev_time_offset = qemu_get_clock_ns(rt_clock);

                }

                blk->aiocb = bdrv_aio_readv(bmds->bs, sector, &blk->qiov,

                                            nr_sectors, blk_mig_read_cb, blk);

                if (!blk->aiocb) {

                    goto error;

                }

                block_mig_state.submitted++;

                bmds_set_aio_inflight(bmds, sector, nr_sectors, 1);

            } else {

                ret = bdrv_read(bmds->bs, sector, blk->buf, nr_sectors);

                if (ret < 0) {

                    goto error;

                }

                blk_send(f, blk);

                g_free(blk->buf);

                g_free(blk);

            }

            bdrv_reset_dirty(bmds->bs, sector, nr_sectors);

            break;

        }

        sector += BDRV_SECTORS_PER_DIRTY_CHUNK;

        bmds->cur_dirty = sector;

    }

    return (bmds->cur_dirty >= bmds->total_sectors);

error:

    monitor_printf(mon, "Error reading sector %" PRId64 "\n", sector);

    qemu_file_set_error(f, ret);

    g_free(blk->buf);

    g_free(blk);

    return 0;

}


static void pm_reset(void *opaque)

{

    ICH9LPCPMRegs *pm = opaque;

    ich9_pm_iospace_update(pm, 0);

    acpi_pm1_evt_reset(&pm->acpi_regs);

    acpi_pm1_cnt_reset(&pm->acpi_regs);

    acpi_pm_tmr_reset(&pm->acpi_regs);

    acpi_gpe_reset(&pm->acpi_regs);

    if (kvm_enabled()) {

        /* Mark SMM as already inited to prevent SMM from running. KVM does not

         * support SMM mode. */

        pm->smi_en |= ICH9_PMIO_SMI_EN_APMC_EN;

    }

    pm->smi_en_wmask = ~0;

    acpi_update_sci(&pm->acpi_regs, pm->irq);

}


int bdrv_read_unthrottled(BlockDriverState *bs, int64_t sector_num,

                          uint8_t *buf, int nb_sectors)

{

    bool enabled;

    int ret;

    enabled = bs->io_limits_enabled;

    bs->io_limits_enabled = false;

    ret = bdrv_read(bs, sector_num, buf, nb_sectors);

    bs->io_limits_enabled = enabled;

    return ret;

}


static void bdrv_aio_bh_cb(void *opaque)

{

    BlockAIOCBSync *acb = opaque;

    if (!acb->is_write && acb->ret >= 0) {

        qemu_iovec_from_buf(acb->qiov, 0, acb->bounce, acb->qiov->size);

    }

    qemu_vfree(acb->bounce);

    acb->common.cb(acb->common.opaque, acb->ret);

    qemu_bh_delete(acb->bh);

    acb->bh = NULL;

    qemu_aio_unref(acb);

}


int ff_h263_decode_frame(AVCodecContext *avctx,

                             void *data, int *data_size,

                             UINT8 *buf, int buf_size)

{

    MpegEncContext *s = avctx->priv_data;

    int ret,i;

    AVFrame *pict = data;

    float new_aspect;

#ifdef PRINT_FRAME_TIME

uint64_t time= rdtsc();

#endif

#ifdef DEBUG

    printf("*****frame %d size=%d\n", avctx->frame_number, buf_size);

    printf("bytes=%x %x %x %x\n", buf[0], buf[1], buf[2], buf[3]);

#endif

    s->flags= avctx->flags;

    *data_size = 0;

   /* no supplementary picture */

    if (buf_size == 0) {

        return 0;

    }

    if(s->flags&CODEC_FLAG_TRUNCATED){

        int next;

        ParseContext *pc= &s->parse_context;

        pc->last_index= pc->index;

        if(s->codec_id==CODEC_ID_MPEG4){

            next= mpeg4_find_frame_end(s, buf, buf_size);

        }else{

            fprintf(stderr, "this codec doesnt support truncated bitstreams\n");

            return -1;

        }

        if(next==-1){

            if(buf_size + FF_INPUT_BUFFER_PADDING_SIZE + pc->index > pc->buffer_size){

                pc->buffer_size= buf_size + pc->index + 10*1024;

                pc->buffer= realloc(pc->buffer, pc->buffer_size);

            }

            memcpy(&pc->buffer[pc->index], buf, buf_size);

            pc->index += buf_size;

            return buf_size;

        }

        if(pc->index){

            if(next + FF_INPUT_BUFFER_PADDING_SIZE + pc->index > pc->buffer_size){

                pc->buffer_size= next + pc->index + 10*1024;

                pc->buffer= realloc(pc->buffer, pc->buffer_size);

            }

            memcpy(&pc->buffer[pc->index], buf, next + FF_INPUT_BUFFER_PADDING_SIZE );

            pc->index = 0;

            buf= pc->buffer;

            buf_size= pc->last_index + next;

        }

    }

retry:

    if(s->bitstream_buffer_size && buf_size<20){ //divx 5.01+ frame reorder

        init_get_bits(&s->gb, s->bitstream_buffer, s->bitstream_buffer_size);

    }else

        init_get_bits(&s->gb, buf, buf_size);

    s->bitstream_buffer_size=0;

    if (!s->context_initialized) {

        if (MPV_common_init(s) < 0) //we need the idct permutaton for reading a custom matrix

            return -1;

    }

    /* let's go :-) */

    if (s->msmpeg4_version==5) {

        ret= ff_wmv2_decode_picture_header(s);

    } else if (s->msmpeg4_version) {

        ret = msmpeg4_decode_picture_header(s);

    } else if (s->h263_pred) {

        if(s->avctx->extradata_size && s->picture_number==0){

            GetBitContext gb;

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

            ret = ff_mpeg4_decode_picture_header(s, &gb);

        }

        ret = ff_mpeg4_decode_picture_header(s, &s->gb);

        if(s->flags& CODEC_FLAG_LOW_DELAY)

            s->low_delay=1;

    } else if (s->h263_intel) {

        ret = intel_h263_decode_picture_header(s);

    } else {

        ret = h263_decode_picture_header(s);

    }

    avctx->has_b_frames= !s->low_delay;

    if(s->workaround_bugs&FF_BUG_AUTODETECT){

        if(s->padding_bug_score > -2 && !s->data_partitioning)

            s->workaround_bugs |=  FF_BUG_NO_PADDING;

        else

            s->workaround_bugs &= ~FF_BUG_NO_PADDING;

        if(s->avctx->fourcc == ff_get_fourcc("XVIX"))

            s->workaround_bugs|= FF_BUG_XVID_ILACE;

#if 0

        if(s->avctx->fourcc == ff_get_fourcc("MP4S"))

            s->workaround_bugs|= FF_BUG_AC_VLC;

        if(s->avctx->fourcc == ff_get_fourcc("M4S2"))

            s->workaround_bugs|= FF_BUG_AC_VLC;

#endif

        if(s->avctx->fourcc == ff_get_fourcc("UMP4")){

            s->workaround_bugs|= FF_BUG_UMP4;

            s->workaround_bugs|= FF_BUG_AC_VLC;

        }

        if(s->divx_version){

            s->workaround_bugs|= FF_BUG_QPEL_CHROMA;

        }

        if(s->avctx->fourcc == ff_get_fourcc("XVID") && s->xvid_build==0)

            s->workaround_bugs|= FF_BUG_QPEL_CHROMA;

        if(s->avctx->fourcc == ff_get_fourcc("XVID") && s->xvid_build==0)

            s->padding_bug_score= 256*256*256*64;

        if(s->xvid_build && s->xvid_build<=3)

            s->padding_bug_score= 256*256*256*64;

        if(s->xvid_build && s->xvid_build<=1)

            s->workaround_bugs|= FF_BUG_QPEL_CHROMA;

#define SET_QPEL_FUNC(postfix1, postfix2) \

    s->dsp.put_ ## postfix1 = ff_put_ ## postfix2;\

    s->dsp.put_no_rnd_ ## postfix1 = ff_put_no_rnd_ ## postfix2;\

    s->dsp.avg_ ## postfix1 = ff_avg_ ## postfix2;

        if(s->lavc_build && s->lavc_build<4653)

            s->workaround_bugs|= FF_BUG_STD_QPEL;

//printf("padding_bug_score: %d\n", s->padding_bug_score);

#if 0

        if(s->divx_version==500)

            s->workaround_bugs|= FF_BUG_NO_PADDING;

        /* very ugly XVID padding bug detection FIXME/XXX solve this differently

         * lets hope this at least works

         */

        if(   s->resync_marker==0 && s->data_partitioning==0 && s->divx_version==0

           && s->codec_id==CODEC_ID_MPEG4 && s->vo_type==0)

            s->workaround_bugs|= FF_BUG_NO_PADDING;

        if(s->lavc_build && s->lavc_build<4609) //FIXME not sure about the version num but a 4609 file seems ok

            s->workaround_bugs|= FF_BUG_NO_PADDING;

#endif

    }

    if(s->workaround_bugs& FF_BUG_STD_QPEL){

        SET_QPEL_FUNC(qpel_pixels_tab[0][ 5], qpel16_mc11_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[0][ 7], qpel16_mc31_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[0][ 9], qpel16_mc12_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[0][11], qpel16_mc32_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[0][13], qpel16_mc13_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[0][15], qpel16_mc33_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[1][ 5], qpel8_mc11_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[1][ 7], qpel8_mc31_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[1][ 9], qpel8_mc12_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[1][11], qpel8_mc32_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[1][13], qpel8_mc13_old_c)

        SET_QPEL_FUNC(qpel_pixels_tab[1][15], qpel8_mc33_old_c)

    }

#if 0 // dump bits per frame / qp / complexity

{

    static FILE *f=NULL;

    if(!f) f=fopen("rate_qp_cplx.txt", "w");

    fprintf(f, "%d %d %f\n", buf_size, s->qscale, buf_size*(double)s->qscale);

}

#endif

        /* After H263 & mpeg4 header decode we have the height, width,*/

        /* and other parameters. So then we could init the picture   */

        /* FIXME: By the way H263 decoder is evolving it should have */

        /* an H263EncContext                                         */

    if(s->aspected_height)

        new_aspect= s->aspected_width*s->width / (float)(s->height*s->aspected_height);

    else

        new_aspect=0;

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

        || ABS(new_aspect - avctx->aspect_ratio) > 0.001) {

        /* H.263 could change picture size any time */

        MPV_common_end(s);

        s->context_initialized=0;

    }

    if (!s->context_initialized) {

        avctx->width = s->width;

        avctx->height = s->height;

        avctx->aspect_ratio= new_aspect;

        goto retry;

    }

    if((s->codec_id==CODEC_ID_H263 || s->codec_id==CODEC_ID_H263P))

        s->gob_index = ff_h263_get_gob_height(s);

    if(ret==FRAME_SKIPED) return get_consumed_bytes(s, buf_size);

    /* skip if the header was thrashed */

    if (ret < 0){

        fprintf(stderr, "header damaged\n");

        return -1;

    }

    // for hurry_up==5

    s->current_picture.pict_type= s->pict_type;

    s->current_picture.key_frame= s->pict_type == I_TYPE;

    /* skip b frames if we dont have reference frames */

    if(s->last_picture.data[0]==NULL && s->pict_type==B_TYPE) return get_consumed_bytes(s, buf_size);

    /* skip b frames if we are in a hurry */

    if(avctx->hurry_up && s->pict_type==B_TYPE) return get_consumed_bytes(s, buf_size);

    /* skip everything if we are in a hurry>=5 */

    if(avctx->hurry_up>=5) return get_consumed_bytes(s, buf_size);

    if(s->next_p_frame_damaged){

        if(s->pict_type==B_TYPE)

            return get_consumed_bytes(s, buf_size);

        else

            s->next_p_frame_damaged=0;

    }

    if(MPV_frame_start(s, avctx) < 0)

        return -1;

#ifdef DEBUG

    printf("qscale=%d\n", s->qscale);

#endif

    if(s->error_resilience)

        memset(s->error_status_table, MV_ERROR|AC_ERROR|DC_ERROR|VP_START|AC_END|DC_END|MV_END, s->mb_num*sizeof(UINT8));

    /* decode each macroblock */

    s->block_wrap[0]=

    s->block_wrap[1]=

    s->block_wrap[2]=

    s->block_wrap[3]= s->mb_width*2 + 2;

    s->block_wrap[4]=

    s->block_wrap[5]= s->mb_width + 2;

    s->mb_x=0;

    s->mb_y=0;

    decode_slice(s);

    s->error_status_table[0]|= VP_START;

    while(s->mb_y<s->mb_height && s->gb.size*8 - get_bits_count(&s->gb)>16){

        if(s->msmpeg4_version){

            if(s->mb_x!=0 || (s->mb_y%s->slice_height)!=0)

                break;

        }else{

            if(ff_h263_resync(s)<0)

                break;

        }

        if(s->msmpeg4_version<4 && s->h263_pred)

            ff_mpeg4_clean_buffers(s);

        decode_slice(s);

        s->error_status_table[s->resync_mb_x + s->resync_mb_y*s->mb_width]|= VP_START;

    }

    if (s->h263_msmpeg4 && s->msmpeg4_version<4 && s->pict_type==I_TYPE)

        if(msmpeg4_decode_ext_header(s, buf_size) < 0){

            s->error_status_table[s->mb_num-1]= AC_ERROR|DC_ERROR|MV_ERROR;

        }

    /* divx 5.01+ bistream reorder stuff */

    if(s->codec_id==CODEC_ID_MPEG4 && s->bitstream_buffer_size==0 && s->divx_version>=500){

        int current_pos= get_bits_count(&s->gb)>>3;

        if(   buf_size - current_pos > 5

           && buf_size - current_pos < BITSTREAM_BUFFER_SIZE){

            int i;

            int startcode_found=0;

            for(i=current_pos; i<buf_size-3; i++){

                if(buf[i]==0 && buf[i+1]==0 && buf[i+2]==1 && buf[i+3]==0xB6){

                    startcode_found=1;

                    break;

                }

            }

            if(startcode_found){

                memcpy(s->bitstream_buffer, buf + current_pos, buf_size - current_pos);

                s->bitstream_buffer_size= buf_size - current_pos;

            }

        }

    }

    if(s->error_resilience){

        int error=0, num_end_markers=0;

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

            int status= s->error_status_table[i];

#if 0

            if(i%s->mb_width == 0) printf("\n");

            printf("%2X ", status);

#endif

            if(status==0) continue;

            if(status&(DC_ERROR|AC_ERROR|MV_ERROR))

                error=1;

            if(status&VP_START){

                if(num_end_markers)

                    error=1;

                num_end_markers=3;

            }

            if(status&AC_END)

                num_end_markers--;

            if(status&DC_END)

                num_end_markers--;

            if(status&MV_END)

                num_end_markers--;

        }

        if(num_end_markers || error){

            fprintf(stderr, "concealing errors\n");

            ff_error_resilience(s);

        }

    }

    MPV_frame_end(s);

    if((avctx->debug&FF_DEBUG_VIS_MV) && s->last_picture.data[0]){

        const int shift= 1 + s->quarter_sample;

        int mb_y;

        uint8_t *ptr= s->last_picture.data[0];

        s->low_delay=0; //needed to see the vectors without trashing the buffers

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

            int mb_x;

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

                const int mb_index= mb_x + mb_y*s->mb_width;

                if(s->co_located_type_table[mb_index] == MV_TYPE_8X8){

                    int i;

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

                        int sx= mb_x*16 + 4 + 8*(i&1);

                        int sy= mb_y*16 + 4 + 8*(i>>1);

                        int xy= 1 + mb_x*2 + (i&1) + (mb_y*2 + 1 + (i>>1))*(s->mb_width*2 + 2);

                        int mx= (s->motion_val[xy][0]>>shift) + sx;

                        int my= (s->motion_val[xy][1]>>shift) + sy;

                        draw_line(ptr, sx, sy, mx, my, s->width, s->height, s->linesize, 100);

                    }

                }else{

                    int sx= mb_x*16 + 8;

                    int sy= mb_y*16 + 8;

                    int xy= 1 + mb_x*2 + (mb_y*2 + 1)*(s->mb_width*2 + 2);

                    int mx= (s->motion_val[xy][0]>>shift) + sx;

                    int my= (s->motion_val[xy][1]>>shift) + sy;

                    draw_line(ptr, sx, sy, mx, my, s->width, s->height, s->linesize, 100);

                }

                s->mbskip_table[mb_index]=0;

            }

        }

    }

    if(s->pict_type==B_TYPE || s->low_delay){

        *pict= *(AVFrame*)&s->current_picture;

    } else {

        *pict= *(AVFrame*)&s->last_picture;

    }

    if(avctx->debug&FF_DEBUG_QP){

        int8_t *qtab= pict->qscale_table;

        int x,y;

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

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

                printf("%2d ", qtab[x + y*s->mb_width]);

            }

            printf("\n");

        }

        printf("\n");

    }

    /* Return the Picture timestamp as the frame number */

    /* we substract 1 because it is added on utils.c    */

    avctx->frame_number = s->picture_number - 1;

    /* dont output the last pic after seeking */

    if(s->last_picture.data[0] || s->low_delay)

        *data_size = sizeof(AVFrame);

#ifdef PRINT_FRAME_TIME

printf("%Ld\n", rdtsc()-time);

#endif

    return get_consumed_bytes(s, buf_size);

}


static int do_cont(Monitor *mon, const QDict *qdict, QObject **ret_data)

{

    struct bdrv_iterate_context context = { mon, 0 };

    if (incoming_expected) {

        qerror_report(QERR_MIGRATION_EXPECTED);

        return -1;

    }

    bdrv_iterate(encrypted_bdrv_it, &context);

    /* only resume the vm if all keys are set and valid */

    if (!context.err) {

        vm_start();

        return 0;

    } else {

        return -1;

    }

}


void qmp_x_blockdev_del(bool has_id, const char *id,

                        bool has_node_name, const char *node_name, Error **errp)

{

    AioContext *aio_context;

    BlockBackend *blk;

    BlockDriverState *bs;

    if (has_id && has_node_name) {

        error_setg(errp, "Only one of id and node-name must be specified");

        return;

    } else if (!has_id && !has_node_name) {

        error_setg(errp, "No block device specified");

        return;

    }

    if (has_id) {

        /* blk_by_name() never returns a BB that is not owned by the monitor */

        blk = blk_by_name(id);

        if (!blk) {

            error_setg(errp, "Cannot find block backend %s", id);

            return;

        }

        if (blk_legacy_dinfo(blk)) {

            error_setg(errp, "Deleting block backend added with drive-add"

                       " is not supported");

            return;

        }

        if (blk_get_refcnt(blk) > 1) {

            error_setg(errp, "Block backend %s is in use", id);

            return;

        }

        bs = blk_bs(blk);

        aio_context = blk_get_aio_context(blk);

    } else {

        blk = NULL;

        bs = bdrv_find_node(node_name);

        if (!bs) {

            error_setg(errp, "Cannot find node %s", node_name);

            return;

        }

        if (bdrv_has_blk(bs)) {

            error_setg(errp, "Node %s is in use by %s",

                       node_name, bdrv_get_parent_name(bs));

            return;

        }

        aio_context = bdrv_get_aio_context(bs);

    }

    aio_context_acquire(aio_context);

    if (bs) {

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

            goto out;

        }

        if (!blk && !bs->monitor_list.tqe_prev) {

            error_setg(errp, "Node %s is not owned by the monitor",

                       bs->node_name);

            goto out;

        }

        if (bs->refcnt > 1) {

            error_setg(errp, "Block device %s is in use",

                       bdrv_get_device_or_node_name(bs));

            goto out;

        }

    }

    if (blk) {

        monitor_remove_blk(blk);

        blk_unref(blk);

    } else {

        QTAILQ_REMOVE(&monitor_bdrv_states, bs, monitor_list);

        bdrv_unref(bs);

    }

out:

    aio_context_release(aio_context);

}


static void channel_store_c(struct fs_dma_ctrl *ctrl, int c)

{

	target_phys_addr_t addr = channel_reg(ctrl, c, RW_GROUP_DOWN);

	/* Encode and store. FIXME: handle endianness.  */

	D(printf("%s ch=%d addr=" TARGET_FMT_plx "\n", __func__, c, addr));

	D(dump_d(c, &ctrl->channels[c].current_d));

	cpu_physical_memory_write (addr,

				  (void *) &ctrl->channels[c].current_c,

				  sizeof ctrl->channels[c].current_c);

}


void sd_set_cb(SDState *sd, qemu_irq readonly, qemu_irq insert)

{

    sd->readonly_cb = readonly;

    sd->inserted_cb = insert;

    qemu_set_irq(readonly, sd->bdrv ? bdrv_is_read_only(sd->bdrv) : 0);

    qemu_set_irq(insert, sd->bdrv ? bdrv_is_inserted(sd->bdrv) : 0);

}


static int ppc_hash32_check_prot(int prot, int rw, int access_type)

{

    int ret;

    if (access_type == ACCESS_CODE) {

        if (prot & PAGE_EXEC) {

            ret = 0;

        } else {

            ret = -2;

        }

    } else if (rw) {

        if (prot & PAGE_WRITE) {

            ret = 0;

        } else {

            ret = -2;

        }

    } else {

        if (prot & PAGE_READ) {

            ret = 0;

        } else {

            ret = -2;

        }

    }

    return ret;

}


static void spr_write_40x_dbcr0 (void *opaque, int sprn)

{

    DisasContext *ctx = opaque;

    gen_op_store_40x_dbcr0();

    /* We must stop translation as we may have rebooted */

    RET_STOP(ctx);

}


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

{

    mv88w8618_eth_state *s = opaque;

    uint32_t desc_addr;

    mv88w8618_rx_desc desc;

    int i;

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

        desc_addr = s->cur_rx[i];

        if (!desc_addr)

            continue;

        do {

            eth_rx_desc_get(desc_addr, &desc);

            if ((desc.cmdstat & MP_ETH_RX_OWN) && desc.buffer_size >= size) {

                cpu_physical_memory_write(desc.buffer + s->vlan_header,

                                          buf, size);

                desc.bytes = size + s->vlan_header;

                desc.cmdstat &= ~MP_ETH_RX_OWN;

                s->cur_rx[i] = desc.next;

                s->icr |= MP_ETH_IRQ_RX;

                if (s->icr & s->imr)

                    qemu_irq_raise(s->irq);

                eth_rx_desc_put(desc_addr, &desc);

                return;

            }

            desc_addr = desc.next;

        } while (desc_addr != s->rx_queue[i]);

    }

}


static bool version_is_5(void *opaque, int version_id)

{

    return version_id == 5;

}


static int parse_ifo_palette(DVDSubContext *ctx, char *p)

{

    FILE *ifo;

    char ifostr[12];

    uint32_t sp_pgci, pgci, off_pgc, pgc;

    uint8_t r, g, b, yuv[65], *buf;

    int i, y, cb, cr, r_add, g_add, b_add;

    int ret = 0;

    const uint8_t *cm = ff_crop_tab + MAX_NEG_CROP;

    ctx->has_palette = 0;

    if ((ifo = fopen(p, "r")) == NULL) {

        av_log(ctx, AV_LOG_WARNING, "Unable to open IFO file \"%s\": %s\n", p, strerror(errno));

        return AVERROR_EOF;

    }

    if (fread(ifostr, 12, 1, ifo) != 1 || memcmp(ifostr, "DVDVIDEO-VTS", 12)) {

        av_log(ctx, AV_LOG_WARNING, "\"%s\" is not a proper IFO file\n", p);

        ret = AVERROR_INVALIDDATA;

        goto end;

    }

    fseek(ifo, 0xCC, SEEK_SET);

    if (fread(&sp_pgci, 4, 1, ifo) == 1) {

        pgci = av_be2ne32(sp_pgci) * 2048;

        fseek(ifo, pgci + 0x0C, SEEK_SET);

        if (fread(&off_pgc, 4, 1, ifo) == 1) {

            pgc = pgci + av_be2ne32(off_pgc);

            fseek(ifo, pgc + 0xA4, SEEK_SET);

            if (fread(yuv, 64, 1, ifo) == 1) {

                buf = yuv;

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

                    y  = *++buf;

                    cr = *++buf;

                    cb = *++buf;

                    YUV_TO_RGB1_CCIR(cb, cr);

                    YUV_TO_RGB2_CCIR(r, g, b, y);

                    ctx->palette[i] = (r << 16) + (g << 8) + b;

                    buf++;

                }

                ctx->has_palette = 1;

            }

        }

    }

    if (ctx->has_palette == 0) {

        av_log(ctx, AV_LOG_WARNING, "Failed to read palette from IFO file \"%s\"\n", p);

        ret = AVERROR_INVALIDDATA;

    }

end:

    fclose(ifo);

    return ret;

}