static int mpeg4_decode_sprite_trajectory(Mpeg4DecContext *ctx, GetBitContext *gb)

{

    MpegEncContext *s = &ctx->m;

    int a     = 2 << s->sprite_warping_accuracy;

    int rho   = 3  - s->sprite_warping_accuracy;

    int r     = 16 / a;

    int alpha = 0;

    int beta  = 0;

    int w     = s->width;

    int h     = s->height;

    int min_ab, i, w2, h2, w3, h3;

    int sprite_ref[4][2];

    int virtual_ref[2][2];

    // only true for rectangle shapes

    const int vop_ref[4][2] = { { 0, 0 },         { s->width, 0 },

                                { 0, s->height }, { s->width, s->height } };

    int d[4][2]             = { { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 } };

    if (w <= 0 || h <= 0)

        return AVERROR_INVALIDDATA;

    for (i = 0; i < ctx->num_sprite_warping_points; i++) {

        int length;

        int x = 0, y = 0;

        length = get_vlc2(gb, sprite_trajectory.table, SPRITE_TRAJ_VLC_BITS, 3);

        if (length)

            x = get_xbits(gb, length);

        if (!(ctx->divx_version == 500 && ctx->divx_build == 413))

            skip_bits1(gb);     /* marker bit */

        length = get_vlc2(gb, sprite_trajectory.table, SPRITE_TRAJ_VLC_BITS, 3);

        if (length)

            y = get_xbits(gb, length);

        skip_bits1(gb);         /* marker bit */

        ctx->sprite_traj[i][0] = d[i][0] = x;

        ctx->sprite_traj[i][1] = d[i][1] = y;

    }

    for (; i < 4; i++)

        ctx->sprite_traj[i][0] = ctx->sprite_traj[i][1] = 0;

    while ((1 << alpha) < w)

        alpha++;

    while ((1 << beta) < h)

        beta++;  /* typo in the mpeg4 std for the definition of w' and h' */

    w2 = 1 << alpha;

    h2 = 1 << beta;

    // Note, the 4th point isn't used for GMC

    if (ctx->divx_version == 500 && ctx->divx_build == 413) {

        sprite_ref[0][0] = a * vop_ref[0][0] + d[0][0];

        sprite_ref[0][1] = a * vop_ref[0][1] + d[0][1];

        sprite_ref[1][0] = a * vop_ref[1][0] + d[0][0] + d[1][0];

        sprite_ref[1][1] = a * vop_ref[1][1] + d[0][1] + d[1][1];

        sprite_ref[2][0] = a * vop_ref[2][0] + d[0][0] + d[2][0];

        sprite_ref[2][1] = a * vop_ref[2][1] + d[0][1] + d[2][1];

    } else {

        sprite_ref[0][0] = (a >> 1) * (2 * vop_ref[0][0] + d[0][0]);

        sprite_ref[0][1] = (a >> 1) * (2 * vop_ref[0][1] + d[0][1]);

        sprite_ref[1][0] = (a >> 1) * (2 * vop_ref[1][0] + d[0][0] + d[1][0]);

        sprite_ref[1][1] = (a >> 1) * (2 * vop_ref[1][1] + d[0][1] + d[1][1]);

        sprite_ref[2][0] = (a >> 1) * (2 * vop_ref[2][0] + d[0][0] + d[2][0]);

        sprite_ref[2][1] = (a >> 1) * (2 * vop_ref[2][1] + d[0][1] + d[2][1]);

    }

    /* sprite_ref[3][0] = (a >> 1) * (2 * vop_ref[3][0] + d[0][0] + d[1][0] + d[2][0] + d[3][0]);

     * sprite_ref[3][1] = (a >> 1) * (2 * vop_ref[3][1] + d[0][1] + d[1][1] + d[2][1] + d[3][1]); */

    /* this is mostly identical to the mpeg4 std (and is totally unreadable

     * because of that...). Perhaps it should be reordered to be more readable.

     * The idea behind this virtual_ref mess is to be able to use shifts later

     * per pixel instead of divides so the distance between points is converted

     * from w&h based to w2&h2 based which are of the 2^x form. */

    virtual_ref[0][0] = 16 * (vop_ref[0][0] + w2) +

                         ROUNDED_DIV(((w - w2) *

                                      (r * sprite_ref[0][0] - 16 * vop_ref[0][0]) +

                                      w2 * (r * sprite_ref[1][0] - 16 * vop_ref[1][0])), w);

    virtual_ref[0][1] = 16 * vop_ref[0][1] +

                        ROUNDED_DIV(((w - w2) *

                                     (r * sprite_ref[0][1] - 16 * vop_ref[0][1]) +

                                     w2 * (r * sprite_ref[1][1] - 16 * vop_ref[1][1])), w);

    virtual_ref[1][0] = 16 * vop_ref[0][0] +

                        ROUNDED_DIV(((h - h2) * (r * sprite_ref[0][0] - 16 * vop_ref[0][0]) +

                                     h2 * (r * sprite_ref[2][0] - 16 * vop_ref[2][0])), h);

    virtual_ref[1][1] = 16 * (vop_ref[0][1] + h2) +

                        ROUNDED_DIV(((h - h2) * (r * sprite_ref[0][1] - 16 * vop_ref[0][1]) +

                                     h2 * (r * sprite_ref[2][1] - 16 * vop_ref[2][1])), h);

    switch (ctx->num_sprite_warping_points) {

    case 0:

        s->sprite_offset[0][0] =

        s->sprite_offset[0][1] =

        s->sprite_offset[1][0] =

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

        s->sprite_delta[0][0]  = a;

        s->sprite_delta[0][1]  =

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

        s->sprite_delta[1][1]  = a;

        ctx->sprite_shift[0]   =

        ctx->sprite_shift[1]   = 0;

        break;

    case 1:     // GMC only

        s->sprite_offset[0][0] = sprite_ref[0][0] - a * vop_ref[0][0];

        s->sprite_offset[0][1] = sprite_ref[0][1] - a * vop_ref[0][1];

        s->sprite_offset[1][0] = ((sprite_ref[0][0] >> 1) | (sprite_ref[0][0] & 1)) -

                                 a * (vop_ref[0][0] / 2);

        s->sprite_offset[1][1] = ((sprite_ref[0][1] >> 1) | (sprite_ref[0][1] & 1)) -

                                 a * (vop_ref[0][1] / 2);

        s->sprite_delta[0][0]  = a;

        s->sprite_delta[0][1]  =

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

        s->sprite_delta[1][1]  = a;

        ctx->sprite_shift[0]   =

        ctx->sprite_shift[1]   = 0;

        break;

    case 2:

        s->sprite_offset[0][0] = (sprite_ref[0][0] << (alpha + rho)) +

                                 (-r * sprite_ref[0][0] + virtual_ref[0][0]) *

                                 (-vop_ref[0][0]) +

                                 (r * sprite_ref[0][1] - virtual_ref[0][1]) *

                                 (-vop_ref[0][1]) + (1 << (alpha + rho - 1));

        s->sprite_offset[0][1] = (sprite_ref[0][1] << (alpha + rho)) +

                                 (-r * sprite_ref[0][1] + virtual_ref[0][1]) *

                                 (-vop_ref[0][0]) +

                                 (-r * sprite_ref[0][0] + virtual_ref[0][0]) *

                                 (-vop_ref[0][1]) + (1 << (alpha + rho - 1));

        s->sprite_offset[1][0] = ((-r * sprite_ref[0][0] + virtual_ref[0][0]) *

                                  (-2 * vop_ref[0][0] + 1) +

                                  (r * sprite_ref[0][1] - virtual_ref[0][1]) *

                                  (-2 * vop_ref[0][1] + 1) + 2 * w2 * r *

                                  sprite_ref[0][0] - 16 * w2 + (1 << (alpha + rho + 1)));

        s->sprite_offset[1][1] = ((-r * sprite_ref[0][1] + virtual_ref[0][1]) *

                                  (-2 * vop_ref[0][0] + 1) +

                                  (-r * sprite_ref[0][0] + virtual_ref[0][0]) *

                                  (-2 * vop_ref[0][1] + 1) + 2 * w2 * r *

                                  sprite_ref[0][1] - 16 * w2 + (1 << (alpha + rho + 1)));

        s->sprite_delta[0][0] = (-r * sprite_ref[0][0] + virtual_ref[0][0]);

        s->sprite_delta[0][1] = (+r * sprite_ref[0][1] - virtual_ref[0][1]);

        s->sprite_delta[1][0] = (-r * sprite_ref[0][1] + virtual_ref[0][1]);

        s->sprite_delta[1][1] = (-r * sprite_ref[0][0] + virtual_ref[0][0]);

        ctx->sprite_shift[0]  = alpha + rho;

        ctx->sprite_shift[1]  = alpha + rho + 2;

        break;

    case 3:

        min_ab = FFMIN(alpha, beta);

        w3     = w2 >> min_ab;

        h3     = h2 >> min_ab;

        s->sprite_offset[0][0] = (sprite_ref[0][0] << (alpha + beta + rho - min_ab)) +

                                 (-r * sprite_ref[0][0] + virtual_ref[0][0]) *

                                 h3 * (-vop_ref[0][0]) +

                                 (-r * sprite_ref[0][0] + virtual_ref[1][0]) *

                                 w3 * (-vop_ref[0][1]) +

                                 (1 << (alpha + beta + rho - min_ab - 1));

        s->sprite_offset[0][1] = (sprite_ref[0][1] << (alpha + beta + rho - min_ab)) +

                                 (-r * sprite_ref[0][1] + virtual_ref[0][1]) *

                                 h3 * (-vop_ref[0][0]) +

                                 (-r * sprite_ref[0][1] + virtual_ref[1][1]) *

                                 w3 * (-vop_ref[0][1]) +

                                 (1 << (alpha + beta + rho - min_ab - 1));

        s->sprite_offset[1][0] = (-r * sprite_ref[0][0] + virtual_ref[0][0]) *

                                 h3 * (-2 * vop_ref[0][0] + 1) +

                                 (-r * sprite_ref[0][0] + virtual_ref[1][0]) *

                                 w3 * (-2 * vop_ref[0][1] + 1) + 2 * w2 * h3 *

                                 r * sprite_ref[0][0] - 16 * w2 * h3 +

                                 (1 << (alpha + beta + rho - min_ab + 1));

        s->sprite_offset[1][1] = (-r * sprite_ref[0][1] + virtual_ref[0][1]) *

                                 h3 * (-2 * vop_ref[0][0] + 1) +

                                 (-r * sprite_ref[0][1] + virtual_ref[1][1]) *

                                 w3 * (-2 * vop_ref[0][1] + 1) + 2 * w2 * h3 *

                                 r * sprite_ref[0][1] - 16 * w2 * h3 +

                                 (1 << (alpha + beta + rho - min_ab + 1));

        s->sprite_delta[0][0] = (-r * sprite_ref[0][0] + virtual_ref[0][0]) * h3;

        s->sprite_delta[0][1] = (-r * sprite_ref[0][0] + virtual_ref[1][0]) * w3;

        s->sprite_delta[1][0] = (-r * sprite_ref[0][1] + virtual_ref[0][1]) * h3;

        s->sprite_delta[1][1] = (-r * sprite_ref[0][1] + virtual_ref[1][1]) * w3;

        ctx->sprite_shift[0]  = alpha + beta + rho - min_ab;

        ctx->sprite_shift[1]  = alpha + beta + rho - min_ab + 2;

        break;

    }

    /* try to simplify the situation */

    if (s->sprite_delta[0][0] == a << ctx->sprite_shift[0] &&

        s->sprite_delta[0][1] == 0 &&

        s->sprite_delta[1][0] == 0 &&

        s->sprite_delta[1][1] == a << ctx->sprite_shift[0]) {

        s->sprite_offset[0][0] >>= ctx->sprite_shift[0];

        s->sprite_offset[0][1] >>= ctx->sprite_shift[0];

        s->sprite_offset[1][0] >>= ctx->sprite_shift[1];

        s->sprite_offset[1][1] >>= ctx->sprite_shift[1];

        s->sprite_delta[0][0] = a;

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

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

        s->sprite_delta[1][1] = a;

        ctx->sprite_shift[0] = 0;

        ctx->sprite_shift[1] = 0;

        s->real_sprite_warping_points = 1;

    } else {

        int shift_y = 16 - ctx->sprite_shift[0];

        int shift_c = 16 - ctx->sprite_shift[1];

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

            s->sprite_offset[0][i] <<= shift_y;

            s->sprite_offset[1][i] <<= shift_c;

            s->sprite_delta[0][i]  <<= shift_y;

            s->sprite_delta[1][i]  <<= shift_y;

            ctx->sprite_shift[i]     = 16;

        }

        s->real_sprite_warping_points = ctx->num_sprite_warping_points;

    }

    return 0;

}


static int fchmodat_nofollow(int dirfd, const char *name, mode_t mode)

{

    int fd, ret;

    /* FIXME: this should be handled with fchmodat(AT_SYMLINK_NOFOLLOW).

     * Unfortunately, the linux kernel doesn't implement it yet. As an

     * alternative, let's open the file and use fchmod() instead. This

     * may fail depending on the permissions of the file, but it is the

     * best we can do to avoid TOCTTOU. We first try to open read-only

     * in case name points to a directory. If that fails, we try write-only

     * in case name doesn't point to a directory.

     */

    fd = openat_file(dirfd, name, O_RDONLY, 0);

    if (fd == -1) {

        /* In case the file is writable-only and isn't a directory. */

        if (errno == EACCES) {

            fd = openat_file(dirfd, name, O_WRONLY, 0);

        }

        if (fd == -1 && errno == EISDIR) {

            errno = EACCES;

        }

    }

    if (fd == -1) {

        return -1;

    }

    ret = fchmod(fd, mode);

    close_preserve_errno(fd);

    return ret;

}


void virtio_scsi_push_event(VirtIOSCSI *s, SCSIDevice *dev,

                            uint32_t event, uint32_t reason)

