void virtio_scsi_handle_ctrl_req(VirtIOSCSI *s, VirtIOSCSIReq *req)

{

    VirtIODevice *vdev = (VirtIODevice *)s;

    uint32_t type;

    int r = 0;

    if (iov_to_buf(req->elem.out_sg, req->elem.out_num, 0,

                &type, sizeof(type)) < sizeof(type)) {

        virtio_scsi_bad_req();

        return;

    }

    virtio_tswap32s(vdev, &type);

    if (type == VIRTIO_SCSI_T_TMF) {

        if (virtio_scsi_parse_req(req, sizeof(VirtIOSCSICtrlTMFReq),

                    sizeof(VirtIOSCSICtrlTMFResp)) < 0) {

            virtio_scsi_bad_req();

        } else {

            r = virtio_scsi_do_tmf(s, req);

        }

    } else if (type == VIRTIO_SCSI_T_AN_QUERY ||

               type == VIRTIO_SCSI_T_AN_SUBSCRIBE) {

        if (virtio_scsi_parse_req(req, sizeof(VirtIOSCSICtrlANReq),

                    sizeof(VirtIOSCSICtrlANResp)) < 0) {

            virtio_scsi_bad_req();

        } else {

            req->resp.an.event_actual = 0;

            req->resp.an.response = VIRTIO_SCSI_S_OK;

        }

    }

    if (r == 0) {

        virtio_scsi_complete_req(req);

    } else {

        assert(r == -EINPROGRESS);

    }

}


inline static void RENAME(hcscale)(uint16_t *dst, int dstWidth, uint8_t *src1, uint8_t *src2,

				   int srcW, int xInc, int flags, int canMMX2BeUsed, int16_t *hChrFilter,

				   int16_t *hChrFilterPos, int hChrFilterSize, void *funnyUVCode,

				   int srcFormat, uint8_t *formatConvBuffer)

{

    if(srcFormat==IMGFMT_YUY2)

    {

	RENAME(yuy2ToUV)(formatConvBuffer, formatConvBuffer+2048, src1, src2, srcW);

	src1= formatConvBuffer;

	src2= formatConvBuffer+2048;

    }

    else if(srcFormat==IMGFMT_BGR32)

    {

	RENAME(bgr32ToUV)(formatConvBuffer, formatConvBuffer+2048, src1, src2, srcW);

	src1= formatConvBuffer;

	src2= formatConvBuffer+2048;

    }

    else if(srcFormat==IMGFMT_BGR24)

    {

	RENAME(bgr24ToUV)(formatConvBuffer, formatConvBuffer+2048, src1, src2, srcW);

	src1= formatConvBuffer;

	src2= formatConvBuffer+2048;

    }

    else if(srcFormat==IMGFMT_BGR16)

    {

	RENAME(bgr16ToUV)(formatConvBuffer, formatConvBuffer+2048, src1, src2, srcW);

	src1= formatConvBuffer;

	src2= formatConvBuffer+2048;

    }

    else if(srcFormat==IMGFMT_BGR15)

    {

	RENAME(bgr15ToUV)(formatConvBuffer, formatConvBuffer+2048, src1, src2, srcW);

	src1= formatConvBuffer;

	src2= formatConvBuffer+2048;

    }

    else if(srcFormat==IMGFMT_RGB32)

    {

	RENAME(rgb32ToUV)(formatConvBuffer, formatConvBuffer+2048, src1, src2, srcW);

	src1= formatConvBuffer;

	src2= formatConvBuffer+2048;

    }

    else if(srcFormat==IMGFMT_RGB24)

    {

	RENAME(rgb24ToUV)(formatConvBuffer, formatConvBuffer+2048, src1, src2, srcW);

	src1= formatConvBuffer;

	src2= formatConvBuffer+2048;

    }

    else if(isGray(srcFormat))

    {

    	return;

    }

#ifdef HAVE_MMX

	// use the new MMX scaler if th mmx2 cant be used (its faster than the x86asm one)

    if(!(flags&SWS_FAST_BILINEAR) || (!canMMX2BeUsed))

#else

    if(!(flags&SWS_FAST_BILINEAR))

#endif

    {

    	RENAME(hScale)(dst     , dstWidth, src1, srcW, xInc, hChrFilter, hChrFilterPos, hChrFilterSize);

    	RENAME(hScale)(dst+2048, dstWidth, src2, srcW, xInc, hChrFilter, hChrFilterPos, hChrFilterSize);

    }

    else // Fast Bilinear upscale / crap downscale

    {

#ifdef ARCH_X86

#ifdef HAVE_MMX2

	int i;

	if(canMMX2BeUsed)

	{

		asm volatile(

		"pxor %%mm7, %%mm7		\n\t"

		"pxor %%mm2, %%mm2		\n\t" // 2*xalpha

		"movd %5, %%mm6			\n\t" // xInc&0xFFFF

		"punpcklwd %%mm6, %%mm6		\n\t"

		"punpcklwd %%mm6, %%mm6		\n\t"

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

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

		"paddw %%mm6, %%mm2		\n\t"

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

		"paddw %%mm6, %%mm2		\n\t"

		"psllq $16, %%mm2		\n\t" //0,t,2t,3t		t=xInc&0xFFFF

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

		"movd %4, %%mm6			\n\t" //(xInc*4)&0xFFFF

		"punpcklwd %%mm6, %%mm6		\n\t"

		"punpcklwd %%mm6, %%mm6		\n\t"

		"xorl %%eax, %%eax		\n\t" // i

		"movl %0, %%esi			\n\t" // src

		"movl %1, %%edi			\n\t" // buf1

		"movl %3, %%edx			\n\t" // (xInc*4)>>16

		"xorl %%ecx, %%ecx		\n\t"

		"xorl %%ebx, %%ebx		\n\t"

		"movw %4, %%bx			\n\t" // (xInc*4)&0xFFFF

#define FUNNYUVCODE \

			PREFETCH" 1024(%%esi)		\n\t"\

			PREFETCH" 1056(%%esi)		\n\t"\

			PREFETCH" 1088(%%esi)		\n\t"\

			"call *%7			\n\t"\

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

			"xorl %%ecx, %%ecx		\n\t"

FUNNYUVCODE

FUNNYUVCODE

FUNNYUVCODE

FUNNYUVCODE

FUNNYUVCODE

FUNNYUVCODE

FUNNYUVCODE

FUNNYUVCODE

		"xorl %%eax, %%eax		\n\t" // i

		"movl %6, %%esi			\n\t" // src

		"movl %1, %%edi			\n\t" // buf1

		"addl $4096, %%edi		\n\t"

FUNNYUVCODE

FUNNYUVCODE

FUNNYUVCODE

FUNNYUVCODE

FUNNYUVCODE

FUNNYUVCODE

FUNNYUVCODE

FUNNYUVCODE

		:: "m" (src1), "m" (dst), "m" (dstWidth), "m" ((xInc*4)>>16),

		  "m" ((xInc*4)&0xFFFF), "m" (xInc&0xFFFF), "m" (src2), "m" (funnyUVCode)

		: "%eax", "%ebx", "%ecx", "%edx", "%esi", "%edi"

	);

		for(i=dstWidth-1; (i*xInc)>>16 >=srcW-1; i--)

		{

//			printf("%d %d %d\n", dstWidth, i, srcW);

			dst[i] = src1[srcW-1]*128;

			dst[i+2048] = src2[srcW-1]*128;

		}

	}

	else

	{

#endif

	asm volatile(

		"xorl %%eax, %%eax		\n\t" // i

		"xorl %%ebx, %%ebx		\n\t" // xx

		"xorl %%ecx, %%ecx		\n\t" // 2*xalpha

		".balign 16			\n\t"

		"1:				\n\t"

		"movl %0, %%esi			\n\t"

		"movzbl  (%%esi, %%ebx), %%edi	\n\t" //src[xx]

		"movzbl 1(%%esi, %%ebx), %%esi	\n\t" //src[xx+1]

		"subl %%edi, %%esi		\n\t" //src[xx+1] - src[xx]

		"imull %%ecx, %%esi		\n\t" //(src[xx+1] - src[xx])*2*xalpha

		"shll $16, %%edi		\n\t"

		"addl %%edi, %%esi		\n\t" //src[xx+1]*2*xalpha + src[xx]*(1-2*xalpha)

		"movl %1, %%edi			\n\t"

		"shrl $9, %%esi			\n\t"

		"movw %%si, (%%edi, %%eax, 2)	\n\t"

		"movzbl  (%5, %%ebx), %%edi	\n\t" //src[xx]

		"movzbl 1(%5, %%ebx), %%esi	\n\t" //src[xx+1]

		"subl %%edi, %%esi		\n\t" //src[xx+1] - src[xx]

		"imull %%ecx, %%esi		\n\t" //(src[xx+1] - src[xx])*2*xalpha

		"shll $16, %%edi		\n\t"

		"addl %%edi, %%esi		\n\t" //src[xx+1]*2*xalpha + src[xx]*(1-2*xalpha)

		"movl %1, %%edi			\n\t"

		"shrl $9, %%esi			\n\t"

		"movw %%si, 4096(%%edi, %%eax, 2)\n\t"

		"addw %4, %%cx			\n\t" //2*xalpha += xInc&0xFF

		"adcl %3, %%ebx			\n\t" //xx+= xInc>>8 + carry

		"addl $1, %%eax			\n\t"

		"cmpl %2, %%eax			\n\t"

		" jb 1b				\n\t"

		:: "m" (src1), "m" (dst), "m" (dstWidth), "m" (xInc>>16), "m" (xInc&0xFFFF),

		"r" (src2)

		: "%eax", "%ebx", "%ecx", "%edi", "%esi"

		);

#ifdef HAVE_MMX2

	} //if MMX2 cant be used

#endif

#else

	int i;

	unsigned int xpos=0;

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

	{

		register unsigned int xx=xpos>>16;

		register unsigned int xalpha=(xpos&0xFFFF)>>9;

		dst[i]=(src1[xx]*(xalpha^127)+src1[xx+1]*xalpha);

		dst[i+2048]=(src2[xx]*(xalpha^127)+src2[xx+1]*xalpha);

/* slower

	  dst[i]= (src1[xx]<<7) + (src1[xx+1] - src1[xx])*xalpha;

	  dst[i+2048]=(src2[xx]<<7) + (src2[xx+1] - src2[xx])*xalpha;

*/

		xpos+=xInc;

	}

#endif

   }

}


static uint64_t sniff_channel_order(uint8_t (*layout_map)[3], int tags)

{

    int i, n, total_non_cc_elements;

    struct elem_to_channel e2c_vec[MAX_ELEM_ID] = {{ 0 }};

    int num_front_channels, num_side_channels, num_back_channels;

    uint64_t layout;

    i = 0;

    num_front_channels =

        count_paired_channels(layout_map, tags, AAC_CHANNEL_FRONT, &i);

    if (num_front_channels < 0)

        return 0;

    num_side_channels =

        count_paired_channels(layout_map, tags, AAC_CHANNEL_SIDE, &i);

    if (num_side_channels < 0)

        return 0;

    num_back_channels =

        count_paired_channels(layout_map, tags, AAC_CHANNEL_BACK, &i);

    if (num_back_channels < 0)

        return 0;

    i = 0;

    if (num_front_channels & 1) {

        e2c_vec[i] = (struct elem_to_channel) {

            .av_position = AV_CH_FRONT_CENTER, .syn_ele = TYPE_SCE,

            .elem_id = layout_map[i][1], .aac_position = AAC_CHANNEL_FRONT };

        i++;

        num_front_channels--;

    }

    if (num_front_channels >= 4) {

        i += assign_pair(e2c_vec, layout_map, i, tags,

                         AV_CH_FRONT_LEFT_OF_CENTER,

                         AV_CH_FRONT_RIGHT_OF_CENTER,

                         AAC_CHANNEL_FRONT);

        num_front_channels -= 2;

    }

    if (num_front_channels >= 2) {

        i += assign_pair(e2c_vec, layout_map, i, tags,

                         AV_CH_FRONT_LEFT,

                         AV_CH_FRONT_RIGHT,

                         AAC_CHANNEL_FRONT);

        num_front_channels -= 2;

    }

    while (num_front_channels >= 2) {

        i += assign_pair(e2c_vec, layout_map, i, tags,

                         UINT64_MAX,

                         UINT64_MAX,

                         AAC_CHANNEL_FRONT);

        num_front_channels -= 2;

    }

    if (num_side_channels >= 2) {

        i += assign_pair(e2c_vec, layout_map, i, tags,

                         AV_CH_SIDE_LEFT,

                         AV_CH_SIDE_RIGHT,

                         AAC_CHANNEL_FRONT);

        num_side_channels -= 2;

    }

    while (num_side_channels >= 2) {

        i += assign_pair(e2c_vec, layout_map, i, tags,

                         UINT64_MAX,

                         UINT64_MAX,

                         AAC_CHANNEL_SIDE);

        num_side_channels -= 2;

    }

    while (num_back_channels >= 4) {

        i += assign_pair(e2c_vec, layout_map, i, tags,

                         UINT64_MAX,

                         UINT64_MAX,

                         AAC_CHANNEL_BACK);

        num_back_channels -= 2;

    }

    if (num_back_channels >= 2) {

        i += assign_pair(e2c_vec, layout_map, i, tags,

                         AV_CH_BACK_LEFT,

                         AV_CH_BACK_RIGHT,

                         AAC_CHANNEL_BACK);

        num_back_channels -= 2;

    }

    if (num_back_channels) {

        e2c_vec[i] = (struct elem_to_channel) {

          .av_position = AV_CH_BACK_CENTER, .syn_ele = TYPE_SCE,

          .elem_id = layout_map[i][1], .aac_position = AAC_CHANNEL_BACK };

        i++;

        num_back_channels--;

    }

    if (i < tags && layout_map[i][2] == AAC_CHANNEL_LFE) {

        e2c_vec[i] = (struct elem_to_channel) {

          .av_position = AV_CH_LOW_FREQUENCY, .syn_ele = TYPE_LFE,

          .elem_id = layout_map[i][1], .aac_position = AAC_CHANNEL_LFE };

        i++;

    }

    while (i < tags && layout_map[i][2] == AAC_CHANNEL_LFE) {

        e2c_vec[i] = (struct elem_to_channel) {

          .av_position = UINT64_MAX, .syn_ele = TYPE_LFE,

          .elem_id = layout_map[i][1], .aac_position = AAC_CHANNEL_LFE };

        i++;

    }

    // Must choose a stable sort

    total_non_cc_elements = n = i;

    do {

        int next_n = 0;

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

            if (e2c_vec[i-1].av_position > e2c_vec[i].av_position) {

                FFSWAP(struct elem_to_channel, e2c_vec[i-1], e2c_vec[i]);

                next_n = i;

            }

        }

        n = next_n;

    } while (n > 0);

    layout = 0;

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

        layout_map[i][0] = e2c_vec[i].syn_ele;

        layout_map[i][1] = e2c_vec[i].elem_id;

        layout_map[i][2] = e2c_vec[i].aac_position;

        if (e2c_vec[i].av_position != UINT64_MAX) {

            layout |= e2c_vec[i].av_position;

        }

    }

    return layout;

}


