static int coroutine_fn bdrv_co_do_copy_on_readv(BdrvChild *child,
        int64_t offset, unsigned int bytes, QEMUIOVector *qiov)
{
    BlockDriverState *bs = child->bs;
    /* Perform I/O through a temporary buffer so that users who scribble over
     * their read buffer while the operation is in progress do not end up
     * modifying the image file.  This is critical for zero-copy guest I/O
     * where anything might happen inside guest memory.
     */
    void *bounce_buffer;
    BlockDriver *drv = bs->drv;
    struct iovec iov;
    QEMUIOVector local_qiov;
    int64_t cluster_offset;
    int64_t cluster_bytes;
    size_t skip_bytes;
    int ret;
    int max_transfer = MIN_NON_ZERO(bs->bl.max_transfer,
                                    BDRV_REQUEST_MAX_BYTES);
    unsigned int progress = 0;
    /* FIXME We cannot require callers to have write permissions when all they
     * are doing is a read request. If we did things right, write permissions
     * would be obtained anyway, but internally by the copy-on-read code. As
     * long as it is implemented here rather than in a separate filter driver,
     * the copy-on-read code doesn't have its own BdrvChild, however, for which
     * it could request permissions. Therefore we have to bypass the permission
     * system for the moment. */
    // assert(child->perm & (BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE));
    /* Cover entire cluster so no additional backing file I/O is required when
     * allocating cluster in the image file.  Note that this value may exceed
     * BDRV_REQUEST_MAX_BYTES (even when the original read did not), which
     * is one reason we loop rather than doing it all at once.
     */
    bdrv_round_to_clusters(bs, offset, bytes, &cluster_offset, &cluster_bytes);
    skip_bytes = offset - cluster_offset;
    trace_bdrv_co_do_copy_on_readv(bs, offset, bytes,
                                   cluster_offset, cluster_bytes);
    bounce_buffer = qemu_try_blockalign(bs,
                                        MIN(MIN(max_transfer, cluster_bytes),
                                            MAX_BOUNCE_BUFFER));
    if (bounce_buffer == NULL) {
        ret = -ENOMEM;
        goto err;
    while (cluster_bytes) {
        int64_t pnum;
        ret = bdrv_is_allocated(bs, cluster_offset,
                                MIN(cluster_bytes, max_transfer), &pnum);
        if (ret < 0) {
            /* Safe to treat errors in querying allocation as if
             * unallocated; we'll probably fail again soon on the
             * read, but at least that will set a decent errno.
             */
            pnum = MIN(cluster_bytes, max_transfer);
        assert(skip_bytes < pnum);
        if (ret <= 0) {
            /* Must copy-on-read; use the bounce buffer */
            iov.iov_base = bounce_buffer;
            iov.iov_len = pnum = MIN(pnum, MAX_BOUNCE_BUFFER);
            qemu_iovec_init_external(&local_qiov, &iov, 1);
            ret = bdrv_driver_preadv(bs, cluster_offset, pnum,
                                     &local_qiov, 0);
            if (ret < 0) {
                goto err;
            bdrv_debug_event(bs, BLKDBG_COR_WRITE);
            if (drv->bdrv_co_pwrite_zeroes &&
                buffer_is_zero(bounce_buffer, pnum)) {
                /* FIXME: Should we (perhaps conditionally) be setting
                 * BDRV_REQ_MAY_UNMAP, if it will allow for a sparser copy
                 * that still correctly reads as zero? */
                ret = bdrv_co_do_pwrite_zeroes(bs, cluster_offset, pnum, 0);
            } else {
                /* This does not change the data on the disk, it is not
                 * necessary to flush even in cache=writethrough mode.
                 */
                ret = bdrv_driver_pwritev(bs, cluster_offset, pnum,
                                          &local_qiov, 0);
            if (ret < 0) {
                /* It might be okay to ignore write errors for guest
                 * requests.  If this is a deliberate copy-on-read
                 * then we don't want to ignore the error.  Simply
                 * report it in all cases.
                 */
                goto err;
            qemu_iovec_from_buf(qiov, progress, bounce_buffer + skip_bytes,
                                pnum - skip_bytes);
        } else {
            /* Read directly into the destination */
            qemu_iovec_init(&local_qiov, qiov->niov);
            qemu_iovec_concat(&local_qiov, qiov, progress, pnum - skip_bytes);
            ret = bdrv_driver_preadv(bs, offset + progress, local_qiov.size,
                                     &local_qiov, 0);
            qemu_iovec_destroy(&local_qiov);
            if (ret < 0) {
                goto err;
        cluster_offset += pnum;
        cluster_bytes -= pnum;
        progress += pnum - skip_bytes;
        skip_bytes = 0;
    ret = 0;
err:
    qemu_vfree(bounce_buffer);
    return ret;


static void virtio_scsi_device_unrealize(DeviceState *dev, Error **errp)
{
    virtio_scsi_common_unrealize(dev, errp);
}


static int protocol_client_init(VncState *vs, uint8_t *data, size_t len)

{

    char buf[1024];

    VncShareMode mode;

    int size;

    mode = data[0] ? VNC_SHARE_MODE_SHARED : VNC_SHARE_MODE_EXCLUSIVE;

    switch (vs->vd->share_policy) {

    case VNC_SHARE_POLICY_IGNORE:

        /*

         * Ignore the shared flag.  Nothing to do here.

         *

         * Doesn't conform to the rfb spec but is traditional qemu

         * behavior, thus left here as option for compatibility

         * reasons.

         */

        break;

    case VNC_SHARE_POLICY_ALLOW_EXCLUSIVE:

        /*

         * Policy: Allow clients ask for exclusive access.

         *

         * Implementation: When a client asks for exclusive access,

         * disconnect all others. Shared connects are allowed as long

         * as no exclusive connection exists.

         *

         * This is how the rfb spec suggests to handle the shared flag.

         */

        if (mode == VNC_SHARE_MODE_EXCLUSIVE) {

            VncState *client;

            QTAILQ_FOREACH(client, &vs->vd->clients, next) {

                if (vs == client) {

                    continue;

                }

                if (client->share_mode != VNC_SHARE_MODE_EXCLUSIVE &&

                    client->share_mode != VNC_SHARE_MODE_SHARED) {

                    continue;

                }

                vnc_disconnect_start(client);

            }

        }

        if (mode == VNC_SHARE_MODE_SHARED) {

            if (vs->vd->num_exclusive > 0) {

                vnc_disconnect_start(vs);

                return 0;

            }

        }

        break;

    case VNC_SHARE_POLICY_FORCE_SHARED:

        /*

         * Policy: Shared connects only.

         * Implementation: Disallow clients asking for exclusive access.

         *

         * Useful for shared desktop sessions where you don't want

         * someone forgetting to say -shared when running the vnc

         * client disconnect everybody else.

         */

        if (mode == VNC_SHARE_MODE_EXCLUSIVE) {

            vnc_disconnect_start(vs);

            return 0;

        }

        break;

    }

    vnc_set_share_mode(vs, mode);

    vs->client_width = surface_width(vs->vd->ds);

    vs->client_height = surface_height(vs->vd->ds);

    vnc_write_u16(vs, vs->client_width);

    vnc_write_u16(vs, vs->client_height);

    pixel_format_message(vs);

    if (qemu_name)

        size = snprintf(buf, sizeof(buf), "QEMU (%s)", qemu_name);

    else

        size = snprintf(buf, sizeof(buf), "QEMU");

    vnc_write_u32(vs, size);

    vnc_write(vs, buf, size);

    vnc_flush(vs);

    vnc_client_cache_auth(vs);

    vnc_qmp_event(vs, QAPI_EVENT_VNC_INITIALIZED);

    vnc_read_when(vs, protocol_client_msg, 1);

    return 0;

}


static void avc_luma_hv_qrt_and_aver_dst_4x4_msa(const uint8_t *src_x,

                                                 const uint8_t *src_y,

                                                 int32_t src_stride,

                                                 uint8_t *dst,

                                                 int32_t dst_stride)

{

    v16i8 src_hz0, src_hz1, src_hz2, src_hz3;

    v16u8 dst0, dst1, dst2, dst3;

    v16i8 src_vt0, src_vt1, src_vt2, src_vt3, src_vt4;

    v16i8 src_vt5, src_vt6, src_vt7, src_vt8;

    v16i8 mask0, mask1, mask2;

    v8i16 hz_out0, hz_out1, vert_out0, vert_out1;

    v8i16 res0, res1;

    v16u8 res;

    LD_SB3(&luma_mask_arr[48], 16, mask0, mask1, mask2);

    LD_SB5(src_y, src_stride, src_vt0, src_vt1, src_vt2, src_vt3, src_vt4);

    src_y += (5 * src_stride);

    src_vt0 = (v16i8) __msa_insve_w((v4i32) src_vt0, 1, (v4i32) src_vt1);

    src_vt1 = (v16i8) __msa_insve_w((v4i32) src_vt1, 1, (v4i32) src_vt2);

    src_vt2 = (v16i8) __msa_insve_w((v4i32) src_vt2, 1, (v4i32) src_vt3);

    src_vt3 = (v16i8) __msa_insve_w((v4i32) src_vt3, 1, (v4i32) src_vt4);

    XORI_B4_128_SB(src_vt0, src_vt1, src_vt2, src_vt3);

    LD_SB4(src_x, src_stride, src_hz0, src_hz1, src_hz2, src_hz3);

    LD_UB4(dst, dst_stride, dst0, dst1, dst2, dst3);

    XORI_B4_128_SB(src_hz0, src_hz1, src_hz2, src_hz3);

    hz_out0 = AVC_XOR_VSHF_B_AND_APPLY_6TAP_HORIZ_FILT_SH(src_hz0, src_hz1,

                                                          mask0, mask1, mask2);

    hz_out1 = AVC_XOR_VSHF_B_AND_APPLY_6TAP_HORIZ_FILT_SH(src_hz2, src_hz3,

                                                          mask0, mask1, mask2);

    SRARI_H2_SH(hz_out0, hz_out1, 5);

    SAT_SH2_SH(hz_out0, hz_out1, 7);

    LD_SB4(src_y, src_stride, src_vt5, src_vt6, src_vt7, src_vt8);

    src_vt4 = (v16i8) __msa_insve_w((v4i32) src_vt4, 1, (v4i32) src_vt5);

    src_vt5 = (v16i8) __msa_insve_w((v4i32) src_vt5, 1, (v4i32) src_vt6);

    src_vt6 = (v16i8) __msa_insve_w((v4i32) src_vt6, 1, (v4i32) src_vt7);

    src_vt7 = (v16i8) __msa_insve_w((v4i32) src_vt7, 1, (v4i32) src_vt8);

    XORI_B4_128_SB(src_vt4, src_vt5, src_vt6, src_vt7);

    /* filter calc */

    vert_out0 = AVC_CALC_DPADD_B_6PIX_2COEFF_R_SH(src_vt0, src_vt1, src_vt2,

                                                  src_vt3, src_vt4, src_vt5);

    vert_out1 = AVC_CALC_DPADD_B_6PIX_2COEFF_R_SH(src_vt2, src_vt3, src_vt4,

                                                  src_vt5, src_vt6, src_vt7);

    SRARI_H2_SH(vert_out0, vert_out1, 5);

    SAT_SH2_SH(vert_out0, vert_out1, 7);

    res1 = __msa_srari_h((hz_out1 + vert_out1), 1);

    res0 = __msa_srari_h((hz_out0 + vert_out0), 1);

    SAT_SH2_SH(res0, res1, 7);

    res = PCKEV_XORI128_UB(res0, res1);

    dst0 = (v16u8) __msa_insve_w((v4i32) dst0, 1, (v4i32) dst1);

    dst1 = (v16u8) __msa_insve_w((v4i32) dst2, 1, (v4i32) dst3);

    dst0 = (v16u8) __msa_insve_d((v2i64) dst0, 1, (v2i64) dst1);

    dst0 = __msa_aver_u_b(res, dst0);

    ST4x4_UB(dst0, dst0, 0, 1, 2, 3, dst, dst_stride);

}


static BlockDriverAIOCB *raw_aio_readv(BlockDriverState *bs,

                         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,

                         BlockDriverCompletionFunc *cb, void *opaque)

{

    BDRVRawState *s = bs->opaque;

    return paio_submit(bs, s->hfile, sector_num, qiov, nb_sectors,

                       cb, opaque, QEMU_AIO_READ);

}


static void tcx_blit_writel(void *opaque, hwaddr addr,

                            uint64_t val, unsigned size)

{

    TCXState *s = opaque;

    uint32_t adsr, len;

    int i;

    if (!(addr & 4)) {

        s->tmpblit = val;

    } else {

        addr = (addr >> 3) & 0xfffff;

        adsr = val & 0xffffff;

        len = ((val >> 24) & 0x1f) + 1;

        if (adsr == 0xffffff) {

            memset(&s->vram[addr], s->tmpblit, len);

            if (s->depth == 24) {

                val = s->tmpblit & 0xffffff;

                val = cpu_to_be32(val);

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

                    s->vram24[addr + i] = val;

                }

            }

        } else {

            memcpy(&s->vram[addr], &s->vram[adsr], len);

            if (s->depth == 24) {

                memcpy(&s->vram24[addr], &s->vram24[adsr], len * 4);

            }

        }

        memory_region_set_dirty(&s->vram_mem, addr, len);

    }

}


static void avc_loopfilter_cb_or_cr_intra_edge_ver_msa(uint8_t *data_cb_or_cr,

                                                       uint8_t alpha_in,

                                                       uint8_t beta_in,

                                                       uint32_t img_width)

{

    uint16_t out0, out1, out2, out3;

    v8i16 tmp1;

    v16u8 alpha, beta, is_less_than;

    v8i16 p0_or_q0, q0_or_p0;

    v16u8 p1_or_q1_org, p0_or_q0_org, q0_or_p0_org, q1_or_p1_org;

    v16i8 zero = { 0 };

    v16u8 p0_asub_q0, p1_asub_p0, q1_asub_q0;

    v16u8 is_less_than_alpha, is_less_than_beta;

    v8i16 p1_org_r, p0_org_r, q0_org_r, q1_org_r;

    {

        v16u8 row0, row1, row2, row3, row4, row5, row6, row7;

        LOAD_8VECS_UB((data_cb_or_cr - 2), img_width,

                      row0, row1, row2, row3, row4, row5, row6, row7);

        TRANSPOSE8x4_B_UB(row0, row1, row2, row3, row4, row5, row6, row7,

                          p1_or_q1_org, p0_or_q0_org,

                          q0_or_p0_org, q1_or_p1_org);

    }

    alpha = (v16u8) __msa_fill_b(alpha_in);

    beta = (v16u8) __msa_fill_b(beta_in);

    p0_asub_q0 = __msa_asub_u_b(p0_or_q0_org, q0_or_p0_org);

    p1_asub_p0 = __msa_asub_u_b(p1_or_q1_org, p0_or_q0_org);

    q1_asub_q0 = __msa_asub_u_b(q1_or_p1_org, q0_or_p0_org);

    is_less_than_alpha = (p0_asub_q0 < alpha);

    is_less_than_beta = (p1_asub_p0 < beta);

    is_less_than = is_less_than_beta & is_less_than_alpha;

    is_less_than_beta = (q1_asub_q0 < beta);

    is_less_than = is_less_than_beta & is_less_than;

    is_less_than = (v16u8) __msa_ilvr_d((v2i64) zero, (v2i64) is_less_than);

    if (!__msa_test_bz_v(is_less_than)) {

        p1_org_r = (v8i16) __msa_ilvr_b(zero, (v16i8) p1_or_q1_org);

        p0_org_r = (v8i16) __msa_ilvr_b(zero, (v16i8) p0_or_q0_org);

        q0_org_r = (v8i16) __msa_ilvr_b(zero, (v16i8) q0_or_p0_org);

        q1_org_r = (v8i16) __msa_ilvr_b(zero, (v16i8) q1_or_p1_org);

        AVC_LOOP_FILTER_P0_OR_Q0(p0_org_r, q1_org_r, p1_org_r, p0_or_q0);

        AVC_LOOP_FILTER_P0_OR_Q0(q0_org_r, p1_org_r, q1_org_r, q0_or_p0);

        /* convert 16 bit output into 8 bit output */

        p0_or_q0 = (v8i16) __msa_pckev_b(zero, (v16i8) p0_or_q0);

        q0_or_p0 = (v8i16) __msa_pckev_b(zero, (v16i8) q0_or_p0);

        p0_or_q0_org =

            __msa_bmnz_v(p0_or_q0_org, (v16u8) p0_or_q0, is_less_than);

        q0_or_p0_org =

            __msa_bmnz_v(q0_or_p0_org, (v16u8) q0_or_p0, is_less_than);

        tmp1 = (v8i16) __msa_ilvr_b((v16i8) q0_or_p0_org, (v16i8) p0_or_q0_org);

        data_cb_or_cr -= 1;

        out0 = __msa_copy_u_h(tmp1, 0);

        out1 = __msa_copy_u_h(tmp1, 1);

        out2 = __msa_copy_u_h(tmp1, 2);

        out3 = __msa_copy_u_h(tmp1, 3);

        STORE_HWORD(data_cb_or_cr, out0);

        data_cb_or_cr += img_width;

        STORE_HWORD(data_cb_or_cr, out1);

        data_cb_or_cr += img_width;

        STORE_HWORD(data_cb_or_cr, out2);

        data_cb_or_cr += img_width;

        STORE_HWORD(data_cb_or_cr, out3);

        data_cb_or_cr += img_width;

        out0 = __msa_copy_u_h(tmp1, 4);

        out1 = __msa_copy_u_h(tmp1, 5);

        out2 = __msa_copy_u_h(tmp1, 6);

        out3 = __msa_copy_u_h(tmp1, 7);

        STORE_HWORD(data_cb_or_cr, out0);

        data_cb_or_cr += img_width;

        STORE_HWORD(data_cb_or_cr, out1);

        data_cb_or_cr += img_width;

        STORE_HWORD(data_cb_or_cr, out2);

        data_cb_or_cr += img_width;

        STORE_HWORD(data_cb_or_cr, out3);

    }

}


int ff_h261_handle_packet(AVFormatContext *ctx, PayloadContext *data,

                          AVStream *st, AVPacket *pkt, uint32_t *timestamp,

                          const uint8_t *buf, int len, uint16_t seq, int flags)

{

    int sbit, ebit, gobn, mbap, quant;

    int res;

    //av_log(ctx, AV_LOG_DEBUG, "got h261 RTP packet with time: %u\n", timestamp);

    /* drop data of previous packets in case of non-continuous (loss) packet stream */

    if (data->buf && data->timestamp != *timestamp) {

        h261_free_dyn_buffer(&data->buf);

    }

    /* sanity check for size of input packet */

    if (len < 5 /* 4 bytes header and 1 byte payload at least */) {

        av_log(ctx, AV_LOG_ERROR, "Too short H.261 RTP packet\n");

        return AVERROR_INVALIDDATA;

    }

    /*

      decode the H.261 payload header according to section 4.1 of RFC 4587:

      (uses 4 bytes between RTP header and H.261 stream per packet)

         0                   1                   2                   3

         0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1

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

        |SBIT |EBIT |I|V| GOBN  |   MBAP  |  QUANT  |  HMVD   |  VMVD   |

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

           Start bit position (SBIT): 3 bits

           End bit position (EBIT): 3 bits

           INTRA-frame encoded data (I): 1 bit

           Motion Vector flag (V): 1 bit

           GOB number (GOBN): 4 bits

           Macroblock address predictor (MBAP): 5 bits

           Quantizer (QUANT): 5 bits

           Horizontal motion vector data (HMVD): 5 bits

           Vertical motion vector data (VMVD): 5 bits

    */

    sbit  =  (buf[0] >> 5) & 0x07;

    ebit  =  (buf[0] >> 2) & 0x07;

    gobn  =  (buf[1] >> 4) & 0x0f;

    mbap  = ((buf[1] << 1) & 0x1e) | ((buf[1] >> 7) & 0x01);

    quant =  (buf[1] >> 4) & 0x0f;

    /* pass the H.261 payload header and continue with the actual payload */

    buf += RTP_H261_PAYLOAD_HEADER_SIZE;

    len -= RTP_H261_PAYLOAD_HEADER_SIZE;

    /* start frame buffering with new dynamic buffer */

    if (!data->buf) {

        /* sanity check: a new frame starts with gobn=0, sbit=0, mbap=0, uqnat=0 */

        if (!gobn  && !sbit && !mbap && !quant){

            res = avio_open_dyn_buf(&data->buf);

            if (res < 0)

                return res;

            /* update the timestamp in the frame packet with the one from the RTP packet */

            data->timestamp = *timestamp;

        } else {

            /* frame not started yet, need more packets */

            return AVERROR(EAGAIN);

        }

    }

    /* do the "byte merging" at the boundaries of two consecutive frame fragments */

    if (data->endbyte_bits || sbit) {

        if (data->endbyte_bits == sbit) {

            data->endbyte |= buf[0] & (0xff >> sbit);

            data->endbyte_bits = 0;

            buf++;

            len--;

            avio_w8(data->buf, data->endbyte);

        } else {

            /* ebit/sbit values inconsistent, assuming packet loss */

            GetBitContext gb;

            init_get_bits(&gb, buf, len*8 - ebit);

            skip_bits(&gb, sbit);

            if (data->endbyte_bits) {

                data->endbyte |= get_bits(&gb, 8 - data->endbyte_bits);

                avio_w8(data->buf, data->endbyte);

            }

            while (get_bits_left(&gb) >= 8)

                avio_w8(data->buf, get_bits(&gb, 8));

            data->endbyte_bits = get_bits_left(&gb);

            if (data->endbyte_bits)

                data->endbyte = get_bits(&gb, data->endbyte_bits) <<

                                (8 - data->endbyte_bits);

            ebit = 0;

            len = 0;

        }

    }

    if (ebit) {

        if (len > 0)

            avio_write(data->buf, buf, len - 1);

        data->endbyte_bits = 8 - ebit;

        data->endbyte = buf[len - 1] & (0xff << ebit);

    } else {

        avio_write(data->buf, buf, len);

    }

    /* RTP marker bit means: last fragment of current frame was received;

       otherwise, an additional fragment is needed for the current frame */

    if (!(flags & RTP_FLAG_MARKER))

        return AVERROR(EAGAIN);

    /* write the completed last byte from the "byte merging" */

    if (data->endbyte_bits)

        avio_w8(data->buf, data->endbyte);

    data->endbyte_bits = 0;

    /* close frame buffering and create resulting A/V packet */

    res = ff_rtp_finalize_packet(pkt, &data->buf, st->index);

    if (res < 0)

        return res;

    return 0;

}


static int vdpau_mpeg_start_frame(AVCodecContext *avctx,

                                  const uint8_t *buffer, uint32_t size)

{

    MpegEncContext * const s = avctx->priv_data;

    Picture *pic             = s->current_picture_ptr;

    struct vdpau_picture_context *pic_ctx = pic->hwaccel_picture_private;

    VdpPictureInfoMPEG1Or2 *info = &pic_ctx->info.mpeg;

    VdpVideoSurface ref;

    int i;

    /* fill VdpPictureInfoMPEG1Or2 struct */

    info->forward_reference  = VDP_INVALID_HANDLE;

    info->backward_reference = VDP_INVALID_HANDLE;

    switch (s->pict_type) {

    case AV_PICTURE_TYPE_B:

        ref = ff_vdpau_get_surface_id(&s->next_picture.f);

        assert(ref != VDP_INVALID_HANDLE);

        info->backward_reference = ref;

        /* fall through to forward prediction */

    case AV_PICTURE_TYPE_P:

        ref = ff_vdpau_get_surface_id(&s->last_picture.f);

        info->forward_reference  = ref;

    }

    info->slice_count                = 0;

    info->picture_structure          = s->picture_structure;

    info->picture_coding_type        = s->pict_type;

    info->intra_dc_precision         = s->intra_dc_precision;

    info->frame_pred_frame_dct       = s->frame_pred_frame_dct;

    info->concealment_motion_vectors = s->concealment_motion_vectors;

    info->intra_vlc_format           = s->intra_vlc_format;

    info->alternate_scan             = s->alternate_scan;

    info->q_scale_type               = s->q_scale_type;

    info->top_field_first            = s->top_field_first;

    // Both for MPEG-1 only, zero for MPEG-2:

    info->full_pel_forward_vector    = s->full_pel[0];

    info->full_pel_backward_vector   = s->full_pel[1];

    // For MPEG-1 fill both horizontal & vertical:

    info->f_code[0][0]               = s->mpeg_f_code[0][0];

    info->f_code[0][1]               = s->mpeg_f_code[0][1];

    info->f_code[1][0]               = s->mpeg_f_code[1][0];

    info->f_code[1][1]               = s->mpeg_f_code[1][1];

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

        info->intra_quantizer_matrix[i]     = s->intra_matrix[i];

        info->non_intra_quantizer_matrix[i] = s->inter_matrix[i];

    }

    return ff_vdpau_common_start_frame(pic_ctx, buffer, size);

}


void h263_decode_init_vlc(MpegEncContext *s)

{

    static int done = 0;

    if (!done) {

        done = 1;

        init_vlc(&intra_MCBPC_vlc, INTRA_MCBPC_VLC_BITS, 9,

                 intra_MCBPC_bits, 1, 1,

                 intra_MCBPC_code, 1, 1);

        init_vlc(&inter_MCBPC_vlc, INTER_MCBPC_VLC_BITS, 28,

                 inter_MCBPC_bits, 1, 1,

                 inter_MCBPC_code, 1, 1);

        init_vlc(&cbpy_vlc, CBPY_VLC_BITS, 16,

                 &cbpy_tab[0][1], 2, 1,

                 &cbpy_tab[0][0], 2, 1);

        init_vlc(&mv_vlc, MV_VLC_BITS, 33,

                 &mvtab[0][1], 2, 1,

                 &mvtab[0][0], 2, 1);

        init_rl(&rl_inter);

        init_rl(&rl_intra);

        init_rl(&rvlc_rl_inter);

        init_rl(&rvlc_rl_intra);

        init_rl(&rl_intra_aic);

        init_vlc_rl(&rl_inter);

        init_vlc_rl(&rl_intra);

        init_vlc_rl(&rvlc_rl_inter);

        init_vlc_rl(&rvlc_rl_intra);

        init_vlc_rl(&rl_intra_aic);

        init_vlc(&dc_lum, DC_VLC_BITS, 10 /* 13 */,

                 &DCtab_lum[0][1], 2, 1,

                 &DCtab_lum[0][0], 2, 1);

        init_vlc(&dc_chrom, DC_VLC_BITS, 10 /* 13 */,

                 &DCtab_chrom[0][1], 2, 1,

                 &DCtab_chrom[0][0], 2, 1);

        init_vlc(&sprite_trajectory, SPRITE_TRAJ_VLC_BITS, 15,

                 &sprite_trajectory_tab[0][1], 4, 2,

                 &sprite_trajectory_tab[0][0], 4, 2);

        init_vlc(&mb_type_b_vlc, MB_TYPE_B_VLC_BITS, 4,

                 &mb_type_b_tab[0][1], 2, 1,

                 &mb_type_b_tab[0][0], 2, 1);

        init_vlc(&h263_mbtype_b_vlc, H263_MBTYPE_B_VLC_BITS, 15,

                 &h263_mbtype_b_tab[0][1], 2, 1,

                 &h263_mbtype_b_tab[0][0], 2, 1);

        init_vlc(&cbpc_b_vlc, CBPC_B_VLC_BITS, 4,

                 &cbpc_b_tab[0][1], 2, 1,

                 &cbpc_b_tab[0][0], 2, 1);

    }

}


static uint64_t icp_pit_read(void *opaque, target_phys_addr_t offset,

                             unsigned size)

{

    icp_pit_state *s = (icp_pit_state *)opaque;

    int n;

    /* ??? Don't know the PrimeCell ID for this device.  */

    n = offset >> 8;

    if (n > 3) {

        hw_error("sp804_read: Bad timer %d\n", n);

    }

    return arm_timer_read(s->timer[n], offset & 0xff);

}


static int mpeg1_decode_sequence(AVCodecContext *avctx,

                                 UINT8 *buf, int buf_size)

{

    Mpeg1Context *s1 = avctx->priv_data;

    MpegEncContext *s = &s1->mpeg_enc_ctx;

    int width, height, i, v, j;

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

    width = get_bits(&s->gb, 12);

    height = get_bits(&s->gb, 12);

    skip_bits(&s->gb, 4);

    s->frame_rate_index = get_bits(&s->gb, 4);

    if (s->frame_rate_index == 0)

        return -1;

    s->bit_rate = get_bits(&s->gb, 18) * 400;

    if (get_bits1(&s->gb) == 0) /* marker */

        return -1;

    if (width <= 0 || height <= 0 ||

        (width % 2) != 0 || (height % 2) != 0)

        return -1;

    if (width != s->width ||

        height != s->height) {

        /* start new mpeg1 context decoding */

        s->out_format = FMT_MPEG1;

        if (s1->mpeg_enc_ctx_allocated) {

            MPV_common_end(s);

        }

        s->width = width;

        s->height = height;

        s->has_b_frames = 1;

        s->avctx = avctx;

        avctx->width = width;

        avctx->height = height;

        avctx->frame_rate = frame_rate_tab[s->frame_rate_index];

        s->frame_rate = avctx->frame_rate;

        avctx->bit_rate = s->bit_rate;

        if (MPV_common_init(s) < 0)

            return -1;

        mpeg1_init_vlc(s);

        s1->mpeg_enc_ctx_allocated = 1;

    }

    skip_bits(&s->gb, 10); /* vbv_buffer_size */

    skip_bits(&s->gb, 1);

    /* get matrix */

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

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

            v = get_bits(&s->gb, 8);

            j = zigzag_direct[i];

            s->intra_matrix[j] = v;

            s->chroma_intra_matrix[j] = v;

        }

#ifdef DEBUG

        dprintf("intra matrix present\n");

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

            dprintf(" %d", s->intra_matrix[zigzag_direct[i]]);

        printf("\n");

#endif

    } else {

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

            v = default_intra_matrix[i];

            s->intra_matrix[i] = v;

            s->chroma_intra_matrix[i] = v;

        }

    }

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

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

            v = get_bits(&s->gb, 8);

            j = zigzag_direct[i];

            s->non_intra_matrix[j] = v;

            s->chroma_non_intra_matrix[j] = v;

        }

#ifdef DEBUG

        dprintf("non intra matrix present\n");

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

            dprintf(" %d", s->non_intra_matrix[zigzag_direct[i]]);

        printf("\n");

#endif

    } else {

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

            v = default_non_intra_matrix[i];

            s->non_intra_matrix[i] = v;

            s->chroma_non_intra_matrix[i] = v;

        }

    }

    /* we set mpeg2 parameters so that it emulates mpeg1 */

    s->progressive_sequence = 1;

    s->progressive_frame = 1;

    s->picture_structure = PICT_FRAME;

    s->frame_pred_frame_dct = 1;

    s->mpeg2 = 0;

    return 0;

}


void ff_rfps_calculate(AVFormatContext *ic)
{
    int i, j;
    for (i = 0; i<ic->nb_streams; i++) {
        AVStream *st = ic->streams[i];
        if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO)
        // the check for tb_unreliable() is not completely correct, since this is not about handling
        // a unreliable/inexact time base, but a time base that is finer than necessary, as e.g.
        // ipmovie.c produces.
        if (tb_unreliable(st->codec) && st->info->duration_count > 15 && st->info->duration_gcd > FFMAX(1, st->time_base.den/(500LL*st->time_base.num)) && !st->r_frame_rate.num)
            av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, st->time_base.den, st->time_base.num * st->info->duration_gcd, INT_MAX);
        if (st->info->duration_count>1 && !st->r_frame_rate.num
            && tb_unreliable(st->codec)) {
            int num = 0;
            double best_error= 0.01;
            for (j=0; j<MAX_STD_TIMEBASES; j++) {
                int k;
                if(st->info->codec_info_duration && st->info->codec_info_duration*av_q2d(st->time_base) < (1001*12.0)/get_std_framerate(j))
                if(!st->info->codec_info_duration && 1.0 < (1001*12.0)/get_std_framerate(j))
                for(k=0; k<2; k++){
                    int n= st->info->duration_count;
                    double a= st->info->duration_error[k][0][j] / n;
                    double error= st->info->duration_error[k][1][j]/n - a*a;
                    if(error < best_error && best_error> 0.000000001){
                        best_error= error;
                        num = get_std_framerate(j);
                    }
                    if(error < 0.02)
                        av_log(NULL, AV_LOG_DEBUG, "rfps: %f %f\n", get_std_framerate(j) / 12.0/1001, error);
                }
            }
            // do not increase frame rate by more than 1 % in order to match a standard rate.
            if (num && (!st->r_frame_rate.num || (double)num/(12*1001) < 1.01 * av_q2d(st->r_frame_rate)))
                av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, num, 12*1001, INT_MAX);
        }
        av_freep(&st->info->duration_error);
        st->info->last_dts = AV_NOPTS_VALUE;
        st->info->duration_count = 0;
        st->info->rfps_duration_sum = 0;
    }
}