{

    VirtIOSCSICommon *vs = VIRTIO_SCSI_COMMON(s);

    VirtIOSCSIReq *req;

    VirtIOSCSIEvent *evt;

    VirtIODevice *vdev = VIRTIO_DEVICE(s);

    if (!(vdev->status & VIRTIO_CONFIG_S_DRIVER_OK)) {

        return;

    }

    if (s->dataplane_started) {

        assert(s->ctx);

        aio_context_acquire(s->ctx);

    }

    req = virtio_scsi_pop_req(s, vs->event_vq);

    if (!req) {

        s->events_dropped = true;

        goto out;

    }

    if (s->events_dropped) {

        event |= VIRTIO_SCSI_T_EVENTS_MISSED;

        s->events_dropped = false;

    }

    if (virtio_scsi_parse_req(req, 0, sizeof(VirtIOSCSIEvent))) {

        virtio_scsi_bad_req();

    }

    evt = &req->resp.event;

    memset(evt, 0, sizeof(VirtIOSCSIEvent));

    evt->event = virtio_tswap32(vdev, event);

    evt->reason = virtio_tswap32(vdev, reason);

    if (!dev) {

        assert(event == VIRTIO_SCSI_T_EVENTS_MISSED);

    } else {

        evt->lun[0] = 1;

        evt->lun[1] = dev->id;

        /* Linux wants us to keep the same encoding we use for REPORT LUNS.  */

        if (dev->lun >= 256) {

            evt->lun[2] = (dev->lun >> 8) | 0x40;

        }

        evt->lun[3] = dev->lun & 0xFF;

    }

    virtio_scsi_complete_req(req);

out:

    if (s->dataplane_started) {

        aio_context_release(s->ctx);

    }

}


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

{

    int32_t *ptr = qdev_get_prop_ptr(dev, prop);

    char *end;

    *ptr = strtol(str, &end, 10);

    if ((*end != '\0') || (end == str)) {

        return -EINVAL;

    }

    return 0;

}


static int decode_frame(AVCodecContext *avctx, void *data, int *got_frame,

                        AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    UtvideoContext *c = avctx->priv_data;

    int i, j;

    const uint8_t *plane_start[5];

    int plane_size, max_slice_size = 0, slice_start, slice_end, slice_size;

    int ret;

    GetByteContext gb;

    ThreadFrame frame = { .f = data };

    if ((ret = ff_thread_get_buffer(avctx, &frame, 0)) < 0)

        return ret;

    /* parse plane structure to get frame flags and validate slice offsets */

    bytestream2_init(&gb, buf, buf_size);

    for (i = 0; i < c->planes; i++) {

        plane_start[i] = gb.buffer;

        if (bytestream2_get_bytes_left(&gb) < 256 + 4 * c->slices) {

            av_log(avctx, AV_LOG_ERROR, "Insufficient data for a plane\n");

            return AVERROR_INVALIDDATA;

        }

        bytestream2_skipu(&gb, 256);

        slice_start = 0;

        slice_end   = 0;

        for (j = 0; j < c->slices; j++) {

            slice_end   = bytestream2_get_le32u(&gb);

            slice_size  = slice_end - slice_start;

            if (slice_end < 0 || slice_size < 0 ||

                bytestream2_get_bytes_left(&gb) < slice_end) {

                av_log(avctx, AV_LOG_ERROR, "Incorrect slice size\n");

                return AVERROR_INVALIDDATA;

            }

            slice_start = slice_end;

            max_slice_size = FFMAX(max_slice_size, slice_size);

        }

        plane_size = slice_end;

        bytestream2_skipu(&gb, plane_size);

    }

    plane_start[c->planes] = gb.buffer;

    if (bytestream2_get_bytes_left(&gb) < c->frame_info_size) {

        av_log(avctx, AV_LOG_ERROR, "Not enough data for frame information\n");

        return AVERROR_INVALIDDATA;

    }

    c->frame_info = bytestream2_get_le32u(&gb);

    av_log(avctx, AV_LOG_DEBUG, "frame information flags %"PRIX32"\n",

           c->frame_info);

    c->frame_pred = (c->frame_info >> 8) & 3;

    if (c->frame_pred == PRED_GRADIENT) {

        avpriv_request_sample(avctx, "Frame with gradient prediction");

        return AVERROR_PATCHWELCOME;

    }

    av_fast_malloc(&c->slice_bits, &c->slice_bits_size,

                   max_slice_size + AV_INPUT_BUFFER_PADDING_SIZE);

    if (!c->slice_bits) {

        av_log(avctx, AV_LOG_ERROR, "Cannot allocate temporary buffer\n");

        return AVERROR(ENOMEM);

    }

    switch (c->avctx->pix_fmt) {

    case AV_PIX_FMT_RGB24:

    case AV_PIX_FMT_RGBA:

        for (i = 0; i < c->planes; i++) {

            ret = decode_plane(c, i, frame.f->data[0] + ff_ut_rgb_order[i],

                               c->planes, frame.f->linesize[0], avctx->width,

                               avctx->height, plane_start[i],

                               c->frame_pred == PRED_LEFT);

            if (ret)

                return ret;

            if (c->frame_pred == PRED_MEDIAN) {

                if (!c->interlaced) {

                    restore_median(frame.f->data[0] + ff_ut_rgb_order[i],

                                   c->planes, frame.f->linesize[0], avctx->width,

                                   avctx->height, c->slices, 0);

                } else {

                    restore_median_il(frame.f->data[0] + ff_ut_rgb_order[i],

                                      c->planes, frame.f->linesize[0],

                                      avctx->width, avctx->height, c->slices,

                                      0);

                }

            }

        }

        restore_rgb_planes(frame.f->data[0], c->planes, frame.f->linesize[0],

                           avctx->width, avctx->height);

        break;

    case AV_PIX_FMT_YUV420P:

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

            ret = decode_plane(c, i, frame.f->data[i], 1, frame.f->linesize[i],

                               avctx->width >> !!i, avctx->height >> !!i,

                               plane_start[i], c->frame_pred == PRED_LEFT);

            if (ret)

                return ret;

            if (c->frame_pred == PRED_MEDIAN) {

                if (!c->interlaced) {

                    restore_median(frame.f->data[i], 1, frame.f->linesize[i],

                                   avctx->width >> !!i, avctx->height >> !!i,

                                   c->slices, !i);

                } else {

                    restore_median_il(frame.f->data[i], 1, frame.f->linesize[i],

                                      avctx->width  >> !!i,

                                      avctx->height >> !!i,

                                      c->slices, !i);

                }

            }

        }

        break;

    case AV_PIX_FMT_YUV422P:

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

            ret = decode_plane(c, i, frame.f->data[i], 1, frame.f->linesize[i],

                               avctx->width >> !!i, avctx->height,

                               plane_start[i], c->frame_pred == PRED_LEFT);

            if (ret)

                return ret;

            if (c->frame_pred == PRED_MEDIAN) {

                if (!c->interlaced) {

                    restore_median(frame.f->data[i], 1, frame.f->linesize[i],

                                   avctx->width >> !!i, avctx->height,

                                   c->slices, 0);

                } else {

                    restore_median_il(frame.f->data[i], 1, frame.f->linesize[i],

                                      avctx->width >> !!i, avctx->height,

                                      c->slices, 0);

                }

            }

        }

        break;

    }

    frame.f->key_frame = 1;

    frame.f->pict_type = AV_PICTURE_TYPE_I;

    frame.f->interlaced_frame = !!c->interlaced;

    *got_frame = 1;

    /* always report that the buffer was completely consumed */

    return buf_size;

}


static av_cold int vaapi_encode_h264_init(AVCodecContext *avctx)

{

    return ff_vaapi_encode_init(avctx, &vaapi_encode_type_h264);

}


static void test_qemu_strtoul_full_max(void)

{

    const char *str = g_strdup_printf("%lu", ULONG_MAX);

    unsigned long res = 999;

    int err;

    err = qemu_strtoul(str, NULL, 0, &res);

    g_assert_cmpint(err, ==, 0);

    g_assert_cmpint(res, ==, ULONG_MAX);

}


static int cloop_open(BlockDriverState *bs, int flags)

{

    BDRVCloopState *s = bs->opaque;

    uint32_t offsets_size, max_compressed_block_size = 1, i;

    bs->read_only = 1;

    /* read header */

    if (bdrv_pread(bs->file, 128, &s->block_size, 4) < 4) {

        goto cloop_close;

    }

    s->block_size = be32_to_cpu(s->block_size);

    if (bdrv_pread(bs->file, 128 + 4, &s->n_blocks, 4) < 4) {

        goto cloop_close;

    }

    s->n_blocks = be32_to_cpu(s->n_blocks);

    /* read offsets */

    offsets_size = s->n_blocks * sizeof(uint64_t);

    s->offsets = g_malloc(offsets_size);

    if (bdrv_pread(bs->file, 128 + 4 + 4, s->offsets, offsets_size) <

            offsets_size) {

        goto cloop_close;

    }

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

        s->offsets[i] = be64_to_cpu(s->offsets[i]);

        if (i > 0) {

            uint32_t size = s->offsets[i] - s->offsets[i - 1];

            if (size > max_compressed_block_size) {

                max_compressed_block_size = size;

            }

        }

    }

    /* initialize zlib engine */

    s->compressed_block = g_malloc(max_compressed_block_size + 1);

    s->uncompressed_block = g_malloc(s->block_size);

    if (inflateInit(&s->zstream) != Z_OK) {

        goto cloop_close;

    }

    s->current_block = s->n_blocks;

    s->sectors_per_block = s->block_size/512;

    bs->total_sectors = s->n_blocks * s->sectors_per_block;

    qemu_co_mutex_init(&s->lock);

    return 0;

cloop_close:

    return -1;

}


static void monitor_find_completion(Monitor *mon,

                                    const char *cmdline)

{

    const char *cmdname;

    char *args[MAX_ARGS];

    int nb_args, i, len;

    const char *ptype, *str;

    const mon_cmd_t *cmd;

    MonitorBlockComplete mbs;

    parse_cmdline(cmdline, &nb_args, args);

#ifdef DEBUG_COMPLETION

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

        monitor_printf(mon, "arg%d = '%s'\n", i, args[i]);

    }

#endif

    /* if the line ends with a space, it means we want to complete the

       next arg */

    len = strlen(cmdline);

    if (len > 0 && qemu_isspace(cmdline[len - 1])) {

        if (nb_args >= MAX_ARGS) {

            goto cleanup;

        }

        args[nb_args++] = g_strdup("");

    }

    if (nb_args <= 1) {

        /* command completion */

        if (nb_args == 0)

            cmdname = "";

        else

            cmdname = args[0];

        readline_set_completion_index(mon->rs, strlen(cmdname));

        for (cmd = mon->cmd_table; cmd->name != NULL; cmd++) {

            cmd_completion(mon, cmdname, cmd->name);

        }

    } else {

        /* find the command */

        for (cmd = mon->cmd_table; cmd->name != NULL; cmd++) {

            if (compare_cmd(args[0], cmd->name)) {

                break;

            }

        }

        if (!cmd->name) {

            goto cleanup;

        }

        ptype = next_arg_type(cmd->args_type);

        for(i = 0; i < nb_args - 2; i++) {

            if (*ptype != '\0') {

                ptype = next_arg_type(ptype);

                while (*ptype == '?')

                    ptype = next_arg_type(ptype);

            }

        }

        str = args[nb_args - 1];

        if (*ptype == '-' && ptype[1] != '\0') {

            ptype = next_arg_type(ptype);

        }

        switch(*ptype) {

        case 'F':

            /* file completion */

            readline_set_completion_index(mon->rs, strlen(str));

            file_completion(mon, str);

            break;

        case 'B':

            /* block device name completion */

            mbs.mon = mon;

            mbs.input = str;

            readline_set_completion_index(mon->rs, strlen(str));

            bdrv_iterate(block_completion_it, &mbs);

            break;

        case 's':

            /* XXX: more generic ? */

            if (!strcmp(cmd->name, "info")) {

                readline_set_completion_index(mon->rs, strlen(str));

                for(cmd = info_cmds; cmd->name != NULL; cmd++) {

                    cmd_completion(mon, str, cmd->name);

                }

            } else if (!strcmp(cmd->name, "sendkey")) {

                char *sep = strrchr(str, '-');

                if (sep)

                    str = sep + 1;

                readline_set_completion_index(mon->rs, strlen(str));

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

                    cmd_completion(mon, str, QKeyCode_lookup[i]);

                }

            } else if (!strcmp(cmd->name, "help|?")) {

                readline_set_completion_index(mon->rs, strlen(str));

                for (cmd = mon->cmd_table; cmd->name != NULL; cmd++) {

                    cmd_completion(mon, str, cmd->name);

                }

            }

            break;

        default:

            break;

        }

    }

cleanup:

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

        g_free(args[i]);

    }

}


static void decode_channel_map(uint8_t layout_map[][3],

                               enum ChannelPosition type,

                               GetBitContext *gb, int n)

{

    while (n--) {

        enum RawDataBlockType syn_ele;

        switch (type) {

        case AAC_CHANNEL_FRONT:

        case AAC_CHANNEL_BACK:

        case AAC_CHANNEL_SIDE:

            syn_ele = get_bits1(gb);

            break;

        case AAC_CHANNEL_CC:

            skip_bits1(gb);

            syn_ele = TYPE_CCE;

            break;

        case AAC_CHANNEL_LFE:

            syn_ele = TYPE_LFE;

            break;

        }

        layout_map[0][0] = syn_ele;

        layout_map[0][1] = get_bits(gb, 4);

        layout_map[0][2] = type;

        layout_map++;

    }

}


int qemu_devtree_setprop_cell(void *fdt, const char *node_path,

                              const char *property, uint32_t val)

{

    int offset;

    offset = fdt_path_offset(fdt, node_path);

    if (offset < 0)

        return offset;

    return fdt_setprop_cell(fdt, offset, property, val);

}