static int film_read_header(AVFormatContext *s)

{

    FilmDemuxContext *film = s->priv_data;

    AVIOContext *pb = s->pb;

    AVStream *st;

    unsigned char scratch[256];

    int i, ret;

    unsigned int data_offset;

    unsigned int audio_frame_counter;

    film->sample_table = NULL;

    film->stereo_buffer = NULL;

    film->stereo_buffer_size = 0;

    /* load the main FILM header */

    if (avio_read(pb, scratch, 16) != 16)

        return AVERROR(EIO);

    data_offset = AV_RB32(&scratch[4]);

    film->version = AV_RB32(&scratch[8]);

    /* load the FDSC chunk */

    if (film->version == 0) {

        /* special case for Lemmings .film files; 20-byte header */

        if (avio_read(pb, scratch, 20) != 20)

            return AVERROR(EIO);

        /* make some assumptions about the audio parameters */

        film->audio_type = AV_CODEC_ID_PCM_S8;

        film->audio_samplerate = 22050;

        film->audio_channels = 1;

        film->audio_bits = 8;

    } else {

        /* normal Saturn .cpk files; 32-byte header */

        if (avio_read(pb, scratch, 32) != 32)

            return AVERROR(EIO);

        film->audio_samplerate = AV_RB16(&scratch[24]);

        film->audio_channels = scratch[21];

        if (!film->audio_channels || film->audio_channels > 2) {

            av_log(s, AV_LOG_ERROR,

                   "Invalid number of channels: %d\n", film->audio_channels);

            return AVERROR_INVALIDDATA;

        }

        film->audio_bits = scratch[22];

        if (scratch[23] == 2)

            film->audio_type = AV_CODEC_ID_ADPCM_ADX;

        else if (film->audio_channels > 0) {

            if (film->audio_bits == 8)

                film->audio_type = AV_CODEC_ID_PCM_S8;

            else if (film->audio_bits == 16)

                film->audio_type = AV_CODEC_ID_PCM_S16BE;

            else

                film->audio_type = AV_CODEC_ID_NONE;

        } else

            film->audio_type = AV_CODEC_ID_NONE;

    }

    if (AV_RB32(&scratch[0]) != FDSC_TAG)

        return AVERROR_INVALIDDATA;

    if (AV_RB32(&scratch[8]) == CVID_TAG) {

        film->video_type = AV_CODEC_ID_CINEPAK;

    } else if (AV_RB32(&scratch[8]) == RAW_TAG) {

        film->video_type = AV_CODEC_ID_RAWVIDEO;

    } else {

        film->video_type = AV_CODEC_ID_NONE;

    }

    /* initialize the decoder streams */

    if (film->video_type) {

        st = avformat_new_stream(s, NULL);

        if (!st)

            return AVERROR(ENOMEM);

        film->video_stream_index = st->index;

        st->codec->codec_type = AVMEDIA_TYPE_VIDEO;

        st->codec->codec_id = film->video_type;

        st->codec->codec_tag = 0;  /* no fourcc */

        st->codec->width = AV_RB32(&scratch[16]);

        st->codec->height = AV_RB32(&scratch[12]);

        if (film->video_type == AV_CODEC_ID_RAWVIDEO) {

            if (scratch[20] == 24) {

                st->codec->pix_fmt = AV_PIX_FMT_RGB24;

            } else {

                av_log(s, AV_LOG_ERROR, "raw video is using unhandled %dbpp\n", scratch[20]);

                return -1;

            }

        }

    }

    if (film->audio_type) {

        st = avformat_new_stream(s, NULL);

        if (!st)

            return AVERROR(ENOMEM);

        film->audio_stream_index = st->index;

        st->codec->codec_type = AVMEDIA_TYPE_AUDIO;

        st->codec->codec_id = film->audio_type;

        st->codec->codec_tag = 1;

        st->codec->channels = film->audio_channels;

        st->codec->sample_rate = film->audio_samplerate;

        if (film->audio_type == AV_CODEC_ID_ADPCM_ADX) {

            st->codec->bits_per_coded_sample = 18 * 8 / 32;

            st->codec->block_align = st->codec->channels * 18;

            st->need_parsing = AVSTREAM_PARSE_FULL;

        } else {

            st->codec->bits_per_coded_sample = film->audio_bits;

            st->codec->block_align = st->codec->channels *

                st->codec->bits_per_coded_sample / 8;

        }

        st->codec->bit_rate = st->codec->channels * st->codec->sample_rate *

            st->codec->bits_per_coded_sample;

    }

    /* load the sample table */

    if (avio_read(pb, scratch, 16) != 16)

        return AVERROR(EIO);

    if (AV_RB32(&scratch[0]) != STAB_TAG)

        return AVERROR_INVALIDDATA;

    film->base_clock = AV_RB32(&scratch[8]);

    film->sample_count = AV_RB32(&scratch[12]);

    if(film->sample_count >= UINT_MAX / sizeof(film_sample))

        return -1;

    film->sample_table = av_malloc(film->sample_count * sizeof(film_sample));

    if (!film->sample_table)

        return AVERROR(ENOMEM);

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

        st = s->streams[i];

        if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO)

            avpriv_set_pts_info(st, 33, 1, film->base_clock);

        else

            avpriv_set_pts_info(st, 64, 1, film->audio_samplerate);

    }

    audio_frame_counter = 0;

    for (i = 0; i < film->sample_count; i++) {

        /* load the next sample record and transfer it to an internal struct */

        if (avio_read(pb, scratch, 16) != 16) {

            ret = AVERROR(EIO);

            goto fail;

        }

        film->sample_table[i].sample_offset =

            data_offset + AV_RB32(&scratch[0]);

        film->sample_table[i].sample_size = AV_RB32(&scratch[4]);

        if (film->sample_table[i].sample_size > INT_MAX / 4) {

            ret = AVERROR_INVALIDDATA;

            goto fail;

        }

        if (AV_RB32(&scratch[8]) == 0xFFFFFFFF) {

            film->sample_table[i].stream = film->audio_stream_index;

            film->sample_table[i].pts = audio_frame_counter;

            if (film->audio_type == AV_CODEC_ID_ADPCM_ADX)

                audio_frame_counter += (film->sample_table[i].sample_size * 32 /

                    (18 * film->audio_channels));

            else if (film->audio_type != AV_CODEC_ID_NONE)

                audio_frame_counter += (film->sample_table[i].sample_size /

                    (film->audio_channels * film->audio_bits / 8));

        } else {

            film->sample_table[i].stream = film->video_stream_index;

            film->sample_table[i].pts = AV_RB32(&scratch[8]) & 0x7FFFFFFF;

            film->sample_table[i].keyframe = (scratch[8] & 0x80) ? 0 : 1;

        }

    }

    film->current_sample = 0;

    return 0;

fail:

    film_read_close(s);

    return ret;

}


static BlockDriverAIOCB *qcow_aio_readv(BlockDriverState *bs,

        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,

        BlockDriverCompletionFunc *cb, void *opaque)

{

    QCowAIOCB *acb;

    acb = qemu_aio_get(bs, cb, opaque);

    if (!acb)

        return NULL;

    acb->hd_aiocb = NULL;

    acb->sector_num = sector_num;

    acb->qiov = qiov;

    if (qiov->niov > 1)

        acb->buf = acb->orig_buf = qemu_memalign(512, qiov->size);

    else

        acb->buf = (uint8_t *)qiov->iov->iov_base;

    acb->nb_sectors = nb_sectors;

    acb->n = 0;

    acb->cluster_offset = 0;

    qcow_aio_read_cb(acb, 0);

    return &acb->common;

}


void armv7m_nvic_set_pending(void *opaque, int irq)

{

    NVICState *s = (NVICState *)opaque;

    VecInfo *vec;

    assert(irq > ARMV7M_EXCP_RESET && irq < s->num_irq);

    vec = &s->vectors[irq];

    trace_nvic_set_pending(irq, vec->enabled, vec->prio);

    if (irq >= ARMV7M_EXCP_HARD && irq < ARMV7M_EXCP_PENDSV) {

        /* If a synchronous exception is pending then it may be

         * escalated to HardFault if:

         *  * it is equal or lower priority to current execution

         *  * it is disabled

         * (ie we need to take it immediately but we can't do so).

         * Asynchronous exceptions (and interrupts) simply remain pending.

         *

         * For QEMU, we don't have any imprecise (asynchronous) faults,

         * so we can assume that PREFETCH_ABORT and DATA_ABORT are always

         * synchronous.

         * Debug exceptions are awkward because only Debug exceptions

         * resulting from the BKPT instruction should be escalated,

         * but we don't currently implement any Debug exceptions other

         * than those that result from BKPT, so we treat all debug exceptions

         * as needing escalation.

         *

         * This all means we can identify whether to escalate based only on

         * the exception number and don't (yet) need the caller to explicitly

         * tell us whether this exception is synchronous or not.

         */

        int running = nvic_exec_prio(s);

        bool escalate = false;

        if (vec->prio >= running) {

            trace_nvic_escalate_prio(irq, vec->prio, running);

            escalate = true;

        } else if (!vec->enabled) {

            trace_nvic_escalate_disabled(irq);

            escalate = true;

        }

        if (escalate) {

            if (running < 0) {

                /* We want to escalate to HardFault but we can't take a

                 * synchronous HardFault at this point either. This is a

                 * Lockup condition due to a guest bug. We don't model

                 * Lockup, so report via cpu_abort() instead.

                 */

                cpu_abort(&s->cpu->parent_obj,

                          "Lockup: can't escalate %d to HardFault "

                          "(current priority %d)\n", irq, running);

            }

            /* We can do the escalation, so we take HardFault instead */

            irq = ARMV7M_EXCP_HARD;

            vec = &s->vectors[irq];

            s->cpu->env.v7m.hfsr |= R_V7M_HFSR_FORCED_MASK;

        }

    }

    if (!vec->pending) {

        vec->pending = 1;

        nvic_irq_update(s);

    }

}


static void generate_bootsect(target_phys_addr_t option_rom,

                              uint32_t gpr[8], uint16_t segs[6], uint16_t ip)

{

    uint8_t rom[512], *p, *reloc;

    uint8_t sum;

    int i;

    memset(rom, 0, sizeof(rom));

    p = rom;

    /* Make sure we have an option rom signature */

    *p++ = 0x55;

    *p++ = 0xaa;

    /* ROM size in sectors*/

    *p++ = 1;

    /* Hook int19 */

    *p++ = 0x50;		/* push ax */

    *p++ = 0x1e;		/* push ds */

    *p++ = 0x31; *p++ = 0xc0;	/* xor ax, ax */

    *p++ = 0x8e; *p++ = 0xd8;	/* mov ax, ds */

    *p++ = 0xc7; *p++ = 0x06;   /* movvw _start,0x64 */

    *p++ = 0x64; *p++ = 0x00;

    reloc = p;

    *p++ = 0x00; *p++ = 0x00;

    *p++ = 0x8c; *p++ = 0x0e;   /* mov cs,0x66 */

    *p++ = 0x66; *p++ = 0x00;

    *p++ = 0x1f;		/* pop ds */

    *p++ = 0x58;		/* pop ax */

    *p++ = 0xcb;		/* lret */

    /* Actual code */

    *reloc = (p - rom);

    *p++ = 0xfa;		/* CLI */

    *p++ = 0xfc;		/* CLD */

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

	if (i == 1)		/* Skip CS */

	    continue;

	*p++ = 0xb8;		/* MOV AX,imm16 */

	*p++ = segs[i];

	*p++ = segs[i] >> 8;

	*p++ = 0x8e;		/* MOV <seg>,AX */

	*p++ = 0xc0 + (i << 3);

    }

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

	*p++ = 0x66;		/* 32-bit operand size */

	*p++ = 0xb8 + i;	/* MOV <reg>,imm32 */

	*p++ = gpr[i];

	*p++ = gpr[i] >> 8;

	*p++ = gpr[i] >> 16;

	*p++ = gpr[i] >> 24;

    }

    *p++ = 0xea;		/* JMP FAR */

    *p++ = ip;			/* IP */

    *p++ = ip >> 8;

    *p++ = segs[1];		/* CS */

    *p++ = segs[1] >> 8;

    /* sign rom */

    sum = 0;

    for (i = 0; i < (sizeof(rom) - 1); i++)

        sum += rom[i];

    rom[sizeof(rom) - 1] = -sum;

    cpu_physical_memory_write_rom(option_rom, rom, sizeof(rom));

    option_rom_setup_reset(option_rom, sizeof (rom));

}