static void gen_compute_eflags_o(DisasContext *s, TCGv reg)

{

    gen_compute_eflags(s);

    tcg_gen_shri_tl(reg, cpu_cc_src, 11);

    tcg_gen_andi_tl(reg, reg, 1);

}


static void pred_spatial_direct_motion(const H264Context *const h, H264SliceContext *sl,

                                       int *mb_type)

{

    int b8_stride = 2;

    int b4_stride = h->b_stride;

    int mb_xy = sl->mb_xy, mb_y = sl->mb_y;

    int mb_type_col[2];

    const int16_t (*l1mv0)[2], (*l1mv1)[2];

    const int8_t *l1ref0, *l1ref1;

    const int is_b8x8 = IS_8X8(*mb_type);

    unsigned int sub_mb_type = MB_TYPE_L0L1;

    int i8, i4;

    int ref[2];

    int mv[2];

    int list;

    assert(sl->ref_list[1][0].reference & 3);

    await_reference_mb_row(h, sl->ref_list[1][0].parent,

                           sl->mb_y + !!IS_INTERLACED(*mb_type));

#define MB_TYPE_16x16_OR_INTRA (MB_TYPE_16x16 | MB_TYPE_INTRA4x4 | \

                                MB_TYPE_INTRA16x16 | MB_TYPE_INTRA_PCM)

    /* ref = min(neighbors) */

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

        int left_ref     = sl->ref_cache[list][scan8[0] - 1];

        int top_ref      = sl->ref_cache[list][scan8[0] - 8];

        int refc         = sl->ref_cache[list][scan8[0] - 8 + 4];

        const int16_t *C = sl->mv_cache[list][scan8[0]  - 8 + 4];

        if (refc == PART_NOT_AVAILABLE) {

            refc = sl->ref_cache[list][scan8[0] - 8 - 1];

            C    = sl->mv_cache[list][scan8[0]  - 8 - 1];

        }

        ref[list] = FFMIN3((unsigned)left_ref,

                           (unsigned)top_ref,

                           (unsigned)refc);

        if (ref[list] >= 0) {

            /* This is just pred_motion() but with the cases removed that

             * cannot happen for direct blocks. */

            const int16_t *const A = sl->mv_cache[list][scan8[0] - 1];

            const int16_t *const B = sl->mv_cache[list][scan8[0] - 8];

            int match_count = (left_ref == ref[list]) +

                              (top_ref  == ref[list]) +

                              (refc     == ref[list]);

            if (match_count > 1) { // most common

                mv[list] = pack16to32(mid_pred(A[0], B[0], C[0]),

                                      mid_pred(A[1], B[1], C[1]));

            } else {

                assert(match_count == 1);

                if (left_ref == ref[list])

                    mv[list] = AV_RN32A(A);

                else if (top_ref == ref[list])

                    mv[list] = AV_RN32A(B);

                else

                    mv[list] = AV_RN32A(C);

            }

        } else {

            int mask = ~(MB_TYPE_L0 << (2 * list));

            mv[list]  = 0;

            ref[list] = -1;

            if (!is_b8x8)

                *mb_type &= mask;

            sub_mb_type &= mask;

        }

    }

    if (ref[0] < 0 && ref[1] < 0) {

        ref[0] = ref[1] = 0;

        if (!is_b8x8)

            *mb_type |= MB_TYPE_L0L1;

        sub_mb_type |= MB_TYPE_L0L1;

    }

    if (!(is_b8x8 | mv[0] | mv[1])) {

        fill_rectangle(&sl->ref_cache[0][scan8[0]], 4, 4, 8, (uint8_t)ref[0], 1);

        fill_rectangle(&sl->ref_cache[1][scan8[0]], 4, 4, 8, (uint8_t)ref[1], 1);

        fill_rectangle(&sl->mv_cache[0][scan8[0]], 4, 4, 8, 0, 4);

        fill_rectangle(&sl->mv_cache[1][scan8[0]], 4, 4, 8, 0, 4);

        *mb_type = (*mb_type & ~(MB_TYPE_8x8 | MB_TYPE_16x8 | MB_TYPE_8x16 |

                                 MB_TYPE_P1L0 | MB_TYPE_P1L1)) |

                   MB_TYPE_16x16 | MB_TYPE_DIRECT2;

        return;

    }

    if (IS_INTERLACED(sl->ref_list[1][0].parent->mb_type[mb_xy])) { // AFL/AFR/FR/FL -> AFL/FL

        if (!IS_INTERLACED(*mb_type)) {                    //     AFR/FR    -> AFL/FL

            mb_y  = (sl->mb_y & ~1) + sl->col_parity;

            mb_xy = sl->mb_x +

                    ((sl->mb_y & ~1) + sl->col_parity) * h->mb_stride;

            b8_stride = 0;

        } else {

            mb_y  += sl->col_fieldoff;

            mb_xy += h->mb_stride * sl->col_fieldoff; // non-zero for FL -> FL & differ parity

        }

        goto single_col;

    } else {                                             // AFL/AFR/FR/FL -> AFR/FR

        if (IS_INTERLACED(*mb_type)) {                   // AFL       /FL -> AFR/FR

            mb_y           =  sl->mb_y & ~1;

            mb_xy          = (sl->mb_y & ~1) * h->mb_stride + sl->mb_x;

            mb_type_col[0] = sl->ref_list[1][0].parent->mb_type[mb_xy];

            mb_type_col[1] = sl->ref_list[1][0].parent->mb_type[mb_xy + h->mb_stride];

            b8_stride      = 2 + 4 * h->mb_stride;

            b4_stride     *= 6;

            if (IS_INTERLACED(mb_type_col[0]) !=

                IS_INTERLACED(mb_type_col[1])) {

                mb_type_col[0] &= ~MB_TYPE_INTERLACED;

                mb_type_col[1] &= ~MB_TYPE_INTERLACED;

            }

            sub_mb_type |= MB_TYPE_16x16 | MB_TYPE_DIRECT2; /* B_SUB_8x8 */

            if ((mb_type_col[0] & MB_TYPE_16x16_OR_INTRA) &&

                (mb_type_col[1] & MB_TYPE_16x16_OR_INTRA) &&

                !is_b8x8) {

                *mb_type |= MB_TYPE_16x8 | MB_TYPE_DIRECT2;  /* B_16x8 */

            } else {

                *mb_type |= MB_TYPE_8x8;

            }

        } else {                                         //     AFR/FR    -> AFR/FR

single_col:

            mb_type_col[0] =

            mb_type_col[1] = sl->ref_list[1][0].parent->mb_type[mb_xy];

            sub_mb_type |= MB_TYPE_16x16 | MB_TYPE_DIRECT2; /* B_SUB_8x8 */

            if (!is_b8x8 && (mb_type_col[0] & MB_TYPE_16x16_OR_INTRA)) {

                *mb_type |= MB_TYPE_16x16 | MB_TYPE_DIRECT2; /* B_16x16 */

            } else if (!is_b8x8 &&

                       (mb_type_col[0] & (MB_TYPE_16x8 | MB_TYPE_8x16))) {

                *mb_type |= MB_TYPE_DIRECT2 |

                            (mb_type_col[0] & (MB_TYPE_16x8 | MB_TYPE_8x16));

            } else {

                if (!h->sps.direct_8x8_inference_flag) {

                    /* FIXME: Save sub mb types from previous frames (or derive

                     * from MVs) so we know exactly what block size to use. */

                    sub_mb_type += (MB_TYPE_8x8 - MB_TYPE_16x16); /* B_SUB_4x4 */

                }

                *mb_type |= MB_TYPE_8x8;

            }

        }

    }

    await_reference_mb_row(h, sl->ref_list[1][0].parent, mb_y);

    l1mv0  = &sl->ref_list[1][0].parent->motion_val[0][h->mb2b_xy[mb_xy]];

    l1mv1  = &sl->ref_list[1][0].parent->motion_val[1][h->mb2b_xy[mb_xy]];

    l1ref0 = &sl->ref_list[1][0].parent->ref_index[0][4 * mb_xy];

    l1ref1 = &sl->ref_list[1][0].parent->ref_index[1][4 * mb_xy];

    if (!b8_stride) {

        if (sl->mb_y & 1) {

            l1ref0 += 2;

            l1ref1 += 2;

            l1mv0  += 2 * b4_stride;

            l1mv1  += 2 * b4_stride;

        }

    }

    if (IS_INTERLACED(*mb_type) != IS_INTERLACED(mb_type_col[0])) {

        int n = 0;

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

            int x8  = i8 & 1;

            int y8  = i8 >> 1;

            int xy8 = x8     + y8 * b8_stride;

            int xy4 = x8 * 3 + y8 * b4_stride;

            int a, b;

            if (is_b8x8 && !IS_DIRECT(sl->sub_mb_type[i8]))

                continue;

            sl->sub_mb_type[i8] = sub_mb_type;

            fill_rectangle(&sl->ref_cache[0][scan8[i8 * 4]], 2, 2, 8,

                           (uint8_t)ref[0], 1);

            fill_rectangle(&sl->ref_cache[1][scan8[i8 * 4]], 2, 2, 8,

                           (uint8_t)ref[1], 1);

            if (!IS_INTRA(mb_type_col[y8]) && !sl->ref_list[1][0].parent->long_ref &&

                ((l1ref0[xy8] == 0 &&

                  FFABS(l1mv0[xy4][0]) <= 1 &&

                  FFABS(l1mv0[xy4][1]) <= 1) ||

                 (l1ref0[xy8] < 0 &&

                  l1ref1[xy8] == 0 &&

                  FFABS(l1mv1[xy4][0]) <= 1 &&

                  FFABS(l1mv1[xy4][1]) <= 1))) {

                a =

                b = 0;

                if (ref[0] > 0)

                    a = mv[0];

                if (ref[1] > 0)

                    b = mv[1];

                n++;

            } else {

                a = mv[0];

                b = mv[1];

            }

            fill_rectangle(&sl->mv_cache[0][scan8[i8 * 4]], 2, 2, 8, a, 4);

            fill_rectangle(&sl->mv_cache[1][scan8[i8 * 4]], 2, 2, 8, b, 4);

        }

        if (!is_b8x8 && !(n & 3))

            *mb_type = (*mb_type & ~(MB_TYPE_8x8 | MB_TYPE_16x8 | MB_TYPE_8x16 |

                                     MB_TYPE_P1L0 | MB_TYPE_P1L1)) |

                       MB_TYPE_16x16 | MB_TYPE_DIRECT2;

    } else if (IS_16X16(*mb_type)) {

        int a, b;

        fill_rectangle(&sl->ref_cache[0][scan8[0]], 4, 4, 8, (uint8_t)ref[0], 1);

        fill_rectangle(&sl->ref_cache[1][scan8[0]], 4, 4, 8, (uint8_t)ref[1], 1);

        if (!IS_INTRA(mb_type_col[0]) && !sl->ref_list[1][0].parent->long_ref &&

            ((l1ref0[0] == 0 &&

              FFABS(l1mv0[0][0]) <= 1 &&

              FFABS(l1mv0[0][1]) <= 1) ||

             (l1ref0[0] < 0 && !l1ref1[0] &&

              FFABS(l1mv1[0][0]) <= 1 &&

              FFABS(l1mv1[0][1]) <= 1 &&

              h->x264_build > 33U))) {

            a = b = 0;

            if (ref[0] > 0)

                a = mv[0];

            if (ref[1] > 0)

                b = mv[1];

        } else {

            a = mv[0];

            b = mv[1];

        }

        fill_rectangle(&sl->mv_cache[0][scan8[0]], 4, 4, 8, a, 4);

        fill_rectangle(&sl->mv_cache[1][scan8[0]], 4, 4, 8, b, 4);

    } else {

        int n = 0;

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

            const int x8 = i8 & 1;

            const int y8 = i8 >> 1;

            if (is_b8x8 && !IS_DIRECT(sl->sub_mb_type[i8]))

                continue;

            sl->sub_mb_type[i8] = sub_mb_type;

            fill_rectangle(&sl->mv_cache[0][scan8[i8 * 4]], 2, 2, 8, mv[0], 4);

            fill_rectangle(&sl->mv_cache[1][scan8[i8 * 4]], 2, 2, 8, mv[1], 4);

            fill_rectangle(&sl->ref_cache[0][scan8[i8 * 4]], 2, 2, 8,

                           (uint8_t)ref[0], 1);

            fill_rectangle(&sl->ref_cache[1][scan8[i8 * 4]], 2, 2, 8,

                           (uint8_t)ref[1], 1);

            assert(b8_stride == 2);

            /* col_zero_flag */

            if (!IS_INTRA(mb_type_col[0]) && !sl->ref_list[1][0].parent->long_ref &&

                (l1ref0[i8] == 0 ||

                 (l1ref0[i8] < 0 &&

                  l1ref1[i8] == 0 &&

                  h->x264_build > 33U))) {

                const int16_t (*l1mv)[2] = l1ref0[i8] == 0 ? l1mv0 : l1mv1;

                if (IS_SUB_8X8(sub_mb_type)) {

                    const int16_t *mv_col = l1mv[x8 * 3 + y8 * 3 * b4_stride];

                    if (FFABS(mv_col[0]) <= 1 && FFABS(mv_col[1]) <= 1) {

                        if (ref[0] == 0)

                            fill_rectangle(&sl->mv_cache[0][scan8[i8 * 4]], 2, 2,

                                           8, 0, 4);

                        if (ref[1] == 0)

                            fill_rectangle(&sl->mv_cache[1][scan8[i8 * 4]], 2, 2,

                                           8, 0, 4);

                        n += 4;

                    }

                } else {

                    int m = 0;

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

                        const int16_t *mv_col = l1mv[x8 * 2 + (i4 & 1) +

                                                     (y8 * 2 + (i4 >> 1)) * b4_stride];

                        if (FFABS(mv_col[0]) <= 1 && FFABS(mv_col[1]) <= 1) {

                            if (ref[0] == 0)

                                AV_ZERO32(sl->mv_cache[0][scan8[i8 * 4 + i4]]);

                            if (ref[1] == 0)

                                AV_ZERO32(sl->mv_cache[1][scan8[i8 * 4 + i4]]);

                            m++;

                        }

                    }

                    if (!(m & 3))

                        sl->sub_mb_type[i8] += MB_TYPE_16x16 - MB_TYPE_8x8;

                    n += m;

                }

            }

        }

        if (!is_b8x8 && !(n & 15))

            *mb_type = (*mb_type & ~(MB_TYPE_8x8 | MB_TYPE_16x8 | MB_TYPE_8x16 |

                                     MB_TYPE_P1L0 | MB_TYPE_P1L1)) |

                       MB_TYPE_16x16 | MB_TYPE_DIRECT2;

    }

}