static void qed_copy_from_backing_file(BDRVQEDState *s, uint64_t pos,

                                       uint64_t len, uint64_t offset,

                                       BlockDriverCompletionFunc *cb,

                                       void *opaque)

{

    CopyFromBackingFileCB *copy_cb;

    /* Skip copy entirely if there is no work to do */

    if (len == 0) {

        cb(opaque, 0);

        return;

    }

    copy_cb = gencb_alloc(sizeof(*copy_cb), cb, opaque);

    copy_cb->s = s;

    copy_cb->offset = offset;

    copy_cb->iov.iov_base = qemu_blockalign(s->bs, len);

    copy_cb->iov.iov_len = len;

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

    qed_read_backing_file(s, pos, &copy_cb->qiov,

                          qed_copy_from_backing_file_write, copy_cb);

}


void align_get_bits(GetBitContext *s)

{

    int n= (-get_bits_count(s)) & 7;

    if(n) skip_bits(s, n);

}


static uint64_t do_cvttq(CPUAlphaState *env, uint64_t a, int roundmode)

{

    uint64_t frac, ret = 0;

    uint32_t exp, sign, exc = 0;

    int shift;

    sign = (a >> 63);

    exp = (uint32_t)(a >> 52) & 0x7ff;

    frac = a & 0xfffffffffffffull;

    if (exp == 0) {

        if (unlikely(frac != 0)) {

            goto do_underflow;

        }

    } else if (exp == 0x7ff) {

        exc = FPCR_INV;

    } else {

        /* Restore implicit bit.  */

        frac |= 0x10000000000000ull;

        shift = exp - 1023 - 52;

        if (shift >= 0) {

            /* In this case the number is so large that we must shift

               the fraction left.  There is no rounding to do.  */

            if (shift < 64) {

                ret = frac << shift;

            }

            /* Check for overflow.  Note the special case of -0x1p63.  */

            if (shift >= 11 && a != 0xC3E0000000000000ull) {

                exc = FPCR_IOV | FPCR_INE;

            }

        } else {

            uint64_t round;

            /* In this case the number is smaller than the fraction as

               represented by the 52 bit number.  Here we must think

               about rounding the result.  Handle this by shifting the

               fractional part of the number into the high bits of ROUND.

               This will let us efficiently handle round-to-nearest.  */

            shift = -shift;

            if (shift < 63) {

                ret = frac >> shift;

                round = frac << (64 - shift);

            } else {

                /* The exponent is so small we shift out everything.

                   Leave a sticky bit for proper rounding below.  */

            do_underflow:

                round = 1;

            }

            if (round) {

                exc = FPCR_INE;

                switch (roundmode) {

                case float_round_nearest_even:

                    if (round == (1ull << 63)) {

                        /* Fraction is exactly 0.5; round to even.  */

                        ret += (ret & 1);

                    } else if (round > (1ull << 63)) {

                        ret += 1;

                    }

                    break;

                case float_round_to_zero:

                    break;

                case float_round_up:

                    ret += 1 - sign;

                    break;

                case float_round_down:

                    ret += sign;

                    break;

                }

            }

        }

        if (sign) {

            ret = -ret;

        }

    }

    env->error_code = exc;

    return ret;

}


static inline void RENAME(rgb15to24)(const uint8_t *src, uint8_t *dst, long src_size)

{

	const uint16_t *end;

#ifdef HAVE_MMX

	const uint16_t *mm_end;

#endif

	uint8_t *d = (uint8_t *)dst;

	const uint16_t *s = (uint16_t *)src;

	end = s + src_size/2;

#ifdef HAVE_MMX

	__asm __volatile(PREFETCH"	%0"::"m"(*s):"memory");

	mm_end = end - 7;

	while(s < mm_end)

	{

	    __asm __volatile(

		PREFETCH" 32%1\n\t"

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

		"movq	%1, %%mm1\n\t"

		"movq	%1, %%mm2\n\t"

		"pand	%2, %%mm0\n\t"

		"pand	%3, %%mm1\n\t"

		"pand	%4, %%mm2\n\t"

		"psllq	$3, %%mm0\n\t"

		"psrlq	$2, %%mm1\n\t"

		"psrlq	$7, %%mm2\n\t"

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

		"movq	%%mm1, %%mm4\n\t"

		"movq	%%mm2, %%mm5\n\t"

		"punpcklwd %5, %%mm0\n\t"

		"punpcklwd %5, %%mm1\n\t"

		"punpcklwd %5, %%mm2\n\t"

		"punpckhwd %5, %%mm3\n\t"

		"punpckhwd %5, %%mm4\n\t"

		"punpckhwd %5, %%mm5\n\t"

		"psllq	$8, %%mm1\n\t"

		"psllq	$16, %%mm2\n\t"

		"por	%%mm1, %%mm0\n\t"

		"por	%%mm2, %%mm0\n\t"

		"psllq	$8, %%mm4\n\t"

		"psllq	$16, %%mm5\n\t"

		"por	%%mm4, %%mm3\n\t"

		"por	%%mm5, %%mm3\n\t"

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

		"movq	%%mm3, %%mm7\n\t"

		"movq	8%1, %%mm0\n\t"

		"movq	8%1, %%mm1\n\t"

		"movq	8%1, %%mm2\n\t"

		"pand	%2, %%mm0\n\t"

		"pand	%3, %%mm1\n\t"

		"pand	%4, %%mm2\n\t"

		"psllq	$3, %%mm0\n\t"

		"psrlq	$2, %%mm1\n\t"

		"psrlq	$7, %%mm2\n\t"

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

		"movq	%%mm1, %%mm4\n\t"

		"movq	%%mm2, %%mm5\n\t"

		"punpcklwd %5, %%mm0\n\t"

		"punpcklwd %5, %%mm1\n\t"

		"punpcklwd %5, %%mm2\n\t"

		"punpckhwd %5, %%mm3\n\t"

		"punpckhwd %5, %%mm4\n\t"

		"punpckhwd %5, %%mm5\n\t"

		"psllq	$8, %%mm1\n\t"

		"psllq	$16, %%mm2\n\t"

		"por	%%mm1, %%mm0\n\t"

		"por	%%mm2, %%mm0\n\t"

		"psllq	$8, %%mm4\n\t"

		"psllq	$16, %%mm5\n\t"

		"por	%%mm4, %%mm3\n\t"

		"por	%%mm5, %%mm3\n\t"

		:"=m"(*d)

		:"m"(*s),"m"(mask15b),"m"(mask15g),"m"(mask15r), "m"(mmx_null)

		:"memory");

	    /* Borrowed 32 to 24 */

	    __asm __volatile(

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

		"movq	%%mm3, %%mm5\n\t"

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

		"movq	%%mm7, %%mm1\n\t"

		"movq	%%mm4, %%mm6\n\t"

		"movq	%%mm5, %%mm7\n\t"

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

		"movq	%%mm1, %%mm3\n\t"

		"psrlq	$8, %%mm2\n\t"

		"psrlq	$8, %%mm3\n\t"

		"psrlq	$8, %%mm6\n\t"

		"psrlq	$8, %%mm7\n\t"

		"pand	%2, %%mm0\n\t"

		"pand	%2, %%mm1\n\t"

		"pand	%2, %%mm4\n\t"

		"pand	%2, %%mm5\n\t"

		"pand	%3, %%mm2\n\t"

		"pand	%3, %%mm3\n\t"

		"pand	%3, %%mm6\n\t"

		"pand	%3, %%mm7\n\t"

		"por	%%mm2, %%mm0\n\t"

		"por	%%mm3, %%mm1\n\t"

		"por	%%mm6, %%mm4\n\t"

		"por	%%mm7, %%mm5\n\t"

		"movq	%%mm1, %%mm2\n\t"

		"movq	%%mm4, %%mm3\n\t"

		"psllq	$48, %%mm2\n\t"

		"psllq	$32, %%mm3\n\t"

		"pand	%4, %%mm2\n\t"

		"pand	%5, %%mm3\n\t"

		"por	%%mm2, %%mm0\n\t"

		"psrlq	$16, %%mm1\n\t"

		"psrlq	$32, %%mm4\n\t"

		"psllq	$16, %%mm5\n\t"

		"por	%%mm3, %%mm1\n\t"

		"pand	%6, %%mm5\n\t"

		"por	%%mm5, %%mm4\n\t"

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

		MOVNTQ"	%%mm1, 8%0\n\t"

		MOVNTQ"	%%mm4, 16%0"

		:"=m"(*d)

		:"m"(*s),"m"(mask24l),"m"(mask24h),"m"(mask24hh),"m"(mask24hhh),"m"(mask24hhhh)

		:"memory");

		d += 24;

		s += 8;

	}

	__asm __volatile(SFENCE:::"memory");

	__asm __volatile(EMMS:::"memory");

#endif

	while(s < end)

	{

		register uint16_t bgr;

		bgr = *s++;

		*d++ = (bgr&0x1F)<<3;

		*d++ = (bgr&0x3E0)>>2;

		*d++ = (bgr&0x7C00)>>7;

	}

}


static int pick_geometry(FDrive *drv)

{

    BlockBackend *blk = drv->blk;

    const FDFormat *parse;

    uint64_t nb_sectors, size;

    int i;

    int match, size_match, type_match;

    bool magic = drv->drive == FLOPPY_DRIVE_TYPE_AUTO;

    /* We can only pick a geometry if we have a diskette. */

    if (!drv->blk || !blk_is_inserted(drv->blk) ||

        drv->drive == FLOPPY_DRIVE_TYPE_NONE)

    {

        return -1;

    }

    /* We need to determine the likely geometry of the inserted medium.

     * In order of preference, we look for:

     * (1) The same drive type and number of sectors,

     * (2) The same diskette size and number of sectors,

     * (3) The same drive type.

     *

     * In all cases, matches that occur higher in the drive table will take

     * precedence over matches that occur later in the table.

     */

    blk_get_geometry(blk, &nb_sectors);

    match = size_match = type_match = -1;

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

        parse = &fd_formats[i];

        if (parse->drive == FLOPPY_DRIVE_TYPE_NONE) {

            break;

        }

        size = (parse->max_head + 1) * parse->max_track * parse->last_sect;

        if (nb_sectors == size) {

            if (magic || parse->drive == drv->drive) {

                /* (1) perfect match -- nb_sectors and drive type */

                goto out;

            } else if (drive_size(parse->drive) == drive_size(drv->drive)) {

                /* (2) size match -- nb_sectors and physical medium size */

                match = (match == -1) ? i : match;

            } else {

                /* This is suspicious -- Did the user misconfigure? */

                size_match = (size_match == -1) ? i : size_match;

            }

        } else if (type_match == -1) {

            if ((parse->drive == drv->drive) ||

                (magic && (parse->drive == get_fallback_drive_type(drv)))) {

                /* (3) type match -- nb_sectors mismatch, but matches the type

                 *     specified explicitly by the user, or matches the fallback

                 *     default type when using the drive autodetect mechanism */

                type_match = i;

            }

        }

    }

    /* No exact match found */

    if (match == -1) {

        if (size_match != -1) {

            parse = &fd_formats[size_match];

            FLOPPY_DPRINTF("User requested floppy drive type '%s', "

                           "but inserted medium appears to be a "

                           "%d sector '%s' type\n",

                           FloppyDriveType_lookup[drv->drive],

                           nb_sectors,

                           FloppyDriveType_lookup[parse->drive]);

        }

        match = type_match;

    }

    /* No match of any kind found -- fd_format is misconfigured, abort. */

    if (match == -1) {

        error_setg(&error_abort, "No candidate geometries present in table "

                   " for floppy drive type '%s'",

                   FloppyDriveType_lookup[drv->drive]);

    }

    parse = &(fd_formats[match]);

 out:

    if (parse->max_head == 0) {

        drv->flags &= ~FDISK_DBL_SIDES;

    } else {

        drv->flags |= FDISK_DBL_SIDES;

    }

    drv->max_track = parse->max_track;

    drv->last_sect = parse->last_sect;

    drv->disk = parse->drive;

    drv->media_rate = parse->rate;

    return 0;

}


static int usbredir_get_bufpq(QEMUFile *f, void *priv, size_t unused)

{

    struct endp_data *endp = priv;

    USBRedirDevice *dev = endp->dev;

    struct buf_packet *bufp;

    int i;

    endp->bufpq_size = qemu_get_be32(f);

    for (i = 0; i < endp->bufpq_size; i++) {

        bufp = g_malloc(sizeof(struct buf_packet));

        bufp->len = qemu_get_be32(f);

        bufp->status = qemu_get_be32(f);

        bufp->offset = 0;

        bufp->data = qemu_oom_check(malloc(bufp->len)); /* regular malloc! */

        bufp->free_on_destroy = bufp->data;

        qemu_get_buffer(f, bufp->data, bufp->len);

        QTAILQ_INSERT_TAIL(&endp->bufpq, bufp, next);

        DPRINTF("get_bufpq %d/%d len %d status %d\n", i + 1, endp->bufpq_size,

                bufp->len, bufp->status);

    }

    return 0;

}


static int vp8_packet(AVFormatContext *s, int idx)

{

    struct ogg *ogg = s->priv_data;

    struct ogg_stream *os = ogg->streams + idx;

    uint8_t *p = os->buf + os->pstart;

    if ((!os->lastpts || os->lastpts == AV_NOPTS_VALUE) &&

        !(os->flags & OGG_FLAG_EOS)) {

        int seg;

        int duration;

        uint8_t *last_pkt = p;

        uint8_t *next_pkt;

        seg = os->segp;

        duration = (last_pkt[0] >> 4) & 1;

        next_pkt = last_pkt += os->psize;

        for (; seg < os->nsegs; seg++) {

            if (os->segments[seg] < 255) {

                duration += (last_pkt[0] >> 4) & 1;

                last_pkt  = next_pkt + os->segments[seg];

            }

            next_pkt += os->segments[seg];

        }

        os->lastpts =

        os->lastdts = vp8_gptopts(s, idx, os->granule, NULL) - duration;

        if(s->streams[idx]->start_time == AV_NOPTS_VALUE) {

            s->streams[idx]->start_time = os->lastpts;

            if (s->streams[idx]->duration)

                s->streams[idx]->duration -= s->streams[idx]->start_time;

        }

    }

    if (os->psize > 0)

        os->pduration = (p[0] >> 4) & 1;

    return 0;

}