static int gxf_packet(AVFormatContext *s, AVPacket *pkt) {

    ByteIOContext *pb = s->pb;

    pkt_type_t pkt_type;

    int pkt_len;

    while (!url_feof(pb)) {

        int track_type, track_id, ret;

        int field_nr;

        int stream_index;

        if (!parse_packet_header(pb, &pkt_type, &pkt_len)) {

            if (!url_feof(pb))

                av_log(s, AV_LOG_ERROR, "GXF: sync lost\n");

            return -1;

        }

        if (pkt_type == PKT_FLT) {

            gxf_read_index(s, pkt_len);

            continue;

        }

        if (pkt_type != PKT_MEDIA) {

            url_fskip(pb, pkt_len);

            continue;

        }

        if (pkt_len < 16) {

            av_log(s, AV_LOG_ERROR, "GXF: invalid media packet length\n");

            continue;

        }

        pkt_len -= 16;

        track_type = get_byte(pb);

        track_id = get_byte(pb);

        stream_index = get_sindex(s, track_id, track_type);

        if (stream_index < 0)

            return stream_index;

        field_nr = get_be32(pb);

        get_be32(pb); // field information

        get_be32(pb); // "timeline" field number

        get_byte(pb); // flags

        get_byte(pb); // reserved

        // NOTE: there is also data length information in the

        // field information, it might be better to take this into account

        // as well.

        ret = av_get_packet(pb, pkt, pkt_len);

        pkt->stream_index = stream_index;

        pkt->dts = field_nr;

        return ret;

    }

    return AVERROR(EIO);

}


static int usb_hid_handle_data(USBDevice *dev, USBPacket *p)

{

    USBHIDState *us = DO_UPCAST(USBHIDState, dev, dev);

    HIDState *hs = &us->hid;

    uint8_t buf[p->iov.size];

    int ret = 0;

    switch (p->pid) {

    case USB_TOKEN_IN:

        if (p->devep == 1) {

            int64_t curtime = qemu_get_clock_ns(vm_clock);

            if (!us->changed &&

                (!us->idle || us->next_idle_clock - curtime > 0)) {

                return USB_RET_NAK;

            }

            usb_hid_set_next_idle(us, curtime);

            if (hs->kind == HID_MOUSE || hs->kind == HID_TABLET) {

                ret = hid_pointer_poll(hs, buf, p->iov.size);

            } else if (hs->kind == HID_KEYBOARD) {

                ret = hid_keyboard_poll(hs, buf, p->iov.size);

            }

            usb_packet_copy(p, buf, ret);

            us->changed = hs->n > 0;

        } else {

            goto fail;

        }

        break;

    case USB_TOKEN_OUT:

    default:

    fail:

        ret = USB_RET_STALL;

        break;

    }

    return ret;

}


tcg_target_ulong tcg_qemu_tb_exec(CPUArchState *cpustate, uint8_t *tb_ptr)

