static int handle_connection(HTTPContext *c)

{

    int len, ret;

    switch(c->state) {

    case HTTPSTATE_WAIT_REQUEST:

    case RTSPSTATE_WAIT_REQUEST:

        /* timeout ? */

        if ((c->timeout - cur_time) < 0)

            return -1;

        if (c->poll_entry->revents & (POLLERR | POLLHUP))

            return -1;

        /* no need to read if no events */

        if (!(c->poll_entry->revents & POLLIN))

            return 0;

        /* read the data */

        len = read(c->fd, c->buffer_ptr, 1);

        if (len < 0) {

            if (errno != EAGAIN && errno != EINTR)

                return -1;

        } else if (len == 0) {

            return -1;

        } else {

            /* search for end of request. */

            uint8_t *ptr;

            c->buffer_ptr += len;

            ptr = c->buffer_ptr;

            if ((ptr >= c->buffer + 2 && !memcmp(ptr-2, "\n\n", 2)) ||

                (ptr >= c->buffer + 4 && !memcmp(ptr-4, "\r\n\r\n", 4))) {

                /* request found : parse it and reply */

                if (c->state == HTTPSTATE_WAIT_REQUEST) {

                    ret = http_parse_request(c);

                } else {

                    ret = rtsp_parse_request(c);

                }

                if (ret < 0)

                    return -1;

            } else if (ptr >= c->buffer_end) {

                /* request too long: cannot do anything */

                return -1;

            }

        }

        break;

    case HTTPSTATE_SEND_HEADER:

        if (c->poll_entry->revents & (POLLERR | POLLHUP))

            return -1;

        /* no need to write if no events */

        if (!(c->poll_entry->revents & POLLOUT))

            return 0;

        len = write(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr);

        if (len < 0) {

            if (errno != EAGAIN && errno != EINTR) {

                /* error : close connection */

                av_freep(&c->pb_buffer);

                return -1;

            }

        } else {

            c->buffer_ptr += len;

            if (c->stream)

                c->stream->bytes_served += len;

            c->data_count += len;

            if (c->buffer_ptr >= c->buffer_end) {

                av_freep(&c->pb_buffer);

                /* if error, exit */

                if (c->http_error) {

                    return -1;

                }

                /* all the buffer was sent : synchronize to the incoming stream */

                c->state = HTTPSTATE_SEND_DATA_HEADER;

                c->buffer_ptr = c->buffer_end = c->buffer;

            }

        }

        break;

    case HTTPSTATE_SEND_DATA:

    case HTTPSTATE_SEND_DATA_HEADER:

    case HTTPSTATE_SEND_DATA_TRAILER:

        /* for packetized output, we consider we can always write (the

           input streams sets the speed). It may be better to verify

           that we do not rely too much on the kernel queues */

        if (!c->is_packetized) {

            if (c->poll_entry->revents & (POLLERR | POLLHUP))

                return -1;

            /* no need to read if no events */

            if (!(c->poll_entry->revents & POLLOUT))

                return 0;

        }

        if (http_send_data(c) < 0)

            return -1;

        break;

    case HTTPSTATE_RECEIVE_DATA:

        /* no need to read if no events */

        if (c->poll_entry->revents & (POLLERR | POLLHUP))

            return -1;

        if (!(c->poll_entry->revents & POLLIN))

            return 0;

        if (http_receive_data(c) < 0)

            return -1;

        break;

    case HTTPSTATE_WAIT_FEED:

        /* no need to read if no events */

        if (c->poll_entry->revents & (POLLIN | POLLERR | POLLHUP))

            return -1;

        /* nothing to do, we'll be waken up by incoming feed packets */

        break;

    case HTTPSTATE_WAIT:

        /* if the delay expired, we can send new packets */

        if (compute_send_delay(c) <= 0)

            c->state = HTTPSTATE_SEND_DATA;

        break;

    case HTTPSTATE_WAIT_SHORT:

        /* just return back to send data */

        c->state = HTTPSTATE_SEND_DATA;

        break;

    case RTSPSTATE_SEND_REPLY:

        if (c->poll_entry->revents & (POLLERR | POLLHUP)) {

            av_freep(&c->pb_buffer);

            return -1;

        }

        /* no need to write if no events */

        if (!(c->poll_entry->revents & POLLOUT))

            return 0;

        len = write(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr);

        if (len < 0) {

            if (errno != EAGAIN && errno != EINTR) {

                /* error : close connection */

                av_freep(&c->pb_buffer);

                return -1;

            }

        } else {

            c->buffer_ptr += len;

            c->data_count += len;

            if (c->buffer_ptr >= c->buffer_end) {

                /* all the buffer was sent : wait for a new request */

                av_freep(&c->pb_buffer);

                start_wait_request(c, 1);

            }

        }

        break;

    case HTTPSTATE_READY:

        /* nothing to do */

        break;

    default:

        return -1;

    }

    return 0;

}