static int xen_pt_config_reg_init(XenPCIPassthroughState *s,

                                  XenPTRegGroup *reg_grp, XenPTRegInfo *reg)

{

    XenPTReg *reg_entry;

    uint32_t data = 0;

    int rc = 0;

    reg_entry = g_new0(XenPTReg, 1);

    reg_entry->reg = reg;

    if (reg->init) {

        /* initialize emulate register */

        rc = reg->init(s, reg_entry->reg,

                       reg_grp->base_offset + reg->offset, &data);

        if (rc < 0) {

            free(reg_entry);

            return rc;

        }

        if (data == XEN_PT_INVALID_REG) {

            /* free unused BAR register entry */

            free(reg_entry);

            return 0;

        }

        /* set register value */

        reg_entry->data = data;

    }

    /* list add register entry */

    QLIST_INSERT_HEAD(&reg_grp->reg_tbl_list, reg_entry, entries);

    return 0;

}


static void open_help(void)

{

    printf(

"\n"

" opens a new file in the requested mode\n"

"\n"

" Example:\n"

" 'open -Cn /tmp/data' - creates/opens data file read-write and uncached\n"

"\n"

" Opens a file for subsequent use by all of the other qemu-io commands.\n"

" -r, -- open file read-only\n"

" -s, -- use snapshot file\n"

" -n, -- disable host cache\n"

" -o, -- options to be given to the block driver"

"\n");

}


static const char *scsi_command_name(uint8_t cmd)

{

    static const char *names[] = {

        [ TEST_UNIT_READY          ] = "TEST_UNIT_READY",

        [ REWIND                   ] = "REWIND",

        [ REQUEST_SENSE            ] = "REQUEST_SENSE",

        [ FORMAT_UNIT              ] = "FORMAT_UNIT",

        [ READ_BLOCK_LIMITS        ] = "READ_BLOCK_LIMITS",

        [ REASSIGN_BLOCKS          ] = "REASSIGN_BLOCKS",

        [ READ_6                   ] = "READ_6",

        [ WRITE_6                  ] = "WRITE_6",

        [ SEEK_6                   ] = "SEEK_6",

        [ READ_REVERSE             ] = "READ_REVERSE",

        [ WRITE_FILEMARKS          ] = "WRITE_FILEMARKS",

        [ SPACE                    ] = "SPACE",

        [ INQUIRY                  ] = "INQUIRY",

        [ RECOVER_BUFFERED_DATA    ] = "RECOVER_BUFFERED_DATA",

        [ MAINTENANCE_IN           ] = "MAINTENANCE_IN",

        [ MAINTENANCE_OUT          ] = "MAINTENANCE_OUT",

        [ MODE_SELECT              ] = "MODE_SELECT",

        [ RESERVE                  ] = "RESERVE",

        [ RELEASE                  ] = "RELEASE",

        [ COPY                     ] = "COPY",

        [ ERASE                    ] = "ERASE",

        [ MODE_SENSE               ] = "MODE_SENSE",

        [ START_STOP               ] = "START_STOP",

        [ RECEIVE_DIAGNOSTIC       ] = "RECEIVE_DIAGNOSTIC",

        [ SEND_DIAGNOSTIC          ] = "SEND_DIAGNOSTIC",

        [ ALLOW_MEDIUM_REMOVAL     ] = "ALLOW_MEDIUM_REMOVAL",

        [ READ_CAPACITY_10         ] = "READ_CAPACITY_10",

        [ READ_10                  ] = "READ_10",

        [ WRITE_10                 ] = "WRITE_10",

        [ SEEK_10                  ] = "SEEK_10",

        [ WRITE_VERIFY_10          ] = "WRITE_VERIFY_10",

        [ VERIFY_10                ] = "VERIFY_10",

        [ SEARCH_HIGH              ] = "SEARCH_HIGH",

        [ SEARCH_EQUAL             ] = "SEARCH_EQUAL",

        [ SEARCH_LOW               ] = "SEARCH_LOW",

        [ SET_LIMITS               ] = "SET_LIMITS",

        [ PRE_FETCH                ] = "PRE_FETCH",

        /* READ_POSITION and PRE_FETCH use the same operation code */

        [ SYNCHRONIZE_CACHE        ] = "SYNCHRONIZE_CACHE",

        [ LOCK_UNLOCK_CACHE        ] = "LOCK_UNLOCK_CACHE",

        [ READ_DEFECT_DATA         ] = "READ_DEFECT_DATA",

        [ MEDIUM_SCAN              ] = "MEDIUM_SCAN",

        [ COMPARE                  ] = "COMPARE",

        [ COPY_VERIFY              ] = "COPY_VERIFY",

        [ WRITE_BUFFER             ] = "WRITE_BUFFER",

        [ READ_BUFFER              ] = "READ_BUFFER",

        [ UPDATE_BLOCK             ] = "UPDATE_BLOCK",

        [ READ_LONG_10             ] = "READ_LONG_10",

        [ WRITE_LONG_10            ] = "WRITE_LONG_10",

        [ CHANGE_DEFINITION        ] = "CHANGE_DEFINITION",

        [ WRITE_SAME_10            ] = "WRITE_SAME_10",

        [ UNMAP                    ] = "UNMAP",

        [ READ_TOC                 ] = "READ_TOC",

        [ REPORT_DENSITY_SUPPORT   ] = "REPORT_DENSITY_SUPPORT",

        [ GET_CONFIGURATION        ] = "GET_CONFIGURATION",

        [ LOG_SELECT               ] = "LOG_SELECT",

        [ LOG_SENSE                ] = "LOG_SENSE",

        [ MODE_SELECT_10           ] = "MODE_SELECT_10",

        [ RESERVE_10               ] = "RESERVE_10",

        [ RELEASE_10               ] = "RELEASE_10",

        [ MODE_SENSE_10            ] = "MODE_SENSE_10",

        [ PERSISTENT_RESERVE_IN    ] = "PERSISTENT_RESERVE_IN",

        [ PERSISTENT_RESERVE_OUT   ] = "PERSISTENT_RESERVE_OUT",

        [ WRITE_FILEMARKS_16       ] = "WRITE_FILEMARKS_16",

        [ EXTENDED_COPY            ] = "EXTENDED_COPY",

        [ ATA_PASSTHROUGH          ] = "ATA_PASSTHROUGH",

        [ ACCESS_CONTROL_IN        ] = "ACCESS_CONTROL_IN",

        [ ACCESS_CONTROL_OUT       ] = "ACCESS_CONTROL_OUT",

        [ READ_16                  ] = "READ_16",

        [ COMPARE_AND_WRITE        ] = "COMPARE_AND_WRITE",

        [ WRITE_16                 ] = "WRITE_16",

        [ WRITE_VERIFY_16          ] = "WRITE_VERIFY_16",

        [ VERIFY_16                ] = "VERIFY_16",

        [ SYNCHRONIZE_CACHE_16     ] = "SYNCHRONIZE_CACHE_16",

        [ LOCATE_16                ] = "LOCATE_16",

        [ WRITE_SAME_16            ] = "WRITE_SAME_16",

        [ ERASE_16                 ] = "ERASE_16",

        [ SERVICE_ACTION_IN_16     ] = "SERVICE_ACTION_IN_16",

        [ WRITE_LONG_16            ] = "WRITE_LONG_16",

        [ REPORT_LUNS              ] = "REPORT_LUNS",

        [ BLANK                    ] = "BLANK",

        [ MAINTENANCE_IN           ] = "MAINTENANCE_IN",

        [ MAINTENANCE_OUT          ] = "MAINTENANCE_OUT",

        [ MOVE_MEDIUM              ] = "MOVE_MEDIUM",

        [ LOAD_UNLOAD              ] = "LOAD_UNLOAD",

        [ READ_12                  ] = "READ_12",

        [ WRITE_12                 ] = "WRITE_12",

        [ SERVICE_ACTION_IN_12     ] = "SERVICE_ACTION_IN_12",

        [ WRITE_VERIFY_12          ] = "WRITE_VERIFY_12",

        [ VERIFY_12                ] = "VERIFY_12",

        [ SEARCH_HIGH_12           ] = "SEARCH_HIGH_12",

        [ SEARCH_EQUAL_12          ] = "SEARCH_EQUAL_12",

        [ SEARCH_LOW_12            ] = "SEARCH_LOW_12",

        [ READ_ELEMENT_STATUS      ] = "READ_ELEMENT_STATUS",

        [ SEND_VOLUME_TAG          ] = "SEND_VOLUME_TAG",

        [ READ_DEFECT_DATA_12      ] = "READ_DEFECT_DATA_12",

        [ SET_CD_SPEED             ] = "SET_CD_SPEED",

    };

    if (cmd >= ARRAY_SIZE(names) || names[cmd] == NULL)

        return "*UNKNOWN*";

    return names[cmd];

}


static void intra_predict_vert_dc_8x8_msa(uint8_t *src, int32_t stride)

{

    uint8_t lp_cnt;

    uint32_t out0 = 0, out1 = 0;

    v16u8 src_top;

    v8u16 add;

    v4u32 sum;

    v4i32 res0, res1;

    src_top = LD_UB(src - stride);

    add = __msa_hadd_u_h(src_top, src_top);

    sum = __msa_hadd_u_w(add, add);

    sum = (v4u32) __msa_srari_w((v4i32) sum, 2);

    res0 = (v4i32) __msa_splati_b((v16i8) sum, 0);

    res1 = (v4i32) __msa_splati_b((v16i8) sum, 4);

    out0 = __msa_copy_u_w(res0, 0);

    out1 = __msa_copy_u_w(res1, 0);

    for (lp_cnt = 8; lp_cnt--;) {

        SW(out0, src);

        SW(out1, src + 4);

        src += stride;

    }

}


int bdrv_block_status(BlockDriverState *bs, int64_t offset, int64_t bytes,

                      int64_t *pnum, int64_t *map, BlockDriverState **file)

{

    int64_t ret;

    int n;

    assert(QEMU_IS_ALIGNED(offset | bytes, BDRV_SECTOR_SIZE));

    assert(pnum);

    /*

     * The contract allows us to return pnum smaller than bytes, even

     * if the next query would see the same status; we truncate the

     * request to avoid overflowing the driver's 32-bit interface.

     */

    bytes = MIN(bytes, BDRV_REQUEST_MAX_BYTES);

    ret = bdrv_get_block_status_above(bs, backing_bs(bs),

                                      offset >> BDRV_SECTOR_BITS,

                                      bytes >> BDRV_SECTOR_BITS, &n, file);

    if (ret < 0) {

        assert(INT_MIN <= ret);

        *pnum = 0;

        return ret;

    }

    *pnum = n * BDRV_SECTOR_SIZE;

    if (map) {

        *map = ret & BDRV_BLOCK_OFFSET_MASK;

    } else {

        ret &= ~BDRV_BLOCK_OFFSET_VALID;

    }

    return ret & ~BDRV_BLOCK_OFFSET_MASK;

}


int css_do_csch(SubchDev *sch)

{

    SCSW *s = &sch->curr_status.scsw;

    PMCW *p = &sch->curr_status.pmcw;

    int ret;

    if (!(p->flags & (PMCW_FLAGS_MASK_DNV | PMCW_FLAGS_MASK_ENA))) {

        ret = -ENODEV;

        goto out;

    }

    /* Trigger the clear function. */

    s->ctrl &= ~(SCSW_CTRL_MASK_FCTL | SCSW_CTRL_MASK_ACTL);

    s->ctrl |= SCSW_FCTL_CLEAR_FUNC | SCSW_ACTL_CLEAR_PEND;

    do_subchannel_work(sch, NULL);

    ret = 0;

out:

    return ret;

}


build_dsdt(GArray *table_data, BIOSLinker *linker,

           AcpiPmInfo *pm, AcpiMiscInfo *misc,

           Range *pci_hole, Range *pci_hole64, MachineState *machine)