{

    tcg_target_ulong next_tb = 0;

    env = cpustate;

    tci_reg[TCG_AREG0] = (tcg_target_ulong)env;

    assert(tb_ptr);

    for (;;) {

#if defined(GETPC)

        tci_tb_ptr = (uintptr_t)tb_ptr;

#endif

        TCGOpcode opc = tb_ptr[0];

#if !defined(NDEBUG)

        uint8_t op_size = tb_ptr[1];

        uint8_t *old_code_ptr = tb_ptr;

#endif

        tcg_target_ulong t0;

        tcg_target_ulong t1;

        tcg_target_ulong t2;

        tcg_target_ulong label;

        TCGCond condition;

        target_ulong taddr;

#ifndef CONFIG_SOFTMMU

        tcg_target_ulong host_addr;

#endif

        uint8_t tmp8;

        uint16_t tmp16;

        uint32_t tmp32;

        uint64_t tmp64;

#if TCG_TARGET_REG_BITS == 32

        uint64_t v64;

#endif

        /* Skip opcode and size entry. */

        tb_ptr += 2;

        switch (opc) {

        case INDEX_op_end:

        case INDEX_op_nop:

            break;

        case INDEX_op_nop1:

        case INDEX_op_nop2:

        case INDEX_op_nop3:

        case INDEX_op_nopn:

        case INDEX_op_discard:

            TODO();

            break;

        case INDEX_op_set_label:

            TODO();

            break;

        case INDEX_op_call:

            t0 = tci_read_ri(&tb_ptr);

#if TCG_TARGET_REG_BITS == 32

            tmp64 = ((helper_function)t0)(tci_read_reg(TCG_REG_R0),

                                          tci_read_reg(TCG_REG_R1),

                                          tci_read_reg(TCG_REG_R2),

                                          tci_read_reg(TCG_REG_R3),

                                          tci_read_reg(TCG_REG_R5),

                                          tci_read_reg(TCG_REG_R6),

                                          tci_read_reg(TCG_REG_R7),

                                          tci_read_reg(TCG_REG_R8),

                                          tci_read_reg(TCG_REG_R9),

                                          tci_read_reg(TCG_REG_R10));

            tci_write_reg(TCG_REG_R0, tmp64);

            tci_write_reg(TCG_REG_R1, tmp64 >> 32);

#else

            tmp64 = ((helper_function)t0)(tci_read_reg(TCG_REG_R0),

                                          tci_read_reg(TCG_REG_R1),

                                          tci_read_reg(TCG_REG_R2),

                                          tci_read_reg(TCG_REG_R3),

                                          tci_read_reg(TCG_REG_R5));

            tci_write_reg(TCG_REG_R0, tmp64);

#endif

            break;

        case INDEX_op_br:

            label = tci_read_label(&tb_ptr);

            assert(tb_ptr == old_code_ptr + op_size);

            tb_ptr = (uint8_t *)label;

            continue;

        case INDEX_op_setcond_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_r32(&tb_ptr);

            t2 = tci_read_ri32(&tb_ptr);

            condition = *tb_ptr++;

            tci_write_reg32(t0, tci_compare32(t1, t2, condition));

            break;

#if TCG_TARGET_REG_BITS == 32

        case INDEX_op_setcond2_i32:

            t0 = *tb_ptr++;

            tmp64 = tci_read_r64(&tb_ptr);

            v64 = tci_read_ri64(&tb_ptr);

            condition = *tb_ptr++;

            tci_write_reg32(t0, tci_compare64(tmp64, v64, condition));

            break;

#elif TCG_TARGET_REG_BITS == 64

        case INDEX_op_setcond_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_r64(&tb_ptr);

            t2 = tci_read_ri64(&tb_ptr);

            condition = *tb_ptr++;

            tci_write_reg64(t0, tci_compare64(t1, t2, condition));

            break;

#endif

        case INDEX_op_mov_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_r32(&tb_ptr);

            tci_write_reg32(t0, t1);

            break;

        case INDEX_op_movi_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_i32(&tb_ptr);

            tci_write_reg32(t0, t1);

            break;

            /* Load/store operations (32 bit). */

        case INDEX_op_ld8u_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_r(&tb_ptr);

            t2 = tci_read_i32(&tb_ptr);

            tci_write_reg8(t0, *(uint8_t *)(t1 + t2));

            break;

        case INDEX_op_ld8s_i32:

        case INDEX_op_ld16u_i32:

            TODO();

            break;

        case INDEX_op_ld16s_i32:

            TODO();

            break;

        case INDEX_op_ld_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_r(&tb_ptr);

            t2 = tci_read_i32(&tb_ptr);

            tci_write_reg32(t0, *(uint32_t *)(t1 + t2));

            break;

        case INDEX_op_st8_i32:

            t0 = tci_read_r8(&tb_ptr);

            t1 = tci_read_r(&tb_ptr);

            t2 = tci_read_i32(&tb_ptr);

            *(uint8_t *)(t1 + t2) = t0;

            break;

        case INDEX_op_st16_i32:

            t0 = tci_read_r16(&tb_ptr);

            t1 = tci_read_r(&tb_ptr);

            t2 = tci_read_i32(&tb_ptr);

            *(uint16_t *)(t1 + t2) = t0;

            break;

        case INDEX_op_st_i32:

            t0 = tci_read_r32(&tb_ptr);

            t1 = tci_read_r(&tb_ptr);

            t2 = tci_read_i32(&tb_ptr);

            *(uint32_t *)(t1 + t2) = t0;

            break;

            /* Arithmetic operations (32 bit). */

        case INDEX_op_add_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_ri32(&tb_ptr);

            t2 = tci_read_ri32(&tb_ptr);

            tci_write_reg32(t0, t1 + t2);

            break;

        case INDEX_op_sub_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_ri32(&tb_ptr);

            t2 = tci_read_ri32(&tb_ptr);

            tci_write_reg32(t0, t1 - t2);

            break;

        case INDEX_op_mul_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_ri32(&tb_ptr);

            t2 = tci_read_ri32(&tb_ptr);

            tci_write_reg32(t0, t1 * t2);

            break;

#if TCG_TARGET_HAS_div_i32

        case INDEX_op_div_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_ri32(&tb_ptr);

            t2 = tci_read_ri32(&tb_ptr);

            tci_write_reg32(t0, (int32_t)t1 / (int32_t)t2);

            break;

        case INDEX_op_divu_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_ri32(&tb_ptr);

            t2 = tci_read_ri32(&tb_ptr);

            tci_write_reg32(t0, t1 / t2);

            break;

        case INDEX_op_rem_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_ri32(&tb_ptr);

            t2 = tci_read_ri32(&tb_ptr);

            tci_write_reg32(t0, (int32_t)t1 % (int32_t)t2);

            break;

        case INDEX_op_remu_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_ri32(&tb_ptr);

            t2 = tci_read_ri32(&tb_ptr);

            tci_write_reg32(t0, t1 % t2);

            break;

#elif TCG_TARGET_HAS_div2_i32

        case INDEX_op_div2_i32:

        case INDEX_op_divu2_i32:

            TODO();

            break;

#endif

        case INDEX_op_and_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_ri32(&tb_ptr);

            t2 = tci_read_ri32(&tb_ptr);

            tci_write_reg32(t0, t1 & t2);

            break;

        case INDEX_op_or_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_ri32(&tb_ptr);

            t2 = tci_read_ri32(&tb_ptr);

            tci_write_reg32(t0, t1 | t2);

            break;

        case INDEX_op_xor_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_ri32(&tb_ptr);

            t2 = tci_read_ri32(&tb_ptr);

            tci_write_reg32(t0, t1 ^ t2);

            break;

            /* Shift/rotate operations (32 bit). */

        case INDEX_op_shl_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_ri32(&tb_ptr);

            t2 = tci_read_ri32(&tb_ptr);

            tci_write_reg32(t0, t1 << t2);

            break;

        case INDEX_op_shr_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_ri32(&tb_ptr);

            t2 = tci_read_ri32(&tb_ptr);

            tci_write_reg32(t0, t1 >> t2);

            break;

        case INDEX_op_sar_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_ri32(&tb_ptr);

            t2 = tci_read_ri32(&tb_ptr);

            tci_write_reg32(t0, ((int32_t)t1 >> t2));

            break;

#if TCG_TARGET_HAS_rot_i32

        case INDEX_op_rotl_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_ri32(&tb_ptr);

            t2 = tci_read_ri32(&tb_ptr);

            tci_write_reg32(t0, (t1 << t2) | (t1 >> (32 - t2)));

            break;

        case INDEX_op_rotr_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_ri32(&tb_ptr);

            t2 = tci_read_ri32(&tb_ptr);

            tci_write_reg32(t0, (t1 >> t2) | (t1 << (32 - t2)));

            break;

#endif

#if TCG_TARGET_HAS_deposit_i32

        case INDEX_op_deposit_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_r32(&tb_ptr);

            t2 = tci_read_r32(&tb_ptr);

            tmp16 = *tb_ptr++;

            tmp8 = *tb_ptr++;

            tmp32 = (((1 << tmp8) - 1) << tmp16);

            tci_write_reg32(t0, (t1 & ~tmp32) | ((t2 << tmp16) & tmp32));

            break;

#endif

        case INDEX_op_brcond_i32:

            t0 = tci_read_r32(&tb_ptr);

            t1 = tci_read_ri32(&tb_ptr);

            condition = *tb_ptr++;

            label = tci_read_label(&tb_ptr);

            if (tci_compare32(t0, t1, condition)) {

                assert(tb_ptr == old_code_ptr + op_size);

                tb_ptr = (uint8_t *)label;

                continue;

            }

            break;

#if TCG_TARGET_REG_BITS == 32

        case INDEX_op_add2_i32:

            t0 = *tb_ptr++;

            t1 = *tb_ptr++;

            tmp64 = tci_read_r64(&tb_ptr);

            tmp64 += tci_read_r64(&tb_ptr);

            tci_write_reg64(t1, t0, tmp64);

            break;

        case INDEX_op_sub2_i32:

            t0 = *tb_ptr++;

            t1 = *tb_ptr++;

            tmp64 = tci_read_r64(&tb_ptr);

            tmp64 -= tci_read_r64(&tb_ptr);

            tci_write_reg64(t1, t0, tmp64);

            break;

        case INDEX_op_brcond2_i32:

            tmp64 = tci_read_r64(&tb_ptr);

            v64 = tci_read_ri64(&tb_ptr);

            condition = *tb_ptr++;

            label = tci_read_label(&tb_ptr);

            if (tci_compare64(tmp64, v64, condition)) {

                assert(tb_ptr == old_code_ptr + op_size);

                tb_ptr = (uint8_t *)label;

                continue;

            }

            break;

        case INDEX_op_mulu2_i32:

            t0 = *tb_ptr++;

            t1 = *tb_ptr++;

            t2 = tci_read_r32(&tb_ptr);

            tmp64 = tci_read_r32(&tb_ptr);

            tci_write_reg64(t1, t0, t2 * tmp64);

            break;

#endif /* TCG_TARGET_REG_BITS == 32 */

#if TCG_TARGET_HAS_ext8s_i32

        case INDEX_op_ext8s_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_r8s(&tb_ptr);

            tci_write_reg32(t0, t1);

            break;

#endif

#if TCG_TARGET_HAS_ext16s_i32

        case INDEX_op_ext16s_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_r16s(&tb_ptr);

            tci_write_reg32(t0, t1);

            break;

#endif

#if TCG_TARGET_HAS_ext8u_i32

        case INDEX_op_ext8u_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_r8(&tb_ptr);

            tci_write_reg32(t0, t1);

            break;

#endif

#if TCG_TARGET_HAS_ext16u_i32

        case INDEX_op_ext16u_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_r16(&tb_ptr);

            tci_write_reg32(t0, t1);

            break;

#endif

#if TCG_TARGET_HAS_bswap16_i32

        case INDEX_op_bswap16_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_r16(&tb_ptr);

            tci_write_reg32(t0, bswap16(t1));

            break;

#endif

#if TCG_TARGET_HAS_bswap32_i32

        case INDEX_op_bswap32_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_r32(&tb_ptr);

            tci_write_reg32(t0, bswap32(t1));

            break;

#endif

#if TCG_TARGET_HAS_not_i32

        case INDEX_op_not_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_r32(&tb_ptr);

            tci_write_reg32(t0, ~t1);

            break;

#endif

#if TCG_TARGET_HAS_neg_i32

        case INDEX_op_neg_i32:

            t0 = *tb_ptr++;

            t1 = tci_read_r32(&tb_ptr);

            tci_write_reg32(t0, -t1);

            break;

#endif

#if TCG_TARGET_REG_BITS == 64

        case INDEX_op_mov_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_r64(&tb_ptr);

            tci_write_reg64(t0, t1);

            break;

        case INDEX_op_movi_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_i64(&tb_ptr);

            tci_write_reg64(t0, t1);

            break;

            /* Load/store operations (64 bit). */

        case INDEX_op_ld8u_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_r(&tb_ptr);

            t2 = tci_read_i32(&tb_ptr);

            tci_write_reg8(t0, *(uint8_t *)(t1 + t2));

            break;

        case INDEX_op_ld8s_i64:

        case INDEX_op_ld16u_i64:

        case INDEX_op_ld16s_i64:

            TODO();

            break;

        case INDEX_op_ld32u_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_r(&tb_ptr);

            t2 = tci_read_i32(&tb_ptr);

            tci_write_reg32(t0, *(uint32_t *)(t1 + t2));

            break;

        case INDEX_op_ld32s_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_r(&tb_ptr);

            t2 = tci_read_i32(&tb_ptr);

            tci_write_reg32s(t0, *(int32_t *)(t1 + t2));

            break;

        case INDEX_op_ld_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_r(&tb_ptr);

            t2 = tci_read_i32(&tb_ptr);

            tci_write_reg64(t0, *(uint64_t *)(t1 + t2));

            break;

        case INDEX_op_st8_i64:

            t0 = tci_read_r8(&tb_ptr);

            t1 = tci_read_r(&tb_ptr);

            t2 = tci_read_i32(&tb_ptr);

            *(uint8_t *)(t1 + t2) = t0;

            break;

        case INDEX_op_st16_i64:

            t0 = tci_read_r16(&tb_ptr);

            t1 = tci_read_r(&tb_ptr);

            t2 = tci_read_i32(&tb_ptr);

            *(uint16_t *)(t1 + t2) = t0;

            break;

        case INDEX_op_st32_i64:

            t0 = tci_read_r32(&tb_ptr);

            t1 = tci_read_r(&tb_ptr);

            t2 = tci_read_i32(&tb_ptr);

            *(uint32_t *)(t1 + t2) = t0;

            break;

        case INDEX_op_st_i64:

            t0 = tci_read_r64(&tb_ptr);

            t1 = tci_read_r(&tb_ptr);

            t2 = tci_read_i32(&tb_ptr);

            *(uint64_t *)(t1 + t2) = t0;

            break;

            /* Arithmetic operations (64 bit). */

        case INDEX_op_add_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_ri64(&tb_ptr);

            t2 = tci_read_ri64(&tb_ptr);

            tci_write_reg64(t0, t1 + t2);

            break;

        case INDEX_op_sub_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_ri64(&tb_ptr);

            t2 = tci_read_ri64(&tb_ptr);

            tci_write_reg64(t0, t1 - t2);

            break;

        case INDEX_op_mul_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_ri64(&tb_ptr);

            t2 = tci_read_ri64(&tb_ptr);

            tci_write_reg64(t0, t1 * t2);

            break;

#if TCG_TARGET_HAS_div_i64

        case INDEX_op_div_i64:

        case INDEX_op_divu_i64:

        case INDEX_op_rem_i64:

        case INDEX_op_remu_i64:

            TODO();

            break;

#elif TCG_TARGET_HAS_div2_i64

        case INDEX_op_div2_i64:

        case INDEX_op_divu2_i64:

            TODO();

            break;

#endif

        case INDEX_op_and_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_ri64(&tb_ptr);

            t2 = tci_read_ri64(&tb_ptr);

            tci_write_reg64(t0, t1 & t2);

            break;

        case INDEX_op_or_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_ri64(&tb_ptr);

            t2 = tci_read_ri64(&tb_ptr);

            tci_write_reg64(t0, t1 | t2);

            break;

        case INDEX_op_xor_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_ri64(&tb_ptr);

            t2 = tci_read_ri64(&tb_ptr);

            tci_write_reg64(t0, t1 ^ t2);

            break;

            /* Shift/rotate operations (64 bit). */

        case INDEX_op_shl_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_ri64(&tb_ptr);

            t2 = tci_read_ri64(&tb_ptr);

            tci_write_reg64(t0, t1 << t2);

            break;

        case INDEX_op_shr_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_ri64(&tb_ptr);

            t2 = tci_read_ri64(&tb_ptr);

            tci_write_reg64(t0, t1 >> t2);

            break;

        case INDEX_op_sar_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_ri64(&tb_ptr);

            t2 = tci_read_ri64(&tb_ptr);

            tci_write_reg64(t0, ((int64_t)t1 >> t2));

            break;

#if TCG_TARGET_HAS_rot_i64

        case INDEX_op_rotl_i64:

        case INDEX_op_rotr_i64:

            TODO();

            break;

#endif

#if TCG_TARGET_HAS_deposit_i64

        case INDEX_op_deposit_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_r64(&tb_ptr);

            t2 = tci_read_r64(&tb_ptr);

            tmp16 = *tb_ptr++;

            tmp8 = *tb_ptr++;

            tmp64 = (((1ULL << tmp8) - 1) << tmp16);

            tci_write_reg64(t0, (t1 & ~tmp64) | ((t2 << tmp16) & tmp64));

            break;

#endif

        case INDEX_op_brcond_i64:

            t0 = tci_read_r64(&tb_ptr);

            t1 = tci_read_ri64(&tb_ptr);

            condition = *tb_ptr++;

            label = tci_read_label(&tb_ptr);

            if (tci_compare64(t0, t1, condition)) {

                assert(tb_ptr == old_code_ptr + op_size);

                tb_ptr = (uint8_t *)label;

                continue;

            }

            break;

#if TCG_TARGET_HAS_ext8u_i64

        case INDEX_op_ext8u_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_r8(&tb_ptr);

            tci_write_reg64(t0, t1);

            break;

#endif

#if TCG_TARGET_HAS_ext8s_i64

        case INDEX_op_ext8s_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_r8s(&tb_ptr);

            tci_write_reg64(t0, t1);

            break;

#endif

#if TCG_TARGET_HAS_ext16s_i64

        case INDEX_op_ext16s_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_r16s(&tb_ptr);

            tci_write_reg64(t0, t1);

            break;

#endif

#if TCG_TARGET_HAS_ext16u_i64

        case INDEX_op_ext16u_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_r16(&tb_ptr);

            tci_write_reg64(t0, t1);

            break;

#endif

#if TCG_TARGET_HAS_ext32s_i64

        case INDEX_op_ext32s_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_r32s(&tb_ptr);

            tci_write_reg64(t0, t1);

            break;

#endif

#if TCG_TARGET_HAS_ext32u_i64

        case INDEX_op_ext32u_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_r32(&tb_ptr);

            tci_write_reg64(t0, t1);

            break;

#endif

#if TCG_TARGET_HAS_bswap16_i64

        case INDEX_op_bswap16_i64:

            TODO();

            t0 = *tb_ptr++;

            t1 = tci_read_r16(&tb_ptr);

            tci_write_reg64(t0, bswap16(t1));

            break;

#endif

#if TCG_TARGET_HAS_bswap32_i64

        case INDEX_op_bswap32_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_r32(&tb_ptr);

            tci_write_reg64(t0, bswap32(t1));

            break;

#endif

#if TCG_TARGET_HAS_bswap64_i64

        case INDEX_op_bswap64_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_r64(&tb_ptr);

            tci_write_reg64(t0, bswap64(t1));

            break;

#endif

#if TCG_TARGET_HAS_not_i64

        case INDEX_op_not_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_r64(&tb_ptr);

            tci_write_reg64(t0, ~t1);

            break;

#endif

#if TCG_TARGET_HAS_neg_i64

        case INDEX_op_neg_i64:

            t0 = *tb_ptr++;

            t1 = tci_read_r64(&tb_ptr);

            tci_write_reg64(t0, -t1);

            break;

#endif

#endif /* TCG_TARGET_REG_BITS == 64 */

            /* QEMU specific operations. */

#if TARGET_LONG_BITS > TCG_TARGET_REG_BITS

        case INDEX_op_debug_insn_start:

            TODO();

            break;

#else

        case INDEX_op_debug_insn_start:

            TODO();

            break;

#endif

        case INDEX_op_exit_tb:

            next_tb = *(uint64_t *)tb_ptr;

            goto exit;

            break;

        case INDEX_op_goto_tb:

            t0 = tci_read_i32(&tb_ptr);

            assert(tb_ptr == old_code_ptr + op_size);

            tb_ptr += (int32_t)t0;

            continue;

        case INDEX_op_qemu_ld8u:

            t0 = *tb_ptr++;

            taddr = tci_read_ulong(&tb_ptr);

#ifdef CONFIG_SOFTMMU

            tmp8 = helper_ldb_mmu(env, taddr, tci_read_i(&tb_ptr));

#else

            host_addr = (tcg_target_ulong)taddr;

            assert(taddr == host_addr);

            tmp8 = *(uint8_t *)(host_addr + GUEST_BASE);

#endif

            tci_write_reg8(t0, tmp8);

            break;

        case INDEX_op_qemu_ld8s:

            t0 = *tb_ptr++;

            taddr = tci_read_ulong(&tb_ptr);

#ifdef CONFIG_SOFTMMU

            tmp8 = helper_ldb_mmu(env, taddr, tci_read_i(&tb_ptr));

#else

            host_addr = (tcg_target_ulong)taddr;

            assert(taddr == host_addr);

            tmp8 = *(uint8_t *)(host_addr + GUEST_BASE);

#endif

            tci_write_reg8s(t0, tmp8);

            break;

        case INDEX_op_qemu_ld16u:

            t0 = *tb_ptr++;

            taddr = tci_read_ulong(&tb_ptr);

#ifdef CONFIG_SOFTMMU

            tmp16 = helper_ldw_mmu(env, taddr, tci_read_i(&tb_ptr));

#else

            host_addr = (tcg_target_ulong)taddr;

            assert(taddr == host_addr);

            tmp16 = tswap16(*(uint16_t *)(host_addr + GUEST_BASE));

#endif

            tci_write_reg16(t0, tmp16);

            break;

        case INDEX_op_qemu_ld16s:

            t0 = *tb_ptr++;

            taddr = tci_read_ulong(&tb_ptr);

#ifdef CONFIG_SOFTMMU

            tmp16 = helper_ldw_mmu(env, taddr, tci_read_i(&tb_ptr));

#else

            host_addr = (tcg_target_ulong)taddr;

            assert(taddr == host_addr);

            tmp16 = tswap16(*(uint16_t *)(host_addr + GUEST_BASE));

#endif

            tci_write_reg16s(t0, tmp16);

            break;

#if TCG_TARGET_REG_BITS == 64

        case INDEX_op_qemu_ld32u:

            t0 = *tb_ptr++;

            taddr = tci_read_ulong(&tb_ptr);

#ifdef CONFIG_SOFTMMU

            tmp32 = helper_ldl_mmu(env, taddr, tci_read_i(&tb_ptr));

#else

            host_addr = (tcg_target_ulong)taddr;

            assert(taddr == host_addr);

            tmp32 = tswap32(*(uint32_t *)(host_addr + GUEST_BASE));

#endif

            tci_write_reg32(t0, tmp32);

            break;

        case INDEX_op_qemu_ld32s:

            t0 = *tb_ptr++;

            taddr = tci_read_ulong(&tb_ptr);

#ifdef CONFIG_SOFTMMU

            tmp32 = helper_ldl_mmu(env, taddr, tci_read_i(&tb_ptr));

#else

            host_addr = (tcg_target_ulong)taddr;

            assert(taddr == host_addr);

            tmp32 = tswap32(*(uint32_t *)(host_addr + GUEST_BASE));

#endif

            tci_write_reg32s(t0, tmp32);

            break;

#endif /* TCG_TARGET_REG_BITS == 64 */

        case INDEX_op_qemu_ld32:

            t0 = *tb_ptr++;

            taddr = tci_read_ulong(&tb_ptr);

#ifdef CONFIG_SOFTMMU

            tmp32 = helper_ldl_mmu(env, taddr, tci_read_i(&tb_ptr));

#else

            host_addr = (tcg_target_ulong)taddr;

            assert(taddr == host_addr);

            tmp32 = tswap32(*(uint32_t *)(host_addr + GUEST_BASE));

#endif

            tci_write_reg32(t0, tmp32);

            break;

        case INDEX_op_qemu_ld64:

            t0 = *tb_ptr++;

#if TCG_TARGET_REG_BITS == 32

            t1 = *tb_ptr++;

#endif

            taddr = tci_read_ulong(&tb_ptr);

#ifdef CONFIG_SOFTMMU

            tmp64 = helper_ldq_mmu(env, taddr, tci_read_i(&tb_ptr));

#else

            host_addr = (tcg_target_ulong)taddr;

            assert(taddr == host_addr);

            tmp64 = tswap64(*(uint64_t *)(host_addr + GUEST_BASE));

#endif

            tci_write_reg(t0, tmp64);

#if TCG_TARGET_REG_BITS == 32

            tci_write_reg(t1, tmp64 >> 32);

#endif

            break;

        case INDEX_op_qemu_st8:

            t0 = tci_read_r8(&tb_ptr);

            taddr = tci_read_ulong(&tb_ptr);

#ifdef CONFIG_SOFTMMU

            t2 = tci_read_i(&tb_ptr);

            helper_stb_mmu(env, taddr, t0, t2);

#else

            host_addr = (tcg_target_ulong)taddr;

            assert(taddr == host_addr);

            *(uint8_t *)(host_addr + GUEST_BASE) = t0;

#endif

            break;

        case INDEX_op_qemu_st16:

            t0 = tci_read_r16(&tb_ptr);

            taddr = tci_read_ulong(&tb_ptr);

#ifdef CONFIG_SOFTMMU

            t2 = tci_read_i(&tb_ptr);

            helper_stw_mmu(env, taddr, t0, t2);

#else

            host_addr = (tcg_target_ulong)taddr;

            assert(taddr == host_addr);

            *(uint16_t *)(host_addr + GUEST_BASE) = tswap16(t0);

#endif

            break;

        case INDEX_op_qemu_st32:

            t0 = tci_read_r32(&tb_ptr);

            taddr = tci_read_ulong(&tb_ptr);

#ifdef CONFIG_SOFTMMU

            t2 = tci_read_i(&tb_ptr);

            helper_stl_mmu(env, taddr, t0, t2);

#else

            host_addr = (tcg_target_ulong)taddr;

            assert(taddr == host_addr);

            *(uint32_t *)(host_addr + GUEST_BASE) = tswap32(t0);

#endif

            break;

        case INDEX_op_qemu_st64:

            tmp64 = tci_read_r64(&tb_ptr);

            taddr = tci_read_ulong(&tb_ptr);

#ifdef CONFIG_SOFTMMU

            t2 = tci_read_i(&tb_ptr);

            helper_stq_mmu(env, taddr, tmp64, t2);

#else

            host_addr = (tcg_target_ulong)taddr;

            assert(taddr == host_addr);

            *(uint64_t *)(host_addr + GUEST_BASE) = tswap64(tmp64);

#endif

            break;

        default:

            TODO();

            break;

        }

        assert(tb_ptr == old_code_ptr + op_size);

    }

exit:

    return next_tb;

}