static void gem_write(void *opaque, target_phys_addr_t offset, uint64_t val,

        unsigned size)

{

    GemState *s = (GemState *)opaque;

    uint32_t readonly;

    DB_PRINT("offset: 0x%04x write: 0x%08x ", offset, (unsigned)val);

    offset >>= 2;

    /* Squash bits which are read only in write value */

    val &= ~(s->regs_ro[offset]);

    /* Preserve (only) bits which are read only in register */

    readonly = s->regs[offset];

    readonly &= s->regs_ro[offset];

    /* Squash bits which are write 1 to clear */

    val &= ~(s->regs_w1c[offset] & val);

    /* Copy register write to backing store */

    s->regs[offset] = val | readonly;

    /* Handle register write side effects */

    switch (offset) {

    case GEM_NWCTRL:

        if (val & GEM_NWCTRL_TXSTART) {

            gem_transmit(s);

        }

        if (!(val & GEM_NWCTRL_TXENA)) {

            /* Reset to start of Q when transmit disabled. */

            s->tx_desc_addr = s->regs[GEM_TXQBASE];

        }

        if (!(val & GEM_NWCTRL_RXENA)) {

            /* Reset to start of Q when receive disabled. */

            s->rx_desc_addr = s->regs[GEM_RXQBASE];

        }

        break;

    case GEM_TXSTATUS:

        gem_update_int_status(s);

        break;

    case GEM_RXQBASE:

        s->rx_desc_addr = val;

        break;

    case GEM_TXQBASE:

        s->tx_desc_addr = val;

        break;

    case GEM_RXSTATUS:

        gem_update_int_status(s);

        break;

    case GEM_IER:

        s->regs[GEM_IMR] &= ~val;

        gem_update_int_status(s);

        break;

    case GEM_IDR:

        s->regs[GEM_IMR] |= val;

        gem_update_int_status(s);

        break;

    case GEM_PHYMNTNC:

        if (val & GEM_PHYMNTNC_OP_W) {

            uint32_t phy_addr, reg_num;

            phy_addr = (val & GEM_PHYMNTNC_ADDR) >> GEM_PHYMNTNC_ADDR_SHFT;

            if (phy_addr == BOARD_PHY_ADDRESS) {

                reg_num = (val & GEM_PHYMNTNC_REG) >> GEM_PHYMNTNC_REG_SHIFT;

                gem_phy_write(s, reg_num, val);

            }

        }

        break;

    }

    DB_PRINT("newval: 0x%08x\n", s->regs[offset]);

}