{

    CrsRangeEntry *entry;

    Aml *dsdt, *sb_scope, *scope, *dev, *method, *field, *pkg, *crs;

    GPtrArray *mem_ranges = g_ptr_array_new_with_free_func(crs_range_free);

    GPtrArray *io_ranges = g_ptr_array_new_with_free_func(crs_range_free);

    PCMachineState *pcms = PC_MACHINE(machine);

    PCMachineClass *pcmc = PC_MACHINE_GET_CLASS(machine);

    uint32_t nr_mem = machine->ram_slots;

    int root_bus_limit = 0xFF;

    PCIBus *bus = NULL;

    int i;

    dsdt = init_aml_allocator();

    /* Reserve space for header */

    acpi_data_push(dsdt->buf, sizeof(AcpiTableHeader));

    build_dbg_aml(dsdt);

    if (misc->is_piix4) {

        sb_scope = aml_scope("_SB");

        dev = aml_device("PCI0");

        aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0A03")));

        aml_append(dev, aml_name_decl("_ADR", aml_int(0)));

        aml_append(dev, aml_name_decl("_UID", aml_int(1)));

        aml_append(sb_scope, dev);

        aml_append(dsdt, sb_scope);

        build_hpet_aml(dsdt);

        build_piix4_pm(dsdt);

        build_piix4_isa_bridge(dsdt);

        build_isa_devices_aml(dsdt);

        build_piix4_pci_hotplug(dsdt);

        build_piix4_pci0_int(dsdt);

    } else {

        sb_scope = aml_scope("_SB");

        aml_append(sb_scope,

            aml_operation_region("PCST", AML_SYSTEM_IO, aml_int(0xae00), 0x0c));

        aml_append(sb_scope,

            aml_operation_region("PCSB", AML_SYSTEM_IO, aml_int(0xae0c), 0x01));

        field = aml_field("PCSB", AML_ANY_ACC, AML_NOLOCK, AML_WRITE_AS_ZEROS);

        aml_append(field, aml_named_field("PCIB", 8));

        aml_append(sb_scope, field);

        aml_append(dsdt, sb_scope);

        sb_scope = aml_scope("_SB");

        dev = aml_device("PCI0");

        aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0A08")));

        aml_append(dev, aml_name_decl("_CID", aml_eisaid("PNP0A03")));

        aml_append(dev, aml_name_decl("_ADR", aml_int(0)));

        aml_append(dev, aml_name_decl("_UID", aml_int(1)));

        aml_append(dev, aml_name_decl("SUPP", aml_int(0)));

        aml_append(dev, aml_name_decl("CTRL", aml_int(0)));

        aml_append(dev, build_q35_osc_method());

        aml_append(sb_scope, dev);

        aml_append(dsdt, sb_scope);

        build_hpet_aml(dsdt);

        build_q35_isa_bridge(dsdt);

        build_isa_devices_aml(dsdt);

        build_q35_pci0_int(dsdt);

    }

    if (pcmc->legacy_cpu_hotplug) {

        build_legacy_cpu_hotplug_aml(dsdt, machine, pm->cpu_hp_io_base);

    } else {

        CPUHotplugFeatures opts = {

            .apci_1_compatible = true, .has_legacy_cphp = true

        };

        build_cpus_aml(dsdt, machine, opts, pm->cpu_hp_io_base,

                       "\\_SB.PCI0", "\\_GPE._E02");

    }

    build_memory_hotplug_aml(dsdt, nr_mem, pm->mem_hp_io_base,

                             pm->mem_hp_io_len);

    scope =  aml_scope("_GPE");

    {

        aml_append(scope, aml_name_decl("_HID", aml_string("ACPI0006")));

        if (misc->is_piix4) {

            method = aml_method("_E01", 0, AML_NOTSERIALIZED);

            aml_append(method,

                aml_acquire(aml_name("\\_SB.PCI0.BLCK"), 0xFFFF));

            aml_append(method, aml_call0("\\_SB.PCI0.PCNT"));

            aml_append(method, aml_release(aml_name("\\_SB.PCI0.BLCK")));

            aml_append(scope, method);

        }

        method = aml_method("_E03", 0, AML_NOTSERIALIZED);

        aml_append(method, aml_call0(MEMORY_HOTPLUG_HANDLER_PATH));

        aml_append(scope, method);

    }

    aml_append(dsdt, scope);

    bus = PC_MACHINE(machine)->bus;

    if (bus) {

        QLIST_FOREACH(bus, &bus->child, sibling) {

            uint8_t bus_num = pci_bus_num(bus);

            uint8_t numa_node = pci_bus_numa_node(bus);

            /* look only for expander root buses */

            if (!pci_bus_is_root(bus)) {

                continue;

            }

            if (bus_num < root_bus_limit) {

                root_bus_limit = bus_num - 1;

            }

            scope = aml_scope("\\_SB");

            dev = aml_device("PC%.02X", bus_num);

            aml_append(dev, aml_name_decl("_UID", aml_int(bus_num)));

            aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0A03")));

            aml_append(dev, aml_name_decl("_BBN", aml_int(bus_num)));

            if (numa_node != NUMA_NODE_UNASSIGNED) {

                aml_append(dev, aml_name_decl("_PXM", aml_int(numa_node)));

            }

            aml_append(dev, build_prt(false));

            crs = build_crs(PCI_HOST_BRIDGE(BUS(bus)->parent),

                            io_ranges, mem_ranges);

            aml_append(dev, aml_name_decl("_CRS", crs));

            aml_append(scope, dev);

            aml_append(dsdt, scope);

        }

    }

    scope = aml_scope("\\_SB.PCI0");

    /* build PCI0._CRS */

    crs = aml_resource_template();

    aml_append(crs,

        aml_word_bus_number(AML_MIN_FIXED, AML_MAX_FIXED, AML_POS_DECODE,

                            0x0000, 0x0, root_bus_limit,

                            0x0000, root_bus_limit + 1));

    aml_append(crs, aml_io(AML_DECODE16, 0x0CF8, 0x0CF8, 0x01, 0x08));

    aml_append(crs,

        aml_word_io(AML_MIN_FIXED, AML_MAX_FIXED,

                    AML_POS_DECODE, AML_ENTIRE_RANGE,

                    0x0000, 0x0000, 0x0CF7, 0x0000, 0x0CF8));

    crs_replace_with_free_ranges(io_ranges, 0x0D00, 0xFFFF);

    for (i = 0; i < io_ranges->len; i++) {

        entry = g_ptr_array_index(io_ranges, i);

        aml_append(crs,

            aml_word_io(AML_MIN_FIXED, AML_MAX_FIXED,

                        AML_POS_DECODE, AML_ENTIRE_RANGE,

                        0x0000, entry->base, entry->limit,

                        0x0000, entry->limit - entry->base + 1));

    }

    aml_append(crs,

        aml_dword_memory(AML_POS_DECODE, AML_MIN_FIXED, AML_MAX_FIXED,

                         AML_CACHEABLE, AML_READ_WRITE,

                         0, 0x000A0000, 0x000BFFFF, 0, 0x00020000));

    crs_replace_with_free_ranges(mem_ranges,

                                 pci_hole->begin, pci_hole->end - 1);

    for (i = 0; i < mem_ranges->len; i++) {

        entry = g_ptr_array_index(mem_ranges, i);

        aml_append(crs,

            aml_dword_memory(AML_POS_DECODE, AML_MIN_FIXED, AML_MAX_FIXED,

                             AML_NON_CACHEABLE, AML_READ_WRITE,

                             0, entry->base, entry->limit,

                             0, entry->limit - entry->base + 1));

    }

    if (pci_hole64->begin) {

        aml_append(crs,

            aml_qword_memory(AML_POS_DECODE, AML_MIN_FIXED, AML_MAX_FIXED,

                             AML_CACHEABLE, AML_READ_WRITE,

                             0, pci_hole64->begin, pci_hole64->end - 1, 0,

                             pci_hole64->end - pci_hole64->begin));

    }

    if (misc->tpm_version != TPM_VERSION_UNSPEC) {

        aml_append(crs, aml_memory32_fixed(TPM_TIS_ADDR_BASE,

                   TPM_TIS_ADDR_SIZE, AML_READ_WRITE));

    }

    aml_append(scope, aml_name_decl("_CRS", crs));

    /* reserve GPE0 block resources */

    dev = aml_device("GPE0");

    aml_append(dev, aml_name_decl("_HID", aml_string("PNP0A06")));

    aml_append(dev, aml_name_decl("_UID", aml_string("GPE0 resources")));

    /* device present, functioning, decoding, not shown in UI */

    aml_append(dev, aml_name_decl("_STA", aml_int(0xB)));

    crs = aml_resource_template();

    aml_append(crs,

        aml_io(AML_DECODE16, pm->gpe0_blk, pm->gpe0_blk, 1, pm->gpe0_blk_len)

    );

    aml_append(dev, aml_name_decl("_CRS", crs));

    aml_append(scope, dev);

    g_ptr_array_free(io_ranges, true);

    g_ptr_array_free(mem_ranges, true);

    /* reserve PCIHP resources */

    if (pm->pcihp_io_len) {

        dev = aml_device("PHPR");

        aml_append(dev, aml_name_decl("_HID", aml_string("PNP0A06")));

        aml_append(dev,

            aml_name_decl("_UID", aml_string("PCI Hotplug resources")));

        /* device present, functioning, decoding, not shown in UI */

        aml_append(dev, aml_name_decl("_STA", aml_int(0xB)));

        crs = aml_resource_template();

        aml_append(crs,

            aml_io(AML_DECODE16, pm->pcihp_io_base, pm->pcihp_io_base, 1,

                   pm->pcihp_io_len)

        );

        aml_append(dev, aml_name_decl("_CRS", crs));

        aml_append(scope, dev);

    }

    aml_append(dsdt, scope);

    /*  create S3_ / S4_ / S5_ packages if necessary */

    scope = aml_scope("\\");

    if (!pm->s3_disabled) {

        pkg = aml_package(4);

        aml_append(pkg, aml_int(1)); /* PM1a_CNT.SLP_TYP */

        aml_append(pkg, aml_int(1)); /* PM1b_CNT.SLP_TYP, FIXME: not impl. */

        aml_append(pkg, aml_int(0)); /* reserved */

        aml_append(pkg, aml_int(0)); /* reserved */

        aml_append(scope, aml_name_decl("_S3", pkg));

    }

    if (!pm->s4_disabled) {

        pkg = aml_package(4);

        aml_append(pkg, aml_int(pm->s4_val)); /* PM1a_CNT.SLP_TYP */

        /* PM1b_CNT.SLP_TYP, FIXME: not impl. */

        aml_append(pkg, aml_int(pm->s4_val));

        aml_append(pkg, aml_int(0)); /* reserved */

        aml_append(pkg, aml_int(0)); /* reserved */

        aml_append(scope, aml_name_decl("_S4", pkg));

    }

    pkg = aml_package(4);

    aml_append(pkg, aml_int(0)); /* PM1a_CNT.SLP_TYP */

    aml_append(pkg, aml_int(0)); /* PM1b_CNT.SLP_TYP not impl. */

    aml_append(pkg, aml_int(0)); /* reserved */

    aml_append(pkg, aml_int(0)); /* reserved */

    aml_append(scope, aml_name_decl("_S5", pkg));

    aml_append(dsdt, scope);

    /* create fw_cfg node, unconditionally */

    {

        /* when using port i/o, the 8-bit data register *always* overlaps

         * with half of the 16-bit control register. Hence, the total size

         * of the i/o region used is FW_CFG_CTL_SIZE; when using DMA, the

         * DMA control register is located at FW_CFG_DMA_IO_BASE + 4 */

        uint8_t io_size = object_property_get_bool(OBJECT(pcms->fw_cfg),

                                                   "dma_enabled", NULL) ?

                          ROUND_UP(FW_CFG_CTL_SIZE, 4) + sizeof(dma_addr_t) :

                          FW_CFG_CTL_SIZE;

        scope = aml_scope("\\_SB.PCI0");

        dev = aml_device("FWCF");

        aml_append(dev, aml_name_decl("_HID", aml_string("QEMU0002")));

        /* device present, functioning, decoding, not shown in UI */

        aml_append(dev, aml_name_decl("_STA", aml_int(0xB)));

        crs = aml_resource_template();

        aml_append(crs,

            aml_io(AML_DECODE16, FW_CFG_IO_BASE, FW_CFG_IO_BASE, 0x01, io_size)

        );

        aml_append(dev, aml_name_decl("_CRS", crs));

        aml_append(scope, dev);

        aml_append(dsdt, scope);

    }

    if (misc->applesmc_io_base) {

        scope = aml_scope("\\_SB.PCI0.ISA");

        dev = aml_device("SMC");

        aml_append(dev, aml_name_decl("_HID", aml_eisaid("APP0001")));

        /* device present, functioning, decoding, not shown in UI */

        aml_append(dev, aml_name_decl("_STA", aml_int(0xB)));

        crs = aml_resource_template();

        aml_append(crs,

            aml_io(AML_DECODE16, misc->applesmc_io_base, misc->applesmc_io_base,

                   0x01, APPLESMC_MAX_DATA_LENGTH)

        );

        aml_append(crs, aml_irq_no_flags(6));

        aml_append(dev, aml_name_decl("_CRS", crs));

        aml_append(scope, dev);

        aml_append(dsdt, scope);

    }

    if (misc->pvpanic_port) {

        scope = aml_scope("\\_SB.PCI0.ISA");

        dev = aml_device("PEVT");

        aml_append(dev, aml_name_decl("_HID", aml_string("QEMU0001")));

        crs = aml_resource_template();

        aml_append(crs,

            aml_io(AML_DECODE16, misc->pvpanic_port, misc->pvpanic_port, 1, 1)

        );

        aml_append(dev, aml_name_decl("_CRS", crs));

        aml_append(dev, aml_operation_region("PEOR", AML_SYSTEM_IO,

                                              aml_int(misc->pvpanic_port), 1));

        field = aml_field("PEOR", AML_BYTE_ACC, AML_NOLOCK, AML_PRESERVE);

        aml_append(field, aml_named_field("PEPT", 8));

        aml_append(dev, field);

        /* device present, functioning, decoding, shown in UI */

        aml_append(dev, aml_name_decl("_STA", aml_int(0xF)));

        method = aml_method("RDPT", 0, AML_NOTSERIALIZED);

        aml_append(method, aml_store(aml_name("PEPT"), aml_local(0)));

        aml_append(method, aml_return(aml_local(0)));

        aml_append(dev, method);

        method = aml_method("WRPT", 1, AML_NOTSERIALIZED);

        aml_append(method, aml_store(aml_arg(0), aml_name("PEPT")));

        aml_append(dev, method);

        aml_append(scope, dev);

        aml_append(dsdt, scope);

    }

    sb_scope = aml_scope("\\_SB");

    {

        build_memory_devices(sb_scope, nr_mem, pm->mem_hp_io_base,

                             pm->mem_hp_io_len);

        {

            Object *pci_host;

            PCIBus *bus = NULL;

            pci_host = acpi_get_i386_pci_host();

            if (pci_host) {

                bus = PCI_HOST_BRIDGE(pci_host)->bus;

            }

            if (bus) {

                Aml *scope = aml_scope("PCI0");

                /* Scan all PCI buses. Generate tables to support hotplug. */

                build_append_pci_bus_devices(scope, bus, pm->pcihp_bridge_en);

                if (misc->tpm_version != TPM_VERSION_UNSPEC) {

                    dev = aml_device("ISA.TPM");

                    aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0C31")));

                    aml_append(dev, aml_name_decl("_STA", aml_int(0xF)));

                    crs = aml_resource_template();

                    aml_append(crs, aml_memory32_fixed(TPM_TIS_ADDR_BASE,

                               TPM_TIS_ADDR_SIZE, AML_READ_WRITE));

                    /*

                        FIXME: TPM_TIS_IRQ=5 conflicts with PNP0C0F irqs,

                        Rewrite to take IRQ from TPM device model and

                        fix default IRQ value there to use some unused IRQ

                     */

                    /* aml_append(crs, aml_irq_no_flags(TPM_TIS_IRQ)); */

                    aml_append(dev, aml_name_decl("_CRS", crs));

                    aml_append(scope, dev);

                }

                aml_append(sb_scope, scope);

            }

        }

        aml_append(dsdt, sb_scope);

    }

    /* copy AML table into ACPI tables blob and patch header there */

    g_array_append_vals(table_data, dsdt->buf->data, dsdt->buf->len);

    build_header(linker, table_data,

        (void *)(table_data->data + table_data->len - dsdt->buf->len),

        "DSDT", dsdt->buf->len, 1, NULL, NULL);

    free_aml_allocator();

}