void *g_realloc_n(void *ptr, size_t nmemb, size_t size)

{

    size_t sz;

    __coverity_negative_sink__(nmemb);

    __coverity_negative_sink__(size);

    sz = nmemb * size;

    __coverity_escape__(ptr);

    ptr = __coverity_alloc__(size);

    /*

     * Memory beyond the old size isn't actually initialized.  Can't

     * model that.  See Coverity's realloc() model

     */

    __coverity_writeall__(ptr);

    __coverity_mark_as_afm_allocated__(ptr, AFM_free);

    return ptr;

}


static void net_socket_send_dgram(void *opaque)

{

    NetSocketState *s = opaque;

    int size;

    size = qemu_recv(s->fd, s->buf, sizeof(s->buf), 0);

    if (size < 0)

        return;

    if (size == 0) {

        /* end of connection */

        net_socket_read_poll(s, false);

        net_socket_write_poll(s, false);

        return;

    }

    qemu_send_packet(&s->nc, s->buf, size);

}


static int tight_fill_palette(VncState *vs, int x, int y,

                              size_t count, uint32_t *bg, uint32_t *fg,

                              struct QDict **palette)

{

    int max;

    max = count / tight_conf[vs->tight_compression].idx_max_colors_divisor;

    if (max < 2 &&

        count >= tight_conf[vs->tight_compression].mono_min_rect_size) {

        max = 2;

    }

    if (max >= 256) {

        max = 256;

    }

    switch(vs->clientds.pf.bytes_per_pixel) {

    case 4:

        return tight_fill_palette32(vs, x, y, max, count, bg, fg, palette);

    case 2:

        return tight_fill_palette16(vs, x, y, max, count, bg, fg, palette);

    default:

        max = 2;

        return tight_fill_palette8(vs, x, y, max, count, bg, fg, palette);

    }

    return 0;

}


static int term_can_read(void *opaque)

{

    return 128;

}


void do_tlbwi (void)

{

    /* Discard cached TLB entries.  We could avoid doing this if the

       tlbwi is just upgrading access permissions on the current entry;

       that might be a further win.  */

    mips_tlb_flush_extra (env, MIPS_TLB_NB);

    /* Wildly undefined effects for CP0_index containing a too high value and

       MIPS_TLB_NB not being a power of two.  But so does real silicon.  */

    invalidate_tlb(env->CP0_index & (MIPS_TLB_NB - 1), 0);

    fill_tlb(env->CP0_index & (MIPS_TLB_NB - 1));

}


static void tcg_out_modrm_sib_offset(TCGContext *s, int opc, int r, int rm,

                                     int index, int shift, intptr_t offset)

{

    int mod, len;

    if (index < 0 && rm < 0) {

        if (TCG_TARGET_REG_BITS == 64) {

            /* Try for a rip-relative addressing mode.  This has replaced

               the 32-bit-mode absolute addressing encoding.  */

            intptr_t pc = (intptr_t)s->code_ptr + 5 + ~rm;

            intptr_t disp = offset - pc;

            if (disp == (int32_t)disp) {

                tcg_out_opc(s, opc, r, 0, 0);

                tcg_out8(s, (LOWREGMASK(r) << 3) | 5);

                tcg_out32(s, disp);

                return;

            }

            /* Try for an absolute address encoding.  This requires the

               use of the MODRM+SIB encoding and is therefore larger than

               rip-relative addressing.  */

            if (offset == (int32_t)offset) {

                tcg_out_opc(s, opc, r, 0, 0);

                tcg_out8(s, (LOWREGMASK(r) << 3) | 4);

                tcg_out8(s, (4 << 3) | 5);

                tcg_out32(s, offset);

                return;

            }

            /* ??? The memory isn't directly addressable.  */

            tcg_abort();

        } else {

            /* Absolute address.  */

            tcg_out_opc(s, opc, r, 0, 0);

            tcg_out8(s, (r << 3) | 5);

            tcg_out32(s, offset);

            return;

        }

    }

    /* Find the length of the immediate addend.  Note that the encoding

       that would be used for (%ebp) indicates absolute addressing.  */

    if (rm < 0) {

        mod = 0, len = 4, rm = 5;

    } else if (offset == 0 && LOWREGMASK(rm) != TCG_REG_EBP) {

        mod = 0, len = 0;

    } else if (offset == (int8_t)offset) {

        mod = 0x40, len = 1;

    } else {

        mod = 0x80, len = 4;

    }

    /* Use a single byte MODRM format if possible.  Note that the encoding

       that would be used for %esp is the escape to the two byte form.  */

    if (index < 0 && LOWREGMASK(rm) != TCG_REG_ESP) {

        /* Single byte MODRM format.  */

        tcg_out_opc(s, opc, r, rm, 0);

        tcg_out8(s, mod | (LOWREGMASK(r) << 3) | LOWREGMASK(rm));

    } else {

        /* Two byte MODRM+SIB format.  */

        /* Note that the encoding that would place %esp into the index

           field indicates no index register.  In 64-bit mode, the REX.X

           bit counts, so %r12 can be used as the index.  */

        if (index < 0) {

            index = 4;

        } else {

            assert(index != TCG_REG_ESP);

        }

        tcg_out_opc(s, opc, r, rm, index);

        tcg_out8(s, mod | (LOWREGMASK(r) << 3) | 4);

        tcg_out8(s, (shift << 6) | (LOWREGMASK(index) << 3) | LOWREGMASK(rm));

    }

    if (len == 1) {

        tcg_out8(s, offset);

    } else if (len == 4) {

        tcg_out32(s, offset);

    }

}


static int common_bind(struct common *c)

{

    int mfn;

    if (xenstore_read_fe_int(&c->xendev, "page-ref", &mfn) == -1)

	return -1;

    if (xenstore_read_fe_int(&c->xendev, "event-channel", &c->xendev.remote_port) == -1)

	return -1;

    c->page = xc_map_foreign_range(xen_xc, c->xendev.dom,

				   XC_PAGE_SIZE,

				   PROT_READ | PROT_WRITE, mfn);

    if (c->page == NULL)

	return -1;

    xen_be_bind_evtchn(&c->xendev);

    xen_be_printf(&c->xendev, 1, "ring mfn %d, remote-port %d, local-port %d\n",

		  mfn, c->xendev.remote_port, c->xendev.local_port);

    return 0;

}


static int nvenc_get_frame(AVCodecContext *avctx, AVPacket *pkt)

{

    NVENCContext *ctx               = avctx->priv_data;

    NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;

    NV_ENC_LOCK_BITSTREAM params    = { 0 };

    NVENCOutputSurface *out         = NULL;

    int ret;

    ret = nvenc_dequeue_surface(ctx->pending, &out);

    if (ret)

        return ret;

    params.version         = NV_ENC_LOCK_BITSTREAM_VER;

    params.outputBitstream = out->out;

    ret = nv->nvEncLockBitstream(ctx->nvenc_ctx, &params);

    if (ret < 0)

        return nvenc_print_error(avctx, ret, "Cannot lock the bitstream");

    ret = ff_alloc_packet(pkt, params.bitstreamSizeInBytes);

    if (ret < 0)

        return ret;

    memcpy(pkt->data, params.bitstreamBufferPtr, pkt->size);

    ret = nv->nvEncUnlockBitstream(ctx->nvenc_ctx, out->out);

    if (ret < 0)

        return nvenc_print_error(avctx, ret, "Cannot unlock the bitstream");

    out->busy = out->in->locked = 0;

    ret = nvenc_set_timestamp(ctx, &params, pkt);

    if (ret < 0)

        return ret;

    switch (params.pictureType) {

    case NV_ENC_PIC_TYPE_IDR:

        pkt->flags |= AV_PKT_FLAG_KEY;

#if FF_API_CODED_FRAME

FF_DISABLE_DEPRECATION_WARNINGS

    case NV_ENC_PIC_TYPE_INTRA_REFRESH:

    case NV_ENC_PIC_TYPE_I:

        avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;

        break;

    case NV_ENC_PIC_TYPE_P:

        avctx->coded_frame->pict_type = AV_PICTURE_TYPE_P;

        break;

    case NV_ENC_PIC_TYPE_B:

        avctx->coded_frame->pict_type = AV_PICTURE_TYPE_B;

        break;

    case NV_ENC_PIC_TYPE_BI:

        avctx->coded_frame->pict_type = AV_PICTURE_TYPE_BI;

        break;

FF_ENABLE_DEPRECATION_WARNINGS

#endif

    }

    return 0;

}


static ssize_t rtl8139_do_receive(VLANClientState *nc, const uint8_t *buf, size_t size_, int do_interrupt)