static int disas_coproc_insn(CPUARMState * env, DisasContext *s, uint32_t insn)
{
    int cpnum, is64, crn, crm, opc1, opc2, isread, rt, rt2;
    const ARMCPRegInfo *ri;
    cpnum = (insn >> 8) & 0xf;
    if (arm_feature(env, ARM_FEATURE_XSCALE)
	    && ((env->cp15.c15_cpar ^ 0x3fff) & (1 << cpnum)))
	return 1;
    /* First check for coprocessor space used for actual instructions */
    switch (cpnum) {
      case 0:
      case 1:
	if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
	    return disas_iwmmxt_insn(env, s, insn);
	} else if (arm_feature(env, ARM_FEATURE_XSCALE)) {
	    return disas_dsp_insn(env, s, insn);
	return 1;
    default:
        break;
    /* Otherwise treat as a generic register access */
    is64 = (insn & (1 << 25)) == 0;
    if (!is64 && ((insn & (1 << 4)) == 0)) {
        /* cdp */
        return 1;
    crm = insn & 0xf;
    if (is64) {
        crn = 0;
        opc1 = (insn >> 4) & 0xf;
        opc2 = 0;
        rt2 = (insn >> 16) & 0xf;
    } else {
        crn = (insn >> 16) & 0xf;
        opc1 = (insn >> 21) & 7;
        opc2 = (insn >> 5) & 7;
        rt2 = 0;
    isread = (insn >> 20) & 1;
    rt = (insn >> 12) & 0xf;
    ri = get_arm_cp_reginfo(s->cp_regs,
                            ENCODE_CP_REG(cpnum, is64, crn, crm, opc1, opc2));
    if (ri) {
        /* Check access permissions */
        if (!cp_access_ok(s->current_pl, ri, isread)) {
            return 1;
        /* Handle special cases first */
        switch (ri->type & ~(ARM_CP_FLAG_MASK & ~ARM_CP_SPECIAL)) {
        case ARM_CP_NOP:
            return 0;
        case ARM_CP_WFI:
            if (isread) {
                return 1;
            s->is_jmp = DISAS_WFI;
            return 0;
        default:
            break;
        if (use_icount && (ri->type & ARM_CP_IO)) {
            gen_io_start();
        if (isread) {
            /* Read */
            if (is64) {
                TCGv_i64 tmp64;
                TCGv_i32 tmp;
                if (ri->type & ARM_CP_CONST) {
                    tmp64 = tcg_const_i64(ri->resetvalue);
                } else if (ri->readfn) {
                    tmp64 = tcg_temp_new_i64();
                    gen_helper_get_cp_reg64(tmp64, cpu_env, tmpptr);
                } else {
                    tmp64 = tcg_temp_new_i64();
                    tcg_gen_ld_i64(tmp64, cpu_env, ri->fieldoffset);
                tmp = tcg_temp_new_i32();
                tcg_gen_trunc_i64_i32(tmp, tmp64);
                store_reg(s, rt, tmp);
                tcg_gen_shri_i64(tmp64, tmp64, 32);
                tmp = tcg_temp_new_i32();
                tcg_gen_trunc_i64_i32(tmp, tmp64);
                tcg_temp_free_i64(tmp64);
                store_reg(s, rt2, tmp);
            } else {
                TCGv_i32 tmp;
                if (ri->type & ARM_CP_CONST) {
                    tmp = tcg_const_i32(ri->resetvalue);
                } else if (ri->readfn) {
                    tmp = tcg_temp_new_i32();
                    gen_helper_get_cp_reg(tmp, cpu_env, tmpptr);
                } else {
                    tmp = load_cpu_offset(ri->fieldoffset);
                if (rt == 15) {
                    /* Destination register of r15 for 32 bit loads sets
                     * the condition codes from the high 4 bits of the value
                    gen_set_nzcv(tmp);
                    tcg_temp_free_i32(tmp);
                } else {
                    store_reg(s, rt, tmp);
        } else {
            /* Write */
            if (ri->type & ARM_CP_CONST) {
                /* If not forbidden by access permissions, treat as WI */
                return 0;
            if (is64) {
                TCGv_i32 tmplo, tmphi;
                TCGv_i64 tmp64 = tcg_temp_new_i64();
                tmplo = load_reg(s, rt);
                tmphi = load_reg(s, rt2);
                tcg_gen_concat_i32_i64(tmp64, tmplo, tmphi);
                tcg_temp_free_i32(tmplo);
                tcg_temp_free_i32(tmphi);
                if (ri->writefn) {
                    TCGv_ptr tmpptr = tcg_const_ptr(ri);
                    gen_helper_set_cp_reg64(cpu_env, tmpptr, tmp64);
                } else {
                    tcg_gen_st_i64(tmp64, cpu_env, ri->fieldoffset);
                tcg_temp_free_i64(tmp64);
            } else {
                if (ri->writefn) {
                    TCGv_i32 tmp;
                    tmp = load_reg(s, rt);
                    gen_helper_set_cp_reg(cpu_env, tmpptr, tmp);
                    tcg_temp_free_i32(tmp);
                } else {
                    TCGv_i32 tmp = load_reg(s, rt);
                    store_cpu_offset(tmp, ri->fieldoffset);
        if (use_icount && (ri->type & ARM_CP_IO)) {
            /* I/O operations must end the TB here (whether read or write) */
            gen_io_end();
            gen_lookup_tb(s);
        } else if (!isread && !(ri->type & ARM_CP_SUPPRESS_TB_END)) {
            /* We default to ending the TB on a coprocessor register write,
             * but allow this to be suppressed by the register definition
             * (usually only necessary to work around guest bugs).
            gen_lookup_tb(s);
        return 0;
    /* Unknown register; this might be a guest error or a QEMU
     * unimplemented feature.
    if (is64) {
        qemu_log_mask(LOG_UNIMP, "%s access to unsupported AArch32 "
                      "64 bit system register cp:%d opc1: %d crm:%d\n",
                      isread ? "read" : "write", cpnum, opc1, crm);
    } else {
        qemu_log_mask(LOG_UNIMP, "%s access to unsupported AArch32 "
                      "system register cp:%d opc1:%d crn:%d crm:%d opc2:%d\n",
                      isread ? "read" : "write", cpnum, opc1, crn, crm, opc2);
    return 1;


static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb,

                                 AVStream *st, MOVStreamContext *sc)

{

    uint8_t codec_name[32];

    int64_t stsd_start;

    unsigned int len;

    /* The first 16 bytes of the video sample description are already

     * read in ff_mov_read_stsd_entries() */

    stsd_start = avio_tell(pb) - 16;

    avio_rb16(pb); /* version */

    avio_rb16(pb); /* revision level */

    avio_rb32(pb); /* vendor */

    avio_rb32(pb); /* temporal quality */

    avio_rb32(pb); /* spatial quality */

    st->codecpar->width  = avio_rb16(pb); /* width */

    st->codecpar->height = avio_rb16(pb); /* height */

    avio_rb32(pb); /* horiz resolution */

    avio_rb32(pb); /* vert resolution */

    avio_rb32(pb); /* data size, always 0 */

    avio_rb16(pb); /* frames per samples */

    len = avio_r8(pb); /* codec name, pascal string */

    if (len > 31)

        len = 31;

    mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name));

    if (len < 31)

        avio_skip(pb, 31 - len);

    if (codec_name[0])

        av_dict_set(&st->metadata, "encoder", codec_name, 0);

    /* codec_tag YV12 triggers an UV swap in rawdec.c */

    if (!memcmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) {

        st->codecpar->codec_tag = MKTAG('I', '4', '2', '0');

        st->codecpar->width &= ~1;

        st->codecpar->height &= ~1;

    }

    /* Flash Media Server uses tag H.263 with Sorenson Spark */

    if (st->codecpar->codec_tag == MKTAG('H','2','6','3') &&

        !memcmp(codec_name, "Sorenson H263", 13))

        st->codecpar->codec_id = AV_CODEC_ID_FLV1;

    st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* depth */

    avio_seek(pb, stsd_start, SEEK_SET);

    if (ff_get_qtpalette(st->codecpar->codec_id, pb, sc->palette)) {

        st->codecpar->bits_per_coded_sample &= 0x1F;

        sc->has_palette = 1;

    }

}


static inline void gen_check_tlb_flush(DisasContext *ctx) { }


static int64_t coroutine_fn qcow_co_get_block_status(BlockDriverState *bs,

        int64_t sector_num, int nb_sectors, int *pnum, BlockDriverState **file)

{

    BDRVQcowState *s = bs->opaque;

    int index_in_cluster, n;

    uint64_t cluster_offset;

    qemu_co_mutex_lock(&s->lock);

    cluster_offset = get_cluster_offset(bs, sector_num << 9, 0, 0, 0, 0);

    qemu_co_mutex_unlock(&s->lock);

    index_in_cluster = sector_num & (s->cluster_sectors - 1);

    n = s->cluster_sectors - index_in_cluster;

    if (n > nb_sectors)

        n = nb_sectors;

    *pnum = n;

    if (!cluster_offset) {

        return 0;

    }

    if ((cluster_offset & QCOW_OFLAG_COMPRESSED) || s->crypto) {

        return BDRV_BLOCK_DATA;

    }

    cluster_offset |= (index_in_cluster << BDRV_SECTOR_BITS);

    *file = bs->file->bs;

    return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | cluster_offset;

}


static void H264_CHROMA_MC8_TMPL(uint8_t *dst/*align 8*/, uint8_t *src/*align 1*/, int stride, int h, int x, int y, int rnd)

{

    if(y==0 && x==0) {

        /* no filter needed */

        H264_CHROMA_MC8_MV0(dst, src, stride, h);

        return;

    }

    assert(x<8 && y<8 && x>=0 && y>=0);

    if(y==0 || x==0)

    {

        /* 1 dimensional filter only */

        asm volatile(

            "movd %0, %%xmm7 \n\t"

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

            "pshuflw $0, %%xmm7, %%xmm7 \n\t"

            "movlhps %%xmm6, %%xmm6 \n\t"

            "movlhps %%xmm7, %%xmm7 \n\t"

            :: "r"(255*(x+y)+8), "m"(rnd?ff_pw_4:ff_pw_3));

        if(x) {

            asm volatile(

                "1: \n\t"

                "movq (%1), %%xmm0 \n\t"

                "movq 1(%1), %%xmm1 \n\t"

                "movq (%1,%3), %%xmm2 \n\t"

                "movq 1(%1,%3), %%xmm3 \n\t"

                "punpcklbw %%xmm1, %%xmm0 \n\t"

                "punpcklbw %%xmm3, %%xmm2 \n\t"

                "pmaddubsw %%xmm7, %%xmm0 \n\t"

                "pmaddubsw %%xmm7, %%xmm2 \n\t"

         AVG_OP("movq (%0), %%xmm4 \n\t")

         AVG_OP("movhps (%0,%3), %%xmm4 \n\t")

                "paddw %%xmm6, %%xmm0 \n\t"

                "paddw %%xmm6, %%xmm2 \n\t"

                "psrlw $3, %%xmm0 \n\t"

                "psrlw $3, %%xmm2 \n\t"

                "packuswb %%xmm2, %%xmm0 \n\t"

         AVG_OP("pavgb %%xmm4, %%xmm0 \n\t")

                "movq %%xmm0, (%0) \n\t"

                "movhps %%xmm0, (%0,%3) \n\t"

                "sub $2, %2 \n\t"

                "lea (%1,%3,2), %1 \n\t"

                "lea (%0,%3,2), %0 \n\t"

                "jg 1b \n\t"

                :"+r"(dst), "+r"(src), "+r"(h)

                :"r"((long)stride)

            );

        } else {

            asm volatile(

                "1: \n\t"

                "movq (%1), %%xmm0 \n\t"

                "movq (%1,%3), %%xmm1 \n\t"

                "movdqa %%xmm1, %%xmm2 \n\t"

                "movq (%1,%3,2), %%xmm3 \n\t"

                "punpcklbw %%xmm1, %%xmm0 \n\t"

                "punpcklbw %%xmm3, %%xmm2 \n\t"

                "pmaddubsw %%xmm7, %%xmm0 \n\t"

                "pmaddubsw %%xmm7, %%xmm2 \n\t"

         AVG_OP("movq (%0), %%xmm4 \n\t")

         AVG_OP("movhps (%0,%3), %%xmm4 \n\t")

                "paddw %%xmm6, %%xmm0 \n\t"

                "paddw %%xmm6, %%xmm2 \n\t"

                "psrlw $3, %%xmm0 \n\t"

                "psrlw $3, %%xmm2 \n\t"

                "packuswb %%xmm2, %%xmm0 \n\t"

         AVG_OP("pavgb %%xmm4, %%xmm0 \n\t")

                "movq %%xmm0, (%0) \n\t"

                "movhps %%xmm0, (%0,%3) \n\t"

                "sub $2, %2 \n\t"

                "lea (%1,%3,2), %1 \n\t"

                "lea (%0,%3,2), %0 \n\t"

                "jg 1b \n\t"

                :"+r"(dst), "+r"(src), "+r"(h)

                :"r"((long)stride)

            );

        }

        return;

    }

    /* general case, bilinear */

    asm volatile(

        "movd %0, %%xmm7 \n\t"

        "movd %1, %%xmm6 \n\t"

        "movdqa %2, %%xmm5 \n\t"

        "pshuflw $0, %%xmm7, %%xmm7 \n\t"

        "pshuflw $0, %%xmm6, %%xmm6 \n\t"

        "movlhps %%xmm7, %%xmm7 \n\t"

        "movlhps %%xmm6, %%xmm6 \n\t"

        :: "r"((x*255+8)*(8-y)), "r"((x*255+8)*y), "m"(rnd?ff_pw_32:ff_pw_28)

    );

    asm volatile(

        "movq (%1), %%xmm0 \n\t"

        "movq 1(%1), %%xmm1 \n\t"

        "punpcklbw %%xmm1, %%xmm0 \n\t"

        "add %3, %1 \n\t"

        "1: \n\t"

        "movq (%1), %%xmm1 \n\t"

        "movq 1(%1), %%xmm2 \n\t"

        "movq (%1,%3), %%xmm3 \n\t"

        "movq 1(%1,%3), %%xmm4 \n\t"

        "lea (%1,%3,2), %1 \n\t"

        "punpcklbw %%xmm2, %%xmm1 \n\t"

        "punpcklbw %%xmm4, %%xmm3 \n\t"

        "movdqa %%xmm1, %%xmm2 \n\t"

        "movdqa %%xmm3, %%xmm4 \n\t"

        "pmaddubsw %%xmm7, %%xmm0 \n\t"

        "pmaddubsw %%xmm6, %%xmm1 \n\t"

        "pmaddubsw %%xmm7, %%xmm2 \n\t"

        "pmaddubsw %%xmm6, %%xmm3 \n\t"

        "paddw %%xmm5, %%xmm0 \n\t"

        "paddw %%xmm5, %%xmm2 \n\t"

        "paddw %%xmm0, %%xmm1 \n\t"

        "paddw %%xmm2, %%xmm3 \n\t"

        "movdqa %%xmm4, %%xmm0 \n\t"

        "psrlw $6, %%xmm1 \n\t"

        "psrlw $6, %%xmm3 \n\t"

 AVG_OP("movq (%0), %%xmm2 \n\t")

 AVG_OP("movhps (%0,%3), %%xmm2 \n\t")

        "packuswb %%xmm3, %%xmm1 \n\t"

 AVG_OP("pavgb %%xmm2, %%xmm1 \n\t")

        "movq %%xmm1, (%0)\n\t"

        "movhps %%xmm1, (%0,%3)\n\t"

        "sub $2, %2 \n\t"

        "lea (%0,%3,2), %0 \n\t"

        "jg 1b \n\t"

        :"+r"(dst), "+r"(src), "+r"(h)

        :"r"((long)stride)

    );

}


static void vhost_virtqueue_stop(struct vhost_dev *dev,

                                    struct VirtIODevice *vdev,

                                    struct vhost_virtqueue *vq,

                                    unsigned idx)

{

    int vhost_vq_index = dev->vhost_ops->vhost_get_vq_index(dev, idx);

    struct vhost_vring_state state = {

        .index = vhost_vq_index,

    };

    int r;

    r = dev->vhost_ops->vhost_get_vring_base(dev, &state);

    if (r < 0) {

        VHOST_OPS_DEBUG("vhost VQ %d ring restore failed: %d", idx, r);

    } else {

        virtio_queue_set_last_avail_idx(vdev, idx, state.num);

    }

    virtio_queue_invalidate_signalled_used(vdev, idx);

    virtio_queue_update_used_idx(vdev, idx);

    /* In the cross-endian case, we need to reset the vring endianness to

     * native as legacy devices expect so by default.

    if (vhost_needs_vring_endian(vdev)) {

        vhost_virtqueue_set_vring_endian_legacy(dev,

                                                !virtio_is_big_endian(vdev),

                                                vhost_vq_index);

    }

    vhost_memory_unmap(dev, vq->used, virtio_queue_get_used_size(vdev, idx),

                       1, virtio_queue_get_used_size(vdev, idx));

    vhost_memory_unmap(dev, vq->avail, virtio_queue_get_avail_size(vdev, idx),

                       0, virtio_queue_get_avail_size(vdev, idx));

    vhost_memory_unmap(dev, vq->desc, virtio_queue_get_desc_size(vdev, idx),

                       0, virtio_queue_get_desc_size(vdev, idx));

}


BlockDeviceInfoList *bdrv_named_nodes_list(void)

{

    BlockDeviceInfoList *list, *entry;

    BlockDriverState *bs;

    list = NULL;

    QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {

        entry = g_malloc0(sizeof(*entry));

        entry->value = bdrv_block_device_info(bs);

        entry->next = list;

        list = entry;

    }

    return list;

}


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

                                 ptrdiff_t stride)

{

    avc_luma_vt_qrt_16w_msa(src - (stride * 2), stride, dst, stride, 16, 0);

}


int ff_thread_can_start_frame(AVCodecContext *avctx)

{

    PerThreadContext *p = avctx->thread_opaque;

    if ((avctx->active_thread_type&FF_THREAD_FRAME) && p->state != STATE_SETTING_UP &&

        (avctx->codec->update_thread_context || (!avctx->thread_safe_callbacks &&

                avctx->get_buffer != avcodec_default_get_buffer))) {

        return 0;

    }

    return 1;

}


static int decode_cblk(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *codsty,

                       Jpeg2000T1Context *t1, Jpeg2000Cblk *cblk,

                       int width, int height, int bandpos)

{

    int passno = cblk->npasses, pass_t = 2, bpno = cblk->nonzerobits - 1, y;

    int clnpass_cnt = 0;

    int bpass_csty_symbol           = codsty->cblk_style & JPEG2000_CBLK_BYPASS;

    int vert_causal_ctx_csty_symbol = codsty->cblk_style & JPEG2000_CBLK_VSC;

    av_assert0(width  <= JPEG2000_MAX_CBLKW);

    av_assert0(height <= JPEG2000_MAX_CBLKH);

    for (y = 0; y < height; y++)

        memset(t1->data[y], 0, width * sizeof(**t1->data));

    /* If code-block contains no compressed data: nothing to do. */

    if (!cblk->length)

        return 0;

    for (y = 0; y < height + 2; y++)

        memset(t1->flags[y], 0, (width + 2) * sizeof(**t1->flags));

    cblk->data[cblk->length] = 0xff;

    cblk->data[cblk->length+1] = 0xff;

    ff_mqc_initdec(&t1->mqc, cblk->data);

    while (passno--) {

        switch(pass_t) {

        case 0:

            decode_sigpass(t1, width, height, bpno + 1, bandpos,

                           bpass_csty_symbol && (clnpass_cnt >= 4),

                           vert_causal_ctx_csty_symbol);

            break;

        case 1:

            decode_refpass(t1, width, height, bpno + 1);

            if (bpass_csty_symbol && clnpass_cnt >= 4)

                ff_mqc_initdec(&t1->mqc, cblk->data);

            break;

        case 2:

            decode_clnpass(s, t1, width, height, bpno + 1, bandpos,

                           codsty->cblk_style & JPEG2000_CBLK_SEGSYM,

                           vert_causal_ctx_csty_symbol);

            clnpass_cnt = clnpass_cnt + 1;

            if (bpass_csty_symbol && clnpass_cnt >= 4)

                ff_mqc_initdec(&t1->mqc, cblk->data);

            break;

        }

        pass_t++;

        if (pass_t == 3) {

            bpno--;

            pass_t = 0;

        }

    }

    return 0;

}


unsigned int av_codec_get_tag(const AVCodecTag *tags[4], enum CodecID id)

{

    int i;

    for(i=0; i<4 && tags[i]; i++){

        int tag= codec_get_tag(tags[i], id);

        if(tag) return tag;

    }

    return 0;

}


const char *avcodec_get_pix_fmt_name(enum PixelFormat pix_fmt)

{

    if (pix_fmt < 0 || pix_fmt >= PIX_FMT_NB)

        return NULL;

    else

        return av_pix_fmt_descriptors[pix_fmt].name;

}


static int decode_residual_block(AVSContext *h, GetBitContext *gb,

                                 const struct dec_2dvlc *r, int esc_golomb_order,

                                 int qp, uint8_t *dst, int stride) {

    int i, level_code, esc_code, level, run, mask;

    DCTELEM level_buf[65];

    uint8_t run_buf[65];

    DCTELEM *block = h->block;

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

        level_code = get_ue_code(gb,r->golomb_order);

        if(level_code >= ESCAPE_CODE) {

            run = ((level_code - ESCAPE_CODE) >> 1) + 1;

            esc_code = get_ue_code(gb,esc_golomb_order);

            level = esc_code + (run > r->max_run ? 1 : r->level_add[run]);

            while(level > r->inc_limit)

                r++;

            mask = -(level_code & 1);

            level = (level^mask) - mask;

        } else {

            level = r->rltab[level_code][0];

            if(!level) //end of block signal

                break;

            run   = r->rltab[level_code][1];

            r += r->rltab[level_code][2];

        }

        level_buf[i] = level;

        run_buf[i] = run;

    }

    if(dequant(h,level_buf, run_buf, block, ff_cavs_dequant_mul[qp],

               ff_cavs_dequant_shift[qp], i))

        return -1;

    h->cdsp.cavs_idct8_add(dst,block,stride);

    h->s.dsp.clear_block(block);

    return 0;

}


static void free_duplicate_context(MpegEncContext *s){

    if(s==NULL) return;

    av_freep(&s->allocated_edge_emu_buffer); s->edge_emu_buffer= NULL;

    av_freep(&s->me.scratchpad);

    s->me.temp=

    s->rd_scratchpad=

    s->b_scratchpad=

    s->obmc_scratchpad= NULL;

    av_freep(&s->dct_error_sum);

    av_freep(&s->me.map);

    av_freep(&s->me.score_map);

    av_freep(&s->blocks);

    av_freep(&s->ac_val_base);

    s->block= NULL;

}


int cpu_gen_code(CPUState *env, TranslationBlock *tb,

                 int max_code_size, int *gen_code_size_ptr)

{

    uint8_t *gen_code_buf;

    int gen_code_size;

    if (gen_intermediate_code(env, tb) < 0)

        return -1;

    /* generate machine code */

    tb->tb_next_offset[0] = 0xffff;

    tb->tb_next_offset[1] = 0xffff;

    gen_code_buf = tb->tc_ptr;

#ifdef USE_DIRECT_JUMP

    /* the following two entries are optional (only used for string ops) */

    tb->tb_jmp_offset[2] = 0xffff;

    tb->tb_jmp_offset[3] = 0xffff;

#endif

    dyngen_labels(gen_labels, nb_gen_labels, gen_code_buf, gen_opc_buf);

    gen_code_size = dyngen_code(gen_code_buf, tb->tb_next_offset,

#ifdef USE_DIRECT_JUMP

                                tb->tb_jmp_offset,

#else

                                NULL,

#endif

                                gen_opc_buf, gen_opparam_buf, gen_labels);

    *gen_code_size_ptr = gen_code_size;

#ifdef DEBUG_DISAS

    if (loglevel & CPU_LOG_TB_OUT_ASM) {

        fprintf(logfile, "OUT: [size=%d]\n", *gen_code_size_ptr);

        disas(logfile, tb->tc_ptr, *gen_code_size_ptr);

        fprintf(logfile, "\n");

        fflush(logfile);

    }

#endif

    return 0;

}


vnc_display_setup_auth(VncDisplay *vs,

                       bool password,

                       bool sasl,

                       bool tls,

                       bool x509,

                       bool websocket)

{

    /*

     * We have a choice of 3 authentication options

     *

     *   1. none

     *   2. vnc

     *   3. sasl

     *

     * The channel can be run in 2 modes

     *

     *   1. clear

     *   2. tls

     *

     * And TLS can use 2 types of credentials

     *

     *   1. anon

     *   2. x509

     *

     * We thus have 9 possible logical combinations

     *

     *   1. clear + none

     *   2. clear + vnc

     *   3. clear + sasl

     *   4. tls + anon + none

     *   5. tls + anon + vnc

     *   6. tls + anon + sasl

     *   7. tls + x509 + none

     *   8. tls + x509 + vnc

     *   9. tls + x509 + sasl

     *

     * These need to be mapped into the VNC auth schemes

     * in an appropriate manner. In regular VNC, all the

     * TLS options get mapped into VNC_AUTH_VENCRYPT

     * sub-auth types.

     *

     * In websockets, the https:// protocol already provides

     * TLS support, so there is no need to make use of the

     * VeNCrypt extension. Furthermore, websockets browser

     * clients could not use VeNCrypt even if they wanted to,

     * as they cannot control when the TLS handshake takes

     * place. Thus there is no option but to rely on https://,

     * meaning combinations 4->6 and 7->9 will be mapped to

     * VNC auth schemes in the same way as combos 1->3.

     *

     * Regardless of fact that we have a different mapping to

     * VNC auth mechs for plain VNC vs websockets VNC, the end

     * result has the same security characteristics.

     */

    if (password) {

        if (tls) {

            vs->auth = VNC_AUTH_VENCRYPT;

            if (websocket) {

                vs->ws_tls = true;

            }

            if (x509) {

                VNC_DEBUG("Initializing VNC server with x509 password auth\n");

                vs->subauth = VNC_AUTH_VENCRYPT_X509VNC;

            } else {

                VNC_DEBUG("Initializing VNC server with TLS password auth\n");

                vs->subauth = VNC_AUTH_VENCRYPT_TLSVNC;

            }

        } else {

            VNC_DEBUG("Initializing VNC server with password auth\n");

            vs->auth = VNC_AUTH_VNC;

            vs->subauth = VNC_AUTH_INVALID;

        }

        if (websocket) {

            vs->ws_auth = VNC_AUTH_VNC;

        } else {

            vs->ws_auth = VNC_AUTH_INVALID;

        }

    } else if (sasl) {

        if (tls) {

            vs->auth = VNC_AUTH_VENCRYPT;

            if (websocket) {

                vs->ws_tls = true;

            }

            if (x509) {

                VNC_DEBUG("Initializing VNC server with x509 SASL auth\n");

                vs->subauth = VNC_AUTH_VENCRYPT_X509SASL;

            } else {

                VNC_DEBUG("Initializing VNC server with TLS SASL auth\n");

                vs->subauth = VNC_AUTH_VENCRYPT_TLSSASL;

            }

        } else {

            VNC_DEBUG("Initializing VNC server with SASL auth\n");

            vs->auth = VNC_AUTH_SASL;

            vs->subauth = VNC_AUTH_INVALID;

        }

        if (websocket) {

            vs->ws_auth = VNC_AUTH_SASL;

        } else {

            vs->ws_auth = VNC_AUTH_INVALID;

        }

    } else {

        if (tls) {

            vs->auth = VNC_AUTH_VENCRYPT;

            if (websocket) {

                vs->ws_tls = true;

            }

            if (x509) {

                VNC_DEBUG("Initializing VNC server with x509 no auth\n");

                vs->subauth = VNC_AUTH_VENCRYPT_X509NONE;

            } else {

                VNC_DEBUG("Initializing VNC server with TLS no auth\n");

                vs->subauth = VNC_AUTH_VENCRYPT_TLSNONE;

            }

        } else {

            VNC_DEBUG("Initializing VNC server with no auth\n");

            vs->auth = VNC_AUTH_NONE;

            vs->subauth = VNC_AUTH_INVALID;

        }

        if (websocket) {

            vs->ws_auth = VNC_AUTH_NONE;

        } else {

            vs->ws_auth = VNC_AUTH_INVALID;

        }

    }

}


static av_cold int peak_init_writer(AVFormatContext *s)

{

    WAVMuxContext *wav = s->priv_data;

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

    if (enc->codec_id != AV_CODEC_ID_PCM_S8 &&

        enc->codec_id != AV_CODEC_ID_PCM_S16LE &&

        enc->codec_id != AV_CODEC_ID_PCM_U8 &&

        enc->codec_id != AV_CODEC_ID_PCM_U16LE) {

        av_log(s, AV_LOG_ERROR, "%s codec not supported for Peak Chunk\n",

               s->streams[0]->codec->codec ? s->streams[0]->codec->codec->name : "NONE");

        return -1;

    }

    wav->peak_bps = av_get_bits_per_sample(enc->codec_id) / 8;

    if (wav->peak_bps == 1 && wav->peak_format == PEAK_FORMAT_UINT16) {

        av_log(s, AV_LOG_ERROR,

               "Writing 16 bit peak for 8 bit audio does not make sense\n");

        return AVERROR(EINVAL);

    }

    wav->peak_maxpos = av_mallocz(enc->channels * sizeof(*wav->peak_maxpos));

    if (!wav->peak_maxpos)

        goto nomem;

    wav->peak_maxneg = av_mallocz(enc->channels * sizeof(*wav->peak_maxneg));

    if (!wav->peak_maxneg)

        goto nomem;

    wav->peak_output = av_malloc(PEAK_BUFFER_SIZE);

    if (!wav->peak_output)

        goto nomem;

    wav->peak_outbuf_size = PEAK_BUFFER_SIZE;

    return 0;

nomem:

    av_log(s, AV_LOG_ERROR, "Out of memory\n");

    peak_free_buffers(s);

    return AVERROR(ENOMEM);

}


static int grow_refcount_table(BlockDriverState *bs, int min_size)

{

    BDRVQcowState *s = bs->opaque;

    int new_table_size, new_table_size2, refcount_table_clusters, i, ret;

    uint64_t *new_table;

    int64_t table_offset;

    uint8_t data[12];

    int old_table_size;

    int64_t old_table_offset;

    if (min_size <= s->refcount_table_size)

        return 0;

    /* compute new table size */

    new_table_size = next_refcount_table_size(s, min_size);

#ifdef DEBUG_ALLOC2

    printf("grow_refcount_table from %d to %d\n",

           s->refcount_table_size,

           new_table_size);

#endif

    new_table_size2 = new_table_size * sizeof(uint64_t);

    new_table = qemu_mallocz(new_table_size2);

    memcpy(new_table, s->refcount_table,

           s->refcount_table_size * sizeof(uint64_t));

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

        cpu_to_be64s(&new_table[i]);

    /* Note: we cannot update the refcount now to avoid recursion */

    table_offset = alloc_clusters_noref(bs, new_table_size2);

    ret = bdrv_pwrite(s->hd, table_offset, new_table, new_table_size2);

    if (ret != new_table_size2)

        goto fail;

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

        be64_to_cpus(&new_table[i]);

    cpu_to_be64w((uint64_t*)data, table_offset);

    cpu_to_be32w((uint32_t*)(data + 8), refcount_table_clusters);

    ret = bdrv_pwrite(s->hd, offsetof(QCowHeader, refcount_table_offset),

                    data, sizeof(data));

    if (ret != sizeof(data)) {

        goto fail;

    }

    qemu_free(s->refcount_table);

    old_table_offset = s->refcount_table_offset;

    old_table_size = s->refcount_table_size;

    s->refcount_table = new_table;

    s->refcount_table_size = new_table_size;

    s->refcount_table_offset = table_offset;

    update_refcount(bs, table_offset, new_table_size2, 1);

    qcow2_free_clusters(bs, old_table_offset, old_table_size * sizeof(uint64_t));

    return 0;

 fail:

    qemu_free(new_table);

    return ret < 0 ? ret : -EIO;

}


static void vnc_dpy_switch(DisplayChangeListener *dcl,

                           DisplaySurface *surface)

{

    VncDisplay *vd = container_of(dcl, VncDisplay, dcl);

    VncState *vs;

    vnc_abort_display_jobs(vd);

    /* server surface */

    qemu_pixman_image_unref(vd->server);

    vd->ds = surface;

    vd->server = pixman_image_create_bits(VNC_SERVER_FB_FORMAT,

                                          surface_width(vd->ds),

                                          surface_height(vd->ds),

                                          NULL, 0);

    /* guest surface */

#if 0 /* FIXME */

    if (ds_get_bytes_per_pixel(ds) != vd->guest.ds->pf.bytes_per_pixel)

        console_color_init(ds);

#endif

    qemu_pixman_image_unref(vd->guest.fb);

    vd->guest.fb = pixman_image_ref(surface->image);

    vd->guest.format = surface->format;

    VNC_SET_VISIBLE_PIXELS_DIRTY(vd->guest.dirty,

                                 surface_width(vd->ds),

                                 surface_height(vd->ds));

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

        vnc_colordepth(vs);

        vnc_desktop_resize(vs);

        if (vs->vd->cursor) {

            vnc_cursor_define(vs);

        }

        VNC_SET_VISIBLE_PIXELS_DIRTY(vs->dirty,

                                     surface_width(vd->ds),

                                     surface_height(vd->ds));

    }

}


static int parse_video_var(AVFormatContext *avctx, AVStream *st, const char *name, int size)

{

    AVIOContext *pb = avctx->pb;

    if (!strcmp(name, "__DIR_COUNT")) {

        st->nb_frames = st->duration = var_read_int(pb, size);

    } else if (!strcmp(name, "COMPRESSION")) {

        char * str = var_read_string(pb, size);

        if (!strcmp(str, "1")) {

            st->codec->codec_id = AV_CODEC_ID_MVC1;

        } else if (!strcmp(str, "2")) {

            st->codec->pix_fmt  = AV_PIX_FMT_ABGR;

            st->codec->codec_id = AV_CODEC_ID_RAWVIDEO;

        } else if (!strcmp(str, "3")) {

            st->codec->codec_id = AV_CODEC_ID_SGIRLE;

        } else if (!strcmp(str, "10")) {

            st->codec->codec_id = AV_CODEC_ID_MJPEG;

        } else if (!strcmp(str, "MVC2")) {

            st->codec->codec_id = AV_CODEC_ID_MVC2;

        } else {

            av_log_ask_for_sample(avctx, "unknown video compression %s\n", str);

        }

        av_free(str);

    } else if (!strcmp(name, "FPS")) {

        st->time_base = av_inv_q(var_read_float(pb, size));

    } else if (!strcmp(name, "HEIGHT")) {

        st->codec->height = var_read_int(pb, size);

    } else if (!strcmp(name, "PIXEL_ASPECT")) {

        st->sample_aspect_ratio = var_read_float(pb, size);

        av_reduce(&st->sample_aspect_ratio.num, &st->sample_aspect_ratio.den,

                  st->sample_aspect_ratio.num, st->sample_aspect_ratio.den, INT_MAX);

    } else if (!strcmp(name, "WIDTH")) {

        st->codec->width = var_read_int(pb, size);

    } else if (!strcmp(name, "ORIENTATION")) {

        if (var_read_int(pb, size) == 1101) {

            st->codec->extradata       = av_strdup("BottomUp");

            st->codec->extradata_size  = 9;

        }

    } else if (!strcmp(name, "Q_SPATIAL") || !strcmp(name, "Q_TEMPORAL")) {

        var_read_metadata(avctx, name, size);

    } else if (!strcmp(name, "INTERLACING") || !strcmp(name, "PACKING")) {

        avio_skip(pb, size); // ignore

    } else

        return -1;

    return 0;

}


static int uhci_handle_td(UHCIState *s, UHCIQueue *q, uint32_t qh_addr,

                          UHCI_TD *td, uint32_t td_addr, uint32_t *int_mask)

{

    int ret, max_len;

    bool spd;

    bool queuing = (q != NULL);

    uint8_t pid = td->token & 0xff;

    UHCIAsync *async;

    switch (pid) {

    case USB_TOKEN_OUT:

    case USB_TOKEN_SETUP:

    case USB_TOKEN_IN:

        break;

    default:

        /* invalid pid : frame interrupted */

        s->status |= UHCI_STS_HCPERR;

        s->cmd &= ~UHCI_CMD_RS;

        uhci_update_irq(s);

        return TD_RESULT_STOP_FRAME;

    }

    async = uhci_async_find_td(s, td_addr);

    if (async) {

        if (uhci_queue_verify(async->queue, qh_addr, td, td_addr, queuing)) {

            assert(q == NULL || q == async->queue);

            q = async->queue;

        } else {

            uhci_queue_free(async->queue, "guest re-used pending td");

            async = NULL;

        }

    }

    if (q == NULL) {

        q = uhci_queue_find(s, td);

        if (q && !uhci_queue_verify(q, qh_addr, td, td_addr, queuing)) {

            uhci_queue_free(q, "guest re-used qh");

            q = NULL;

        }

    }

    if (q) {

        q->valid = QH_VALID;

    }

    /* Is active ? */

    if (!(td->ctrl & TD_CTRL_ACTIVE)) {

        if (async) {

            /* Guest marked a pending td non-active, cancel the queue */

            uhci_queue_free(async->queue, "pending td non-active");

        }

        /*

         * ehci11d spec page 22: "Even if the Active bit in the TD is already

         * cleared when the TD is fetched ... an IOC interrupt is generated"

         */

        if (td->ctrl & TD_CTRL_IOC) {

                *int_mask |= 0x01;

        }

        return TD_RESULT_NEXT_QH;

    }

    if (async) {

        if (queuing) {

            /* we are busy filling the queue, we are not prepared

               to consume completed packages then, just leave them

               in async state */

            return TD_RESULT_ASYNC_CONT;

        }

        if (!async->done) {

            UHCI_TD last_td;

            UHCIAsync *last = QTAILQ_LAST(&async->queue->asyncs, asyncs_head);

            /*

             * While we are waiting for the current td to complete, the guest

             * may have added more tds to the queue. Note we re-read the td

             * rather then caching it, as we want to see guest made changes!

             */

            uhci_read_td(s, &last_td, last->td_addr);

            uhci_queue_fill(async->queue, &last_td);

            return TD_RESULT_ASYNC_CONT;

        }

        uhci_async_unlink(async);

        goto done;

    }

    if (s->completions_only) {

        return TD_RESULT_ASYNC_CONT;

    }

    /* Allocate new packet */

    if (q == NULL) {

        USBDevice *dev = uhci_find_device(s, (td->token >> 8) & 0x7f);

        USBEndpoint *ep = usb_ep_get(dev, pid, (td->token >> 15) & 0xf);

        if (ep == NULL) {

            return uhci_handle_td_error(s, td, td_addr, USB_RET_NODEV,

                                        int_mask);

        }

        q = uhci_queue_new(s, qh_addr, td, ep);

    }

    async = uhci_async_alloc(q, td_addr);

    max_len = ((td->token >> 21) + 1) & 0x7ff;

    spd = (pid == USB_TOKEN_IN && (td->ctrl & TD_CTRL_SPD) != 0);

    usb_packet_setup(&async->packet, pid, q->ep, 0, td_addr, spd,

                     (td->ctrl & TD_CTRL_IOC) != 0);

    if (max_len <= sizeof(async->static_buf)) {

        async->buf = async->static_buf;

    } else {

        async->buf = g_malloc(max_len);

    }

    usb_packet_addbuf(&async->packet, async->buf, max_len);

    switch(pid) {

    case USB_TOKEN_OUT:

    case USB_TOKEN_SETUP:

        pci_dma_read(&s->dev, td->buffer, async->buf, max_len);

        usb_handle_packet(q->ep->dev, &async->packet);

        if (async->packet.status == USB_RET_SUCCESS) {

            async->packet.actual_length = max_len;

        }

        break;

    case USB_TOKEN_IN:

        usb_handle_packet(q->ep->dev, &async->packet);

        break;

    default:

        abort(); /* Never to execute */

    }

    if (async->packet.status == USB_RET_ASYNC) {

        uhci_async_link(async);

        if (!queuing) {

            uhci_queue_fill(q, td);

        }

        return TD_RESULT_ASYNC_START;

    }

done:

    ret = uhci_complete_td(s, td, async, int_mask);

    uhci_async_free(async);

    return ret;

}


static int milkymist_minimac2_init(SysBusDevice *sbd)

{

    DeviceState *dev = DEVICE(sbd);

    MilkymistMinimac2State *s = MILKYMIST_MINIMAC2(dev);

    size_t buffers_size = TARGET_PAGE_ALIGN(3 * MINIMAC2_BUFFER_SIZE);

    sysbus_init_irq(sbd, &s->rx_irq);

    sysbus_init_irq(sbd, &s->tx_irq);

    memory_region_init_io(&s->regs_region, OBJECT(dev), &minimac2_ops, s,

                          "milkymist-minimac2", R_MAX * 4);

    sysbus_init_mmio(sbd, &s->regs_region);

    /* register buffers memory */

    memory_region_init_ram(&s->buffers, OBJECT(dev), "milkymist-minimac2.buffers",

                           buffers_size, &error_abort);

    vmstate_register_ram_global(&s->buffers);

    s->rx0_buf = memory_region_get_ram_ptr(&s->buffers);

    s->rx1_buf = s->rx0_buf + MINIMAC2_BUFFER_SIZE;

    s->tx_buf = s->rx1_buf + MINIMAC2_BUFFER_SIZE;

    sysbus_init_mmio(sbd, &s->buffers);

    qemu_macaddr_default_if_unset(&s->conf.macaddr);

    s->nic = qemu_new_nic(&net_milkymist_minimac2_info, &s->conf,

                          object_get_typename(OBJECT(dev)), dev->id, s);

    qemu_format_nic_info_str(qemu_get_queue(s->nic), s->conf.macaddr.a);

    return 0;

}


static void tcg_out_qemu_ld (TCGContext *s, const TCGArg *args, int opc)

{

    int addr_reg, data_reg, data_reg2, r0, r1, rbase, bswap;

#ifdef CONFIG_SOFTMMU

    int mem_index, s_bits, r2, addr_reg2;

    uint8_t *label_ptr;

#endif

    data_reg = *args++;

    if (opc == 3)

        data_reg2 = *args++;

    else

        data_reg2 = 0;

    addr_reg = *args++;

#ifdef CONFIG_SOFTMMU

#if TARGET_LONG_BITS == 64

    addr_reg2 = *args++;

#else

    addr_reg2 = 0;

#endif

    mem_index = *args;

    s_bits = opc & 3;

    r0 = 3;

    r1 = 4;

    r2 = 0;

    rbase = 0;

    tcg_out_tlb_check (

        s, r0, r1, r2, addr_reg, addr_reg2, s_bits,

        offsetof (CPUArchState, tlb_table[mem_index][0].addr_read),

        offsetof (CPUTLBEntry, addend) - offsetof (CPUTLBEntry, addr_read),

        &label_ptr

        );

#else  /* !CONFIG_SOFTMMU */

    r0 = addr_reg;

    r1 = 3;

    rbase = GUEST_BASE ? TCG_GUEST_BASE_REG : 0;

#endif

#ifdef TARGET_WORDS_BIGENDIAN

    bswap = 0;

#else

    bswap = 1;

#endif

    switch (opc) {

    default:

    case 0:

        tcg_out32 (s, LBZX | TAB (data_reg, rbase, r0));

        break;

    case 0|4:

        tcg_out32 (s, LBZX | TAB (data_reg, rbase, r0));

        tcg_out32 (s, EXTSB | RA (data_reg) | RS (data_reg));

        break;

    case 1:

        if (bswap)

            tcg_out32 (s, LHBRX | TAB (data_reg, rbase, r0));

        else

            tcg_out32 (s, LHZX | TAB (data_reg, rbase, r0));

        break;

    case 1|4:

        if (bswap) {

            tcg_out32 (s, LHBRX | TAB (data_reg, rbase, r0));

            tcg_out32 (s, EXTSH | RA (data_reg) | RS (data_reg));

        }

        else tcg_out32 (s, LHAX | TAB (data_reg, rbase, r0));

        break;

    case 2:

        if (bswap)

            tcg_out32 (s, LWBRX | TAB (data_reg, rbase, r0));

        else

            tcg_out32 (s, LWZX | TAB (data_reg, rbase, r0));

        break;

    case 3:

        if (bswap) {

            tcg_out32 (s, ADDI | RT (r1) | RA (r0) | 4);

            tcg_out32 (s, LWBRX | TAB (data_reg, rbase, r0));

            tcg_out32 (s, LWBRX | TAB (data_reg2, rbase, r1));

        }

        else {

#ifdef CONFIG_USE_GUEST_BASE

            tcg_out32 (s, ADDI | RT (r1) | RA (r0) | 4);

            tcg_out32 (s, LWZX | TAB (data_reg2, rbase, r0));

            tcg_out32 (s, LWZX | TAB (data_reg, rbase, r1));

#else

            if (r0 == data_reg2) {

                tcg_out32 (s, LWZ | RT (0) | RA (r0));

                tcg_out32 (s, LWZ | RT (data_reg) | RA (r0) | 4);

                tcg_out_mov (s, TCG_TYPE_I32, data_reg2, 0);

            }

            else {

                tcg_out32 (s, LWZ | RT (data_reg2) | RA (r0));

                tcg_out32 (s, LWZ | RT (data_reg) | RA (r0) | 4);

            }

#endif

        }

        break;

    }

#ifdef CONFIG_SOFTMMU

    add_qemu_ldst_label (s,

                         1,

                         opc,

                         data_reg,

                         data_reg2,

                         addr_reg,

                         addr_reg2,

                         mem_index,

                         s->code_ptr,

                         label_ptr);

#endif

}


static int url_connect(struct variant *var, AVDictionary *opts)

{

    AVDictionary *tmp = NULL;

    int ret;

    av_dict_copy(&tmp, opts, 0);

    av_opt_set_dict(var->input, &tmp);

    if ((ret = ffurl_connect(var->input, NULL)) < 0) {

        ffurl_close(var->input);

        var->input = NULL;

    }

    av_dict_free(&tmp);

    return ret;

}


void test_self_modifying_code(void)

{

    int (*func)(void);

    func = (void *)code;

    printf("self modifying code:\n");

    printf("func1 = 0x%x\n", func());

    code[1] = 0x2;

    printf("func1 = 0x%x\n", func());

}


static void fdt_add_psci_node(const VirtBoardInfo *vbi)

{

    void *fdt = vbi->fdt;

    ARMCPU *armcpu = ARM_CPU(qemu_get_cpu(0));

    /* No PSCI for TCG yet */

    if (kvm_enabled()) {

        qemu_fdt_add_subnode(fdt, "/psci");

        if (armcpu->psci_version == 2) {

            const char comp[] = "arm,psci-0.2\0arm,psci";

            qemu_fdt_setprop(fdt, "/psci", "compatible", comp, sizeof(comp));

        } else {

            qemu_fdt_setprop_string(fdt, "/psci", "compatible", "arm,psci");

        }

        qemu_fdt_setprop_string(fdt, "/psci", "method", "hvc");

        qemu_fdt_setprop_cell(fdt, "/psci", "cpu_suspend",

                                  QEMU_PSCI_0_1_FN_CPU_SUSPEND);

        qemu_fdt_setprop_cell(fdt, "/psci", "cpu_off", QEMU_PSCI_0_1_FN_CPU_OFF);

        qemu_fdt_setprop_cell(fdt, "/psci", "cpu_on", QEMU_PSCI_0_1_FN_CPU_ON);

        qemu_fdt_setprop_cell(fdt, "/psci", "migrate", QEMU_PSCI_0_1_FN_MIGRATE);

    }

}


static uint64_t ppc_radix64_walk_tree(PowerPCCPU *cpu, int rwx, vaddr eaddr,

                                      uint64_t base_addr, uint64_t nls,

                                      hwaddr *raddr, int *psize,

                                      int *fault_cause, int *prot,

                                      hwaddr *pte_addr)

{

    CPUState *cs = CPU(cpu);

    uint64_t index, pde;

    if (nls < 5) { /* Directory maps less than 2**5 entries */

        *fault_cause |= DSISR_R_BADCONFIG;

        return 0;

    }

    /* Read page <directory/table> entry from guest address space */

    index = eaddr >> (*psize - nls); /* Shift */

    index &= ((1UL << nls) - 1); /* Mask */

    pde = ldq_phys(cs->as, base_addr + (index * sizeof(pde)));

    if (!(pde & R_PTE_VALID)) { /* Invalid Entry */

        *fault_cause |= DSISR_NOPTE;

        return 0;

    }

    *psize -= nls;

    /* Check if Leaf Entry -> Page Table Entry -> Stop the Search */

    if (pde & R_PTE_LEAF) {

        uint64_t rpn = pde & R_PTE_RPN;

        uint64_t mask = (1UL << *psize) - 1;

        if (ppc_radix64_check_prot(cpu, rwx, pde, fault_cause, prot)) {

            return 0; /* Protection Denied Access */

        }

        /* Or high bits of rpn and low bits to ea to form whole real addr */

        *raddr = (rpn & ~mask) | (eaddr & mask);

        *pte_addr = base_addr + (index * sizeof(pde));

        return pde;

    }

    /* Next Level of Radix Tree */

    return ppc_radix64_walk_tree(cpu, rwx, eaddr, pde & R_PDE_NLB,

                                 pde & R_PDE_NLS, raddr, psize,

                                 fault_cause, prot, pte_addr);

}


static int cpu_mips_register (CPUMIPSState *env, const mips_def_t *def)

{

    env->CP0_PRid = def->CP0_PRid;

    env->CP0_Config0 = def->CP0_Config0;

#ifdef TARGET_WORDS_BIGENDIAN

    env->CP0_Config0 |= (1 << CP0C0_BE);

#endif

    env->CP0_Config1 = def->CP0_Config1;

    env->CP0_Config2 = def->CP0_Config2;

    env->CP0_Config3 = def->CP0_Config3;

    env->CP0_Config6 = def->CP0_Config6;

    env->CP0_Config7 = def->CP0_Config7;

    env->SYNCI_Step = def->SYNCI_Step;

    env->CCRes = def->CCRes;

    env->CP0_Status_rw_bitmask = def->CP0_Status_rw_bitmask;

    env->CP0_TCStatus_rw_bitmask = def->CP0_TCStatus_rw_bitmask;

    env->CP0_SRSCtl = def->CP0_SRSCtl;

    env->current_tc = 0;

    env->SEGBITS = def->SEGBITS;

    env->SEGMask = (target_ulong)((1ULL << def->SEGBITS) - 1);

#if defined(TARGET_MIPS64)

    if (def->insn_flags & ISA_MIPS3) {

        env->hflags |= MIPS_HFLAG_64;

        env->SEGMask |= 3ULL << 62;

    }

#endif

    env->PABITS = def->PABITS;

    env->PAMask = (target_ulong)((1ULL << def->PABITS) - 1);

    env->CP0_SRSConf0_rw_bitmask = def->CP0_SRSConf0_rw_bitmask;

    env->CP0_SRSConf0 = def->CP0_SRSConf0;

    env->CP0_SRSConf1_rw_bitmask = def->CP0_SRSConf1_rw_bitmask;

    env->CP0_SRSConf1 = def->CP0_SRSConf1;

    env->CP0_SRSConf2_rw_bitmask = def->CP0_SRSConf2_rw_bitmask;

    env->CP0_SRSConf2 = def->CP0_SRSConf2;

    env->CP0_SRSConf3_rw_bitmask = def->CP0_SRSConf3_rw_bitmask;

    env->CP0_SRSConf3 = def->CP0_SRSConf3;

    env->CP0_SRSConf4_rw_bitmask = def->CP0_SRSConf4_rw_bitmask;

    env->CP0_SRSConf4 = def->CP0_SRSConf4;

    env->insn_flags = def->insn_flags;

#ifndef CONFIG_USER_ONLY

    if (!env->user_mode_only)

        mmu_init(env, def);

#endif

    fpu_init(env, def);

    mvp_init(env, def);

    return 0;

}


static void scsi_write_do_fua(SCSIDiskReq *r)

{

    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);

    if (r->req.io_canceled) {

        scsi_req_cancel_complete(&r->req);

        goto done;

    }

    if (scsi_is_cmd_fua(&r->req.cmd)) {

        block_acct_start(bdrv_get_stats(s->qdev.conf.bs), &r->acct, 0,

                         BLOCK_ACCT_FLUSH);

        r->req.aiocb = bdrv_aio_flush(s->qdev.conf.bs, scsi_aio_complete, r);

        return;

    }

    scsi_req_complete(&r->req, GOOD);

done:

    scsi_req_unref(&r->req);

}


static uint32_t m5206_mbar_readb(void *opaque, target_phys_addr_t offset)

{

    m5206_mbar_state *s = (m5206_mbar_state *)opaque;

    offset &= 0x3ff;

    if (offset >= 0x200) {

        hw_error("Bad MBAR read offset 0x%x", (int)offset);

    }

    if (m5206_mbar_width[offset >> 2] > 1) {

        uint16_t val;

        val = m5206_mbar_readw(opaque, offset & ~1);

        if ((offset & 1) == 0) {

            val >>= 8;

        }

        return val & 0xff;

    }

    return m5206_mbar_read(s, offset, 1);

}


void HELPER(mvpg)(CPUS390XState *env, uint64_t r0, uint64_t r1, uint64_t r2)

{

    /* XXX missing r0 handling */

    env->cc_op = 0;

#ifdef CONFIG_USER_ONLY

    memmove(g2h(r1), g2h(r2), TARGET_PAGE_SIZE);

#else

    mvc_fast_memmove(env, TARGET_PAGE_SIZE, r1, r2);

#endif

}


int64_t qmp_guest_fsfreeze_thaw(Error **err)

{

    int ret;

    GuestFsfreezeMountList mounts;

    GuestFsfreezeMount *mount;

    int fd, i = 0, logged;

    QTAILQ_INIT(&mounts);

    ret = guest_fsfreeze_build_mount_list(&mounts);

    if (ret) {

        error_set(err, QERR_QGA_COMMAND_FAILED,

                  "failed to enumerate filesystems");

        return 0;

    }

    QTAILQ_FOREACH(mount, &mounts, next) {

        logged = false;

        fd = qemu_open(mount->dirname, O_RDONLY);

        if (fd == -1) {

            continue;

        }

        /* we have no way of knowing whether a filesystem was actually unfrozen

         * as a result of a successful call to FITHAW, only that if an error

         * was returned the filesystem was *not* unfrozen by that particular

         * call.

         *

         * since multiple preceeding FIFREEZEs require multiple calls to FITHAW

         * to unfreeze, continuing issuing FITHAW until an error is returned,

         * in which case either the filesystem is in an unfreezable state, or,

         * more likely, it was thawed previously (and remains so afterward).

         *

         * also, since the most recent successful call is the one that did

         * the actual unfreeze, we can use this to provide an accurate count

         * of the number of filesystems unfrozen by guest-fsfreeze-thaw, which

         * may * be useful for determining whether a filesystem was unfrozen

         * during the freeze/thaw phase by a process other than qemu-ga.

         */

        do {

            ret = ioctl(fd, FITHAW);

            if (ret == 0 && !logged) {

                i++;

                logged = true;

            }

        } while (ret == 0);

        close(fd);

    }

    guest_fsfreeze_state.status = GUEST_FSFREEZE_STATUS_THAWED;

    enable_logging();

    guest_fsfreeze_free_mount_list(&mounts);

    return i;

}


static av_cold int xwd_encode_init(AVCodecContext *avctx)

{

    avctx->coded_frame = av_frame_alloc();

    if (!avctx->coded_frame)

        return AVERROR(ENOMEM);

    return 0;

}


bool cpu_exec_all(void)

{

    int ret = 0;

    if (next_cpu == NULL)

        next_cpu = first_cpu;

    for (; next_cpu != NULL && !exit_request; next_cpu = next_cpu->next_cpu) {

        CPUState *env = next_cpu;

        qemu_clock_enable(vm_clock,

                          (env->singlestep_enabled & SSTEP_NOTIMER) == 0);

        if (qemu_alarm_pending())

            break;

        if (cpu_can_run(env))

            ret = qemu_cpu_exec(env);

        else if (env->stop)

            break;

        if (ret == EXCP_DEBUG) {

            gdb_set_stop_cpu(env);

            debug_requested = EXCP_DEBUG;

            break;

        }

    }

    exit_request = 0;

    return any_cpu_has_work();

}


static inline void *alloc_code_gen_buffer(void)

{

    int flags = MAP_PRIVATE | MAP_ANONYMOUS;

    uintptr_t start = 0;

    size_t size = tcg_ctx.code_gen_buffer_size;

    void *buf;

    /* Constrain the position of the buffer based on the host cpu.

       Note that these addresses are chosen in concert with the

       addresses assigned in the relevant linker script file.  */

# if defined(__PIE__) || defined(__PIC__)

    /* Don't bother setting a preferred location if we're building

       a position-independent executable.  We're more likely to get

       an address near the main executable if we let the kernel

       choose the address.  */

# elif defined(__x86_64__) && defined(MAP_32BIT)

    /* Force the memory down into low memory with the executable.

       Leave the choice of exact location with the kernel.  */

    flags |= MAP_32BIT;

    /* Cannot expect to map more than 800MB in low memory.  */

    if (size > 800u * 1024 * 1024) {

        tcg_ctx.code_gen_buffer_size = size = 800u * 1024 * 1024;

    }

# elif defined(__sparc__)

    start = 0x40000000ul;

# elif defined(__s390x__)

    start = 0x90000000ul;

# elif defined(__mips__)

#  if _MIPS_SIM == _ABI64

    start = 0x128000000ul;

#  else

    start = 0x08000000ul;

#  endif

# endif

    buf = mmap((void *)start, size + qemu_real_host_page_size,

               PROT_NONE, flags, -1, 0);

    if (buf == MAP_FAILED) {

        return NULL;

    }

#ifdef __mips__

    if (cross_256mb(buf, size)) {

        /* Try again, with the original still mapped, to avoid re-acquiring

           that 256mb crossing.  This time don't specify an address.  */

        size_t size2;

        void *buf2 = mmap(NULL, size + qemu_real_host_page_size,

                          PROT_NONE, flags, -1, 0);

        switch (buf2 != MAP_FAILED) {

        case 1:

            if (!cross_256mb(buf2, size)) {

                /* Success!  Use the new buffer.  */

                munmap(buf, size);

                break;

            }

            /* Failure.  Work with what we had.  */

            munmap(buf2, size);

            /* fallthru */

        default:

            /* Split the original buffer.  Free the smaller half.  */

            buf2 = split_cross_256mb(buf, size);

            size2 = tcg_ctx.code_gen_buffer_size;

            if (buf == buf2) {

                munmap(buf + size2 + qemu_real_host_page_size, size - size2);

            } else {

                munmap(buf, size - size2);

            }

            size = size2;

            break;

        }

        buf = buf2;

    }

#endif

    /* Make the final buffer accessible.  The guard page at the end

       will remain inaccessible with PROT_NONE.  */

    mprotect(buf, size, PROT_WRITE | PROT_READ | PROT_EXEC);

    /* Request large pages for the buffer.  */

    qemu_madvise(buf, size, QEMU_MADV_HUGEPAGE);

    return buf;

}


size_t iov_from_buf(struct iovec *iov, unsigned int iov_cnt, size_t iov_off,

                    const void *buf, size_t size)

{

    size_t iovec_off, buf_off;

    unsigned int i;

    iovec_off = 0;

    buf_off = 0;

    for (i = 0; i < iov_cnt && size; i++) {

        if (iov_off < (iovec_off + iov[i].iov_len)) {

            size_t len = MIN((iovec_off + iov[i].iov_len) - iov_off, size);

            memcpy(iov[i].iov_base + (iov_off - iovec_off), buf + buf_off, len);

            buf_off += len;

            iov_off += len;

            size -= len;

        }

        iovec_off += iov[i].iov_len;

    }

    return buf_off;

}


static int eth_can_rx(NetClientState *nc)

{

    struct xlx_ethlite *s = DO_UPCAST(NICState, nc, nc)->opaque;

    int r;

    r = !(s->regs[R_RX_CTRL0] & CTRL_S);

    return r;

}


static uint64_t exynos4210_pmu_read(void *opaque, target_phys_addr_t offset,

                                    unsigned size)

{

    Exynos4210PmuState *s = (Exynos4210PmuState *)opaque;

    unsigned i;

    const Exynos4210PmuReg *reg_p = exynos4210_pmu_regs;

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

        if (reg_p->offset == offset) {

            PRINT_DEBUG_EXTEND("%s [0x%04x] -> 0x%04x\n", reg_p->name,

                                   (uint32_t)offset, s->reg[i]);

            return s->reg[i];

        }

        reg_p++;

    }

    PRINT_DEBUG("QEMU PMU ERROR: bad read offset 0x%04x\n", (uint32_t)offset);

    return 0;

}


static void simple_number(void)

{

    int i;

    struct {

        const char *encoded;

        int64_t decoded;

        int skip;

    } test_cases[] = {

        { "0", 0 },

        { "1234", 1234 },

        { "1", 1 },

        { "-32", -32 },

        { "-0", 0, .skip = 1 },

        { },

    };

    for (i = 0; test_cases[i].encoded; i++) {

        QObject *obj;

        QInt *qint;

        obj = qobject_from_json(test_cases[i].encoded);

        g_assert(obj != NULL);

        g_assert(qobject_type(obj) == QTYPE_QINT);

        qint = qobject_to_qint(obj);

        g_assert(qint_get_int(qint) == test_cases[i].decoded);

        if (test_cases[i].skip == 0) {

            QString *str;

            str = qobject_to_json(obj);

            g_assert(strcmp(qstring_get_str(str), test_cases[i].encoded) == 0);

            QDECREF(str);

        }

        QDECREF(qint);

    }

}


static int check_exception(int intno, int *error_code)

{

    int first_contributory = env->old_exception == 0 ||

                              (env->old_exception >= 10 &&

                               env->old_exception <= 13);

    int second_contributory = intno == 0 ||

                               (intno >= 10 && intno <= 13);

    qemu_log_mask(CPU_LOG_INT, "check_exception old: 0x%x new 0x%x\n",

                env->old_exception, intno);

    if (env->old_exception == EXCP08_DBLE)

        cpu_abort(env, "triple fault");

    if ((first_contributory && second_contributory)

        || (env->old_exception == EXCP0E_PAGE &&

            (second_contributory || (intno == EXCP0E_PAGE)))) {

        intno = EXCP08_DBLE;

        *error_code = 0;

    }

    if (second_contributory || (intno == EXCP0E_PAGE) ||

        (intno == EXCP08_DBLE))

        env->old_exception = intno;

    return intno;

}


yuv2rgb48_1_c_template(SwsContext *c, const int32_t *buf0,

                       const int32_t *ubuf[2], const int32_t *vbuf[2],

                       const int32_t *abuf0, uint16_t *dest, int dstW,

                       int uvalpha, int y, enum PixelFormat target)

{

    const int32_t *ubuf0 = ubuf[0], *ubuf1 = ubuf[1],

                  *vbuf0 = vbuf[0], *vbuf1 = vbuf[1];

    int i;

    if (uvalpha < 2048) {

        for (i = 0; i < (dstW >> 1); i++) {

            int Y1 = (buf0[i * 2]    ) >> 2;

            int Y2 = (buf0[i * 2 + 1]) >> 2;

            int U  = (ubuf0[i] + (-128 << 11)) >> 2;

            int V  = (vbuf0[i] + (-128 << 11)) >> 2;

            int R, G, B;

            Y1 -= c->yuv2rgb_y_offset;

            Y2 -= c->yuv2rgb_y_offset;

            Y1 *= c->yuv2rgb_y_coeff;

            Y2 *= c->yuv2rgb_y_coeff;

            Y1 += 1 << 13;

            Y2 += 1 << 13;

            R = V * c->yuv2rgb_v2r_coeff;

            G = V * c->yuv2rgb_v2g_coeff + U * c->yuv2rgb_u2g_coeff;

            B =                            U * c->yuv2rgb_u2b_coeff;

            output_pixel(&dest[0], av_clip_uintp2(R_B + Y1, 30) >> 14);

            output_pixel(&dest[1], av_clip_uintp2(  G + Y1, 30) >> 14);

            output_pixel(&dest[2], av_clip_uintp2(B_R + Y1, 30) >> 14);

            output_pixel(&dest[3], av_clip_uintp2(R_B + Y2, 30) >> 14);

            output_pixel(&dest[4], av_clip_uintp2(  G + Y2, 30) >> 14);

            output_pixel(&dest[5], av_clip_uintp2(B_R + Y2, 30) >> 14);

            dest += 6;

        }

    } else {

        for (i = 0; i < (dstW >> 1); i++) {

            int Y1 = (buf0[i * 2]    ) >> 2;

            int Y2 = (buf0[i * 2 + 1]) >> 2;

            int U  = (ubuf0[i] + ubuf1[i] + (-128 << 11)) >> 3;

            int V  = (vbuf0[i] + vbuf1[i] + (-128 << 11)) >> 3;

            int R, G, B;

            Y1 -= c->yuv2rgb_y_offset;

            Y2 -= c->yuv2rgb_y_offset;

            Y1 *= c->yuv2rgb_y_coeff;

            Y2 *= c->yuv2rgb_y_coeff;

            Y1 += 1 << 13;

            Y2 += 1 << 13;

            R = V * c->yuv2rgb_v2r_coeff;

            G = V * c->yuv2rgb_v2g_coeff + U * c->yuv2rgb_u2g_coeff;

            B =                            U * c->yuv2rgb_u2b_coeff;

            output_pixel(&dest[0], av_clip_uintp2(R_B + Y1, 30) >> 14);

            output_pixel(&dest[1], av_clip_uintp2(  G + Y1, 30) >> 14);

            output_pixel(&dest[2], av_clip_uintp2(B_R + Y1, 30) >> 14);

            output_pixel(&dest[3], av_clip_uintp2(R_B + Y2, 30) >> 14);

            output_pixel(&dest[4], av_clip_uintp2(  G + Y2, 30) >> 14);

            output_pixel(&dest[5], av_clip_uintp2(B_R + Y2, 30) >> 14);

            dest += 6;

        }

    }

}


static void mxf_read_pixel_layout(AVIOContext *pb, MXFDescriptor *descriptor)

{

    int code, value, ofs = 0;

    char layout[16] = {0}; /* not for printing, may end up not terminated on purpose */

    do {

        code = avio_r8(pb);

        value = avio_r8(pb);

        av_dlog(NULL, "pixel layout: code %#x\n", code);

        if (ofs <= 14) {

            layout[ofs++] = code;

            layout[ofs++] = value;

        }

    } while (code != 0); /* SMPTE 377M E.2.46 */

    ff_mxf_decode_pixel_layout(layout, &descriptor->pix_fmt);

}


static av_always_inline void rv40_weak_loop_filter(uint8_t *src,

                                                   const int step,

                                                   const ptrdiff_t stride,

                                                   const int filter_p1,

                                                   const int filter_q1,

                                                   const int alpha,

                                                   const int beta,

                                                   const int lim_p0q0,

                                                   const int lim_q1,

                                                   const int lim_p1)

{

    const uint8_t *cm = ff_crop_tab + MAX_NEG_CROP;

    int i, t, u, diff;

    for (i = 0; i < 4; i++, src += stride) {

        int diff_p1p0 = src[-2*step] - src[-1*step];

        int diff_q1q0 = src[ 1*step] - src[ 0*step];

        int diff_p1p2 = src[-2*step] - src[-3*step];

        int diff_q1q2 = src[ 1*step] - src[ 2*step];

        t = src[0*step] - src[-1*step];

        if (!t)

            continue;

        u = (alpha * FFABS(t)) >> 7;

        if (u > 3 - (filter_p1 && filter_q1))

            continue;

        t <<= 2;

        if (filter_p1 && filter_q1)

            t += src[-2*step] - src[1*step];

        diff = CLIP_SYMM((t + 4) >> 3, lim_p0q0);

        src[-1*step] = cm[src[-1*step] + diff];

        src[ 0*step] = cm[src[ 0*step] - diff];

        if (filter_p1 && FFABS(diff_p1p2) <= beta) {

            t = (diff_p1p0 + diff_p1p2 - diff) >> 1;

            src[-2*step] = cm[src[-2*step] - CLIP_SYMM(t, lim_p1)];

        }

        if (filter_q1 && FFABS(diff_q1q2) <= beta) {

            t = (diff_q1q0 + diff_q1q2 + diff) >> 1;

            src[ 1*step] = cm[src[ 1*step] - CLIP_SYMM(t, lim_q1)];

        }

    }

}


static int tak_decode_frame(AVCodecContext *avctx, void *data,

                            int *got_frame_ptr, AVPacket *pkt)

{

    TAKDecContext *s  = avctx->priv_data;

    AVFrame *frame    = data;

    ThreadFrame tframe = { .f = data };

    GetBitContext *gb = &s->gb;

    int chan, i, ret, hsize;

    if (pkt->size < TAK_MIN_FRAME_HEADER_BYTES)

        return AVERROR_INVALIDDATA;

    if ((ret = init_get_bits8(gb, pkt->data, pkt->size)) < 0)

        return ret;

    if ((ret = ff_tak_decode_frame_header(avctx, gb, &s->ti, 0)) < 0)

        return ret;

    hsize = get_bits_count(gb) / 8;

    if (avctx->err_recognition & (AV_EF_CRCCHECK|AV_EF_COMPLIANT)) {

        if (ff_tak_check_crc(pkt->data, hsize)) {

            av_log(avctx, AV_LOG_ERROR, "CRC error\n");

            if (avctx->err_recognition & AV_EF_EXPLODE)

                return AVERROR_INVALIDDATA;

        }

    }

    if (s->ti.codec != TAK_CODEC_MONO_STEREO &&

        s->ti.codec != TAK_CODEC_MULTICHANNEL) {

        avpriv_report_missing_feature(avctx, "TAK codec type %d", s->ti.codec);

        return AVERROR_PATCHWELCOME;

    }

    if (s->ti.data_type) {

        av_log(avctx, AV_LOG_ERROR,

               "unsupported data type: %d\n", s->ti.data_type);

        return AVERROR_INVALIDDATA;

    }

    if (s->ti.codec == TAK_CODEC_MONO_STEREO && s->ti.channels > 2) {

        av_log(avctx, AV_LOG_ERROR,

               "invalid number of channels: %d\n", s->ti.channels);

        return AVERROR_INVALIDDATA;

    }

    if (s->ti.channels > 6) {

        av_log(avctx, AV_LOG_ERROR,

               "unsupported number of channels: %d\n", s->ti.channels);

        return AVERROR_INVALIDDATA;

    }

    if (s->ti.frame_samples <= 0) {

        av_log(avctx, AV_LOG_ERROR, "unsupported/invalid number of samples\n");

        return AVERROR_INVALIDDATA;

    }

    avctx->bits_per_raw_sample = s->ti.bps;

    if ((ret = set_bps_params(avctx)) < 0)

        return ret;

    if (s->ti.sample_rate != avctx->sample_rate) {

        avctx->sample_rate = s->ti.sample_rate;

        set_sample_rate_params(avctx);

    }

    if (s->ti.ch_layout)

        avctx->channel_layout = s->ti.ch_layout;

    avctx->channels = s->ti.channels;

    s->nb_samples = s->ti.last_frame_samples ? s->ti.last_frame_samples

                                             : s->ti.frame_samples;

    frame->nb_samples = s->nb_samples;

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

        return ret;

    ff_thread_finish_setup(avctx);

    if (avctx->bits_per_raw_sample <= 16) {

        int buf_size = av_samples_get_buffer_size(NULL, avctx->channels,

                                                  s->nb_samples,

                                                  AV_SAMPLE_FMT_S32P, 0);

        if (buf_size < 0)

            return buf_size;

        av_fast_malloc(&s->decode_buffer, &s->decode_buffer_size, buf_size);

        if (!s->decode_buffer)

            return AVERROR(ENOMEM);

        ret = av_samples_fill_arrays((uint8_t **)s->decoded, NULL,

                                     s->decode_buffer, avctx->channels,

                                     s->nb_samples, AV_SAMPLE_FMT_S32P, 0);

        if (ret < 0)

            return ret;

    } else {

        for (chan = 0; chan < avctx->channels; chan++)

            s->decoded[chan] = (int32_t *)frame->extended_data[chan];

    }

    if (s->nb_samples < 16) {

        for (chan = 0; chan < avctx->channels; chan++) {

            int32_t *decoded = s->decoded[chan];

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

                decoded[i] = get_sbits(gb, avctx->bits_per_raw_sample);

        }

    } else {

        if (s->ti.codec == TAK_CODEC_MONO_STEREO) {

            for (chan = 0; chan < avctx->channels; chan++)

                if (ret = decode_channel(s, chan))

                    return ret;

            if (avctx->channels == 2) {

                s->nb_subframes = get_bits(gb, 1) + 1;

                if (s->nb_subframes > 1) {

                    s->subframe_len[1] = get_bits(gb, 6);

                }

                s->dmode = get_bits(gb, 3);

                if (ret = decorrelate(s, 0, 1, s->nb_samples - 1))

                    return ret;

            }

        } else if (s->ti.codec == TAK_CODEC_MULTICHANNEL) {

            if (get_bits1(gb)) {

                int ch_mask = 0;

                chan = get_bits(gb, 4) + 1;

                if (chan > avctx->channels)

                    return AVERROR_INVALIDDATA;

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

                    int nbit = get_bits(gb, 4);

                    if (nbit >= avctx->channels)

                        return AVERROR_INVALIDDATA;

                    if (ch_mask & 1 << nbit)

                        return AVERROR_INVALIDDATA;

                    s->mcdparams[i].present = get_bits1(gb);

                    if (s->mcdparams[i].present) {

                        s->mcdparams[i].index = get_bits(gb, 2);

                        s->mcdparams[i].chan2 = get_bits(gb, 4);

                        if (s->mcdparams[i].chan2 >= avctx->channels) {

                            av_log(avctx, AV_LOG_ERROR,

                                   "invalid channel 2 (%d) for %d channel(s)\n",

                                   s->mcdparams[i].chan2, avctx->channels);

                            return AVERROR_INVALIDDATA;

                        }

                        if (s->mcdparams[i].index == 1) {

                            if ((nbit == s->mcdparams[i].chan2) ||

                                (ch_mask & 1 << s->mcdparams[i].chan2))

                                return AVERROR_INVALIDDATA;

                            ch_mask |= 1 << s->mcdparams[i].chan2;

                        } else if (!(ch_mask & 1 << s->mcdparams[i].chan2)) {

                            return AVERROR_INVALIDDATA;

                        }

                    }

                    s->mcdparams[i].chan1 = nbit;

                    ch_mask |= 1 << nbit;

                }

            } else {

                chan = avctx->channels;

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

                    s->mcdparams[i].present = 0;

                    s->mcdparams[i].chan1   = i;

                }

            }

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

                if (s->mcdparams[i].present && s->mcdparams[i].index == 1)

                    if (ret = decode_channel(s, s->mcdparams[i].chan2))

                        return ret;

                if (ret = decode_channel(s, s->mcdparams[i].chan1))

                    return ret;

                if (s->mcdparams[i].present) {

                    s->dmode = mc_dmodes[s->mcdparams[i].index];

                    if (ret = decorrelate(s,

                                          s->mcdparams[i].chan2,

                                          s->mcdparams[i].chan1,

                                          s->nb_samples - 1))

                        return ret;

                }

            }

        }

        for (chan = 0; chan < avctx->channels; chan++) {

            int32_t *decoded = s->decoded[chan];

            if (s->lpc_mode[chan])

                decode_lpc(decoded, s->lpc_mode[chan], s->nb_samples);

            if (s->sample_shift[chan] > 0)

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

                    decoded[i] *= 1 << s->sample_shift[chan];

        }

    }

    align_get_bits(gb);

    skip_bits(gb, 24);

    if (get_bits_left(gb) < 0)

        av_log(avctx, AV_LOG_DEBUG, "overread\n");

    else if (get_bits_left(gb) > 0)

        av_log(avctx, AV_LOG_DEBUG, "underread\n");

    if (avctx->err_recognition & (AV_EF_CRCCHECK | AV_EF_COMPLIANT)) {

        if (ff_tak_check_crc(pkt->data + hsize,

                             get_bits_count(gb) / 8 - hsize)) {

            av_log(avctx, AV_LOG_ERROR, "CRC error\n");

            if (avctx->err_recognition & AV_EF_EXPLODE)

                return AVERROR_INVALIDDATA;

        }

    }

    /* convert to output buffer */

    switch (avctx->sample_fmt) {

    case AV_SAMPLE_FMT_U8P:

        for (chan = 0; chan < avctx->channels; chan++) {

            uint8_t *samples = (uint8_t *)frame->extended_data[chan];

            int32_t *decoded = s->decoded[chan];

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

                samples[i] = decoded[i] + 0x80;

        }

        break;

    case AV_SAMPLE_FMT_S16P:

        for (chan = 0; chan < avctx->channels; chan++) {

            int16_t *samples = (int16_t *)frame->extended_data[chan];

            int32_t *decoded = s->decoded[chan];

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

                samples[i] = decoded[i];

        }

        break;

    case AV_SAMPLE_FMT_S32P:

        for (chan = 0; chan < avctx->channels; chan++) {

            int32_t *samples = (int32_t *)frame->extended_data[chan];

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

                samples[i] *= 1 << 8;

        }

        break;

    }

    *got_frame_ptr = 1;

    return pkt->size;

}


static int msnwc_tcp_read_packet(AVFormatContext *ctx, AVPacket *pkt)

{

    AVIOContext *pb = ctx->pb;

    uint16_t keyframe;

    uint32_t size, timestamp;

    avio_skip(pb, 1); /* one byte has been read ahead */

    avio_skip(pb, 2);

    avio_skip(pb, 2);

    keyframe = avio_rl16(pb);

    size = avio_rl32(pb);

    avio_skip(pb, 4);

    avio_skip(pb, 4);

    timestamp = avio_rl32(pb);

    if(!size || av_get_packet(pb, pkt, size) != size)

        return -1;

    avio_skip(pb, 1); /* Read ahead one byte of struct size like read_header */

    pkt->pts = timestamp;

    pkt->dts = timestamp;

    pkt->stream_index = 0;

    /* Some aMsn generated videos (or was it Mercury Messenger?) don't set

     * this bit and rely on the codec to get keyframe information */

    if(keyframe&1)

        pkt->flags |= AV_PKT_FLAG_KEY;

    return HEADER_SIZE + size;

}


static int zerocodec_decode_frame(AVCodecContext *avctx, void *data,

                                  int *data_size, AVPacket *avpkt)

{

    ZeroCodecContext *zc = avctx->priv_data;

    AVFrame *pic         = avctx->coded_frame;

    AVFrame *prev_pic    = &zc->previous_frame;

    z_stream *zstream    = &zc->zstream;

    uint8_t *prev, *dst;

    int i, j, zret;

    pic->reference = 3;

    if (avctx->get_buffer(avctx, pic) < 0) {

        av_log(avctx, AV_LOG_ERROR, "Could not allocate buffer.\n");

        return AVERROR(ENOMEM);

    zret = inflateReset(zstream);

    if (zret != Z_OK) {

        av_log(avctx, AV_LOG_ERROR, "Could not reset inflate: %d\n", zret);

        return AVERROR(EINVAL);

    zstream->next_in   = avpkt->data;

    zstream->avail_in  = avpkt->size;

    prev = prev_pic->data[0];

    dst  = pic->data[0];

    /**

     * ZeroCodec has very simple interframe compression. If a value

     * is the same as the previous frame, set it to 0.

     */

    if (avpkt->flags & AV_PKT_FLAG_KEY) {

        pic->key_frame = 1;

        pic->pict_type = AV_PICTURE_TYPE_I;

    } else {

        pic->key_frame = 0;

        pic->pict_type = AV_PICTURE_TYPE_P;

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

        zstream->next_out  = dst;

        zstream->avail_out = avctx->width << 1;

        zret = inflate(zstream, Z_SYNC_FLUSH);

        if (zret != Z_OK && zret != Z_STREAM_END) {

            av_log(avctx, AV_LOG_ERROR,

                   "Inflate failed with return code: %d\n", zret);

            return AVERROR(EINVAL);

        if (!(avpkt->flags & AV_PKT_FLAG_KEY))

            for (j = 0; j < avctx->width << 1; j++)

                dst[j] += prev[j] & -!dst[j];

        prev += prev_pic->linesize[0];

        dst  += pic->linesize[0];

    /* Release the previous buffer if need be */

    if (prev_pic->data[0])

        avctx->release_buffer(avctx, prev_pic);

    /* Store the previouse frame for use later */

    *prev_pic = *pic;

    *data_size = sizeof(AVFrame);

    *(AVFrame *)data = *pic;

    return avpkt->size;


bool virtio_scsi_handle_cmd_vq(VirtIOSCSI *s, VirtQueue *vq)

{

    VirtIOSCSIReq *req, *next;

    int ret = 0;

    bool progress = false;

    QTAILQ_HEAD(, VirtIOSCSIReq) reqs = QTAILQ_HEAD_INITIALIZER(reqs);

    virtio_scsi_acquire(s);

    do {

        virtio_queue_set_notification(vq, 0);

        while ((req = virtio_scsi_pop_req(s, vq))) {

            progress = true;

            ret = virtio_scsi_handle_cmd_req_prepare(s, req);

            if (!ret) {

                QTAILQ_INSERT_TAIL(&reqs, req, next);

            } else if (ret == -EINVAL) {

                /* The device is broken and shouldn't process any request */

                while (!QTAILQ_EMPTY(&reqs)) {

                    req = QTAILQ_FIRST(&reqs);

                    QTAILQ_REMOVE(&reqs, req, next);

                    blk_io_unplug(req->sreq->dev->conf.blk);

                    scsi_req_unref(req->sreq);

                    virtqueue_detach_element(req->vq, &req->elem, 0);

                    virtio_scsi_free_req(req);

                }

            }

        }

        virtio_queue_set_notification(vq, 1);

    } while (ret != -EINVAL && !virtio_queue_empty(vq));

    QTAILQ_FOREACH_SAFE(req, &reqs, next, next) {

        virtio_scsi_handle_cmd_req_submit(s, req);

    }

    virtio_scsi_release(s);

    return progress;

}


int ff_vda_create_decoder(struct vda_context *vda_ctx,

                          uint8_t *extradata,

                          int extradata_size)

{

    OSStatus status = kVDADecoderNoErr;

    CFNumberRef height;

    CFNumberRef width;

    CFNumberRef format;

    CFDataRef avc_data;

    CFMutableDictionaryRef config_info;

    CFMutableDictionaryRef buffer_attributes;

    CFMutableDictionaryRef io_surface_properties;

    CFNumberRef cv_pix_fmt;

    /* Each VCL NAL in the bistream sent to the decoder

     * is preceded by a 4 bytes length header.

     * Change the avcC atom header if needed, to signal headers of 4 bytes. */

    if (extradata_size >= 4 && (extradata[4] & 0x03) != 0x03) {

        uint8_t *rw_extradata;

        if (!(rw_extradata = av_malloc(extradata_size)))

            return AVERROR(ENOMEM);

        memcpy(rw_extradata, extradata, extradata_size);

        rw_extradata[4] |= 0x03;

        avc_data = CFDataCreate(kCFAllocatorDefault, rw_extradata, extradata_size);

        av_freep(&rw_extradata);

    } else {

        avc_data = CFDataCreate(kCFAllocatorDefault, extradata, extradata_size);

    }

    config_info = CFDictionaryCreateMutable(kCFAllocatorDefault,

                                            4,

                                            &kCFTypeDictionaryKeyCallBacks,

                                            &kCFTypeDictionaryValueCallBacks);

    height   = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &vda_ctx->height);

    width    = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &vda_ctx->width);

    format   = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &vda_ctx->format);

    CFDictionarySetValue(config_info, kVDADecoderConfiguration_Height, height);

    CFDictionarySetValue(config_info, kVDADecoderConfiguration_Width, width);

    CFDictionarySetValue(config_info, kVDADecoderConfiguration_SourceFormat, format);

    CFDictionarySetValue(config_info, kVDADecoderConfiguration_avcCData, avc_data);

    buffer_attributes = CFDictionaryCreateMutable(kCFAllocatorDefault,

                                                  2,

                                                  &kCFTypeDictionaryKeyCallBacks,

                                                  &kCFTypeDictionaryValueCallBacks);

    io_surface_properties = CFDictionaryCreateMutable(kCFAllocatorDefault,

                                                      0,

                                                      &kCFTypeDictionaryKeyCallBacks,

                                                      &kCFTypeDictionaryValueCallBacks);

    cv_pix_fmt      = CFNumberCreate(kCFAllocatorDefault,

                                     kCFNumberSInt32Type,

                                     &vda_ctx->cv_pix_fmt_type);

    CFDictionarySetValue(buffer_attributes,

                         kCVPixelBufferPixelFormatTypeKey,

                         cv_pix_fmt);

    CFDictionarySetValue(buffer_attributes,

                         kCVPixelBufferIOSurfacePropertiesKey,

                         io_surface_properties);

    status = VDADecoderCreate(config_info,

                              buffer_attributes,

                              vda_decoder_callback,

                              vda_ctx,

                              &vda_ctx->decoder);

    CFRelease(height);

    CFRelease(width);

    CFRelease(format);

    CFRelease(avc_data);

    CFRelease(config_info);

    CFRelease(io_surface_properties);

    CFRelease(cv_pix_fmt);

    CFRelease(buffer_attributes);

    return status;

}


static int qcow2_check(BlockDriverState *bs, BdrvCheckResult *result,

                       BdrvCheckMode fix)

{

    return qcow2_check_refcounts(bs, result, fix);

}


bool memory_region_present(MemoryRegion *parent, hwaddr addr)

{

    MemoryRegion *mr = memory_region_find(parent, addr, 1).mr;

    if (!mr) {

        return false;

    }

    memory_region_unref(mr);

    return true;

}


static int nut_probe(AVProbeData *p) {

    if (p->buf_size >= ID_LENGTH && !memcmp(p->buf, ID_STRING, ID_LENGTH)) return AVPROBE_SCORE_MAX;

    return 0;

}


static void check_native_list(QObject *qobj,

                              UserDefNativeListUnionKind kind)

{

    QDict *qdict;

    QList *qlist;

    int i;

    g_assert(qobj);

    g_assert(qobject_type(qobj) == QTYPE_QDICT);

    qdict = qobject_to_qdict(qobj);

    g_assert(qdict);

    g_assert(qdict_haskey(qdict, "data"));

    qlist = qlist_copy(qobject_to_qlist(qdict_get(qdict, "data")));

    switch (kind) {

    case USER_DEF_NATIVE_LIST_UNION_KIND_S8:

    case USER_DEF_NATIVE_LIST_UNION_KIND_S16:

    case USER_DEF_NATIVE_LIST_UNION_KIND_S32:

    case USER_DEF_NATIVE_LIST_UNION_KIND_S64:

    case USER_DEF_NATIVE_LIST_UNION_KIND_U8:

    case USER_DEF_NATIVE_LIST_UNION_KIND_U16:

    case USER_DEF_NATIVE_LIST_UNION_KIND_U32:

    case USER_DEF_NATIVE_LIST_UNION_KIND_U64:

        /* all integer elements in JSON arrays get stored into QInts when

         * we convert to QObjects, so we can check them all in the same

         * fashion, so simply fall through here

         */

    case USER_DEF_NATIVE_LIST_UNION_KIND_INTEGER:

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

            QObject *tmp;

            QInt *qvalue;

            tmp = qlist_peek(qlist);

            g_assert(tmp);

            qvalue = qobject_to_qint(tmp);

            g_assert_cmpint(qint_get_int(qvalue), ==, i);

            qobject_decref(qlist_pop(qlist));

        }

        break;

    case USER_DEF_NATIVE_LIST_UNION_KIND_BOOLEAN:

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

            QObject *tmp;

            QBool *qvalue;

            tmp = qlist_peek(qlist);

            g_assert(tmp);

            qvalue = qobject_to_qbool(tmp);

            g_assert_cmpint(qbool_get_bool(qvalue), ==, i % 3 == 0);

            qobject_decref(qlist_pop(qlist));

        }

        break;

    case USER_DEF_NATIVE_LIST_UNION_KIND_STRING:

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

            QObject *tmp;

            QString *qvalue;

            gchar str[8];

            tmp = qlist_peek(qlist);

            g_assert(tmp);

            qvalue = qobject_to_qstring(tmp);

            sprintf(str, "%d", i);

            g_assert_cmpstr(qstring_get_str(qvalue), ==, str);

            qobject_decref(qlist_pop(qlist));

        }

        break;

    case USER_DEF_NATIVE_LIST_UNION_KIND_NUMBER:

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

            QObject *tmp;

            QFloat *qvalue;

            GString *double_expected = g_string_new("");

            GString *double_actual = g_string_new("");

            tmp = qlist_peek(qlist);

            g_assert(tmp);

            qvalue = qobject_to_qfloat(tmp);

            g_string_printf(double_expected, "%.6f", (double)i / 3);

            g_string_printf(double_actual, "%.6f", qfloat_get_double(qvalue));

            g_assert_cmpstr(double_actual->str, ==, double_expected->str);

            qobject_decref(qlist_pop(qlist));

            g_string_free(double_expected, true);

            g_string_free(double_actual, true);

        }

        break;

    default:

        g_assert_not_reached();

    }

    QDECREF(qlist);

}


static void term_eol(void)

{

    term_cmd_buf_index = term_cmd_buf_size;

}


static SCSIRequest *scsi_new_request(SCSIDevice *d, uint32_t tag,

                                     uint32_t lun, void *hba_private)

{

    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d);

    SCSIRequest *req;

    SCSIDiskReq *r;

    req = scsi_req_alloc(&scsi_disk_reqops, &s->qdev, tag, lun, hba_private);

    r = DO_UPCAST(SCSIDiskReq, req, req);

    r->iov.iov_base = qemu_blockalign(s->bs, SCSI_DMA_BUF_SIZE);

    return req;

}


int main_loop_wait(int nonblocking)

{

    int ret;

    uint32_t timeout = UINT32_MAX;

    int64_t timeout_ns;

    if (nonblocking) {

        timeout = 0;

    }

    /* poll any events */

    g_array_set_size(gpollfds, 0); /* reset for new iteration */

    /* XXX: separate device handlers from system ones */

#ifdef CONFIG_SLIRP

    slirp_pollfds_fill(gpollfds, &timeout);

#endif

    if (timeout == UINT32_MAX) {

        timeout_ns = -1;

    } else {

        timeout_ns = (uint64_t)timeout * (int64_t)(SCALE_MS);

    }

    timeout_ns = qemu_soonest_timeout(timeout_ns,

                                      timerlistgroup_deadline_ns(

                                          &main_loop_tlg));

    ret = os_host_main_loop_wait(timeout_ns);

#ifdef CONFIG_SLIRP

    slirp_pollfds_poll(gpollfds, (ret < 0));

#endif

    /* CPU thread can infinitely wait for event after

       missing the warp */

    qemu_start_warp_timer();

    qemu_clock_run_all_timers();

    return ret;

}


int cpu_mips_handle_mmu_fault (CPUState *env, target_ulong address, int rw,

                               int mmu_idx, int is_softmmu)

{

#if !defined(CONFIG_USER_ONLY)

    target_phys_addr_t physical;

    int prot;

#endif

    int access_type;

    int ret = 0;

#if 0

    log_cpu_state(env, 0);

#endif

    qemu_log("%s pc " TARGET_FMT_lx " ad " TARGET_FMT_lx " rw %d mmu_idx %d smmu %d\n",

              __func__, env->active_tc.PC, address, rw, mmu_idx, is_softmmu);

    rw &= 1;

    /* data access */

    /* XXX: put correct access by using cpu_restore_state()

       correctly */

    access_type = ACCESS_INT;

#if defined(CONFIG_USER_ONLY)

    ret = TLBRET_NOMATCH;

#else

    ret = get_physical_address(env, &physical, &prot,

                               address, rw, access_type);

    qemu_log("%s address=" TARGET_FMT_lx " ret %d physical " TARGET_FMT_plx " prot %d\n",

              __func__, address, ret, physical, prot);

    if (ret == TLBRET_MATCH) {

       ret = tlb_set_page(env, address & TARGET_PAGE_MASK,

                          physical & TARGET_PAGE_MASK, prot,

                          mmu_idx, is_softmmu);

    } else if (ret < 0)

#endif

    {

        raise_mmu_exception(env, address, rw, ret);

        ret = 1;

    }

    return ret;

}


static uint64_t vtd_context_cache_invalidate(IntelIOMMUState *s, uint64_t val)

{

    uint64_t caig;

    uint64_t type = val & VTD_CCMD_CIRG_MASK;

    switch (type) {

    case VTD_CCMD_GLOBAL_INVL:

        VTD_DPRINTF(INV, "Global invalidation request");

        caig = VTD_CCMD_GLOBAL_INVL_A;

        break;

    case VTD_CCMD_DOMAIN_INVL:

        VTD_DPRINTF(INV, "Domain-selective invalidation request");

        caig = VTD_CCMD_DOMAIN_INVL_A;

        break;

    case VTD_CCMD_DEVICE_INVL:

        VTD_DPRINTF(INV, "Domain-selective invalidation request");

        caig = VTD_CCMD_DEVICE_INVL_A;

        break;

    default:

        VTD_DPRINTF(GENERAL,

                    "error: wrong context-cache invalidation granularity");

        caig = 0;

    }

    return caig;

}


uint64_t HELPER(paired_cmpxchg64_le)(CPUARMState *env, uint64_t addr,

                                     uint64_t new_lo, uint64_t new_hi)

{

    uintptr_t ra = GETPC();

    Int128 oldv, cmpv, newv;

    bool success;

    cmpv = int128_make128(env->exclusive_val, env->exclusive_high);

    newv = int128_make128(new_lo, new_hi);

    if (parallel_cpus) {

#ifndef CONFIG_ATOMIC128

        cpu_loop_exit_atomic(ENV_GET_CPU(env), ra);

#else

        int mem_idx = cpu_mmu_index(env, false);

        TCGMemOpIdx oi = make_memop_idx(MO_LEQ | MO_ALIGN_16, mem_idx);

        oldv = helper_atomic_cmpxchgo_le_mmu(env, addr, cmpv, newv, oi, ra);

        success = int128_eq(oldv, cmpv);

#endif

    } else {

        uint64_t o0, o1;

#ifdef CONFIG_USER_ONLY

        /* ??? Enforce alignment.  */

        uint64_t *haddr = g2h(addr);

        o0 = ldq_le_p(haddr + 0);

        o1 = ldq_le_p(haddr + 1);

        oldv = int128_make128(o0, o1);

        success = int128_eq(oldv, cmpv);

        if (success) {

            stq_le_p(haddr + 0, int128_getlo(newv));

            stq_le_p(haddr + 1, int128_gethi(newv));

        }

#else

        int mem_idx = cpu_mmu_index(env, false);

        TCGMemOpIdx oi0 = make_memop_idx(MO_LEQ | MO_ALIGN_16, mem_idx);

        TCGMemOpIdx oi1 = make_memop_idx(MO_LEQ, mem_idx);

        o0 = helper_le_ldq_mmu(env, addr + 0, oi0, ra);

        o1 = helper_le_ldq_mmu(env, addr + 8, oi1, ra);

        oldv = int128_make128(o0, o1);

        success = int128_eq(oldv, cmpv);

        if (success) {

            helper_le_stq_mmu(env, addr + 0, int128_getlo(newv), oi1, ra);

            helper_le_stq_mmu(env, addr + 8, int128_gethi(newv), oi1, ra);

        }

#endif

    }

    return !success;

}


static int h264_mp4toannexb_filter(AVBitStreamFilterContext *bsfc,

                                   AVCodecContext *avctx, const char *args,

                                   uint8_t **poutbuf, int *poutbuf_size,

                                   const uint8_t *buf, int buf_size,

                                   int keyframe)

{

    H264BSFContext *ctx = bsfc->priv_data;

    int i;

    uint8_t unit_type;

    int32_t nal_size;

    uint32_t cumul_size    = 0;

    const uint8_t *buf_end = buf + buf_size;

    int ret = 0;

    /* nothing to filter */

    if (!avctx->extradata || avctx->extradata_size < 6) {

        *poutbuf      = (uint8_t *)buf;

        *poutbuf_size = buf_size;

        return 0;

    }

    /* retrieve sps and pps NAL units from extradata */

    if (!ctx->extradata_parsed) {

        if (args && strstr(args, "private_spspps_buf"))

            ctx->private_spspps = 1;

        ret = h264_extradata_to_annexb(ctx, avctx, AV_INPUT_BUFFER_PADDING_SIZE);

        if (ret < 0)

            return ret;

        ctx->length_size      = ret;

        ctx->new_idr          = 1;

        ctx->idr_sps_seen     = 0;

        ctx->idr_pps_seen     = 0;

        ctx->extradata_parsed = 1;

    }

    *poutbuf_size = 0;

    *poutbuf      = NULL;

    do {

        ret= AVERROR(EINVAL);

        if (buf + ctx->length_size > buf_end)

            goto fail;

        for (nal_size = 0, i = 0; i<ctx->length_size; i++)

            nal_size = (nal_size << 8) | buf[i];

        buf      += ctx->length_size;

        unit_type = *buf & 0x1f;

        if (buf + nal_size > buf_end || nal_size < 0)

            goto fail;

        if (unit_type == 7)

            ctx->idr_sps_seen = ctx->new_idr = 1;

        else if (unit_type == 8) {

            ctx->idr_pps_seen = ctx->new_idr = 1;

            /* if SPS has not been seen yet, prepend the AVCC one to PPS */

            if (!ctx->idr_sps_seen) {

                if (ctx->sps_offset == -1)

                    av_log(avctx, AV_LOG_WARNING, "SPS not present in the stream, nor in AVCC, stream may be unreadable\n");

                else {

                    if ((ret = alloc_and_copy(poutbuf, poutbuf_size,

                                         ctx->spspps_buf + ctx->sps_offset,

                                         ctx->pps_offset != -1 ? ctx->pps_offset : ctx->spspps_size - ctx->sps_offset,

                                         buf, nal_size)) < 0)

                        goto fail;

                    ctx->idr_sps_seen = 1;

                    goto next_nal;

                }

            }

        }

        /* if this is a new IDR picture following an IDR picture, reset the idr flag.

         * Just check first_mb_in_slice to be 0 as this is the simplest solution.

         * This could be checking idr_pic_id instead, but would complexify the parsing. */

        if (!ctx->new_idr && unit_type == 5 && (buf[1] & 0x80))

            ctx->new_idr = 1;

        /* prepend only to the first type 5 NAL unit of an IDR picture, if no sps/pps are already present */

        if (ctx->new_idr && unit_type == 5 && !ctx->idr_sps_seen && !ctx->idr_pps_seen) {

            if ((ret=alloc_and_copy(poutbuf, poutbuf_size,

                               ctx->spspps_buf, ctx->spspps_size,

                               buf, nal_size)) < 0)

                goto fail;

            ctx->new_idr = 0;

        /* if only SPS has been seen, also insert PPS */

        } else if (ctx->new_idr && unit_type == 5 && ctx->idr_sps_seen && !ctx->idr_pps_seen) {

            if (ctx->pps_offset == -1) {

                av_log(avctx, AV_LOG_WARNING, "PPS not present in the stream, nor in AVCC, stream may be unreadable\n");

                if ((ret = alloc_and_copy(poutbuf, poutbuf_size,

                                     NULL, 0, buf, nal_size)) < 0)

                    goto fail;

            } else if ((ret = alloc_and_copy(poutbuf, poutbuf_size,

                                        ctx->spspps_buf + ctx->pps_offset, ctx->spspps_size - ctx->pps_offset,

                                        buf, nal_size)) < 0)

                goto fail;

        } else {

            if ((ret=alloc_and_copy(poutbuf, poutbuf_size,

                               NULL, 0, buf, nal_size)) < 0)

                goto fail;

            if (!ctx->new_idr && unit_type == 1) {

                ctx->new_idr = 1;

                ctx->idr_sps_seen = 0;

                ctx->idr_pps_seen = 0;

            }

        }

next_nal:

        buf        += nal_size;

        cumul_size += nal_size + ctx->length_size;

    } while (cumul_size < buf_size);

    return 1;

fail:

    av_freep(poutbuf);

    *poutbuf_size = 0;

    return ret;

}


void qemu_notify_event(void)

{

    /* Write 8 bytes to be compatible with eventfd.  */

    static const uint64_t val = 1;

    ssize_t ret;

    if (io_thread_fd == -1) {

        return;

    }

    do {

        ret = write(io_thread_fd, &val, sizeof(val));

    } while (ret < 0 && errno == EINTR);

    /* EAGAIN is fine, a read must be pending.  */

    if (ret < 0 && errno != EAGAIN) {

        fprintf(stderr, "qemu_notify_event: write() failed: %s\n",

                strerror(errno));

        exit(1);

    }

}


uint16_t virtio_get_cylinders(void)

{

    return blk_cfg.geometry.cylinders;

}