static void ics_kvm_realize(DeviceState *dev, Error **errp)

{

    ICSState *ics = ICS_SIMPLE(dev);

    if (!ics->nr_irqs) {

        error_setg(errp, "Number of interrupts needs to be greater 0");

        return;

    }

    ics->irqs = g_malloc0(ics->nr_irqs * sizeof(ICSIRQState));

    ics->qirqs = qemu_allocate_irqs(ics_kvm_set_irq, ics, ics->nr_irqs);

    qemu_register_reset(ics_kvm_reset, dev);

}


ram_addr_t memory_region_get_ram_addr(MemoryRegion *mr)

{

    assert(mr->backend_registered);

    return mr->ram_addr;

}


static void tpm_passthrough_cancel_cmd(TPMBackend *tb)

{

    /* cancelling an ongoing command is known not to work with some TPMs */

}


void hmp_info_spice(Monitor *mon, const QDict *qdict)

{

    SpiceChannelList *chan;

    SpiceInfo *info;

    const char *channel_name;

    const char * const channel_names[] = {

        [SPICE_CHANNEL_MAIN] = "main",

        [SPICE_CHANNEL_DISPLAY] = "display",

        [SPICE_CHANNEL_INPUTS] = "inputs",

        [SPICE_CHANNEL_CURSOR] = "cursor",

        [SPICE_CHANNEL_PLAYBACK] = "playback",

        [SPICE_CHANNEL_RECORD] = "record",

        [SPICE_CHANNEL_TUNNEL] = "tunnel",

        [SPICE_CHANNEL_SMARTCARD] = "smartcard",

        [SPICE_CHANNEL_USBREDIR] = "usbredir",

        [SPICE_CHANNEL_PORT] = "port",

#if 0

        /* minimum spice-protocol is 0.12.3, webdav was added in 0.12.7,

         * no easy way to #ifdef (SPICE_CHANNEL_* is a enum).  Disable

         * as quick fix for build failures with older versions. */

        [SPICE_CHANNEL_WEBDAV] = "webdav",

#endif

    };

    info = qmp_query_spice(NULL);

    if (!info->enabled) {

        monitor_printf(mon, "Server: disabled\n");

        goto out;

    }

    monitor_printf(mon, "Server:\n");

    if (info->has_port) {

        monitor_printf(mon, "     address: %s:%" PRId64 "\n",

                       info->host, info->port);

    }

    if (info->has_tls_port) {

        monitor_printf(mon, "     address: %s:%" PRId64 " [tls]\n",

                       info->host, info->tls_port);

    }

    monitor_printf(mon, "    migrated: %s\n",

                   info->migrated ? "true" : "false");

    monitor_printf(mon, "        auth: %s\n", info->auth);

    monitor_printf(mon, "    compiled: %s\n", info->compiled_version);

    monitor_printf(mon, "  mouse-mode: %s\n",

                   SpiceQueryMouseMode_lookup[info->mouse_mode]);

    if (!info->has_channels || info->channels == NULL) {

        monitor_printf(mon, "Channels: none\n");

    } else {

        for (chan = info->channels; chan; chan = chan->next) {

            monitor_printf(mon, "Channel:\n");

            monitor_printf(mon, "     address: %s:%s%s\n",

                           chan->value->base->host, chan->value->base->port,

                           chan->value->tls ? " [tls]" : "");

            monitor_printf(mon, "     session: %" PRId64 "\n",

                           chan->value->connection_id);

            monitor_printf(mon, "     channel: %" PRId64 ":%" PRId64 "\n",

                           chan->value->channel_type, chan->value->channel_id);

            channel_name = "unknown";

            if (chan->value->channel_type > 0 &&

                chan->value->channel_type < ARRAY_SIZE(channel_names) &&

                channel_names[chan->value->channel_type]) {

                channel_name = channel_names[chan->value->channel_type];

            }

            monitor_printf(mon, "     channel name: %s\n", channel_name);

        }

    }

out:

    qapi_free_SpiceInfo(info);

}


START_TEST(qdict_get_try_int_test)

{

    int ret;

    const int value = 100;

    const char *key = "int";

    qdict_put(tests_dict, key, qint_from_int(value));

    ret = qdict_get_try_int(tests_dict, key, 0);

    fail_unless(ret == value);

}


static int get_cv_transfer_function(AVCodecContext *avctx,

                                    CFStringRef *transfer_fnc,

                                    CFNumberRef *gamma_level)

{

    enum AVColorTransferCharacteristic trc = avctx->color_trc;

    Float32 gamma;

    *gamma_level = NULL;

    switch (trc) {

        case AVCOL_TRC_UNSPECIFIED:

            *transfer_fnc = NULL;

            break;

        case AVCOL_TRC_BT709:

            *transfer_fnc = kCVImageBufferTransferFunction_ITU_R_709_2;

            break;

        case AVCOL_TRC_SMPTE240M:

            *transfer_fnc = kCVImageBufferTransferFunction_SMPTE_240M_1995;

            break;

        case AVCOL_TRC_GAMMA22:

            gamma = 2.2;

            *transfer_fnc = kCVImageBufferTransferFunction_UseGamma;

            *gamma_level = CFNumberCreate(NULL, kCFNumberFloat32Type, &gamma);

            break;

        case AVCOL_TRC_GAMMA28:

            gamma = 2.8;

            *transfer_fnc = kCVImageBufferTransferFunction_UseGamma;

            *gamma_level = CFNumberCreate(NULL, kCFNumberFloat32Type, &gamma);

            break;

        case AVCOL_TRC_BT2020_10:

        case AVCOL_TRC_BT2020_12:

            *transfer_fnc = kCVImageBufferTransferFunction_ITU_R_2020;

            break;

        default:

            av_log(avctx, AV_LOG_ERROR, "Transfer function %s is not supported.\n", av_color_transfer_name(trc));

            return -1;

    }

    return 0;

}


void qmp_block_set_io_throttle(const char *device, int64_t bps, int64_t bps_rd,

                               int64_t bps_wr,

                               int64_t iops,

                               int64_t iops_rd,

                               int64_t iops_wr,

                               bool has_bps_max,

                               int64_t bps_max,

                               bool has_bps_rd_max,

                               int64_t bps_rd_max,

                               bool has_bps_wr_max,

                               int64_t bps_wr_max,

                               bool has_iops_max,

                               int64_t iops_max,

                               bool has_iops_rd_max,

                               int64_t iops_rd_max,

                               bool has_iops_wr_max,

                               int64_t iops_wr_max,

                               bool has_iops_size,

                               int64_t iops_size,

                               bool has_group,

                               const char *group, Error **errp)