{

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

    int size = size_;

    uint32_t packet_header = 0;

    uint8_t buf1[60];

    static const uint8_t broadcast_macaddr[6] =

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

    DEBUG_PRINT((">>> RTL8139: received len=%d\n", size));

    /* test if board clock is stopped */

    if (!s->clock_enabled)

    {

        DEBUG_PRINT(("RTL8139: stopped ==========================\n"));

        return -1;

    }

    /* first check if receiver is enabled */

    if (!rtl8139_receiver_enabled(s))

    {

        DEBUG_PRINT(("RTL8139: receiver disabled ================\n"));

        return -1;

    }

    /* XXX: check this */

    if (s->RxConfig & AcceptAllPhys) {

        /* promiscuous: receive all */

        DEBUG_PRINT((">>> RTL8139: packet received in promiscuous mode\n"));

    } else {

        if (!memcmp(buf,  broadcast_macaddr, 6)) {

            /* broadcast address */

            if (!(s->RxConfig & AcceptBroadcast))

            {

                DEBUG_PRINT((">>> RTL8139: broadcast packet rejected\n"));

                /* update tally counter */

                ++s->tally_counters.RxERR;

                return size;

            }

            packet_header |= RxBroadcast;

            DEBUG_PRINT((">>> RTL8139: broadcast packet received\n"));

            /* update tally counter */

            ++s->tally_counters.RxOkBrd;

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

            /* multicast */

            if (!(s->RxConfig & AcceptMulticast))

            {

                DEBUG_PRINT((">>> RTL8139: multicast packet rejected\n"));

                /* update tally counter */

                ++s->tally_counters.RxERR;

                return size;

            }

            int mcast_idx = compute_mcast_idx(buf);

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

            {

                DEBUG_PRINT((">>> RTL8139: multicast address mismatch\n"));

                /* update tally counter */

                ++s->tally_counters.RxERR;

                return size;

            }

            packet_header |= RxMulticast;

            DEBUG_PRINT((">>> RTL8139: multicast packet received\n"));

            /* update tally counter */

            ++s->tally_counters.RxOkMul;

        } else if (s->phys[0] == buf[0] &&

                   s->phys[1] == buf[1] &&

                   s->phys[2] == buf[2] &&

                   s->phys[3] == buf[3] &&

                   s->phys[4] == buf[4] &&

                   s->phys[5] == buf[5]) {

            /* match */

            if (!(s->RxConfig & AcceptMyPhys))

            {

                DEBUG_PRINT((">>> RTL8139: rejecting physical address matching packet\n"));

                /* update tally counter */

                ++s->tally_counters.RxERR;

                return size;

            }

            packet_header |= RxPhysical;

            DEBUG_PRINT((">>> RTL8139: physical address matching packet received\n"));

            /* update tally counter */

            ++s->tally_counters.RxOkPhy;

        } else {

            DEBUG_PRINT((">>> RTL8139: unknown packet\n"));

            /* update tally counter */

            ++s->tally_counters.RxERR;

            return size;

        }

    }

    /* if too small buffer, then expand it */

    if (size < MIN_BUF_SIZE) {

        memcpy(buf1, buf, size);

        memset(buf1 + size, 0, MIN_BUF_SIZE - size);

        buf = buf1;

        size = MIN_BUF_SIZE;

    }

    if (rtl8139_cp_receiver_enabled(s))

    {

        DEBUG_PRINT(("RTL8139: in C+ Rx mode ================\n"));

        /* begin C+ receiver mode */

/* w0 ownership flag */

#define CP_RX_OWN (1<<31)

/* w0 end of ring flag */

#define CP_RX_EOR (1<<30)

/* w0 bits 0...12 : buffer size */

#define CP_RX_BUFFER_SIZE_MASK ((1<<13) - 1)

/* w1 tag available flag */

#define CP_RX_TAVA (1<<16)

/* w1 bits 0...15 : VLAN tag */

#define CP_RX_VLAN_TAG_MASK ((1<<16) - 1)

/* w2 low  32bit of Rx buffer ptr */

/* w3 high 32bit of Rx buffer ptr */

        int descriptor = s->currCPlusRxDesc;

        target_phys_addr_t cplus_rx_ring_desc;

        cplus_rx_ring_desc = rtl8139_addr64(s->RxRingAddrLO, s->RxRingAddrHI);

        cplus_rx_ring_desc += 16 * descriptor;

        DEBUG_PRINT(("RTL8139: +++ C+ mode reading RX descriptor %d from host memory at %08x %08x = %016" PRIx64 "\n",

               descriptor, s->RxRingAddrHI, s->RxRingAddrLO, (uint64_t)cplus_rx_ring_desc));

        uint32_t val, rxdw0,rxdw1,rxbufLO,rxbufHI;

        cpu_physical_memory_read(cplus_rx_ring_desc,    (uint8_t *)&val, 4);

        rxdw0 = le32_to_cpu(val);

        cpu_physical_memory_read(cplus_rx_ring_desc+4,  (uint8_t *)&val, 4);

        rxdw1 = le32_to_cpu(val);

        cpu_physical_memory_read(cplus_rx_ring_desc+8,  (uint8_t *)&val, 4);

        rxbufLO = le32_to_cpu(val);

        cpu_physical_memory_read(cplus_rx_ring_desc+12, (uint8_t *)&val, 4);

        rxbufHI = le32_to_cpu(val);

        DEBUG_PRINT(("RTL8139: +++ C+ mode RX descriptor %d %08x %08x %08x %08x\n",

               descriptor,

               rxdw0, rxdw1, rxbufLO, rxbufHI));

        if (!(rxdw0 & CP_RX_OWN))

        {

            DEBUG_PRINT(("RTL8139: C+ Rx mode : descriptor %d is owned by host\n", descriptor));

            s->IntrStatus |= RxOverflow;

            ++s->RxMissed;

            /* update tally counter */

            ++s->tally_counters.RxERR;

            ++s->tally_counters.MissPkt;

            rtl8139_update_irq(s);

            return size_;

        }

        uint32_t rx_space = rxdw0 & CP_RX_BUFFER_SIZE_MASK;

        /* TODO: scatter the packet over available receive ring descriptors space */

        if (size+4 > rx_space)

        {

            DEBUG_PRINT(("RTL8139: C+ Rx mode : descriptor %d size %d received %d + 4\n",

                   descriptor, rx_space, size));

            s->IntrStatus |= RxOverflow;

            ++s->RxMissed;

            /* update tally counter */

            ++s->tally_counters.RxERR;

            ++s->tally_counters.MissPkt;

            rtl8139_update_irq(s);

            return size_;

        }

        target_phys_addr_t rx_addr = rtl8139_addr64(rxbufLO, rxbufHI);

        /* receive/copy to target memory */

        cpu_physical_memory_write( rx_addr, buf, size );

        if (s->CpCmd & CPlusRxChkSum)

        {

            /* do some packet checksumming */

        }

        /* write checksum */

#if defined (RTL8139_CALCULATE_RXCRC)

        val = cpu_to_le32(crc32(0, buf, size));

#else

        val = 0;

#endif

        cpu_physical_memory_write( rx_addr+size, (uint8_t *)&val, 4);

/* first segment of received packet flag */

#define CP_RX_STATUS_FS (1<<29)

/* last segment of received packet flag */

#define CP_RX_STATUS_LS (1<<28)

/* multicast packet flag */

#define CP_RX_STATUS_MAR (1<<26)

/* physical-matching packet flag */

#define CP_RX_STATUS_PAM (1<<25)

/* broadcast packet flag */

#define CP_RX_STATUS_BAR (1<<24)

/* runt packet flag */

#define CP_RX_STATUS_RUNT (1<<19)

/* crc error flag */

#define CP_RX_STATUS_CRC (1<<18)

/* IP checksum error flag */

#define CP_RX_STATUS_IPF (1<<15)

/* UDP checksum error flag */

#define CP_RX_STATUS_UDPF (1<<14)

/* TCP checksum error flag */

#define CP_RX_STATUS_TCPF (1<<13)

        /* transfer ownership to target */

        rxdw0 &= ~CP_RX_OWN;

        /* set first segment bit */

        rxdw0 |= CP_RX_STATUS_FS;

        /* set last segment bit */

        rxdw0 |= CP_RX_STATUS_LS;

        /* set received packet type flags */

        if (packet_header & RxBroadcast)

            rxdw0 |= CP_RX_STATUS_BAR;

        if (packet_header & RxMulticast)

            rxdw0 |= CP_RX_STATUS_MAR;

        if (packet_header & RxPhysical)

            rxdw0 |= CP_RX_STATUS_PAM;

        /* set received size */

        rxdw0 &= ~CP_RX_BUFFER_SIZE_MASK;

        rxdw0 |= (size+4);

        /* reset VLAN tag flag */

        rxdw1 &= ~CP_RX_TAVA;

        /* update ring data */

        val = cpu_to_le32(rxdw0);

        cpu_physical_memory_write(cplus_rx_ring_desc,    (uint8_t *)&val, 4);

        val = cpu_to_le32(rxdw1);

        cpu_physical_memory_write(cplus_rx_ring_desc+4,  (uint8_t *)&val, 4);

        /* update tally counter */

        ++s->tally_counters.RxOk;

        /* seek to next Rx descriptor */

        if (rxdw0 & CP_RX_EOR)

        {

            s->currCPlusRxDesc = 0;

        }

        else

        {

            ++s->currCPlusRxDesc;

        }

        DEBUG_PRINT(("RTL8139: done C+ Rx mode ----------------\n"));

    }

    else

    {

        DEBUG_PRINT(("RTL8139: in ring Rx mode ================\n"));

        /* begin ring receiver mode */

        int avail = MOD2(s->RxBufferSize + s->RxBufPtr - s->RxBufAddr, s->RxBufferSize);

        /* if receiver buffer is empty then avail == 0 */

        if (avail != 0 && size + 8 >= avail)

        {

            DEBUG_PRINT(("rx overflow: rx buffer length %d head 0x%04x read 0x%04x === available 0x%04x need 0x%04x\n",

                   s->RxBufferSize, s->RxBufAddr, s->RxBufPtr, avail, size + 8));

            s->IntrStatus |= RxOverflow;

            ++s->RxMissed;

            rtl8139_update_irq(s);

            return size_;

        }

        packet_header |= RxStatusOK;

        packet_header |= (((size+4) << 16) & 0xffff0000);

        /* write header */

        uint32_t val = cpu_to_le32(packet_header);

        rtl8139_write_buffer(s, (uint8_t *)&val, 4);

        rtl8139_write_buffer(s, buf, size);

        /* write checksum */

#if defined (RTL8139_CALCULATE_RXCRC)

        val = cpu_to_le32(crc32(0, buf, size));

#else

        val = 0;

#endif

        rtl8139_write_buffer(s, (uint8_t *)&val, 4);

        /* correct buffer write pointer */

        s->RxBufAddr = MOD2((s->RxBufAddr + 3) & ~0x3, s->RxBufferSize);

        /* now we can signal we have received something */

        DEBUG_PRINT(("   received: rx buffer length %d head 0x%04x read 0x%04x\n",

               s->RxBufferSize, s->RxBufAddr, s->RxBufPtr));

    }

    s->IntrStatus |= RxOK;

    if (do_interrupt)

    {

        rtl8139_update_irq(s);

    }

    return size_;

}


static void build_pci_bus_end(PCIBus *bus, void *bus_state)