void cpu_loop(CPUMIPSState *env)

{

    target_siginfo_t info;

    int trapnr, ret;

    unsigned int syscall_num;

    for(;;) {

        trapnr = cpu_mips_exec(env);

        switch(trapnr) {

        case EXCP_SYSCALL:

            syscall_num = env->active_tc.gpr[2] - 4000;

            env->active_tc.PC += 4;

            if (syscall_num >= sizeof(mips_syscall_args)) {

                ret = -ENOSYS;

            } else {

                int nb_args;

                abi_ulong sp_reg;

                abi_ulong arg5 = 0, arg6 = 0, arg7 = 0, arg8 = 0;

                nb_args = mips_syscall_args[syscall_num];

                sp_reg = env->active_tc.gpr[29];

                switch (nb_args) {

                /* these arguments are taken from the stack */

                /* FIXME - what to do if get_user() fails? */

                case 8: get_user_ual(arg8, sp_reg + 28);

                case 7: get_user_ual(arg7, sp_reg + 24);

                case 6: get_user_ual(arg6, sp_reg + 20);

                case 5: get_user_ual(arg5, sp_reg + 16);

                default:

                ret = do_syscall(env, env->active_tc.gpr[2],

                                 env->active_tc.gpr[4],

                                 env->active_tc.gpr[5],

                                 env->active_tc.gpr[6],

                                 env->active_tc.gpr[7],

                                 arg5, arg6/*, arg7, arg8*/);

            if ((unsigned int)ret >= (unsigned int)(-1133)) {

                env->active_tc.gpr[7] = 1; /* error flag */

                ret = -ret;

            } else {

                env->active_tc.gpr[7] = 0; /* error flag */

            env->active_tc.gpr[2] = ret;

        case EXCP_TLBL:

        case EXCP_TLBS:

            info.si_signo = TARGET_SIGSEGV;

            info.si_errno = 0;

            /* XXX: check env->error_code */

            info.si_code = TARGET_SEGV_MAPERR;

            info._sifields._sigfault._addr = env->CP0_BadVAddr;

            queue_signal(env, info.si_signo, &info);

        case EXCP_CpU:

        case EXCP_RI:

            info.si_signo = TARGET_SIGILL;

            info.si_errno = 0;

            info.si_code = 0;

            queue_signal(env, info.si_signo, &info);

        case EXCP_INTERRUPT:

            /* just indicate that signals should be handled asap */

        case EXCP_DEBUG:

            {

                int sig;

                sig = gdb_handlesig (env, TARGET_SIGTRAP);

                if (sig)

                  {

                    info.si_signo = sig;

                    info.si_errno = 0;

                    info.si_code = TARGET_TRAP_BRKPT;

                    queue_signal(env, info.si_signo, &info);

        default:

            //        error:

            fprintf(stderr, "qemu: unhandled CPU exception 0x%x - aborting\n",

                    trapnr);

            cpu_dump_state(env, stderr, fprintf, 0);

            abort();

        process_pending_signals(env);


static int tmv_read_seek(AVFormatContext *s, int stream_index,

                         int64_t timestamp, int flags)

{

    TMVContext *tmv = s->priv_data;

    int64_t pos;

    if (stream_index)

        return -1;

    pos = timestamp *

          (tmv->audio_chunk_size + tmv->video_chunk_size + tmv->padding);

    avio_seek(s->pb, pos + TMV_HEADER_SIZE, SEEK_SET);

    tmv->stream_index = 0;

    return 0;

}


static void bonito_ldma_writel(void *opaque, hwaddr addr,
                               uint64_t val, unsigned size)
{
    PCIBonitoState *s = opaque;
    ((uint32_t *)(&s->bonldma))[addr/sizeof(uint32_t)] = val & 0xffffffff;


static int jpeg2000_decode_packet(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile, int *tp_index,

                                  Jpeg2000CodingStyle *codsty,

                                  Jpeg2000ResLevel *rlevel, int precno,

                                  int layno, uint8_t *expn, int numgbits)

{

    int bandno, cblkno, ret, nb_code_blocks;

    int cwsno;

    if (layno < rlevel->band[0].prec[precno].decoded_layers)

        return 0;

    rlevel->band[0].prec[precno].decoded_layers = layno + 1;

    if (bytestream2_get_bytes_left(&s->g) == 0 && s->bit_index == 8) {

        if (*tp_index < FF_ARRAY_ELEMS(tile->tile_part) - 1) {

            s->g = tile->tile_part[++(*tp_index)].tpg;

        }

    }

    if (bytestream2_peek_be32(&s->g) == JPEG2000_SOP_FIXED_BYTES)

        bytestream2_skip(&s->g, JPEG2000_SOP_BYTE_LENGTH);

    if (!(ret = get_bits(s, 1))) {

        jpeg2000_flush(s);

        return 0;

    } else if (ret < 0)

        return ret;

    for (bandno = 0; bandno < rlevel->nbands; bandno++) {

        Jpeg2000Band *band = rlevel->band + bandno;

        Jpeg2000Prec *prec = band->prec + precno;

        if (band->coord[0][0] == band->coord[0][1] ||

            band->coord[1][0] == band->coord[1][1])

            continue;

        nb_code_blocks =  prec->nb_codeblocks_height *

                          prec->nb_codeblocks_width;

        for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {

            Jpeg2000Cblk *cblk = prec->cblk + cblkno;

            int incl, newpasses, llen;

            if (cblk->npasses)

                incl = get_bits(s, 1);

            else

                incl = tag_tree_decode(s, prec->cblkincl + cblkno, layno + 1) == layno;

            if (!incl)

                continue;

            else if (incl < 0)

                return incl;

            if (!cblk->npasses) {

                int v = expn[bandno] + numgbits - 1 -

                        tag_tree_decode(s, prec->zerobits + cblkno, 100);

                if (v < 0 || v > 30) {

                    av_log(s->avctx, AV_LOG_ERROR,

                           "nonzerobits %d invalid or unsupported\n", v);

                    return AVERROR_INVALIDDATA;

                }

                cblk->nonzerobits = v;

            }

            if ((newpasses = getnpasses(s)) < 0)

                return newpasses;

            av_assert2(newpasses > 0);

            if (cblk->npasses + newpasses >= JPEG2000_MAX_PASSES) {

                avpriv_request_sample(s->avctx, "Too many passes");

                return AVERROR_PATCHWELCOME;

            }

            if ((llen = getlblockinc(s)) < 0)

                return llen;

            if (cblk->lblock + llen + av_log2(newpasses) > 16) {

                avpriv_request_sample(s->avctx,

                                      "Block with length beyond 16 bits");

                return AVERROR_PATCHWELCOME;

            }

            cblk->lblock += llen;

            cblk->nb_lengthinc = 0;

            cblk->nb_terminationsinc = 0;

            do {

                int newpasses1 = 0;

                while (newpasses1 < newpasses) {

                    newpasses1 ++;

                    if (needs_termination(codsty->cblk_style, cblk->npasses + newpasses1 - 1)) {

                        cblk->nb_terminationsinc ++;

                        break;

                    }

                }

                if ((ret = get_bits(s, av_log2(newpasses1) + cblk->lblock)) < 0)

                    return ret;

                if (ret > sizeof(cblk->data)) {

                    avpriv_request_sample(s->avctx,

                                        "Block with lengthinc greater than %"SIZE_SPECIFIER"",

                                        sizeof(cblk->data));

                    return AVERROR_PATCHWELCOME;

                }

                cblk->lengthinc[cblk->nb_lengthinc++] = ret;

                cblk->npasses  += newpasses1;

                newpasses -= newpasses1;

            } while(newpasses);

        }

    }

    jpeg2000_flush(s);

    if (codsty->csty & JPEG2000_CSTY_EPH) {

        if (bytestream2_peek_be16(&s->g) == JPEG2000_EPH)

            bytestream2_skip(&s->g, 2);

        else

            av_log(s->avctx, AV_LOG_ERROR, "EPH marker not found. instead %X\n", bytestream2_peek_be32(&s->g));

    }

    for (bandno = 0; bandno < rlevel->nbands; bandno++) {

        Jpeg2000Band *band = rlevel->band + bandno;

        Jpeg2000Prec *prec = band->prec + precno;

        nb_code_blocks = prec->nb_codeblocks_height * prec->nb_codeblocks_width;

        for (cblkno = 0; cblkno < nb_code_blocks; cblkno++) {

            Jpeg2000Cblk *cblk = prec->cblk + cblkno;

            for (cwsno = 0; cwsno < cblk->nb_lengthinc; cwsno ++) {

                if (   bytestream2_get_bytes_left(&s->g) < cblk->lengthinc[cwsno]

                    || sizeof(cblk->data) < cblk->length + cblk->lengthinc[cwsno] + 4

                ) {

                    av_log(s->avctx, AV_LOG_ERROR,

                        "Block length %"PRIu16" or lengthinc %d is too large, left %d\n",

                        cblk->length, cblk->lengthinc[cwsno], bytestream2_get_bytes_left(&s->g));

                    return AVERROR_INVALIDDATA;

                }

                bytestream2_get_bufferu(&s->g, cblk->data + cblk->length, cblk->lengthinc[cwsno]);

                cblk->length   += cblk->lengthinc[cwsno];

                cblk->lengthinc[cwsno] = 0;

                if (cblk->nb_terminationsinc) {

                    cblk->nb_terminationsinc--;

                    cblk->nb_terminations++;

                    cblk->data[cblk->length++] = 0xFF;

                    cblk->data[cblk->length++] = 0xFF;

                    cblk->data_start[cblk->nb_terminations] = cblk->length;

                }

            }

        }

    }

    return 0;

}


static void curses_refresh(DisplayChangeListener *dcl)

{

    int chr, nextchr, keysym, keycode, keycode_alt;

    curses_winch_check();

    if (invalidate) {

        clear();

        refresh();

        curses_calc_pad();

        graphic_hw_invalidate(NULL);

        invalidate = 0;

    }

    graphic_hw_text_update(NULL, screen);

    nextchr = ERR;

    while (1) {

        /* while there are any pending key strokes to process */

        if (nextchr == ERR)

            chr = getch();

        else {

            chr = nextchr;

            nextchr = ERR;

        }

        if (chr == ERR)

            break;

#ifdef KEY_RESIZE

        /* this shouldn't occur when we use a custom SIGWINCH handler */

        if (chr == KEY_RESIZE) {

            clear();

            refresh();

            curses_calc_pad();

            curses_update(dcl, 0, 0, width, height);

            continue;

        }

#endif

        keycode = curses2keycode[chr];

        keycode_alt = 0;

        /* alt key */

        if (keycode == 1) {

            nextchr = getch();

            if (nextchr != ERR) {

                chr = nextchr;

                keycode_alt = ALT;

                keycode = curses2keycode[nextchr];

                nextchr = ERR;

                if (keycode != -1) {

                    keycode |= ALT;

                    /* process keys reserved for qemu */

                    if (keycode >= QEMU_KEY_CONSOLE0 &&

                            keycode < QEMU_KEY_CONSOLE0 + 9) {

                        erase();

                        wnoutrefresh(stdscr);

                        console_select(keycode - QEMU_KEY_CONSOLE0);

                        invalidate = 1;

                        continue;

                    }

                }

            }

        }

        if (kbd_layout) {

            keysym = -1;

            if (chr < CURSES_KEYS)

                keysym = curses2keysym[chr];

            if (keysym == -1) {

                if (chr < ' ') {

                    keysym = chr + '@';

                    if (keysym >= 'A' && keysym <= 'Z')

                        keysym += 'a' - 'A';

                    keysym |= KEYSYM_CNTRL;

                } else

                    keysym = chr;

            }

            keycode = keysym2scancode(kbd_layout, keysym & KEYSYM_MASK);

            if (keycode == 0)

                continue;

            keycode |= (keysym & ~KEYSYM_MASK) >> 16;

            keycode |= keycode_alt;

        }

        if (keycode == -1)

            continue;

        if (qemu_console_is_graphic(NULL)) {

            /* since terminals don't know about key press and release

             * events, we need to emit both for each key received */

            if (keycode & SHIFT) {

                qemu_input_event_send_key_number(NULL, SHIFT_CODE, true);

                qemu_input_event_send_key_delay(0);

            }

            if (keycode & CNTRL) {

                qemu_input_event_send_key_number(NULL, CNTRL_CODE, true);

                qemu_input_event_send_key_delay(0);

            }

            if (keycode & ALT) {

                qemu_input_event_send_key_number(NULL, ALT_CODE, true);

                qemu_input_event_send_key_delay(0);

            }

            if (keycode & ALTGR) {

                qemu_input_event_send_key_number(NULL, GREY | ALT_CODE, true);

                qemu_input_event_send_key_delay(0);

            }

            qemu_input_event_send_key_number(NULL, keycode & KEY_MASK, true);

            qemu_input_event_send_key_delay(0);

            qemu_input_event_send_key_number(NULL, keycode & KEY_MASK, false);

            qemu_input_event_send_key_delay(0);

            if (keycode & ALTGR) {

                qemu_input_event_send_key_number(NULL, GREY | ALT_CODE, false);

                qemu_input_event_send_key_delay(0);

            }

            if (keycode & ALT) {

                qemu_input_event_send_key_number(NULL, ALT_CODE, false);

                qemu_input_event_send_key_delay(0);

            }

            if (keycode & CNTRL) {

                qemu_input_event_send_key_number(NULL, CNTRL_CODE, false);

                qemu_input_event_send_key_delay(0);

            }

            if (keycode & SHIFT) {

                qemu_input_event_send_key_number(NULL, SHIFT_CODE, false);

                qemu_input_event_send_key_delay(0);

            }

        } else {

            keysym = curses2qemu[chr];

            if (keysym == -1)

                keysym = chr;

            kbd_put_keysym(keysym);

        }

    }

}


static int64_t read_ts(char **line, int *duration)

{

    int64_t start, end;

    if (sscanf(*line, "%"SCNd64",%"SCNd64, &start, &end) == 2) {

        *line += strcspn(*line, "\"") + 1;

        *duration = end - start;

        return start;

    }

    return AV_NOPTS_VALUE;

}


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

{

    PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);

    DeviceClass *dc = DEVICE_CLASS(klass);

    k->init = raven_init;

    k->vendor_id = PCI_VENDOR_ID_MOTOROLA;

    k->device_id = PCI_DEVICE_ID_MOTOROLA_RAVEN;

    k->revision = 0x00;

    k->class_id = PCI_CLASS_BRIDGE_HOST;

    dc->desc = "PReP Host Bridge - Motorola Raven";

    dc->vmsd = &vmstate_raven;

    dc->no_user = 1;

}


static void pci_add_option_rom(PCIDevice *pdev, bool is_default_rom,

                               Error **errp)

{

    int size;

    char *path;

    void *ptr;

    char name[32];

    const VMStateDescription *vmsd;

    if (!pdev->romfile)

        return;

    if (strlen(pdev->romfile) == 0)

        return;

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

        /*

         * Hot-plugged devices can't use the option ROM

         * if the rom bar is disabled.

         */

        if (DEVICE(pdev)->hotplugged) {

            error_setg(errp, "Hot-plugged device without ROM bar"

                       " can't have an option ROM");

            return;

        }

        if (class == 0x0300) {

            rom_add_vga(pdev->romfile);

        } else {

            rom_add_option(pdev->romfile, -1);

        }

        return;

    }

    path = qemu_find_file(QEMU_FILE_TYPE_BIOS, pdev->romfile);

    if (path == NULL) {

        path = g_strdup(pdev->romfile);

    }

    size = get_image_size(path);

    if (size < 0) {

        error_setg(errp, "failed to find romfile \"%s\"", pdev->romfile);

        g_free(path);

        return;

    } else if (size == 0) {

        error_setg(errp, "romfile \"%s\" is empty", pdev->romfile);

        g_free(path);

        return;

    }

    size = pow2ceil(size);

    vmsd = qdev_get_vmsd(DEVICE(pdev));

    if (vmsd) {

        snprintf(name, sizeof(name), "%s.rom", vmsd->name);

    } else {

        snprintf(name, sizeof(name), "%s.rom", object_get_typename(OBJECT(pdev)));

    }

    pdev->has_rom = true;

    memory_region_init_ram(&pdev->rom, OBJECT(pdev), name, size, &error_abort);

    vmstate_register_ram(&pdev->rom, &pdev->qdev);

    ptr = memory_region_get_ram_ptr(&pdev->rom);

    load_image(path, ptr);

    g_free(path);

    if (is_default_rom) {

        /* Only the default rom images will be patched (if needed). */

        pci_patch_ids(pdev, ptr, size);

    }

    pci_register_bar(pdev, PCI_ROM_SLOT, 0, &pdev->rom);

}


static void mov_write_uuidprof_tag(AVIOContext *pb, AVFormatContext *s)

{

    AVStream       *video_st    = s->streams[0];

    AVCodecParameters *video_par = s->streams[0]->codecpar;

    AVCodecParameters *audio_par = s->streams[1]->codecpar;

    int audio_rate = audio_par->sample_rate;

    // TODO: should be avg_frame_rate

    int frame_rate = ((video_st->time_base.den) * (0x10000)) / (video_st->time_base.num);

    int audio_kbitrate = audio_par->bit_rate / 1000;

    int video_kbitrate = FFMIN(video_par->bit_rate / 1000, 800 - audio_kbitrate);

    avio_wb32(pb, 0x94); /* size */

    ffio_wfourcc(pb, "uuid");

    ffio_wfourcc(pb, "PROF");

    avio_wb32(pb, 0x21d24fce); /* 96 bit UUID */

    avio_wb32(pb, 0xbb88695c);

    avio_wb32(pb, 0xfac9c740);

    avio_wb32(pb, 0x0);  /* ? */

    avio_wb32(pb, 0x3);  /* 3 sections ? */

    avio_wb32(pb, 0x14); /* size */

    ffio_wfourcc(pb, "FPRF");

    avio_wb32(pb, 0x0);  /* ? */

    avio_wb32(pb, 0x0);  /* ? */

    avio_wb32(pb, 0x0);  /* ? */

    avio_wb32(pb, 0x2c);  /* size */

    ffio_wfourcc(pb, "APRF"); /* audio */

    avio_wb32(pb, 0x0);

    avio_wb32(pb, 0x2);   /* TrackID */

    ffio_wfourcc(pb, "mp4a");

    avio_wb32(pb, 0x20f);

    avio_wb32(pb, 0x0);

    avio_wb32(pb, audio_kbitrate);

    avio_wb32(pb, audio_kbitrate);

    avio_wb32(pb, audio_rate);

    avio_wb32(pb, audio_par->channels);

    avio_wb32(pb, 0x34);  /* size */

    ffio_wfourcc(pb, "VPRF");   /* video */

    avio_wb32(pb, 0x0);

    avio_wb32(pb, 0x1);    /* TrackID */

    if (video_par->codec_id == AV_CODEC_ID_H264) {

        ffio_wfourcc(pb, "avc1");

        avio_wb16(pb, 0x014D);

        avio_wb16(pb, 0x0015);

    } else {

        ffio_wfourcc(pb, "mp4v");

        avio_wb16(pb, 0x0000);

        avio_wb16(pb, 0x0103);

    }

    avio_wb32(pb, 0x0);

    avio_wb32(pb, video_kbitrate);

    avio_wb32(pb, video_kbitrate);

    avio_wb32(pb, frame_rate);

    avio_wb32(pb, frame_rate);

    avio_wb16(pb, video_par->width);

    avio_wb16(pb, video_par->height);

    avio_wb32(pb, 0x010001); /* ? */

}


static char *spapr_phb_vfio_get_loc_code(sPAPRPHBState *sphb,  PCIDevice *pdev)

{

    char *path = NULL, *buf = NULL, *host = NULL;

    /* Get the PCI VFIO host id */

    host = object_property_get_str(OBJECT(pdev), "host", NULL);

    if (!host) {

        goto err_out;

    }

    /* Construct the path of the file that will give us the DT location */

    path = g_strdup_printf("/sys/bus/pci/devices/%s/devspec", host);

    g_free(host);

    if (!path || !g_file_get_contents(path, &buf, NULL, NULL)) {

        goto err_out;

    }

    g_free(path);

    /* Construct and read from host device tree the loc-code */

    path = g_strdup_printf("/proc/device-tree%s/ibm,loc-code", buf);

    g_free(buf);

    if (!path || !g_file_get_contents(path, &buf, NULL, NULL)) {

        goto err_out;

    }

    return buf;

err_out:

    g_free(path);

    return NULL;

}


static inline void yuv2nv12XinC(int16_t *lumFilter, int16_t **lumSrc, int lumFilterSize,

                                int16_t *chrFilter, int16_t **chrSrc, int chrFilterSize,

                                uint8_t *dest, uint8_t *uDest, int dstW, int chrDstW, int dstFormat)

{

    //FIXME Optimize (just quickly writen not opti..)

    int i;

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

    {

        int val=1<<18;

        int j;

        for (j=0; j<lumFilterSize; j++)

            val += lumSrc[j][i] * lumFilter[j];

        dest[i]= av_clip_uint8(val>>19);

    }

    if (!uDest)

        return;

    if (dstFormat == PIX_FMT_NV12)

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

        {

            int u=1<<18;

            int v=1<<18;

            int j;

            for (j=0; j<chrFilterSize; j++)

            {

                u += chrSrc[j][i] * chrFilter[j];

                v += chrSrc[j][i + 2048] * chrFilter[j];

            }

            uDest[2*i]= av_clip_uint8(u>>19);

            uDest[2*i+1]= av_clip_uint8(v>>19);

        }

    else

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

        {

            int u=1<<18;

            int v=1<<18;

            int j;

            for (j=0; j<chrFilterSize; j++)

            {

                u += chrSrc[j][i] * chrFilter[j];

                v += chrSrc[j][i + 2048] * chrFilter[j];

            }

            uDest[2*i]= av_clip_uint8(v>>19);

            uDest[2*i+1]= av_clip_uint8(u>>19);

        }

}


static void nvme_process_db(NvmeCtrl *n, hwaddr addr, int val)

{

    uint32_t qid;

    if (addr & ((1 << 2) - 1)) {

        return;

    }

    if (((addr - 0x1000) >> 2) & 1) {

        uint16_t new_head = val & 0xffff;

        int start_sqs;

        NvmeCQueue *cq;

        qid = (addr - (0x1000 + (1 << 2))) >> 3;

        if (nvme_check_cqid(n, qid)) {

            return;

        }

        cq = n->cq[qid];

        if (new_head >= cq->size) {

            return;

        }

        start_sqs = nvme_cq_full(cq) ? 1 : 0;

        cq->head = new_head;

        if (start_sqs) {

            NvmeSQueue *sq;

            QTAILQ_FOREACH(sq, &cq->sq_list, entry) {

                timer_mod(sq->timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + 500);

            }

            timer_mod(cq->timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + 500);

        }

        if (cq->tail != cq->head) {

            nvme_isr_notify(n, cq);

        }

    } else {

        uint16_t new_tail = val & 0xffff;

        NvmeSQueue *sq;

        qid = (addr - 0x1000) >> 3;

        if (nvme_check_sqid(n, qid)) {

            return;

        }

        sq = n->sq[qid];

        if (new_tail >= sq->size) {

            return;

        }

        sq->tail = new_tail;

        timer_mod(sq->timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + 500);

    }

}


static void gen_storeq_reg(DisasContext *s, int rlow, int rhigh, TCGv_i64 val)

{

    TCGv tmp;

    tmp = new_tmp();

    tcg_gen_trunc_i64_i32(tmp, val);

    store_reg(s, rlow, tmp);

    tmp = new_tmp();

    tcg_gen_shri_i64(val, val, 32);

    tcg_gen_trunc_i64_i32(tmp, val);

    store_reg(s, rhigh, tmp);

}


static int ccid_bulk_in_copy_to_guest(USBCCIDState *s, uint8_t *data, int len)

{

    int ret = 0;

    assert(len > 0);

    ccid_bulk_in_get(s);

    if (s->current_bulk_in != NULL) {

        ret = MIN(s->current_bulk_in->len - s->current_bulk_in->pos, len);

        memcpy(data, s->current_bulk_in->data + s->current_bulk_in->pos, ret);

        s->current_bulk_in->pos += ret;

        if (s->current_bulk_in->pos == s->current_bulk_in->len) {

            ccid_bulk_in_release(s);

        }

    } else {

        /* return when device has no data - usb 2.0 spec Table 8-4 */

        ret = USB_RET_NAK;

    }

    if (ret > 0) {

        DPRINTF(s, D_MORE_INFO,

                "%s: %d/%d req/act to guest (BULK_IN)\n", __func__, len, ret);

    }

    if (ret != USB_RET_NAK && ret < len) {

        DPRINTF(s, 1,

            "%s: returning short (EREMOTEIO) %d < %d\n", __func__, ret, len);

    }

    return ret;

}


static void lms_update(WmallDecodeCtx *s, int ich, int ilms, int16_t input, int16_t pred)

{

    int16_t icoef;

    int recent = s->cdlms[ich][ilms].recent;

    int16_t range = 1 << (s->bits_per_sample - 1);

    int bps = s->bits_per_sample > 16 ? 4 : 2; // bytes per sample

    if (input > pred) {

        for (icoef = 0; icoef < s->cdlms[ich][ilms].order; icoef++)

            s->cdlms[ich][ilms].coefs[icoef] +=

                s->cdlms[ich][ilms].lms_updates[icoef + recent];

    } else {

        for (icoef = 0; icoef < s->cdlms[ich][ilms].order; icoef++)

            s->cdlms[ich][ilms].coefs[icoef] -=

                s->cdlms[ich][ilms].lms_updates[icoef];     // XXX: [icoef + recent] ?

    }

    s->cdlms[ich][ilms].recent--;

    s->cdlms[ich][ilms].lms_prevvalues[recent] = av_clip(input, -range, range - 1);

    if (input > pred)

        s->cdlms[ich][ilms].lms_updates[recent] = s->update_speed[ich];

    else if (input < pred)

        s->cdlms[ich][ilms].lms_updates[recent] = -s->update_speed[ich];

    /* XXX: spec says:

    cdlms[iCh][ilms].updates[iRecent + cdlms[iCh][ilms].order >> 4] >>= 2;

    lms_updates[iCh][ilms][iRecent + cdlms[iCh][ilms].order >> 3] >>= 1;

        Questions is - are cdlms[iCh][ilms].updates[] and lms_updates[][][] two

        seperate buffers? Here I've assumed that the two are same which makes

        more sense to me.

    */

    s->cdlms[ich][ilms].lms_updates[recent + s->cdlms[ich][ilms].order >> 4] >>= 2;

    s->cdlms[ich][ilms].lms_updates[recent + s->cdlms[ich][ilms].order >> 3] >>= 1;

    /* XXX: recent + (s->cdlms[ich][ilms].order >> 4) ? */

    if (s->cdlms[ich][ilms].recent == 0) {

        /* XXX: This memcpy()s will probably fail if a fixed 32-bit buffer is used.

                follow kshishkov's suggestion of using a union. */

        memcpy(s->cdlms[ich][ilms].lms_prevvalues + s->cdlms[ich][ilms].order,

               s->cdlms[ich][ilms].lms_prevvalues,

               bps * s->cdlms[ich][ilms].order);

        memcpy(s->cdlms[ich][ilms].lms_updates + s->cdlms[ich][ilms].order,

               s->cdlms[ich][ilms].lms_updates,

               bps * s->cdlms[ich][ilms].order);

        s->cdlms[ich][ilms].recent = s->cdlms[ich][ilms].order;

    }

}


static int create_filter(AVFilterContext **filt_ctx, AVFilterGraph *ctx, int index,

                         const char *filt_name, const char *args, AVClass *log_ctx)

{

    AVFilter *filt;

    char inst_name[30];

    char tmp_args[256];

    int ret;

    snprintf(inst_name, sizeof(inst_name), "Parsed filter %d %s", index, filt_name);

    filt = avfilter_get_by_name(filt_name);

    if (!filt) {

        av_log(log_ctx, AV_LOG_ERROR,

               "No such filter: '%s'\n", filt_name);

        return AVERROR(EINVAL);

    }

    ret = avfilter_open(filt_ctx, filt, inst_name);

    if (!*filt_ctx) {

        av_log(log_ctx, AV_LOG_ERROR,

               "Error creating filter '%s'\n", filt_name);

        return ret;

    }

    if ((ret = avfilter_graph_add_filter(ctx, *filt_ctx)) < 0) {

        avfilter_free(*filt_ctx);

        return ret;

    }

    if (!strcmp(filt_name, "scale") && !strstr(args, "flags")) {

        snprintf(tmp_args, sizeof(tmp_args), "%s:%s",

                 args, ctx->scale_sws_opts);

        args = tmp_args;

    }

    if ((ret = avfilter_init_filter(*filt_ctx, args, NULL)) < 0) {

        av_log(log_ctx, AV_LOG_ERROR,

               "Error initializing filter '%s' with args '%s'\n", filt_name, args);

        return ret;

    }

    return 0;

}


static void decode_mclms(WmallDecodeCtx *s)

{

    s->mclms_order = (get_bits(&s->gb, 4) + 1) * 2;

    s->mclms_scaling = get_bits(&s->gb, 4);

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

	// mclms_send_coef

	int i;

	int send_coef_bits;

	int cbits = av_log2(s->mclms_scaling + 1);

	assert(cbits == my_log2(s->mclms_scaling + 1));

	if(1 << cbits < s->mclms_scaling + 1)

	    cbits++;

	send_coef_bits = (cbits ? get_bits(&s->gb, cbits) : 0) + 2;

	for(i = 0; i < s->mclms_order * s->num_channels * s->num_channels; i++) {

	    s->mclms_coeffs[i] = get_bits(&s->gb, send_coef_bits);

	}

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

	    int c;

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

		s->mclms_coeffs_cur[i * s->num_channels + c] = get_bits(&s->gb, send_coef_bits);

	    }

	}

    }

}


static void ppc_spapr_init(ram_addr_t ram_size,
                           const char *boot_device,
                           const char *kernel_filename,
                           const char *kernel_cmdline,
                           const char *initrd_filename,
                           const char *cpu_model)
{
    PowerPCCPU *cpu;
    CPUPPCState *env;
    int i;
    MemoryRegion *sysmem = get_system_memory();
    MemoryRegion *ram = g_new(MemoryRegion, 1);
    target_phys_addr_t rma_alloc_size, rma_size;
    uint32_t initrd_base = 0;
    long kernel_size = 0, initrd_size = 0;
    long load_limit, rtas_limit, fw_size;
    long pteg_shift = 17;
    char *filename;
    spapr = g_malloc0(sizeof(*spapr));
    QLIST_INIT(&spapr->phbs);
    cpu_ppc_hypercall = emulate_spapr_hypercall;
    /* Allocate RMA if necessary */
    rma_alloc_size = kvmppc_alloc_rma("ppc_spapr.rma", sysmem);
    if (rma_alloc_size == -1) {
        hw_error("qemu: Unable to create RMA\n");
        exit(1);
    }
    if (rma_alloc_size && (rma_alloc_size < ram_size)) {
        rma_size = rma_alloc_size;
    } else {
        rma_size = ram_size;
    }
    /* We place the device tree and RTAS just below either the top of the RMA,
     * or just below 2GB, whichever is lowere, so that it can be
     * processed with 32-bit real mode code if necessary */
    rtas_limit = MIN(rma_size, 0x80000000);
    spapr->rtas_addr = rtas_limit - RTAS_MAX_SIZE;
    spapr->fdt_addr = spapr->rtas_addr - FDT_MAX_SIZE;
    load_limit = spapr->fdt_addr - FW_OVERHEAD;
    /* init CPUs */
    if (cpu_model == NULL) {
        cpu_model = kvm_enabled() ? "host" : "POWER7";
    }
    for (i = 0; i < smp_cpus; i++) {
        cpu = cpu_ppc_init(cpu_model);
        if (cpu == NULL) {
            fprintf(stderr, "Unable to find PowerPC CPU definition\n");
            exit(1);
        }
        env = &cpu->env;
        /* Set time-base frequency to 512 MHz */
        cpu_ppc_tb_init(env, TIMEBASE_FREQ);
        qemu_register_reset(spapr_cpu_reset, cpu);
        env->hreset_vector = 0x60;
        env->hreset_excp_prefix = 0;
        env->gpr[3] = env->cpu_index;
    }
    /* allocate RAM */
    spapr->ram_limit = ram_size;
    if (spapr->ram_limit > rma_alloc_size) {
        ram_addr_t nonrma_base = rma_alloc_size;
        ram_addr_t nonrma_size = spapr->ram_limit - rma_alloc_size;
        memory_region_init_ram(ram, "ppc_spapr.ram", nonrma_size);
        vmstate_register_ram_global(ram);
        memory_region_add_subregion(sysmem, nonrma_base, ram);
    }
    /* allocate hash page table.  For now we always make this 16mb,
     * later we should probably make it scale to the size of guest
     * RAM */
    spapr->htab_size = 1ULL << (pteg_shift + 7);
    spapr->htab = qemu_memalign(spapr->htab_size, spapr->htab_size);
    for (env = first_cpu; env != NULL; env = env->next_cpu) {
        env->external_htab = spapr->htab;
        env->htab_base = -1;
        env->htab_mask = spapr->htab_size - 1;
        /* Tell KVM that we're in PAPR mode */
        env->spr[SPR_SDR1] = (unsigned long)spapr->htab |
                             ((pteg_shift + 7) - 18);
        env->spr[SPR_HIOR] = 0;
        if (kvm_enabled()) {
            kvmppc_set_papr(env);
        }
    }
    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, "spapr-rtas.bin");
    spapr->rtas_size = load_image_targphys(filename, spapr->rtas_addr,
                                           rtas_limit - spapr->rtas_addr);
    if (spapr->rtas_size < 0) {
        hw_error("qemu: could not load LPAR rtas '%s'\n", filename);
        exit(1);
    }
    if (spapr->rtas_size > RTAS_MAX_SIZE) {
        hw_error("RTAS too big ! 0x%lx bytes (max is 0x%x)\n",
                 spapr->rtas_size, RTAS_MAX_SIZE);
        exit(1);
    }
    g_free(filename);
    /* Set up Interrupt Controller */
    spapr->icp = xics_system_init(XICS_IRQS);
    spapr->next_irq = 16;
    /* Set up VIO bus */
    spapr->vio_bus = spapr_vio_bus_init();
    for (i = 0; i < MAX_SERIAL_PORTS; i++) {
        if (serial_hds[i]) {
            spapr_vty_create(spapr->vio_bus, serial_hds[i]);
        }
    }
    /* Set up PCI */
    spapr_create_phb(spapr, "pci", SPAPR_PCI_BUID,
                     SPAPR_PCI_MEM_WIN_ADDR,
                     SPAPR_PCI_MEM_WIN_SIZE,
                     SPAPR_PCI_IO_WIN_ADDR);
    for (i = 0; i < nb_nics; i++) {
        NICInfo *nd = &nd_table[i];
        if (!nd->model) {
            nd->model = g_strdup("ibmveth");
        }
        if (strcmp(nd->model, "ibmveth") == 0) {
            spapr_vlan_create(spapr->vio_bus, nd);
        } else {
            pci_nic_init_nofail(&nd_table[i], nd->model, NULL);
        }
    }
    for (i = 0; i <= drive_get_max_bus(IF_SCSI); i++) {
        spapr_vscsi_create(spapr->vio_bus);
    }
    if (rma_size < (MIN_RMA_SLOF << 20)) {
        fprintf(stderr, "qemu: pSeries SLOF firmware requires >= "
                "%ldM guest RMA (Real Mode Area memory)\n", MIN_RMA_SLOF);
        exit(1);
    }
    fprintf(stderr, "sPAPR memory map:\n");
    fprintf(stderr, "RTAS                 : 0x%08lx..%08lx\n",
            (unsigned long)spapr->rtas_addr,
            (unsigned long)(spapr->rtas_addr + spapr->rtas_size - 1));
    fprintf(stderr, "FDT                  : 0x%08lx..%08lx\n",
            (unsigned long)spapr->fdt_addr,
            (unsigned long)(spapr->fdt_addr + FDT_MAX_SIZE - 1));
    if (kernel_filename) {
        uint64_t lowaddr = 0;
        kernel_size = load_elf(kernel_filename, translate_kernel_address, NULL,
                               NULL, &lowaddr, NULL, 1, ELF_MACHINE, 0);
        if (kernel_size < 0) {
            kernel_size = load_image_targphys(kernel_filename,
                                              KERNEL_LOAD_ADDR,
                                              load_limit - KERNEL_LOAD_ADDR);
        }
        if (kernel_size < 0) {
            fprintf(stderr, "qemu: could not load kernel '%s'\n",
                    kernel_filename);
            exit(1);
        }
        fprintf(stderr, "Kernel               : 0x%08x..%08lx\n",
                KERNEL_LOAD_ADDR, KERNEL_LOAD_ADDR + kernel_size - 1);
        /* load initrd */
        if (initrd_filename) {
            /* Try to locate the initrd in the gap between the kernel
             * and the firmware. Add a bit of space just in case
             */
            initrd_base = (KERNEL_LOAD_ADDR + kernel_size + 0x1ffff) & ~0xffff;
            initrd_size = load_image_targphys(initrd_filename, initrd_base,
                                              load_limit - initrd_base);
            if (initrd_size < 0) {
                fprintf(stderr, "qemu: could not load initial ram disk '%s'\n",
                        initrd_filename);
                exit(1);
            }
            fprintf(stderr, "Ramdisk              : 0x%08lx..%08lx\n",
                    (long)initrd_base, (long)(initrd_base + initrd_size - 1));
        } else {
            initrd_base = 0;
            initrd_size = 0;
        }
    }
    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, FW_FILE_NAME);
    fw_size = load_image_targphys(filename, 0, FW_MAX_SIZE);
    if (fw_size < 0) {
        hw_error("qemu: could not load LPAR rtas '%s'\n", filename);
        exit(1);
    }
    g_free(filename);
    fprintf(stderr, "Firmware load        : 0x%08x..%08lx\n",
            0, fw_size);
    fprintf(stderr, "Firmware runtime     : 0x%08lx..%08lx\n",
            load_limit, (unsigned long)spapr->fdt_addr);
    spapr->entry_point = 0x100;
    /* SLOF will startup the secondary CPUs using RTAS */
    for (env = first_cpu; env != NULL; env = env->next_cpu) {
        env->halted = 1;
    }
    /* Prepare the device tree */
    spapr->fdt_skel = spapr_create_fdt_skel(cpu_model, rma_size,
                                            initrd_base, initrd_size,
                                            kernel_size,
                                            boot_device, kernel_cmdline,
                                            pteg_shift + 7);
    assert(spapr->fdt_skel != NULL);
    qemu_register_reset(spapr_reset, spapr);
}


static av_cold int sonic_encode_init(AVCodecContext *avctx)

{

    SonicContext *s = avctx->priv_data;

    PutBitContext pb;

    int i, version = 0;

    if (avctx->channels > MAX_CHANNELS)

    {

        av_log(avctx, AV_LOG_ERROR, "Only mono and stereo streams are supported by now\n");

        return AVERROR(EINVAL); /* only stereo or mono for now */

    }

    if (avctx->channels == 2)

        s->decorrelation = MID_SIDE;

    else

        s->decorrelation = 3;

    if (avctx->codec->id == AV_CODEC_ID_SONIC_LS)

    {

        s->lossless = 1;

        s->num_taps = 32;

        s->downsampling = 1;

        s->quantization = 0.0;

    }

    else

    {

        s->num_taps = 128;

        s->downsampling = 2;

        s->quantization = 1.0;

    }

    // max tap 2048

    if ((s->num_taps < 32) || (s->num_taps > 1024) ||

        ((s->num_taps>>5)<<5 != s->num_taps))

    {

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

        return AVERROR_INVALIDDATA;

    }

    // generate taps

    s->tap_quant = av_calloc(s->num_taps, sizeof(*s->tap_quant));

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

        s->tap_quant[i] = ff_sqrt(i+1);

    s->channels = avctx->channels;

    s->samplerate = avctx->sample_rate;

    s->block_align = 2048LL*s->samplerate/(44100*s->downsampling);

    s->frame_size = s->channels*s->block_align*s->downsampling;

    s->tail_size = s->num_taps*s->channels;

    s->tail = av_calloc(s->tail_size, sizeof(*s->tail));

    if (!s->tail)

        return AVERROR(ENOMEM);

    s->predictor_k = av_calloc(s->num_taps, sizeof(*s->predictor_k) );

    if (!s->predictor_k)

        return AVERROR(ENOMEM);

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

    {

        s->coded_samples[i] = av_calloc(s->block_align, sizeof(**s->coded_samples));

        if (!s->coded_samples[i])

            return AVERROR(ENOMEM);

    }

    s->int_samples = av_calloc(s->frame_size, sizeof(*s->int_samples));

    s->window_size = ((2*s->tail_size)+s->frame_size);

    s->window = av_calloc(s->window_size, sizeof(*s->window));

    if (!s->window)

        return AVERROR(ENOMEM);

    avctx->extradata = av_mallocz(16);

    if (!avctx->extradata)

        return AVERROR(ENOMEM);

    init_put_bits(&pb, avctx->extradata, 16*8);

    put_bits(&pb, 2, version); // version

    if (version == 1)

    {

        put_bits(&pb, 2, s->channels);

        put_bits(&pb, 4, code_samplerate(s->samplerate));

    }

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

    if (!s->lossless)

        put_bits(&pb, 3, SAMPLE_SHIFT); // XXX FIXME: sample precision

    put_bits(&pb, 2, s->decorrelation);

    put_bits(&pb, 2, s->downsampling);

    put_bits(&pb, 5, (s->num_taps >> 5)-1); // 32..1024

    put_bits(&pb, 1, 0); // XXX FIXME: no custom tap quant table

    flush_put_bits(&pb);

    avctx->extradata_size = put_bits_count(&pb)/8;

    av_log(avctx, AV_LOG_INFO, "Sonic: ver: %d ls: %d dr: %d taps: %d block: %d frame: %d downsamp: %d\n",

        version, s->lossless, s->decorrelation, s->num_taps, s->block_align, s->frame_size, s->downsampling);

    avctx->frame_size = s->block_align*s->downsampling;

    return 0;

}


int ff_h264_check_intra_pred_mode(H264Context *h, int mode, int is_chroma)

{

    static const int8_t top[7]  = { LEFT_DC_PRED8x8, 1, -1, -1 };

    static const int8_t left[7] = { TOP_DC_PRED8x8, -1, 2, -1, DC_128_PRED8x8 };

    if (mode > 6U) {

        av_log(h->avctx, AV_LOG_ERROR,

               "out of range intra chroma pred mode at %d %d\n",

               h->mb_x, h->mb_y);

        return -1;

    }

    if (!(h->top_samples_available & 0x8000)) {

        mode = top[mode];

        if (mode < 0) {

            av_log(h->avctx, AV_LOG_ERROR,

                   "top block unavailable for requested intra mode at %d %d\n",

                   h->mb_x, h->mb_y);

            return -1;

        }

    }

    if ((h->left_samples_available & 0x8080) != 0x8080) {

        mode = left[mode];

        if (is_chroma && (h->left_samples_available & 0x8080)) {

            // mad cow disease mode, aka MBAFF + constrained_intra_pred

            mode = ALZHEIMER_DC_L0T_PRED8x8 +

                   (!(h->left_samples_available & 0x8000)) +

                   2 * (mode == DC_128_PRED8x8);

        }

        if (mode < 0) {

            av_log(h->avctx, AV_LOG_ERROR,

                   "left block unavailable for requested intra mode at %d %d\n",

                   h->mb_x, h->mb_y);

            return -1;

        }

    }

    return mode;

}


void audio_pcm_init_info (struct audio_pcm_info *info, audsettings_t *as)

{

    int bits = 8, sign = 0, shift = 0;

    switch (as->fmt) {

    case AUD_FMT_S8:

        sign = 1;

    case AUD_FMT_U8:

        break;

    case AUD_FMT_S16:

        sign = 1;

    case AUD_FMT_U16:

        bits = 16;

        shift = 1;

        break;

    case AUD_FMT_S32:

        sign = 1;

    case AUD_FMT_U32:

        bits = 32;

        shift = 2;

        break;

    }

    info->freq = as->freq;

    info->bits = bits;

    info->sign = sign;

    info->nchannels = as->nchannels;

    info->shift = (as->nchannels == 2) + shift;

    info->align = (1 << info->shift) - 1;

    info->bytes_per_second = info->freq << info->shift;

    info->swap_endianness = (as->endianness != AUDIO_HOST_ENDIANNESS);

}


static void block_job_completed_txn_abort(BlockJob *job)

{

    AioContext *ctx;

    BlockJobTxn *txn = job->txn;

    BlockJob *other_job, *next;

    if (txn->aborting) {

        /*

         * We are cancelled by another job, which will handle everything.

         */

        return;

    }

    txn->aborting = true;

    /* We are the first failed job. Cancel other jobs. */

    QLIST_FOREACH(other_job, &txn->jobs, txn_list) {

        ctx = blk_get_aio_context(other_job->blk);

        aio_context_acquire(ctx);

    }

    QLIST_FOREACH(other_job, &txn->jobs, txn_list) {

        if (other_job == job || other_job->completed) {

            /* Other jobs are "effectively" cancelled by us, set the status for

             * them; this job, however, may or may not be cancelled, depending

             * on the caller, so leave it. */

            if (other_job != job) {

                block_job_cancel_async(other_job);

            }

            continue;

        }

        block_job_cancel_sync(other_job);

        assert(other_job->completed);

    }

    QLIST_FOREACH_SAFE(other_job, &txn->jobs, txn_list, next) {

        ctx = blk_get_aio_context(other_job->blk);

        block_job_completed_single(other_job);

        aio_context_release(ctx);

    }

}


void isa_mmio_setup(MemoryRegion *mr, target_phys_addr_t size)

{

    memory_region_init_io(mr, &isa_mmio_ops, NULL, "isa-mmio", size);

}


int qio_channel_socket_dgram_sync(QIOChannelSocket *ioc,

                                  SocketAddressLegacy *localAddr,

                                  SocketAddressLegacy *remoteAddr,

                                  Error **errp)

{

    int fd;

    trace_qio_channel_socket_dgram_sync(ioc, localAddr, remoteAddr);

    fd = socket_dgram(remoteAddr, localAddr, errp);

    if (fd < 0) {

        trace_qio_channel_socket_dgram_fail(ioc);

        return -1;

    }

    trace_qio_channel_socket_dgram_complete(ioc, fd);

    if (qio_channel_socket_set_fd(ioc, fd, errp) < 0) {

        close(fd);

        return -1;

    }

    return 0;

}


static void dec_bit(DisasContext *dc)

{

    TCGv t0, t1;

    unsigned int op;

    int mem_index = cpu_mmu_index(dc->env);

    op = dc->ir & ((1 << 9) - 1);

    switch (op) {

        case 0x21:

            /* src.  */

            t0 = tcg_temp_new();

            LOG_DIS("src r%d r%d\n", dc->rd, dc->ra);

            tcg_gen_andi_tl(t0, cpu_R[dc->ra], 1);

            if (dc->rd) {

                t1 = tcg_temp_new();

                read_carry(dc, t1);

                tcg_gen_shli_tl(t1, t1, 31);

                tcg_gen_shri_tl(cpu_R[dc->rd], cpu_R[dc->ra], 1);

                tcg_gen_or_tl(cpu_R[dc->rd], cpu_R[dc->rd], t1);

                tcg_temp_free(t1);

            }

            /* Update carry.  */

            write_carry(dc, t0);

            tcg_temp_free(t0);

            break;

        case 0x1:

        case 0x41:

            /* srl.  */

            t0 = tcg_temp_new();

            LOG_DIS("srl r%d r%d\n", dc->rd, dc->ra);

            /* Update carry.  */

            tcg_gen_andi_tl(t0, cpu_R[dc->ra], 1);

            write_carry(dc, t0);

            tcg_temp_free(t0);

            if (dc->rd) {

                if (op == 0x41)

                    tcg_gen_shri_tl(cpu_R[dc->rd], cpu_R[dc->ra], 1);

                else

                    tcg_gen_sari_tl(cpu_R[dc->rd], cpu_R[dc->ra], 1);

            }

            break;

        case 0x60:

            LOG_DIS("ext8s r%d r%d\n", dc->rd, dc->ra);

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

            break;

        case 0x61:

            LOG_DIS("ext16s r%d r%d\n", dc->rd, dc->ra);

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

            break;

        case 0x64:

        case 0x66:

        case 0x74:

        case 0x76:

            /* wdc.  */

            LOG_DIS("wdc r%d\n", dc->ra);

            if ((dc->tb_flags & MSR_EE_FLAG)

                 && mem_index == MMU_USER_IDX) {

                tcg_gen_movi_tl(cpu_SR[SR_ESR], ESR_EC_PRIVINSN);

                t_gen_raise_exception(dc, EXCP_HW_EXCP);

                return;

            }

            break;

        case 0x68:

            /* wic.  */

            LOG_DIS("wic r%d\n", dc->ra);

            if ((dc->tb_flags & MSR_EE_FLAG)

                 && mem_index == MMU_USER_IDX) {

                tcg_gen_movi_tl(cpu_SR[SR_ESR], ESR_EC_PRIVINSN);

                t_gen_raise_exception(dc, EXCP_HW_EXCP);

                return;

            }

            break;

        case 0xe0:

            if ((dc->tb_flags & MSR_EE_FLAG)

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

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

                tcg_gen_movi_tl(cpu_SR[SR_ESR], ESR_EC_ILLEGAL_OP);

                t_gen_raise_exception(dc, EXCP_HW_EXCP);

            }

            if (dc->env->pvr.regs[2] & PVR2_USE_PCMP_INSTR) {

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

            }

            break;

        case 0x1e0:

            /* swapb */

            LOG_DIS("swapb r%d r%d\n", dc->rd, dc->ra);

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

            break;

        case 0x1e2:

            /*swaph */

            LOG_DIS("swaph r%d r%d\n", dc->rd, dc->ra);

            tcg_gen_rotri_i32(cpu_R[dc->rd], cpu_R[dc->ra], 16);

            break;

        default:

            cpu_abort(dc->env, "unknown bit oc=%x op=%x rd=%d ra=%d rb=%d\n",

                     dc->pc, op, dc->rd, dc->ra, dc->rb);

            break;

    }

}


int memory_region_get_fd(MemoryRegion *mr)

{

    if (mr->alias) {

        return memory_region_get_fd(mr->alias);

    }

    assert(mr->terminates);

    return qemu_get_ram_fd(mr->ram_addr & TARGET_PAGE_MASK);

}


static void tcg_out_insn_3314(TCGContext *s, AArch64Insn insn,

                              TCGReg r1, TCGReg r2, TCGReg rn,

                              tcg_target_long ofs, bool pre, bool w)

{

    insn |= 1u << 31; /* ext */

    insn |= pre << 24;

    insn |= w << 23;

    assert(ofs >= -0x200 && ofs < 0x200 && (ofs & 7) == 0);

    insn |= (ofs & (0x7f << 3)) << (15 - 3);

    tcg_out32(s, insn | r2 << 10 | rn << 5 | r1);

}


static void x86_cpuid_set_tsc_freq(Object *obj, Visitor *v, void *opaque,

                                   const char *name, Error **errp)

{

    X86CPU *cpu = X86_CPU(obj);

    const int64_t min = 0;

    const int64_t max = INT_MAX;

    int64_t value;

    visit_type_int(v, &value, name, errp);

    if (error_is_set(errp)) {

        return;

    }

    if (value < min || value > max) {

        error_set(errp, QERR_PROPERTY_VALUE_OUT_OF_RANGE, "",

                  name ? name : "null", value, min, max);

        return;

    }

    cpu->env.tsc_khz = value / 1000;

}


static int cow_create(const char *filename, QemuOpts *opts, Error **errp)

{

    struct cow_header_v2 cow_header;

    struct stat st;

    int64_t image_sectors = 0;

    char *image_filename = NULL;

    Error *local_err = NULL;

    int ret;

    BlockDriverState *cow_bs;

    /* Read out options */

    image_sectors = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0) / 512;

    image_filename = qemu_opt_get_del(opts, BLOCK_OPT_BACKING_FILE);

    ret = bdrv_create_file(filename, opts, &local_err);

    if (ret < 0) {

        error_propagate(errp, local_err);

        goto exit;

    }

    cow_bs = NULL;

    ret = bdrv_open(&cow_bs, filename, NULL, NULL,

                    BDRV_O_RDWR | BDRV_O_PROTOCOL, NULL, &local_err);

    if (ret < 0) {

        error_propagate(errp, local_err);

        goto exit;

    }

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

    cow_header.magic = cpu_to_be32(COW_MAGIC);

    cow_header.version = cpu_to_be32(COW_VERSION);

    if (image_filename) {

        /* Note: if no file, we put a dummy mtime */

        cow_header.mtime = cpu_to_be32(0);

        if (stat(image_filename, &st) != 0) {

            goto mtime_fail;

        }

        cow_header.mtime = cpu_to_be32(st.st_mtime);

    mtime_fail:

        pstrcpy(cow_header.backing_file, sizeof(cow_header.backing_file),

                image_filename);

    }

    cow_header.sectorsize = cpu_to_be32(512);

    cow_header.size = cpu_to_be64(image_sectors * 512);

    ret = bdrv_pwrite(cow_bs, 0, &cow_header, sizeof(cow_header));

    if (ret < 0) {

        goto exit;

    }

    /* resize to include at least all the bitmap */

    ret = bdrv_truncate(cow_bs,

        sizeof(cow_header) + ((image_sectors + 7) >> 3));

    if (ret < 0) {

        goto exit;

    }

exit:

    g_free(image_filename);

    bdrv_unref(cow_bs);

    return ret;

}


static av_cold int check_format(AVCodecContext *avctx)

{

    AVCodecParserContext *parser;

    uint8_t *pout;

    int psize;

    int index;

    H264Context *h;

    int ret = -1;

    /* init parser & parse file */

    parser = av_parser_init(avctx->codec->id);

    if (!parser) {

        av_log(avctx, AV_LOG_ERROR, "Failed to open H.264 parser.\n");

        goto final;

    }

    parser->flags = PARSER_FLAG_COMPLETE_FRAMES;

    index = av_parser_parse2(parser, avctx, &pout, &psize, NULL, 0, 0, 0, 0);

    if (index < 0) {

        av_log(avctx, AV_LOG_ERROR, "Failed to parse this file.\n");

        goto release_parser;

    }

    /* check if support */

    h = parser->priv_data;

    switch (h->sps.bit_depth_luma) {

    case 8:

        if (!CHROMA444(h) && !CHROMA422(h)) {

            // only this will H.264 decoder switch to hwaccel

            ret = 0;

            break;

        }

    default:

        av_log(avctx, AV_LOG_ERROR, "Unsupported file.\n");

    }

release_parser:

    av_parser_close(parser);

final:

    return ret;

}


static unsigned int dec_move_mr(DisasContext *dc)

{

	int memsize = memsize_zz(dc);

	int insn_len;

	DIS(fprintf (logfile, "move.%c [$r%u%s, $r%u\n",

		    memsize_char(memsize),

		    dc->op1, dc->postinc ? "+]" : "]",

		    dc->op2));

	if (memsize == 4) {

		insn_len = dec_prep_move_m(dc, 0, 4, cpu_R[dc->op2]);

		cris_cc_mask(dc, CC_MASK_NZ);

		cris_update_cc_op(dc, CC_OP_MOVE, 4);

		cris_update_cc_x(dc);

		cris_update_result(dc, cpu_R[dc->op2]);

	}

	else {

		TCGv t0;

		t0 = tcg_temp_new(TCG_TYPE_TL);

		insn_len = dec_prep_move_m(dc, 0, memsize, t0);

		cris_cc_mask(dc, CC_MASK_NZ);

		cris_alu(dc, CC_OP_MOVE,

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

		tcg_temp_free(t0);

	}

	do_postinc(dc, memsize);

	return insn_len;

}


static int rtc_initfn(ISADevice *dev)

{

    RTCState *s = DO_UPCAST(RTCState, dev, dev);

    int base = 0x70;

    int isairq = 8;

    isa_init_irq(dev, &s->irq, isairq);

    s->cmos_data[RTC_REG_A] = 0x26;

    s->cmos_data[RTC_REG_B] = 0x02;

    s->cmos_data[RTC_REG_C] = 0x00;

    s->cmos_data[RTC_REG_D] = 0x80;

    rtc_set_date_from_host(s);

    s->periodic_timer = qemu_new_timer(rtc_clock, rtc_periodic_timer, s);

#ifdef TARGET_I386

    if (rtc_td_hack)

        s->coalesced_timer =

            qemu_new_timer(rtc_clock, rtc_coalesced_timer, s);

#endif

    s->second_timer = qemu_new_timer(rtc_clock, rtc_update_second, s);

    s->second_timer2 = qemu_new_timer(rtc_clock, rtc_update_second2, s);

    s->next_second_time =

        qemu_get_clock(rtc_clock) + (get_ticks_per_sec() * 99) / 100;

    qemu_mod_timer(s->second_timer2, s->next_second_time);

    register_ioport_write(base, 2, 1, cmos_ioport_write, s);

    register_ioport_read(base, 2, 1, cmos_ioport_read, s);

    register_savevm("mc146818rtc", base, 1, rtc_save, rtc_load, s);

#ifdef TARGET_I386

    if (rtc_td_hack)

        register_savevm("mc146818rtc-td", base, 1, rtc_save_td, rtc_load_td, s);

#endif

    qemu_register_reset(rtc_reset, s);

    return 0;

}


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

{

    VirtIONet *n = opaque;

    VirtIODevice *vdev = VIRTIO_DEVICE(n);

    if (version_id < 2 || version_id > VIRTIO_NET_VM_VERSION)

        return -EINVAL;

    return virtio_load(vdev, f, version_id);

}