{

    ThrottleConfig cfg;

    BlockDriverState *bs;

    BlockBackend *blk;

    AioContext *aio_context;

    blk = blk_by_name(device);

    if (!blk) {

        error_set(errp, ERROR_CLASS_DEVICE_NOT_FOUND,

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

        return;

    }

    aio_context = blk_get_aio_context(blk);

    aio_context_acquire(aio_context);

    bs = blk_bs(blk);

    if (!bs) {

        error_setg(errp, "Device '%s' has no medium", device);

        goto out;

    }

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

    cfg.buckets[THROTTLE_BPS_TOTAL].avg = bps;

    cfg.buckets[THROTTLE_BPS_READ].avg  = bps_rd;

    cfg.buckets[THROTTLE_BPS_WRITE].avg = bps_wr;

    cfg.buckets[THROTTLE_OPS_TOTAL].avg = iops;

    cfg.buckets[THROTTLE_OPS_READ].avg  = iops_rd;

    cfg.buckets[THROTTLE_OPS_WRITE].avg = iops_wr;

    if (has_bps_max) {

        cfg.buckets[THROTTLE_BPS_TOTAL].max = bps_max;

    }

    if (has_bps_rd_max) {

        cfg.buckets[THROTTLE_BPS_READ].max = bps_rd_max;

    }

    if (has_bps_wr_max) {

        cfg.buckets[THROTTLE_BPS_WRITE].max = bps_wr_max;

    }

    if (has_iops_max) {

        cfg.buckets[THROTTLE_OPS_TOTAL].max = iops_max;

    }

    if (has_iops_rd_max) {

        cfg.buckets[THROTTLE_OPS_READ].max = iops_rd_max;

    }

    if (has_iops_wr_max) {

        cfg.buckets[THROTTLE_OPS_WRITE].max = iops_wr_max;

    }

    if (has_iops_size) {

        cfg.op_size = iops_size;

    }

    if (!check_throttle_config(&cfg, errp)) {

        goto out;

    }

    if (throttle_enabled(&cfg)) {

        /* Enable I/O limits if they're not enabled yet, otherwise

         * just update the throttling group. */

        if (!bs->io_limits_enabled) {

            bdrv_io_limits_enable(bs, has_group ? group : device);

        } else if (has_group) {

            bdrv_io_limits_update_group(bs, group);

        }

        /* Set the new throttling configuration */

        bdrv_set_io_limits(bs, &cfg);

    } else if (bs->io_limits_enabled) {

        /* If all throttling settings are set to 0, disable I/O limits */

        bdrv_io_limits_disable(bs);

    }

out:

    aio_context_release(aio_context);

}


static inline void gen_op_eval_fbue(TCGv dst, TCGv src,

                                    unsigned int fcc_offset)

{

    gen_mov_reg_FCC0(dst, src, fcc_offset);

    gen_mov_reg_FCC1(cpu_tmp0, src, fcc_offset);

    tcg_gen_xor_tl(dst, dst, cpu_tmp0);

    tcg_gen_xori_tl(dst, dst, 0x1);

}


static void vnc_client_error(VncState *vs)

{

    vnc_client_io_error(vs, -1, EINVAL);

}


static void msix_set_pending(PCIDevice *dev, int vector)

{

    *msix_pending_byte(dev, vector) |= msix_pending_mask(vector);

}


static void qlist_destroy_obj(QObject *obj)

{

    QList *qlist;

    QListEntry *entry, *next_entry;

    assert(obj != NULL);

    qlist = qobject_to_qlist(obj);

    QTAILQ_FOREACH_SAFE(entry, &qlist->head, next, next_entry) {

        QTAILQ_REMOVE(&qlist->head, entry, next);

        qobject_decref(entry->value);

        g_free(entry);

    }

    g_free(qlist);

}


static int read_f(int argc, char **argv)

{

    struct timeval t1, t2;

    int Cflag = 0, pflag = 0, qflag = 0, vflag = 0;

    int Pflag = 0, sflag = 0, lflag = 0, bflag = 0;

    int c, cnt;

    char *buf;

    int64_t offset;

    int count;

    /* Some compilers get confused and warn if this is not initialized.  */

    int total = 0;

    int pattern = 0, pattern_offset = 0, pattern_count = 0;

    while ((c = getopt(argc, argv, "bCl:pP:qs:v")) != EOF) {

        switch (c) {

        case 'b':

            bflag = 1;

            break;

        case 'C':

            Cflag = 1;

            break;

        case 'l':

            lflag = 1;

            pattern_count = cvtnum(optarg);

            if (pattern_count < 0) {

                printf("non-numeric length argument -- %s\n", optarg);

                return 0;

            }

            break;

        case 'p':

            pflag = 1;

            break;

        case 'P':

            Pflag = 1;

            pattern = parse_pattern(optarg);

            if (pattern < 0) {

                return 0;

            }

            break;

        case 'q':

            qflag = 1;

            break;

        case 's':

            sflag = 1;

            pattern_offset = cvtnum(optarg);

            if (pattern_offset < 0) {

                printf("non-numeric length argument -- %s\n", optarg);

                return 0;

            }

            break;

        case 'v':

            vflag = 1;

            break;

        default:

            return command_usage(&read_cmd);

        }

    }

    if (optind != argc - 2) {

        return command_usage(&read_cmd);

    }

    if (bflag && pflag) {

        printf("-b and -p cannot be specified at the same time\n");

        return 0;

    }

    offset = cvtnum(argv[optind]);

    if (offset < 0) {

        printf("non-numeric length argument -- %s\n", argv[optind]);

        return 0;

    }

    optind++;

    count = cvtnum(argv[optind]);

    if (count < 0) {

        printf("non-numeric length argument -- %s\n", argv[optind]);

        return 0;

    }

    if (!Pflag && (lflag || sflag)) {

        return command_usage(&read_cmd);

    }

    if (!lflag) {

        pattern_count = count - pattern_offset;

    }

    if ((pattern_count < 0) || (pattern_count + pattern_offset > count))  {

        printf("pattern verification range exceeds end of read data\n");

        return 0;

    }

    if (!pflag) {

        if (offset & 0x1ff) {

            printf("offset %" PRId64 " is not sector aligned\n",

                   offset);

            return 0;

        }

        if (count & 0x1ff) {

            printf("count %d is not sector aligned\n",

                   count);

            return 0;

        }

    }

    buf = qemu_io_alloc(count, 0xab);

    gettimeofday(&t1, NULL);

    if (pflag) {

        cnt = do_pread(buf, offset, count, &total);

    } else if (bflag) {

        cnt = do_load_vmstate(buf, offset, count, &total);

    } else {

        cnt = do_read(buf, offset, count, &total);

    }

    gettimeofday(&t2, NULL);

    if (cnt < 0) {

        printf("read failed: %s\n", strerror(-cnt));

        goto out;

    }

    if (Pflag) {

        void *cmp_buf = malloc(pattern_count);

        memset(cmp_buf, pattern, pattern_count);

        if (memcmp(buf + pattern_offset, cmp_buf, pattern_count)) {

            printf("Pattern verification failed at offset %"

                   PRId64 ", %d bytes\n",

                   offset + pattern_offset, pattern_count);

        }

        free(cmp_buf);

    }

    if (qflag) {

        goto out;

    }

    if (vflag) {

        dump_buffer(buf, offset, count);

    }

    /* Finally, report back -- -C gives a parsable format */

    t2 = tsub(t2, t1);

    print_report("read", &t2, offset, count, total, cnt, Cflag);

out:

    qemu_io_free(buf);

    return 0;

}


static void dec_barrel(DisasContext *dc)

{

    TCGv t0;

    unsigned int s, t;

    if ((dc->tb_flags & MSR_EE_FLAG)

          && !(dc->env->pvr.regs[2] & PVR2_ILL_OPCODE_EXC_MASK)

          && !(dc->env->pvr.regs[0] & PVR0_USE_BARREL_MASK)) {

        tcg_gen_movi_tl(cpu_SR[SR_ESR], ESR_EC_ILLEGAL_OP);

        t_gen_raise_exception(dc, EXCP_HW_EXCP);

        return;

    }

    s = dc->imm & (1 << 10);

    t = dc->imm & (1 << 9);

    LOG_DIS("bs%s%s r%d r%d r%d\n",

            s ? "l" : "r", t ? "a" : "l", dc->rd, dc->ra, dc->rb);

    t0 = tcg_temp_new();

    tcg_gen_mov_tl(t0, *(dec_alu_op_b(dc)));

    tcg_gen_andi_tl(t0, t0, 31);

    if (s)

        tcg_gen_shl_tl(cpu_R[dc->rd], cpu_R[dc->ra], t0);

    else {

        if (t)

            tcg_gen_sar_tl(cpu_R[dc->rd], cpu_R[dc->ra], t0);

        else

            tcg_gen_shr_tl(cpu_R[dc->rd], cpu_R[dc->ra], t0);

    }

}


static void ide_dma_restart_cb(void *opaque, int running, int reason)

{

    BMDMAState *bm = opaque;

    if (!running)

        return;

    if (bm->status & BM_STATUS_DMA_RETRY) {

        bm->status &= ~BM_STATUS_DMA_RETRY;

        ide_dma_restart(bm->ide_if);

    } else if (bm->status & BM_STATUS_PIO_RETRY) {

        bm->status &= ~BM_STATUS_PIO_RETRY;

        ide_sector_write(bm->ide_if);

    }

}


static int ahci_start_transfer(IDEDMA *dma)

{

    AHCIDevice *ad = DO_UPCAST(AHCIDevice, dma, dma);

    IDEState *s = &ad->port.ifs[0];

    uint32_t size = (uint32_t)(s->data_end - s->data_ptr);

    /* write == ram -> device */

    uint32_t opts = le32_to_cpu(ad->cur_cmd->opts);

    int is_write = opts & AHCI_CMD_WRITE;

    int is_atapi = opts & AHCI_CMD_ATAPI;

    int has_sglist = 0;

    if (is_atapi && !ad->done_atapi_packet) {

        /* already prepopulated iobuffer */

        ad->done_atapi_packet = 1;

        goto out;

    }

    if (!ahci_populate_sglist(ad, &s->sg)) {

        has_sglist = 1;

    }

    DPRINTF(ad->port_no, "%sing %d bytes on %s w/%s sglist\n",

            is_write ? "writ" : "read", size, is_atapi ? "atapi" : "ata",

            has_sglist ? "" : "o");

    if (has_sglist && size) {

        if (is_write) {

            dma_buf_write(s->data_ptr, size, &s->sg);

        } else {

            dma_buf_read(s->data_ptr, size, &s->sg);

        }

    }

    /* update number of transferred bytes */

    ad->cur_cmd->status = cpu_to_le32(le32_to_cpu(ad->cur_cmd->status) + size);

out:

    /* declare that we processed everything */

    s->data_ptr = s->data_end;

    if (has_sglist) {

        qemu_sglist_destroy(&s->sg);

    }

    s->end_transfer_func(s);

    if (!(s->status & DRQ_STAT)) {

        /* done with DMA */

        ahci_trigger_irq(ad->hba, ad, PORT_IRQ_STAT_DSS);

    }

    return 0;

}


SocketAddress *socket_address_flatten(SocketAddressLegacy *addr_legacy)

{

    SocketAddress *addr = g_new(SocketAddress, 1);

    if (!addr_legacy) {

        return NULL;

    }

    switch (addr_legacy->type) {

    case SOCKET_ADDRESS_LEGACY_KIND_INET:

        addr->type = SOCKET_ADDRESS_TYPE_INET;

        QAPI_CLONE_MEMBERS(InetSocketAddress, &addr->u.inet,

                           addr_legacy->u.inet.data);

        break;

    case SOCKET_ADDRESS_LEGACY_KIND_UNIX:

        addr->type = SOCKET_ADDRESS_TYPE_UNIX;

        QAPI_CLONE_MEMBERS(UnixSocketAddress, &addr->u.q_unix,

                           addr_legacy->u.q_unix.data);

        break;

    case SOCKET_ADDRESS_LEGACY_KIND_VSOCK:

        addr->type = SOCKET_ADDRESS_TYPE_VSOCK;

        QAPI_CLONE_MEMBERS(VsockSocketAddress, &addr->u.vsock,

                           addr_legacy->u.vsock.data);

        break;

    case SOCKET_ADDRESS_LEGACY_KIND_FD:

        addr->type = SOCKET_ADDRESS_TYPE_FD;

        QAPI_CLONE_MEMBERS(String, &addr->u.fd, addr_legacy->u.fd.data);

        break;

    default:

        abort();

    }

    return addr;

}


static void spapr_cpu_core_realize(DeviceState *dev, Error **errp)

{

    sPAPRCPUCore *sc = SPAPR_CPU_CORE(OBJECT(dev));

    CPUCore *cc = CPU_CORE(OBJECT(dev));

    const char *typename = object_class_get_name(sc->cpu_class);

    size_t size = object_type_get_instance_size(typename);

    Error *local_err = NULL;

    Object *obj;

    int i;

    sc->threads = g_malloc0(size * cc->nr_threads);

    for (i = 0; i < cc->nr_threads; i++) {

        char id[32];

        void *obj = sc->threads + i * size;

        object_initialize(obj, size, typename);

        snprintf(id, sizeof(id), "thread[%d]", i);

        object_property_add_child(OBJECT(sc), id, obj, &local_err);

        if (local_err) {

            goto err;

        }

    }

    object_child_foreach(OBJECT(dev), spapr_cpu_core_realize_child, &local_err);

    if (local_err) {

        goto err;

    } else {

        return;

    }

err:

    while (--i >= 0) {

        obj = sc->threads + i * size;

        object_unparent(obj);

    }

    g_free(sc->threads);

    error_propagate(errp, local_err);

}


static inline void RENAME(vu9_to_vu12)(const uint8_t *src1, const uint8_t *src2,

                                       uint8_t *dst1, uint8_t *dst2,

                                       int width, int height,

                                       int srcStride1, int srcStride2,

                                       int dstStride1, int dstStride2)

{

    x86_reg y;

    int x,w,h;

    w=width/2; h=height/2;

    __asm__ volatile(

        PREFETCH" %0    \n\t"

        PREFETCH" %1    \n\t"

        ::"m"(*(src1+srcStride1)),"m"(*(src2+srcStride2)):"memory");

    for (y=0;y<h;y++) {

        const uint8_t* s1=src1+srcStride1*(y>>1);

        uint8_t* d=dst1+dstStride1*y;

        x=0;

        for (;x<w-31;x+=32) {

            __asm__ volatile(

                PREFETCH"   32%1        \n\t"

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

                "movq        8%1, %%mm2 \n\t"

                "movq       16%1, %%mm4 \n\t"

                "movq       24%1, %%mm6 \n\t"

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

                "movq      %%mm2, %%mm3 \n\t"

                "movq      %%mm4, %%mm5 \n\t"

                "movq      %%mm6, %%mm7 \n\t"

                "punpcklbw %%mm0, %%mm0 \n\t"

                "punpckhbw %%mm1, %%mm1 \n\t"

                "punpcklbw %%mm2, %%mm2 \n\t"

                "punpckhbw %%mm3, %%mm3 \n\t"

                "punpcklbw %%mm4, %%mm4 \n\t"

                "punpckhbw %%mm5, %%mm5 \n\t"

                "punpcklbw %%mm6, %%mm6 \n\t"

                "punpckhbw %%mm7, %%mm7 \n\t"

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

                MOVNTQ"    %%mm1,  8%0  \n\t"

                MOVNTQ"    %%mm2, 16%0  \n\t"

                MOVNTQ"    %%mm3, 24%0  \n\t"

                MOVNTQ"    %%mm4, 32%0  \n\t"

                MOVNTQ"    %%mm5, 40%0  \n\t"

                MOVNTQ"    %%mm6, 48%0  \n\t"

                MOVNTQ"    %%mm7, 56%0"

                :"=m"(d[2*x])

                :"m"(s1[x])

                :"memory");

        }

        for (;x<w;x++) d[2*x]=d[2*x+1]=s1[x];

    }

    for (y=0;y<h;y++) {

        const uint8_t* s2=src2+srcStride2*(y>>1);

        uint8_t* d=dst2+dstStride2*y;

        x=0;

        for (;x<w-31;x+=32) {

            __asm__ volatile(

                PREFETCH"   32%1        \n\t"

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

                "movq        8%1, %%mm2 \n\t"

                "movq       16%1, %%mm4 \n\t"

                "movq       24%1, %%mm6 \n\t"

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

                "movq      %%mm2, %%mm3 \n\t"

                "movq      %%mm4, %%mm5 \n\t"

                "movq      %%mm6, %%mm7 \n\t"

                "punpcklbw %%mm0, %%mm0 \n\t"

                "punpckhbw %%mm1, %%mm1 \n\t"

                "punpcklbw %%mm2, %%mm2 \n\t"

                "punpckhbw %%mm3, %%mm3 \n\t"

                "punpcklbw %%mm4, %%mm4 \n\t"

                "punpckhbw %%mm5, %%mm5 \n\t"

                "punpcklbw %%mm6, %%mm6 \n\t"

                "punpckhbw %%mm7, %%mm7 \n\t"

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

                MOVNTQ"    %%mm1,  8%0  \n\t"

                MOVNTQ"    %%mm2, 16%0  \n\t"

                MOVNTQ"    %%mm3, 24%0  \n\t"

                MOVNTQ"    %%mm4, 32%0  \n\t"

                MOVNTQ"    %%mm5, 40%0  \n\t"

                MOVNTQ"    %%mm6, 48%0  \n\t"

                MOVNTQ"    %%mm7, 56%0"

                :"=m"(d[2*x])

                :"m"(s2[x])

                :"memory");

        }

        for (;x<w;x++) d[2*x]=d[2*x+1]=s2[x];

    }

    __asm__(

            EMMS"       \n\t"

            SFENCE"     \n\t"

            ::: "memory"

        );

}


void rgb16tobgr24(const uint8_t *src, uint8_t *dst, unsigned int src_size)

{

	const uint16_t *end;

	uint8_t *d = (uint8_t *)dst;

	const uint16_t *s = (const uint16_t *)src;

	end = s + src_size/2;

	while(s < end)

	{

		register uint16_t bgr;

		bgr = *s++;

		*d++ = (bgr&0xF800)>>8;

		*d++ = (bgr&0x7E0)>>3;

		*d++ = (bgr&0x1F)<<3;

	}

}


static int dyn_buf_write(void *opaque, uint8_t *buf, int buf_size)

{

    DynBuffer *d = opaque;

    int new_size, new_allocated_size;

    /* reallocate buffer if needed */

    new_size = d->pos + buf_size;

    new_allocated_size = d->allocated_size;

    if(new_size < d->pos || new_size > INT_MAX/2)

        return -1;

    while (new_size > new_allocated_size) {

        if (!new_allocated_size)

            new_allocated_size = new_size;

        else

            new_allocated_size += new_allocated_size / 2 + 1;

    }

    if (new_allocated_size > d->allocated_size) {

        d->buffer = av_realloc(d->buffer, new_allocated_size);

        if(d->buffer == NULL)

             return -1234;

        d->allocated_size = new_allocated_size;

    }

    memcpy(d->buffer + d->pos, buf, buf_size);

    d->pos = new_size;

    if (d->pos > d->size)

        d->size = d->pos;

    return buf_size;

}


static void vfio_msi_enable(VFIOPCIDevice *vdev)

{

    int ret, i;

    vfio_disable_interrupts(vdev);

    vdev->nr_vectors = msi_nr_vectors_allocated(&vdev->pdev);

retry:

    vdev->msi_vectors = g_malloc0(vdev->nr_vectors * sizeof(VFIOMSIVector));

    for (i = 0; i < vdev->nr_vectors; i++) {

        VFIOMSIVector *vector = &vdev->msi_vectors[i];

        MSIMessage msg = msi_get_message(&vdev->pdev, i);

        vector->vdev = vdev;

        vector->virq = -1;

        vector->use = true;

        if (event_notifier_init(&vector->interrupt, 0)) {

            error_report("vfio: Error: event_notifier_init failed");

        }

        qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),

                            vfio_msi_interrupt, NULL, vector);

        /*

         * Attempt to enable route through KVM irqchip,

         * default to userspace handling if unavailable.

         */

        vfio_add_kvm_msi_virq(vdev, vector, &msg, false);

    }

    /* Set interrupt type prior to possible interrupts */

    vdev->interrupt = VFIO_INT_MSI;

    ret = vfio_enable_vectors(vdev, false);

    if (ret) {

        if (ret < 0) {

            error_report("vfio: Error: Failed to setup MSI fds: %m");

        } else if (ret != vdev->nr_vectors) {

            error_report("vfio: Error: Failed to enable %d "

                         "MSI vectors, retry with %d", vdev->nr_vectors, ret);

        }

        for (i = 0; i < vdev->nr_vectors; i++) {

            VFIOMSIVector *vector = &vdev->msi_vectors[i];

            if (vector->virq >= 0) {

                vfio_remove_kvm_msi_virq(vector);

            }

            qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),

                                NULL, NULL, NULL);

            event_notifier_cleanup(&vector->interrupt);

        }

        g_free(vdev->msi_vectors);

        if (ret > 0 && ret != vdev->nr_vectors) {

            vdev->nr_vectors = ret;

            goto retry;

        }

        vdev->nr_vectors = 0;

        /*

         * Failing to setup MSI doesn't really fall within any specification.

         * Let's try leaving interrupts disabled and hope the guest figures

         * out to fall back to INTx for this device.

         */

        error_report("vfio: Error: Failed to enable MSI");

        vdev->interrupt = VFIO_INT_NONE;

        return;

    }

    trace_vfio_msi_enable(vdev->vbasedev.name, vdev->nr_vectors);

}