{

    AcpiBuildPciBusHotplugState *child = bus_state;

    AcpiBuildPciBusHotplugState *parent = child->parent;

    GArray *bus_table = build_alloc_array();

    DECLARE_BITMAP(slot_hotplug_enable, PCI_SLOT_MAX);

    DECLARE_BITMAP(slot_device_present, PCI_SLOT_MAX);

    DECLARE_BITMAP(slot_device_system, PCI_SLOT_MAX);

    DECLARE_BITMAP(slot_device_vga, PCI_SLOT_MAX);

    DECLARE_BITMAP(slot_device_qxl, PCI_SLOT_MAX);

    uint8_t op;

    int i;

    QObject *bsel;

    GArray *method;

    bool bus_hotplug_support = false;

    /*

     * Skip bridge subtree creation if bridge hotplug is disabled

     * to make acpi tables compatible with legacy machine types.

     * Skip creation for hotplugged bridges as well.

     */

    if (bus->parent_dev && (!child->pcihp_bridge_en ||

                            DEVICE(bus->parent_dev)->hotplugged)) {

        build_free_array(bus_table);

        build_pci_bus_state_cleanup(child);

        g_free(child);

        return;

    }

    if (bus->parent_dev) {

        op = 0x82; /* DeviceOp */

        build_append_namestring(bus_table, "S%.02X",

                             bus->parent_dev->devfn);

        build_append_byte(bus_table, 0x08); /* NameOp */

        build_append_namestring(bus_table, "_SUN");

        build_append_int(bus_table, PCI_SLOT(bus->parent_dev->devfn));

        build_append_byte(bus_table, 0x08); /* NameOp */

        build_append_namestring(bus_table, "_ADR");

        build_append_int(bus_table, (PCI_SLOT(bus->parent_dev->devfn) << 16) |

                           PCI_FUNC(bus->parent_dev->devfn));

    } else {

        op = 0x10; /* ScopeOp */;

        build_append_namestring(bus_table, "PCI0");

    }

    bsel = object_property_get_qobject(OBJECT(bus), ACPI_PCIHP_PROP_BSEL, NULL);

    if (bsel) {

        build_append_byte(bus_table, 0x08); /* NameOp */

        build_append_namestring(bus_table, "BSEL");

        build_append_int(bus_table, qint_get_int(qobject_to_qint(bsel)));

        memset(slot_hotplug_enable, 0xff, sizeof slot_hotplug_enable);

    } else {

        /* No bsel - no slots are hot-pluggable */

        memset(slot_hotplug_enable, 0x00, sizeof slot_hotplug_enable);

    }

    memset(slot_device_present, 0x00, sizeof slot_device_present);

    memset(slot_device_system, 0x00, sizeof slot_device_present);

    memset(slot_device_vga, 0x00, sizeof slot_device_vga);

    memset(slot_device_qxl, 0x00, sizeof slot_device_qxl);

    for (i = 0; i < ARRAY_SIZE(bus->devices); i += PCI_FUNC_MAX) {

        DeviceClass *dc;

        PCIDeviceClass *pc;

        PCIDevice *pdev = bus->devices[i];

        int slot = PCI_SLOT(i);

        bool bridge_in_acpi;

        if (!pdev) {

            continue;

        }

        set_bit(slot, slot_device_present);

        pc = PCI_DEVICE_GET_CLASS(pdev);

        dc = DEVICE_GET_CLASS(pdev);

        /* When hotplug for bridges is enabled, bridges are

         * described in ACPI separately (see build_pci_bus_end).

         * In this case they aren't themselves hot-pluggable.

         * Hotplugged bridges *are* hot-pluggable.

         */

        bridge_in_acpi = pc->is_bridge && child->pcihp_bridge_en &&

         !DEVICE(pdev)->hotplugged;

        if (pc->class_id == PCI_CLASS_BRIDGE_ISA || bridge_in_acpi) {

            set_bit(slot, slot_device_system);

        }

        if (pc->class_id == PCI_CLASS_DISPLAY_VGA) {

            set_bit(slot, slot_device_vga);

            if (object_dynamic_cast(OBJECT(pdev), "qxl-vga")) {

                set_bit(slot, slot_device_qxl);

            }

        }

        if (!dc->hotpluggable || bridge_in_acpi) {

            clear_bit(slot, slot_hotplug_enable);

        }

    }

    /* Append Device object for each slot */

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

        bool can_eject = test_bit(i, slot_hotplug_enable);

        bool present = test_bit(i, slot_device_present);

        bool vga = test_bit(i, slot_device_vga);

        bool qxl = test_bit(i, slot_device_qxl);

        bool system = test_bit(i, slot_device_system);

        if (can_eject) {

            void *pcihp = acpi_data_push(bus_table,

                                         ACPI_PCIHP_SIZEOF);

            memcpy(pcihp, ACPI_PCIHP_AML, ACPI_PCIHP_SIZEOF);

            patch_pcihp(i, pcihp);

            bus_hotplug_support = true;

        } else if (qxl) {

            void *pcihp = acpi_data_push(bus_table,

                                         ACPI_PCIQXL_SIZEOF);

            memcpy(pcihp, ACPI_PCIQXL_AML, ACPI_PCIQXL_SIZEOF);

            patch_pciqxl(i, pcihp);

        } else if (vga) {

            void *pcihp = acpi_data_push(bus_table,

                                         ACPI_PCIVGA_SIZEOF);

            memcpy(pcihp, ACPI_PCIVGA_AML, ACPI_PCIVGA_SIZEOF);

            patch_pcivga(i, pcihp);

        } else if (system) {

            /* Nothing to do: system devices are in DSDT or in SSDT above. */

        } else if (present) {

            void *pcihp = acpi_data_push(bus_table,

                                         ACPI_PCINOHP_SIZEOF);

            memcpy(pcihp, ACPI_PCINOHP_AML, ACPI_PCINOHP_SIZEOF);

            patch_pcinohp(i, pcihp);

        }

    }

    if (bsel) {

        method = build_alloc_method("DVNT", 2);

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

            GArray *notify;

            uint8_t op;

            if (!test_bit(i, slot_hotplug_enable)) {

                continue;

            }

            notify = build_alloc_array();

            op = 0xA0; /* IfOp */

            build_append_byte(notify, 0x7B); /* AndOp */

            build_append_byte(notify, 0x68); /* Arg0Op */

            build_append_int(notify, 0x1U << i);

            build_append_byte(notify, 0x00); /* NullName */

            build_append_byte(notify, 0x86); /* NotifyOp */

            build_append_namestring(notify, "S%.02X", PCI_DEVFN(i, 0));

            build_append_byte(notify, 0x69); /* Arg1Op */

            /* Pack it up */

            build_package(notify, op);

            build_append_array(method, notify);

            build_free_array(notify);

        }

        build_append_and_cleanup_method(bus_table, method);

    }

    /* Append PCNT method to notify about events on local and child buses.

     * Add unconditionally for root since DSDT expects it.

     */

    if (bus_hotplug_support || child->notify_table->len || !bus->parent_dev) {

        method = build_alloc_method("PCNT", 0);

        /* If bus supports hotplug select it and notify about local events */

        if (bsel) {

            build_append_byte(method, 0x70); /* StoreOp */

            build_append_int(method, qint_get_int(qobject_to_qint(bsel)));

            build_append_namestring(method, "BNUM");

            build_append_namestring(method, "DVNT");

            build_append_namestring(method, "PCIU");

            build_append_int(method, 1); /* Device Check */

            build_append_namestring(method, "DVNT");

            build_append_namestring(method, "PCID");

            build_append_int(method, 3); /* Eject Request */

        }

        /* Notify about child bus events in any case */

        build_append_array(method, child->notify_table);

        build_append_and_cleanup_method(bus_table, method);

        /* Append description of child buses */

        build_append_array(bus_table, child->device_table);

        /* Pack it up */

        if (bus->parent_dev) {

            build_extop_package(bus_table, op);

        } else {

            build_package(bus_table, op);

        }

        /* Append our bus description to parent table */

        build_append_array(parent->device_table, bus_table);

        /* Also tell parent how to notify us, invoking PCNT method.

         * At the moment this is not needed for root as we have a single root.

         */

        if (bus->parent_dev) {

            build_append_namestring(parent->notify_table, "^PCNT.S%.02X",

                                    bus->parent_dev->devfn);

        }

    }

    qobject_decref(bsel);

    build_free_array(bus_table);

    build_pci_bus_state_cleanup(child);

    g_free(child);

}


static void arm_gicv3_icc_reset(CPUARMState *env, const ARMCPRegInfo *ri)

{

    ARMCPU *cpu;

    GICv3State *s;

    GICv3CPUState *c;

    c = (GICv3CPUState *)env->gicv3state;

    s = c->gic;

    cpu = ARM_CPU(c->cpu);

    /* Initialize to actual HW supported configuration */

    kvm_device_access(s->dev_fd, KVM_DEV_ARM_VGIC_GRP_CPU_SYSREGS,

                      KVM_VGIC_ATTR(ICC_CTLR_EL1, cpu->mp_affinity),

                      &c->icc_ctlr_el1[GICV3_NS], false);

    c->icc_ctlr_el1[GICV3_S] = c->icc_ctlr_el1[GICV3_NS];

    c->icc_pmr_el1 = 0;

    c->icc_bpr[GICV3_G0] = GIC_MIN_BPR;

    c->icc_bpr[GICV3_G1] = GIC_MIN_BPR;

    c->icc_bpr[GICV3_G1NS] = GIC_MIN_BPR;

    c->icc_sre_el1 = 0x7;

    memset(c->icc_apr, 0, sizeof(c->icc_apr));

    memset(c->icc_igrpen, 0, sizeof(c->icc_igrpen));

}


static bool tb_cmp(const void *p, const void *d)

{

    const TranslationBlock *tb = p;

    const struct tb_desc *desc = d;

    if (tb->pc == desc->pc &&

        tb->page_addr[0] == desc->phys_page1 &&

        tb->cs_base == desc->cs_base &&

        tb->flags == desc->flags &&

        tb->trace_vcpu_dstate == desc->trace_vcpu_dstate &&

        !atomic_read(&tb->invalid)) {

        /* check next page if needed */

        if (tb->page_addr[1] == -1) {

            return true;

        } else {

            tb_page_addr_t phys_page2;

            target_ulong virt_page2;

            virt_page2 = (desc->pc & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE;

            phys_page2 = get_page_addr_code(desc->env, virt_page2);

            if (tb->page_addr[1] == phys_page2) {

                return true;

            }

        }

    }

    return false;

}


static int vnc_display_listen_addr(VncDisplay *vd,

                                   SocketAddress *addr,

                                   const char *name,

                                   QIOChannelSocket ***lsock,

                                   guint **lsock_tag,

                                   size_t *nlsock,

                                   Error **errp)

{

    *nlsock = 1;

    *lsock = g_new0(QIOChannelSocket *, 1);

    *lsock_tag = g_new0(guint, 1);

    (*lsock)[0] = qio_channel_socket_new();

    qio_channel_set_name(QIO_CHANNEL((*lsock)[0]), name);

    if (qio_channel_socket_listen_sync((*lsock)[0], addr, errp) < 0) {

        return -1;

    }

    (*lsock_tag)[0] = qio_channel_add_watch(

        QIO_CHANNEL((*lsock)[0]),

        G_IO_IN, vnc_listen_io, vd, NULL);

    return 0;

}


static SpiceChannelList *qmp_query_spice_channels(void)

{

    SpiceChannelList *cur_item = NULL, *head = NULL;

    ChannelList *item;

    QTAILQ_FOREACH(item, &channel_list, link) {

        SpiceChannelList *chan;

        char host[NI_MAXHOST], port[NI_MAXSERV];

        struct sockaddr *paddr;

        socklen_t plen;

        assert(item->info->flags & SPICE_CHANNEL_EVENT_FLAG_ADDR_EXT);

        chan = g_malloc0(sizeof(*chan));

        chan->value = g_malloc0(sizeof(*chan->value));

        chan->value->base = g_malloc0(sizeof(*chan->value->base));

        paddr = (struct sockaddr *)&item->info->paddr_ext;

        plen = item->info->plen_ext;

        getnameinfo(paddr, plen,

                    host, sizeof(host), port, sizeof(port),

                    NI_NUMERICHOST | NI_NUMERICSERV);

        chan->value->base->host = g_strdup(host);

        chan->value->base->port = g_strdup(port);

        chan->value->base->family = inet_netfamily(paddr->sa_family);

        chan->value->connection_id = item->info->connection_id;

        chan->value->channel_type = item->info->type;

        chan->value->channel_id = item->info->id;

        chan->value->tls = item->info->flags & SPICE_CHANNEL_EVENT_FLAG_TLS;

       /* XXX: waiting for the qapi to support GSList */

        if (!cur_item) {

            head = cur_item = chan;

        } else {

            cur_item->next = chan;

            cur_item = chan;

        }

    }

    return head;

}


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

{

    int fd;

    int result = 0;

    int64_t total_size = 0;

    bool nocow = false;

    PreallocMode prealloc;

    char *buf = NULL;

    Error *local_err = NULL;

    strstart(filename, "file:", &filename);

    /* Read out options */

    total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),

                          BDRV_SECTOR_SIZE);

    nocow = qemu_opt_get_bool(opts, BLOCK_OPT_NOCOW, false);

    buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);

    prealloc = qapi_enum_parse(PreallocMode_lookup, buf,

                               PREALLOC_MODE_MAX, PREALLOC_MODE_OFF,

                               &local_err);

    g_free(buf);

    if (local_err) {

        error_propagate(errp, local_err);

        result = -EINVAL;

        goto out;

    }

    fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,

                   0644);

    if (fd < 0) {

        result = -errno;

        error_setg_errno(errp, -result, "Could not create file");

        goto out;

    }

    if (nocow) {

#ifdef __linux__

        /* Set NOCOW flag to solve performance issue on fs like btrfs.

         * This is an optimisation. The FS_IOC_SETFLAGS ioctl return value

         * will be ignored since any failure of this operation should not

         * block the left work.

         */

        int attr;

        if (ioctl(fd, FS_IOC_GETFLAGS, &attr) == 0) {

            attr |= FS_NOCOW_FL;

            ioctl(fd, FS_IOC_SETFLAGS, &attr);

        }

#endif

    }

    if (ftruncate(fd, total_size) != 0) {

        result = -errno;

        error_setg_errno(errp, -result, "Could not resize file");

        goto out_close;

    }

    switch (prealloc) {

#ifdef CONFIG_POSIX_FALLOCATE

    case PREALLOC_MODE_FALLOC:

        /* posix_fallocate() doesn't set errno. */

        result = -posix_fallocate(fd, 0, total_size);

        if (result != 0) {

            error_setg_errno(errp, -result,

                             "Could not preallocate data for the new file");

        }

        break;

#endif

    case PREALLOC_MODE_FULL:

    {

        int64_t num = 0, left = total_size;

        buf = g_malloc0(65536);

        while (left > 0) {

            num = MIN(left, 65536);

            result = write(fd, buf, num);

            if (result < 0) {

                result = -errno;

                error_setg_errno(errp, -result,

                                 "Could not write to the new file");

                break;

            }

            left -= result;

        }

        fsync(fd);

        g_free(buf);

        break;

    }

    case PREALLOC_MODE_OFF:

        break;

    default:

        result = -EINVAL;

        error_setg(errp, "Unsupported preallocation mode: %s",

                   PreallocMode_lookup[prealloc]);

        break;

    }

out_close:

    if (qemu_close(fd) != 0 && result == 0) {

        result = -errno;

        error_setg_errno(errp, -result, "Could not close the new file");

    }

out:

    return result;

}


main (void)

{

  struct timeval t_m = {0, 0};

  struct timezone t_z = {0, 0};

  struct timeval t_m1 = {0, 0};

  int i;

  if (gettimeofday (&t_m, &t_z) != 0)

    err ("gettimeofday");

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

    if (gettimeofday (&t_m1, NULL) != 0)

      err ("gettimeofday 1");

    else

      if (t_m1.tv_sec * 1000000 + t_m1.tv_usec

	  != (t_m.tv_sec * 1000000 + t_m.tv_usec + i * 1000))

	{

	  fprintf (stderr, "t0 (%ld, %ld), i %d, t1 (%ld, %ld)\n",

		   t_m.tv_sec, t_m.tv_usec, i, t_m1.tv_sec, t_m1.tv_usec);

	  abort ();

	}

  if (time (NULL) != t_m1.tv_sec)

    {

      fprintf (stderr, "time != gettod\n");

      abort ();

    }

  printf ("pass\n");

  exit (0);

}


bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)

{

    while (top && top != base) {

        top = top->backing_hd;

    }

    return top != NULL;

}


static void bonito_ldma_writel(void *opaque, target_phys_addr_t addr,

                               uint64_t val, unsigned size)

{

    PCIBonitoState *s = opaque;

    ((uint32_t *)(&s->bonldma))[addr/sizeof(uint32_t)] = val & 0xffffffff;

}


static uint32_t phys_map_node_alloc(void)

{

    unsigned i;

    uint32_t ret;

    ret = next_map.nodes_nb++;

    assert(ret != PHYS_MAP_NODE_NIL);

    assert(ret != next_map.nodes_nb_alloc);

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

        next_map.nodes[ret][i].skip = 1;

        next_map.nodes[ret][i].ptr = PHYS_MAP_NODE_NIL;

    }

    return ret;

}


static bool check_overwrapping_aiocb(BDRVSheepdogState *s, SheepdogAIOCB *aiocb)

{

    SheepdogAIOCB *cb;

    QLIST_FOREACH(cb, &s->inflight_aiocb_head, aiocb_siblings) {

        if (AIOCBOverwrapping(aiocb, cb)) {

            return true;

        }

    }

    QLIST_INSERT_HEAD(&s->inflight_aiocb_head, aiocb, aiocb_siblings);

    return false;

}


static MemTxResult gic_cpu_read(GICState *s, int cpu, int offset,

                                uint64_t *data, MemTxAttrs attrs)

{

    switch (offset) {

    case 0x00: /* Control */

        *data = s->cpu_enabled[cpu];

        break;

    case 0x04: /* Priority mask */

        *data = s->priority_mask[cpu];

        break;

    case 0x08: /* Binary Point */

        if (s->security_extn && !attrs.secure) {

            /* BPR is banked. Non-secure copy stored in ABPR. */

            *data = s->abpr[cpu];

        } else {

            *data = s->bpr[cpu];

        }

        break;

    case 0x0c: /* Acknowledge */

        *data = gic_acknowledge_irq(s, cpu);

        break;

    case 0x14: /* Running Priority */

        *data = s->running_priority[cpu];

        break;

    case 0x18: /* Highest Pending Interrupt */

        *data = s->current_pending[cpu];

        break;

    case 0x1c: /* Aliased Binary Point */

        /* GIC v2, no security: ABPR

         * GIC v1, no security: not implemented (RAZ/WI)

         * With security extensions, secure access: ABPR (alias of NS BPR)

         * With security extensions, nonsecure access: RAZ/WI

         */

        if (!gic_has_groups(s) || (s->security_extn && !attrs.secure)) {

            *data = 0;

        } else {

            *data = s->abpr[cpu];

        }

        break;

    case 0xd0: case 0xd4: case 0xd8: case 0xdc:

        *data = s->apr[(offset - 0xd0) / 4][cpu];

        break;

    default:

        qemu_log_mask(LOG_GUEST_ERROR,

                      "gic_cpu_read: Bad offset %x\n", (int)offset);

        return MEMTX_ERROR;

    }

    return MEMTX_OK;

}


static int64_t coroutine_fn vpc_co_get_block_status(BlockDriverState *bs,

        int64_t sector_num, int nb_sectors, int *pnum)

{

    BDRVVPCState *s = bs->opaque;

    VHDFooter *footer = (VHDFooter*) s->footer_buf;

    int64_t start, offset;

    bool allocated;

    int n;

    if (be32_to_cpu(footer->type) == VHD_FIXED) {

        *pnum = nb_sectors;

        return BDRV_BLOCK_RAW | BDRV_BLOCK_OFFSET_VALID | BDRV_BLOCK_DATA |

               (sector_num << BDRV_SECTOR_BITS);

    }

    offset = get_sector_offset(bs, sector_num, 0);

    start = offset;

    allocated = (offset != -1);

    *pnum = 0;

    do {

        /* All sectors in a block are contiguous (without using the bitmap) */

        n = ROUND_UP(sector_num + 1, s->block_size / BDRV_SECTOR_SIZE)

          - sector_num;

        n = MIN(n, nb_sectors);

        *pnum += n;

        sector_num += n;

        nb_sectors -= n;

        /* *pnum can't be greater than one block for allocated

         * sectors since there is always a bitmap in between. */

        if (allocated) {

            return BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID | start;

        }

        if (nb_sectors == 0) {

            break;

        }

        offset = get_sector_offset(bs, sector_num, 0);

    } while (offset == -1);

    return 0;

}


static coroutine_fn int sd_co_writev(BlockDriverState *bs, int64_t sector_num,

                        int nb_sectors, QEMUIOVector *qiov)

{

    SheepdogAIOCB acb;

    int ret;

    int64_t offset = (sector_num + nb_sectors) * BDRV_SECTOR_SIZE;

    BDRVSheepdogState *s = bs->opaque;

    if (offset > s->inode.vdi_size) {

        ret = sd_truncate(bs, offset);

        if (ret < 0) {

            return ret;

        }

    }

    sd_aio_setup(&acb, s, qiov, sector_num, nb_sectors, AIOCB_WRITE_UDATA);

retry:

    if (check_overlapping_aiocb(s, &acb)) {

        qemu_co_queue_wait(&s->overlapping_queue);

        goto retry;

    }

    sd_co_rw_vector(&acb);

    sd_write_done(&acb);

    QLIST_REMOVE(&acb, aiocb_siblings);

    qemu_co_queue_restart_all(&s->overlapping_queue);

    return acb.ret;

}


long do_rt_sigreturn(CPUS390XState *env)

{

    rt_sigframe *frame;

    abi_ulong frame_addr = env->regs[15];

    qemu_log("%s: frame_addr 0x%llx\n", __FUNCTION__,

             (unsigned long long)frame_addr);

    sigset_t set;

    if (!lock_user_struct(VERIFY_READ, frame, frame_addr, 1)) {

        goto badframe;

    }

    target_to_host_sigset(&set, &frame->uc.tuc_sigmask);

    sigprocmask(SIG_SETMASK, &set, NULL); /* ~_BLOCKABLE? */

    if (restore_sigregs(env, &frame->uc.tuc_mcontext)) {

        goto badframe;

    }

    if (do_sigaltstack(frame_addr + offsetof(rt_sigframe, uc.tuc_stack), 0,

                       get_sp_from_cpustate(env)) == -EFAULT) {

        goto badframe;

    }

    unlock_user_struct(frame, frame_addr, 0);

    return env->regs[2];

badframe:

    unlock_user_struct(frame, frame_addr, 0);

    force_sig(TARGET_SIGSEGV);

    return 0;

}


static bool tracked_request_overlaps(BdrvTrackedRequest *req,

                                     int64_t offset, unsigned int bytes)

{

    /*        aaaa   bbbb */

    if (offset >= req->overlap_offset + req->overlap_bytes) {

        return false;

    }

    /* bbbb   aaaa        */

    if (req->overlap_offset >= offset + bytes) {

        return false;

    }

    return true;

}


static av_cold void init_mv_table(MVTable *tab)

{

    int i, x, y;

    tab->table_mv_index = av_malloc(sizeof(uint16_t) * 4096);

    /* mark all entries as not used */

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

        tab->table_mv_index[i] = tab->n;

    for(i=0;i<tab->n;i++) {

        x = tab->table_mvx[i];

        y = tab->table_mvy[i];

        tab->table_mv_index[(x << 6) | y] = i;

    }

}


static const QListEntry *qmp_input_push(QmpInputVisitor *qiv, QObject *obj,

                                        void *qapi, Error **errp)

{

    GHashTable *h;

    StackObject *tos = g_new0(StackObject, 1);

    assert(obj);

    tos->obj = obj;

    tos->qapi = qapi;

    if (qiv->strict && qobject_type(obj) == QTYPE_QDICT) {

        h = g_hash_table_new(g_str_hash, g_str_equal);

        qdict_iter(qobject_to_qdict(obj), qdict_add_key, h);

        tos->h = h;

    } else if (qobject_type(obj) == QTYPE_QLIST) {

        tos->entry = qlist_first(qobject_to_qlist(obj));

    }

    QSLIST_INSERT_HEAD(&qiv->stack, tos, node);

    return tos->entry;

}


int aio_bh_poll(AioContext *ctx)

{

    QEMUBH *bh, **bhp, *next;

    int ret;

    bool deleted = false;

    qemu_lockcnt_inc(&ctx->list_lock);

    ret = 0;

    for (bh = atomic_rcu_read(&ctx->first_bh); bh; bh = next) {

        next = atomic_rcu_read(&bh->next);

        /* The atomic_xchg is paired with the one in qemu_bh_schedule.  The

         * implicit memory barrier ensures that the callback sees all writes

         * done by the scheduling thread.  It also ensures that the scheduling

         * thread sees the zero before bh->cb has run, and thus will call

         * aio_notify again if necessary.

         */

        if (atomic_xchg(&bh->scheduled, 0)) {

            /* Idle BHs don't count as progress */

            if (!bh->idle) {

                ret = 1;

            }

            bh->idle = 0;

            aio_bh_call(bh);

        }

        if (bh->deleted) {

            deleted = true;

        }

    }

    /* remove deleted bhs */

    if (!deleted) {

        qemu_lockcnt_dec(&ctx->list_lock);

        return ret;

    }

    if (qemu_lockcnt_dec_and_lock(&ctx->list_lock)) {

        bhp = &ctx->first_bh;

        while (*bhp) {

            bh = *bhp;

            if (bh->deleted && !bh->scheduled) {

                *bhp = bh->next;

                g_free(bh);

            } else {

                bhp = &bh->next;

            }

        }

        qemu_lockcnt_unlock(&ctx->list_lock);

    }

    return ret;

}


static void test_dispatch_cmd_error(void)

{

    QDict *req = qdict_new();

    QObject *resp;

    qdict_put_obj(req, "execute", QOBJECT(qstring_from_str("user_def_cmd2")));

    resp = qmp_dispatch(QOBJECT(req));

    assert(resp != NULL);

    assert(qdict_haskey(qobject_to_qdict(resp), "error"));

    g_print("\nresp: %s\n", qstring_get_str(qobject_to_json_pretty(resp)));

    qobject_decref(resp);

    QDECREF(req);

}


int bdrv_truncate(BlockDriverState *bs, int64_t offset)

{

    BlockDriver *drv = bs->drv;

    int ret;

    if (!drv)

        return -ENOMEDIUM;

    if (!drv->bdrv_truncate)

        return -ENOTSUP;

    if (bs->read_only)

        return -EACCES;

    ret = drv->bdrv_truncate(bs, offset);

    if (ret == 0) {

        ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);

        bdrv_dirty_bitmap_truncate(bs);

        if (bs->blk) {

            blk_dev_resize_cb(bs->blk);

        }

    }

    return ret;

}


static uint64_t dbdma_read(void *opaque, target_phys_addr_t addr,

                           unsigned size)

{

    uint32_t value;

    int channel = addr >> DBDMA_CHANNEL_SHIFT;

    DBDMAState *s = opaque;

    DBDMA_channel *ch = &s->channels[channel];

    int reg = (addr - (channel << DBDMA_CHANNEL_SHIFT)) >> 2;

    value = ch->regs[reg];

    DBDMA_DPRINTF("readl 0x" TARGET_FMT_plx " => 0x%08x\n", addr, value);

    DBDMA_DPRINTF("channel 0x%x reg 0x%x\n",

                  (uint32_t)addr >> DBDMA_CHANNEL_SHIFT, reg);

    switch(reg) {

    case DBDMA_CONTROL:

        value = 0;

        break;

    case DBDMA_STATUS:

    case DBDMA_CMDPTR_LO:

    case DBDMA_INTR_SEL:

    case DBDMA_BRANCH_SEL:

    case DBDMA_WAIT_SEL:

        /* nothing to do */

        break;

    case DBDMA_XFER_MODE:

    case DBDMA_CMDPTR_HI:

    case DBDMA_DATA2PTR_HI:

    case DBDMA_DATA2PTR_LO:

    case DBDMA_ADDRESS_HI:

    case DBDMA_BRANCH_ADDR_HI:

        /* unused */

        value = 0;

        break;

    case DBDMA_RES1:

    case DBDMA_RES2:

    case DBDMA_RES3:

    case DBDMA_RES4:

        /* reserved */

        break;

    }

    return value;

}


static int pxb_dev_initfn(PCIDevice *dev)

{

    PXBDev *pxb = PXB_DEV(dev);

    DeviceState *ds, *bds;

    PCIBus *bus;

    const char *dev_name = NULL;

    if (pxb->numa_node != NUMA_NODE_UNASSIGNED &&

        pxb->numa_node >= nb_numa_nodes) {

        error_report("Illegal numa node %d.", pxb->numa_node);

        return -EINVAL;

    }

    if (dev->qdev.id && *dev->qdev.id) {

        dev_name = dev->qdev.id;

    }

    ds = qdev_create(NULL, TYPE_PXB_HOST);

    bus = pci_bus_new(ds, "pxb-internal", NULL, NULL, 0, TYPE_PXB_BUS);

    bus->parent_dev = dev;

    bus->address_space_mem = dev->bus->address_space_mem;

    bus->address_space_io = dev->bus->address_space_io;

    bus->map_irq = pxb_map_irq_fn;

    bds = qdev_create(BUS(bus), "pci-bridge");

    bds->id = dev_name;

    qdev_prop_set_uint8(bds, PCI_BRIDGE_DEV_PROP_CHASSIS_NR, pxb->bus_nr);

    qdev_prop_set_bit(bds, PCI_BRIDGE_DEV_PROP_SHPC, false);

    PCI_HOST_BRIDGE(ds)->bus = bus;

    if (pxb_register_bus(dev, bus)) {

        return -EINVAL;

    }

    qdev_init_nofail(ds);

    qdev_init_nofail(bds);

    pci_word_test_and_set_mask(dev->config + PCI_STATUS,

                               PCI_STATUS_66MHZ | PCI_STATUS_FAST_BACK);

    pci_config_set_class(dev->config, PCI_CLASS_BRIDGE_HOST);

    pxb_dev_list = g_list_insert_sorted(pxb_dev_list, pxb, pxb_compare);

    return 0;

}


static bool blit_region_is_unsafe(struct CirrusVGAState *s,

                                  int32_t pitch, int32_t addr)

{

    if (!pitch) {

        return true;

    }

    if (pitch < 0) {

        int64_t min = addr

            + ((int64_t)s->cirrus_blt_height-1) * pitch;

        int32_t max = addr

            + s->cirrus_blt_width;

        if (min < 0 || max > s->vga.vram_size) {

            return true;

        }

    } else {

        int64_t max = addr

            + ((int64_t)s->cirrus_blt_height-1) * pitch

            + s->cirrus_blt_width;

        if (max > s->vga.vram_size) {

            return true;

        }

    }

    return false;

}