static inline void RENAME(rgb32to24)(const uint8_t *src,uint8_t *dst,unsigned src_size)

{

  uint8_t *dest = dst;

  const uint8_t *s = src;

  const uint8_t *end;

#ifdef HAVE_MMX

  const uint8_t *mm_end;

#endif

  end = s + src_size;

#ifdef HAVE_MMX

  __asm __volatile(PREFETCH"	%0"::"m"(*s):"memory");

  mm_end = end - 31;

  while(s < mm_end)

  {

    __asm __volatile(

	PREFETCH"	32%1\n\t"

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

	"movq	8%1, %%mm1\n\t"

	"movq	16%1, %%mm4\n\t"

	"movq	24%1, %%mm5\n\t"

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

	"movq	%%mm1, %%mm3\n\t"

	"movq	%%mm4, %%mm6\n\t"

	"movq	%%mm5, %%mm7\n\t"

	"psrlq	$8, %%mm2\n\t"

	"psrlq	$8, %%mm3\n\t"

	"psrlq	$8, %%mm6\n\t"

	"psrlq	$8, %%mm7\n\t"

	"pand	%2, %%mm0\n\t"

	"pand	%2, %%mm1\n\t"

	"pand	%2, %%mm4\n\t"

	"pand	%2, %%mm5\n\t"

	"pand	%3, %%mm2\n\t"

	"pand	%3, %%mm3\n\t"

	"pand	%3, %%mm6\n\t"

	"pand	%3, %%mm7\n\t"

	"por	%%mm2, %%mm0\n\t"

	"por	%%mm3, %%mm1\n\t"

	"por	%%mm6, %%mm4\n\t"

	"por	%%mm7, %%mm5\n\t"

	"movq	%%mm1, %%mm2\n\t"

	"movq	%%mm4, %%mm3\n\t"

	"psllq	$48, %%mm2\n\t"

	"psllq	$32, %%mm3\n\t"

	"pand	%4, %%mm2\n\t"

	"pand	%5, %%mm3\n\t"

	"por	%%mm2, %%mm0\n\t"

	"psrlq	$16, %%mm1\n\t"

	"psrlq	$32, %%mm4\n\t"

	"psllq	$16, %%mm5\n\t"

	"por	%%mm3, %%mm1\n\t"

	"pand	%6, %%mm5\n\t"

	"por	%%mm5, %%mm4\n\t"

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

	MOVNTQ"	%%mm1, 8%0\n\t"

	MOVNTQ"	%%mm4, 16%0"

	:"=m"(*dest)

	:"m"(*s),"m"(mask24l),

	 "m"(mask24h),"m"(mask24hh),"m"(mask24hhh),"m"(mask24hhhh)

	:"memory");

    dest += 24;

    s += 32;

  }

  __asm __volatile(SFENCE:::"memory");

  __asm __volatile(EMMS:::"memory");

#endif

  while(s < end)

  {

#ifdef WORDS_BIGENDIAN

    s++;

    *dest++ = *s++;

    *dest++ = *s++;

    *dest++ = *s++;

#else

    *dest++ = *s++;

    *dest++ = *s++;

    *dest++ = *s++;

    s++;

#endif

  }

}


static void scsi_remove_request(SCSIDiskReq *r)

{

    qemu_free(r->iov.iov_base);

    scsi_req_free(&r->req);

}


static void uncouple_channels(AC3DecodeContext * ctx)

{

    ac3_audio_block *ab = &ctx->audio_block;

    int ch, sbnd, bin;

    int index;

    int16_t mantissa;

    /* uncouple channels */

    for (ch = 0; ch < ctx->bsi.nfchans; ch++)

        if (ab->chincpl & (1 << ch))

            for (sbnd = ab->cplbegf; sbnd < 3 + ab->cplendf; sbnd++)

                for (bin = 0; bin < 12; bin++) {

                    index = sbnd * 12 + bin + 37;

                    ab->transform_coeffs[ch + 1][index] = ab->cplcoeffs[index] * ab->cplco[ch][sbnd] * ab->chcoeffs[ch];

                    /* generate dither if required */

                    if (!ab->bap[ch][index] && (ab->chincpl & (1 << ch)) && (ab->dithflag & (1 << ch))) {

                        mantissa = dither_int16(&ctx->state);

                        ab->transform_coeffs[ch + 1][index] = to_float(ab->dexps[ch][index], mantissa) * ab->chcoeffs[ch];

                    }

                }

}


void qemu_input_event_send_key_delay(uint32_t delay_ms)
{
    if (!kbd_timer) {
        kbd_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL, qemu_input_queue_process,
                                 &kbd_queue);
    if (queue_count < queue_limit) {
        qemu_input_queue_delay(&kbd_queue, kbd_timer,
                               delay_ms ? delay_ms : kbd_default_delay_ms);


static int pci_add_option_rom(PCIDevice *pdev)

{

    int size;

    char *path;

    void *ptr;

    char name[32];

    if (!pdev->romfile)

        return 0;

    if (strlen(pdev->romfile) == 0)

        return 0;

    if (!pdev->rom_bar) {

        /*

         * Load rom via fw_cfg instead of creating a rom bar,

         * for 0.11 compatibility.

         */

        int class = pci_get_word(pdev->config + PCI_CLASS_DEVICE);

        if (class == 0x0300) {

            rom_add_vga(pdev->romfile);

        } else {

            rom_add_option(pdev->romfile);

        }

        return 0;

    }

    path = qemu_find_file(QEMU_FILE_TYPE_BIOS, pdev->romfile);

    if (path == NULL) {

        path = qemu_strdup(pdev->romfile);

    }

    size = get_image_size(path);

    if (size < 0) {

        error_report("%s: failed to find romfile \"%s\"",

                     __FUNCTION__, pdev->romfile);

        return -1;

    }

    if (size & (size - 1)) {

        size = 1 << qemu_fls(size);

    }

    if (pdev->qdev.info->vmsd)

        snprintf(name, sizeof(name), "%s.rom", pdev->qdev.info->vmsd->name);

    else

        snprintf(name, sizeof(name), "%s.rom", pdev->qdev.info->name);

    pdev->rom_offset = qemu_ram_alloc(&pdev->qdev, name, size);

    ptr = qemu_get_ram_ptr(pdev->rom_offset);

    load_image(path, ptr);

    qemu_free(path);

    pci_register_bar(pdev, PCI_ROM_SLOT, size,

                     0, pci_map_option_rom);

    return 0;

}


static int convert_zp2tf(AVFilterContext *ctx, int channels)

{

    AudioIIRContext *s = ctx->priv;

    int ch, i, j, ret;

    for (ch = 0; ch < channels; ch++) {

        IIRChannel *iir = &s->iir[ch];

        double *topc, *botc;

        topc = av_calloc((iir->nb_ab[0] + 1) * 2, sizeof(*topc));

        botc = av_calloc((iir->nb_ab[1] + 1) * 2, sizeof(*botc));

        if (!topc || !botc)

            return AVERROR(ENOMEM);

        ret = expand(ctx, iir->ab[0], iir->nb_ab[0], botc);

        if (ret < 0) {

            av_free(topc);

            av_free(botc);

            return ret;

        }

        ret = expand(ctx, iir->ab[1], iir->nb_ab[1], topc);

        if (ret < 0) {

            av_free(topc);

            av_free(botc);

            return ret;

        }

        for (j = 0, i = iir->nb_ab[1]; i >= 0; j++, i--) {

            iir->ab[1][j] = topc[2 * i];

        }

        iir->nb_ab[1]++;

        for (j = 0, i = iir->nb_ab[0]; i >= 0; j++, i--) {

            iir->ab[0][j] = botc[2 * i];

        }

        iir->nb_ab[0]++;

        av_free(topc);

        av_free(botc);

    }

    return 0;

}


static int decode_hybrid(const uint8_t *sptr, uint8_t *dptr, int dx, int dy,

                         int h, int w, int stride, const uint32_t *pal)

{

    int x, y;

    const uint8_t *orig_src = sptr;

    for (y = dx + h; y > dx; y--) {

        uint8_t *dst = dptr + (y * stride) + dy * 3;

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

            if (*sptr & 0x80) {

                /* 15-bit color */

                unsigned c = AV_RB16(sptr) & ~0x8000;

                unsigned b =  c        & 0x1F;

                unsigned g = (c >>  5) & 0x1F;

                unsigned r =  c >> 10;

                /* 000aaabb -> aaabbaaa  */

                *dst++ = (b << 3) | (b >> 2);

                *dst++ = (g << 3) | (g >> 2);

                *dst++ = (r << 3) | (r >> 2);

                sptr += 2;

            } else {

                /* palette index */

                uint32_t c = pal[*sptr++];

                bytestream_put_le24(&dst, c);

            }

        }

    }

    return sptr - orig_src;

}


static void set_sensor_type(IPMIBmcSim *ibs,

                               uint8_t *cmd, unsigned int cmd_len,

                               uint8_t *rsp, unsigned int *rsp_len,

                               unsigned int max_rsp_len)

{

    IPMISensor *sens;

    IPMI_CHECK_CMD_LEN(5);

    if ((cmd[2] > MAX_SENSORS) ||

            !IPMI_SENSOR_GET_PRESENT(ibs->sensors + cmd[2])) {

        rsp[2] = IPMI_CC_REQ_ENTRY_NOT_PRESENT;

        return;

    }

    sens = ibs->sensors + cmd[2];

    sens->sensor_type = cmd[3];

    sens->evt_reading_type_code = cmd[4] & 0x7f;

}


DescRing *desc_ring_alloc(Rocker *r, int index)

{

    DescRing *ring;

    ring = g_malloc0(sizeof(DescRing));

    if (!ring) {

        return NULL;

    }

    ring->r = r;

    ring->index = index;

    return ring;

}


START_TEST(vararg_string)

{

    int i;

    struct {

        const char *decoded;

    } test_cases[] = {

        { "hello world" },

        { "the quick brown fox jumped over the fence" },

        {}

    };

    for (i = 0; test_cases[i].decoded; i++) {

        QObject *obj;

        QString *str;

        obj = qobject_from_jsonf("%s", test_cases[i].decoded);

        fail_unless(obj != NULL);

        fail_unless(qobject_type(obj) == QTYPE_QSTRING);

        str = qobject_to_qstring(obj);

        fail_unless(strcmp(qstring_get_str(str), test_cases[i].decoded) == 0);

        QDECREF(str);

    }

}


static void t_gen_cris_dstep(TCGv d, TCGv a, TCGv b)

{

    int l1;

    l1 = gen_new_label();

    /*

     * d <<= 1

     * if (d >= s)

     *    d -= s;

     */

    tcg_gen_shli_tl(d, a, 1);

    tcg_gen_brcond_tl(TCG_COND_LTU, d, b, l1);

    tcg_gen_sub_tl(d, d, b);

    gen_set_label(l1);

}


static always_inline void gen_arith3 (void *helper,

                                      int ra, int rb, int rc,

                                      int islit, uint8_t lit)

{

    if (unlikely(rc == 31))

        return;

    if (ra != 31) {

        if (islit) {

            TCGv tmp = tcg_const_i64(lit);

            tcg_gen_helper_1_2(helper, cpu_ir[rc], cpu_ir[ra], tmp);

            tcg_temp_free(tmp);

        } else

            tcg_gen_helper_1_2(helper, cpu_ir[rc], cpu_ir[ra], cpu_ir[rb]);

    } else {

        TCGv tmp1 = tcg_const_i64(0);

        if (islit) {

            TCGv tmp2 = tcg_const_i64(lit);

            tcg_gen_helper_1_2(helper, cpu_ir[rc], tmp1, tmp2);

            tcg_temp_free(tmp2);

        } else

            tcg_gen_helper_1_2(helper, cpu_ir[rc], tmp1, cpu_ir[rb]);

        tcg_temp_free(tmp1);

    }

}


int cpu_get_dump_info(ArchDumpInfo *info,

                      const struct GuestPhysBlockList *guest_phys_blocks)

{

    PowerPCCPU *cpu = POWERPC_CPU(first_cpu);

    PowerPCCPUClass *pcc = POWERPC_CPU_GET_CLASS(cpu);

    info->d_machine = PPC_ELF_MACHINE;

    info->d_class = ELFCLASS;

    if ((*pcc->interrupts_big_endian)(cpu)) {

        info->d_endian = ELFDATA2MSB;

    } else {

        info->d_endian = ELFDATA2LSB;

    }

    /* 64KB is the max page size for pseries kernel */

    if (strncmp(object_get_typename(qdev_get_machine()),

                "pseries-", 8) == 0) {

        info->page_size = (1U << 16);

    }

    return 0;

}