static uint64_t get_cluster_offset(BlockDriverState *bs,

                                   uint64_t offset, int allocate,

                                   int compressed_size,

                                   int n_start, int n_end)

{

    BDRVQcowState *s = bs->opaque;

    int min_index, i, j, l1_index, l2_index;

    uint64_t l2_offset, *l2_table, cluster_offset, tmp;

    uint32_t min_count;

    int new_l2_table;

    l1_index = offset >> (s->l2_bits + s->cluster_bits);

    l2_offset = s->l1_table[l1_index];

    new_l2_table = 0;

    if (!l2_offset) {

        if (!allocate)

            return 0;

        /* allocate a new l2 entry */

        l2_offset = bdrv_getlength(bs->file);

        /* round to cluster size */

        l2_offset = (l2_offset + s->cluster_size - 1) & ~(s->cluster_size - 1);

        /* update the L1 entry */

        s->l1_table[l1_index] = l2_offset;

        tmp = cpu_to_be64(l2_offset);

        if (bdrv_pwrite(bs->file, s->l1_table_offset + l1_index * sizeof(tmp),

                        &tmp, sizeof(tmp)) != sizeof(tmp))

            return 0;

        new_l2_table = 1;

    }

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

        if (l2_offset == s->l2_cache_offsets[i]) {

            /* increment the hit count */

            if (++s->l2_cache_counts[i] == 0xffffffff) {

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

                    s->l2_cache_counts[j] >>= 1;

                }

            }

            l2_table = s->l2_cache + (i << s->l2_bits);

            goto found;

        }

    }

    /* not found: load a new entry in the least used one */

    min_index = 0;

    min_count = 0xffffffff;

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

        if (s->l2_cache_counts[i] < min_count) {

            min_count = s->l2_cache_counts[i];

            min_index = i;

        }

    }

    l2_table = s->l2_cache + (min_index << s->l2_bits);

    if (new_l2_table) {

        memset(l2_table, 0, s->l2_size * sizeof(uint64_t));

        if (bdrv_pwrite(bs->file, l2_offset, l2_table, s->l2_size * sizeof(uint64_t)) !=

            s->l2_size * sizeof(uint64_t))

            return 0;

    } else {

        if (bdrv_pread(bs->file, l2_offset, l2_table, s->l2_size * sizeof(uint64_t)) !=

            s->l2_size * sizeof(uint64_t))

            return 0;

    }

    s->l2_cache_offsets[min_index] = l2_offset;

    s->l2_cache_counts[min_index] = 1;

 found:

    l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);

    cluster_offset = be64_to_cpu(l2_table[l2_index]);

    if (!cluster_offset ||

        ((cluster_offset & QCOW_OFLAG_COMPRESSED) && allocate == 1)) {

        if (!allocate)

            return 0;

        /* allocate a new cluster */

        if ((cluster_offset & QCOW_OFLAG_COMPRESSED) &&

            (n_end - n_start) < s->cluster_sectors) {

            /* if the cluster is already compressed, we must

               decompress it in the case it is not completely

               overwritten */

            if (decompress_cluster(bs, cluster_offset) < 0)

                return 0;

            cluster_offset = bdrv_getlength(bs->file);

            cluster_offset = (cluster_offset + s->cluster_size - 1) &

                ~(s->cluster_size - 1);

            /* write the cluster content */

            if (bdrv_pwrite(bs->file, cluster_offset, s->cluster_cache, s->cluster_size) !=

                s->cluster_size)

                return -1;

        } else {

            cluster_offset = bdrv_getlength(bs->file);

            if (allocate == 1) {

                /* round to cluster size */

                cluster_offset = (cluster_offset + s->cluster_size - 1) &

                    ~(s->cluster_size - 1);

                bdrv_truncate(bs->file, cluster_offset + s->cluster_size);

                /* if encrypted, we must initialize the cluster

                   content which won't be written */

                if (s->crypt_method &&

                    (n_end - n_start) < s->cluster_sectors) {

                    uint64_t start_sect;

                    start_sect = (offset & ~(s->cluster_size - 1)) >> 9;

                    memset(s->cluster_data + 512, 0x00, 512);

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

                        if (i < n_start || i >= n_end) {

                            encrypt_sectors(s, start_sect + i,

                                            s->cluster_data,

                                            s->cluster_data + 512, 1, 1,

                                            &s->aes_encrypt_key);

                            if (bdrv_pwrite(bs->file, cluster_offset + i * 512,

                                            s->cluster_data, 512) != 512)

                                return -1;

                        }

                    }

                }

            } else if (allocate == 2) {

                cluster_offset |= QCOW_OFLAG_COMPRESSED |

                    (uint64_t)compressed_size << (63 - s->cluster_bits);

            }

        }

        /* update L2 table */

        tmp = cpu_to_be64(cluster_offset);

        l2_table[l2_index] = tmp;

        if (bdrv_pwrite(bs->file,

                        l2_offset + l2_index * sizeof(tmp), &tmp, sizeof(tmp)) != sizeof(tmp))

            return 0;

    }

    return cluster_offset;

}


static BlockAIOCB *blkverify_aio_flush(BlockDriverState *bs,

                                       BlockCompletionFunc *cb,

                                       void *opaque)

{

    BDRVBlkverifyState *s = bs->opaque;

    /* Only flush test file, the raw file is not important */

    return bdrv_aio_flush(s->test_file->bs, cb, opaque);

}


static int del_existing_snapshots(Monitor *mon, const char *name)

{

    BlockDriverState *bs;

    QEMUSnapshotInfo sn1, *snapshot = &sn1;

    int ret;

    bs = NULL;

    while ((bs = bdrv_next(bs))) {

        if (bdrv_can_snapshot(bs) &&

            bdrv_snapshot_find(bs, snapshot, name) >= 0)

        {

            ret = bdrv_snapshot_delete(bs, name);

            if (ret < 0) {

                monitor_printf(mon,

                               "Error while deleting snapshot on '%s'\n",

                               bdrv_get_device_name(bs));

                return -1;

            }

        }

    }

    return 0;

}


static void wavpack_decode_flush(AVCodecContext *avctx)

{

    WavpackContext *s = avctx->priv_data;

    int i;

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

        wv_reset_saved_context(s->fdec[i]);

}


inline static void RENAME(hcscale)(SwsContext *c, uint16_t *dst, long 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, int16_t *mmx2Filter,

                                   int32_t *mmx2FilterPos, uint8_t *pal)

{

    if (srcFormat==PIX_FMT_YUYV422)

    {

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

        src1= formatConvBuffer;

        src2= formatConvBuffer+VOFW;

    }

    else if (srcFormat==PIX_FMT_UYVY422)

    {

        RENAME(uyvyToUV)(formatConvBuffer, formatConvBuffer+VOFW, src1, src2, srcW);

        src1= formatConvBuffer;

        src2= formatConvBuffer+VOFW;

    }

    else if (srcFormat==PIX_FMT_RGB32)

    {

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

        src1= formatConvBuffer;

        src2= formatConvBuffer+VOFW;

    }

    else if (srcFormat==PIX_FMT_RGB32_1)

    {

        RENAME(bgr32ToUV)(formatConvBuffer, formatConvBuffer+VOFW, src1+ALT32_CORR, src2+ALT32_CORR, srcW);

        src1= formatConvBuffer;

        src2= formatConvBuffer+VOFW;

    }

    else if (srcFormat==PIX_FMT_BGR24)

    {

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

        src1= formatConvBuffer;

        src2= formatConvBuffer+VOFW;

    }

    else if (srcFormat==PIX_FMT_BGR565)

    {

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

        src1= formatConvBuffer;

        src2= formatConvBuffer+VOFW;

    }

    else if (srcFormat==PIX_FMT_BGR555)

    {

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

        src1= formatConvBuffer;

        src2= formatConvBuffer+VOFW;

    }

    else if (srcFormat==PIX_FMT_BGR32)

    {

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

        src1= formatConvBuffer;

        src2= formatConvBuffer+VOFW;

    }

    else if (srcFormat==PIX_FMT_BGR32_1)

    {

        RENAME(rgb32ToUV)(formatConvBuffer, formatConvBuffer+VOFW, src1+ALT32_CORR, src2+ALT32_CORR, srcW);

        src1= formatConvBuffer;

        src2= formatConvBuffer+VOFW;

    }

    else if (srcFormat==PIX_FMT_RGB24)

    {

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

        src1= formatConvBuffer;

        src2= formatConvBuffer+VOFW;

    }

    else if (srcFormat==PIX_FMT_RGB565)

    {

        RENAME(rgb16ToUV)(formatConvBuffer, formatConvBuffer+VOFW, src1, src2, srcW);

        src1= formatConvBuffer;

        src2= formatConvBuffer+VOFW;

    }

    else if (srcFormat==PIX_FMT_RGB555)

    {

        RENAME(rgb15ToUV)(formatConvBuffer, formatConvBuffer+VOFW, src1, src2, srcW);

        src1= formatConvBuffer;

        src2= formatConvBuffer+VOFW;

    }

    else if (isGray(srcFormat))

    {

        return;

    }

    else if (srcFormat==PIX_FMT_RGB8 || srcFormat==PIX_FMT_BGR8 || srcFormat==PIX_FMT_PAL8 || srcFormat==PIX_FMT_BGR4_BYTE  || srcFormat==PIX_FMT_RGB4_BYTE)

    {

        RENAME(palToUV)(formatConvBuffer, formatConvBuffer+VOFW, src1, src2, srcW, (uint32_t*)pal);

        src1= formatConvBuffer;

        src2= formatConvBuffer+VOFW;

    }

#ifdef HAVE_MMX

    // Use the new MMX scaler if the MMX2 one can't be used (it is faster than the x86 ASM 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+VOFW, dstWidth, src2, srcW, xInc, hChrFilter, hChrFilterPos, hChrFilterSize);

    }

    else // fast bilinear upscale / crap downscale

    {

#if defined(ARCH_X86)

#ifdef HAVE_MMX2

        int i;

#if defined(PIC)

        uint64_t ebxsave __attribute__((aligned(8)));

#endif

        if (canMMX2BeUsed)

        {

            asm volatile(

#if defined(PIC)

            "mov          %%"REG_b", %6         \n\t"

#endif

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

            "mov                 %0, %%"REG_c"  \n\t"

            "mov                 %1, %%"REG_D"  \n\t"

            "mov                 %2, %%"REG_d"  \n\t"

            "mov                 %3, %%"REG_b"  \n\t"

            "xor          %%"REG_a", %%"REG_a"  \n\t" // i

            PREFETCH"   (%%"REG_c")             \n\t"

            PREFETCH" 32(%%"REG_c")             \n\t"

            PREFETCH" 64(%%"REG_c")             \n\t"

#ifdef ARCH_X86_64

#define FUNNY_UV_CODE \

            "movl       (%%"REG_b"), %%esi      \n\t"\

            "call               *%4             \n\t"\

            "movl (%%"REG_b", %%"REG_a"), %%esi \n\t"\

            "add          %%"REG_S", %%"REG_c"  \n\t"\

            "add          %%"REG_a", %%"REG_D"  \n\t"\

            "xor          %%"REG_a", %%"REG_a"  \n\t"\

#else

#define FUNNY_UV_CODE \

            "movl       (%%"REG_b"), %%esi      \n\t"\

            "call               *%4             \n\t"\

            "addl (%%"REG_b", %%"REG_a"), %%"REG_c" \n\t"\

            "add          %%"REG_a", %%"REG_D"  \n\t"\

            "xor          %%"REG_a", %%"REG_a"  \n\t"\

#endif /* ARCH_X86_64 */

FUNNY_UV_CODE

FUNNY_UV_CODE

FUNNY_UV_CODE

FUNNY_UV_CODE

            "xor          %%"REG_a", %%"REG_a"  \n\t" // i

            "mov                 %5, %%"REG_c"  \n\t" // src

            "mov                 %1, %%"REG_D"  \n\t" // buf1

            "add              $"AV_STRINGIFY(VOF)", %%"REG_D"  \n\t"

            PREFETCH"   (%%"REG_c")             \n\t"

            PREFETCH" 32(%%"REG_c")             \n\t"

            PREFETCH" 64(%%"REG_c")             \n\t"

FUNNY_UV_CODE

FUNNY_UV_CODE

FUNNY_UV_CODE

FUNNY_UV_CODE

#if defined(PIC)

            "mov %6, %%"REG_b"    \n\t"

#endif

            :: "m" (src1), "m" (dst), "m" (mmx2Filter), "m" (mmx2FilterPos),

            "m" (funnyUVCode), "m" (src2)

#if defined(PIC)

            ,"m" (ebxsave)

#endif

            : "%"REG_a, "%"REG_c, "%"REG_d, "%"REG_S, "%"REG_D

#if !defined(PIC)

             ,"%"REG_b

#endif

            );

            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+VOFW] = src2[srcW-1]*128;

            }

        }

        else

        {

#endif /* HAVE_MMX2 */

            long xInc_shr16 = (long) (xInc >> 16);

            uint16_t xInc_mask = xInc & 0xffff;

            asm volatile(

            "xor %%"REG_a", %%"REG_a"               \n\t" // i

            "xor %%"REG_d", %%"REG_d"               \n\t" // xx

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

            ASMALIGN(4)

            "1:                                     \n\t"

            "mov        %0, %%"REG_S"               \n\t"

            "movzbl  (%%"REG_S", %%"REG_d"), %%edi  \n\t" //src[xx]

            "movzbl 1(%%"REG_S", %%"REG_d"), %%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)

            "mov        %1, %%"REG_D"               \n\t"

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

            "movw     %%si, (%%"REG_D", %%"REG_a", 2)   \n\t"

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

            "movzbl   1(%5, %%"REG_d"), %%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)

            "mov        %1, %%"REG_D"               \n\t"

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

            "movw     %%si, "AV_STRINGIFY(VOF)"(%%"REG_D", %%"REG_a", 2)   \n\t"

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

            "adc        %3, %%"REG_d"               \n\t" //xx+= xInc>>8 + carry

            "add        $1, %%"REG_a"               \n\t"

            "cmp        %2, %%"REG_a"               \n\t"

            " jb        1b                          \n\t"

/* GCC 3.3 makes MPlayer crash on IA-32 machines when using "g" operand here,

   which is needed to support GCC 4.0. */

#if defined(ARCH_X86_64) && ((__GNUC__ > 3) || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))

            :: "m" (src1), "m" (dst), "g" ((long)dstWidth), "m" (xInc_shr16), "m" (xInc_mask),

#else

            :: "m" (src1), "m" (dst), "m" ((long)dstWidth), "m" (xInc_shr16), "m" (xInc_mask),

#endif

            "r" (src2)

            : "%"REG_a, "%"REG_d, "%ecx", "%"REG_D, "%esi"

            );

#ifdef HAVE_MMX2

        } //if MMX2 can't 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+VOFW]=(src2[xx]*(xalpha^127)+src2[xx+1]*xalpha);

            /* slower

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

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

            */

            xpos+=xInc;

        }

#endif /* defined(ARCH_X86) */

    }

    if(c->srcRange != c->dstRange && !(isRGB(c->dstFormat) || isBGR(c->dstFormat))){

        int i;

        //FIXME all pal and rgb srcFormats could do this convertion as well

        //FIXME all scalers more complex than bilinear could do half of this transform

        if(c->srcRange){

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

                dst[i     ]= (dst[i     ]*1799 + 4081085)>>11; //1469

                dst[i+VOFW]= (dst[i+VOFW]*1799 + 4081085)>>11; //1469

            }

        }else{

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

                dst[i     ]= (dst[i     ]*4663 - 9289992)>>12; //-264

                dst[i+VOFW]= (dst[i+VOFW]*4663 - 9289992)>>12; //-264

            }

        }

    }

}


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

                       BdrvCheckMode fix)

{

    int ret = qcow2_check_refcounts(bs, result, fix);

    if (ret < 0) {

        return ret;

    }

    if (fix && result->check_errors == 0 && result->corruptions == 0) {

        return qcow2_mark_clean(bs);

    }

    return ret;

}


static inline void gen_sync_flags(DisasContext *dc)

{

    /* Sync the tb dependent flag between translate and runtime.  */

    if (dc->tb_flags != dc->synced_flags) {

        tcg_gen_movi_tl(env_flags, dc->tb_flags);

        dc->synced_flags = dc->tb_flags;

    }

}


void avcodec_flush_buffers(AVCodecContext *avctx)

{

    if(HAVE_PTHREADS && avctx->active_thread_type&FF_THREAD_FRAME)

        ff_thread_flush(avctx);

    if(avctx->codec->flush)

        avctx->codec->flush(avctx);

}


static int ipvideo_decode_block_opcode_0x5(IpvideoContext *s)

{

    signed char x, y;

    /* copy a block from the previous frame using an expanded range;

     * need 2 more bytes */

    CHECK_STREAM_PTR(2);

    x = *s->stream_ptr++;

    y = *s->stream_ptr++;

    debug_interplay ("    motion bytes = %d, %d\n", x, y);

    return copy_from(s, &s->last_frame, x, y);

}


void smc91c111_init(NICInfo *nd, uint32_t base, qemu_irq irq)

{

    smc91c111_state *s;

    int iomemtype;

    qemu_check_nic_model(nd, "smc91c111");

    s = (smc91c111_state *)qemu_mallocz(sizeof(smc91c111_state));

    iomemtype = cpu_register_io_memory(0, smc91c111_readfn,

                                       smc91c111_writefn, s);

    cpu_register_physical_memory(base, 16, iomemtype);

    s->irq = irq;

    memcpy(s->macaddr, nd->macaddr, 6);

    smc91c111_reset(s);

    s->vc = qemu_new_vlan_client(nd->vlan, nd->model, nd->name,

                                 smc91c111_receive, smc91c111_can_receive, s);

    qemu_format_nic_info_str(s->vc, s->macaddr);

    /* ??? Save/restore.  */

}


static av_cold int vc2_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,

                                      const AVFrame *frame, int *got_packet_ptr)

{

    int ret;

    int max_frame_bytes, sig_size = 256;

    VC2EncContext *s = avctx->priv_data;

    const char aux_data[] = "FFmpeg version "FFMPEG_VERSION;

    const int aux_data_size = sizeof(aux_data);

    const int header_size = 100 + aux_data_size;

    int64_t r_bitrate = avctx->bit_rate >> (s->interlaced);

    s->avctx = avctx;

    s->size_scaler = 1;

    s->prefix_bytes = 0;

    s->last_parse_code = 0;

    s->next_parse_offset = 0;

    /* Rate control */

    max_frame_bytes = (av_rescale(r_bitrate, s->avctx->time_base.num,

                                  s->avctx->time_base.den) >> 3) - header_size;

    /* Find an appropriate size scaler */

    while (sig_size > 255) {

        s->slice_max_bytes = FFALIGN(av_rescale(max_frame_bytes, 1,

                                     s->num_x*s->num_y), s->size_scaler);

        s->slice_max_bytes += 4 + s->prefix_bytes;

        sig_size = s->slice_max_bytes/s->size_scaler; /* Signalled slize size */

        s->size_scaler <<= 1;

    }

    ret = ff_alloc_packet2(avctx, avpkt, max_frame_bytes*2, 0);

    if (ret < 0) {

        av_log(avctx, AV_LOG_ERROR, "Error getting output packet.\n");

        return ret;

    } else {

        init_put_bits(&s->pb, avpkt->data, avpkt->size);

    }

    encode_frame(s, frame, aux_data, s->interlaced);

    if (s->interlaced)

        encode_frame(s, frame, NULL, 2);

    flush_put_bits(&s->pb);

    avpkt->size = put_bits_count(&s->pb) >> 3;

    *got_packet_ptr = 1;

    return 0;

}


static int estimate_best_b_count(MpegEncContext *s)

{

    AVCodec *codec    = avcodec_find_encoder(s->avctx->codec_id);

    AVCodecContext *c = avcodec_alloc_context3(NULL);

    AVFrame input[FF_MAX_B_FRAMES + 2];

    const int scale = s->avctx->brd_scale;

    int i, j, out_size, p_lambda, b_lambda, lambda2;

    int64_t best_rd  = INT64_MAX;

    int best_b_count = -1;

    assert(scale >= 0 && scale <= 3);

    //emms_c();

    //s->next_picture_ptr->quality;

    p_lambda = s->last_lambda_for[AV_PICTURE_TYPE_P];

    //p_lambda * FFABS(s->avctx->b_quant_factor) + s->avctx->b_quant_offset;

    b_lambda = s->last_lambda_for[AV_PICTURE_TYPE_B];

    if (!b_lambda) // FIXME we should do this somewhere else

        b_lambda = p_lambda;

    lambda2  = (b_lambda * b_lambda + (1 << FF_LAMBDA_SHIFT) / 2) >>

               FF_LAMBDA_SHIFT;

    c->width        = s->width  >> scale;

    c->height       = s->height >> scale;

    c->flags        = CODEC_FLAG_QSCALE | CODEC_FLAG_PSNR |

                      CODEC_FLAG_INPUT_PRESERVED /*| CODEC_FLAG_EMU_EDGE*/;

    c->flags       |= s->avctx->flags & CODEC_FLAG_QPEL;

    c->mb_decision  = s->avctx->mb_decision;

    c->me_cmp       = s->avctx->me_cmp;

    c->mb_cmp       = s->avctx->mb_cmp;

    c->me_sub_cmp   = s->avctx->me_sub_cmp;

    c->pix_fmt      = AV_PIX_FMT_YUV420P;

    c->time_base    = s->avctx->time_base;

    c->max_b_frames = s->max_b_frames;

    if (avcodec_open2(c, codec, NULL) < 0)

        return -1;

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

        int ysize = c->width * c->height;

        int csize = (c->width / 2) * (c->height / 2);

        Picture pre_input, *pre_input_ptr = i ? s->input_picture[i - 1] :

                                                s->next_picture_ptr;

        avcodec_get_frame_defaults(&input[i]);

        input[i].data[0]     = av_malloc(ysize + 2 * csize);

        input[i].data[1]     = input[i].data[0] + ysize;

        input[i].data[2]     = input[i].data[1] + csize;

        input[i].linesize[0] = c->width;

        input[i].linesize[1] =

        input[i].linesize[2] = c->width / 2;

        if (pre_input_ptr && (!i || s->input_picture[i - 1])) {

            pre_input = *pre_input_ptr;

            if (!pre_input.shared && i) {

                pre_input.f.data[0] += INPLACE_OFFSET;

                pre_input.f.data[1] += INPLACE_OFFSET;

                pre_input.f.data[2] += INPLACE_OFFSET;

            }

            s->dsp.shrink[scale](input[i].data[0], input[i].linesize[0],

                                 pre_input.f.data[0], pre_input.f.linesize[0],

                                 c->width,      c->height);

            s->dsp.shrink[scale](input[i].data[1], input[i].linesize[1],

                                 pre_input.f.data[1], pre_input.f.linesize[1],

                                 c->width >> 1, c->height >> 1);

            s->dsp.shrink[scale](input[i].data[2], input[i].linesize[2],

                                 pre_input.f.data[2], pre_input.f.linesize[2],

                                 c->width >> 1, c->height >> 1);

        }

    }

    for (j = 0; j < s->max_b_frames + 1; j++) {

        int64_t rd = 0;

        if (!s->input_picture[j])

            break;

        c->error[0] = c->error[1] = c->error[2] = 0;

        input[0].pict_type = AV_PICTURE_TYPE_I;

        input[0].quality   = 1 * FF_QP2LAMBDA;

        out_size = encode_frame(c, &input[0]);

        //rd += (out_size * lambda2) >> FF_LAMBDA_SHIFT;

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

            int is_p = i % (j + 1) == j || i == s->max_b_frames;

            input[i + 1].pict_type = is_p ?

                                     AV_PICTURE_TYPE_P : AV_PICTURE_TYPE_B;

            input[i + 1].quality   = is_p ? p_lambda : b_lambda;

            out_size = encode_frame(c, &input[i + 1]);

            rd += (out_size * lambda2) >> (FF_LAMBDA_SHIFT - 3);

        }

        /* get the delayed frames */

        while (out_size) {

            out_size = encode_frame(c, NULL);

            rd += (out_size * lambda2) >> (FF_LAMBDA_SHIFT - 3);

        }

        rd += c->error[0] + c->error[1] + c->error[2];

        if (rd < best_rd) {

            best_rd = rd;

            best_b_count = j;

        }

    }

    avcodec_close(c);

    av_freep(&c);

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

        av_freep(&input[i].data[0]);

    }

    return best_b_count;

}


static void show_stream(WriterContext *w, AVFormatContext *fmt_ctx, int stream_idx)

{

    AVStream *stream = fmt_ctx->streams[stream_idx];

    AVCodecContext *dec_ctx;

    AVCodec *dec;

    char val_str[128];

    AVRational display_aspect_ratio;

    struct print_buf pbuf = {.s = NULL};

    print_section_header("stream");

    print_int("index", stream->index);

    if ((dec_ctx = stream->codec)) {

        if ((dec = dec_ctx->codec)) {

            print_str("codec_name",      dec->name);

            print_str("codec_long_name", dec->long_name);

        } else {

            print_str("codec_name",      "unknown");

        }

        print_str("codec_type", av_x_if_null(av_get_media_type_string(dec_ctx->codec_type), "unknown"));

        print_fmt("codec_time_base", "%d/%d", dec_ctx->time_base.num, dec_ctx->time_base.den);

        /* print AVI/FourCC tag */

        av_get_codec_tag_string(val_str, sizeof(val_str), dec_ctx->codec_tag);

        print_str("codec_tag_string",    val_str);

        print_fmt("codec_tag", "0x%04x", dec_ctx->codec_tag);

        switch (dec_ctx->codec_type) {

        case AVMEDIA_TYPE_VIDEO:

            print_int("width",        dec_ctx->width);

            print_int("height",       dec_ctx->height);

            print_int("has_b_frames", dec_ctx->has_b_frames);

            if (dec_ctx->sample_aspect_ratio.num) {

                print_fmt("sample_aspect_ratio", "%d:%d",

                          dec_ctx->sample_aspect_ratio.num,

                          dec_ctx->sample_aspect_ratio.den);

                av_reduce(&display_aspect_ratio.num, &display_aspect_ratio.den,

                          dec_ctx->width  * dec_ctx->sample_aspect_ratio.num,

                          dec_ctx->height * dec_ctx->sample_aspect_ratio.den,

                          1024*1024);

                print_fmt("display_aspect_ratio", "%d:%d",

                          display_aspect_ratio.num,

                          display_aspect_ratio.den);

            }

            print_str("pix_fmt", av_x_if_null(av_get_pix_fmt_name(dec_ctx->pix_fmt), "unknown"));

            print_int("level",   dec_ctx->level);

            break;

        case AVMEDIA_TYPE_AUDIO:

            print_str("sample_fmt",

                      av_x_if_null(av_get_sample_fmt_name(dec_ctx->sample_fmt), "unknown"));

            print_val("sample_rate",     dec_ctx->sample_rate, unit_hertz_str);

            print_int("channels",        dec_ctx->channels);

            print_int("bits_per_sample", av_get_bits_per_sample(dec_ctx->codec_id));

            break;

        }

    } else {

        print_str("codec_type", "unknown");

    }

    if (dec_ctx->codec && dec_ctx->codec->priv_class) {

        const AVOption *opt = NULL;

        while (opt = av_opt_next(dec_ctx->priv_data,opt)) {

            uint8_t *str;

            if (opt->flags) continue;

            if (av_opt_get(dec_ctx->priv_data, opt->name, 0, &str) >= 0) {

                print_str(opt->name, str);

                av_free(str);

            }

        }

    }

    if (fmt_ctx->iformat->flags & AVFMT_SHOW_IDS)

        print_fmt("id", "0x%x", stream->id);

    print_fmt("r_frame_rate",   "%d/%d", stream->r_frame_rate.num,   stream->r_frame_rate.den);

    print_fmt("avg_frame_rate", "%d/%d", stream->avg_frame_rate.num, stream->avg_frame_rate.den);

    print_fmt("time_base",      "%d/%d", stream->time_base.num,      stream->time_base.den);

    print_time("start_time",    stream->start_time, &stream->time_base);

    print_time("duration",      stream->duration,   &stream->time_base);

    if (stream->nb_frames)

        print_fmt("nb_frames", "%"PRId64, stream->nb_frames);

    show_tags(stream->metadata);

    print_section_footer("stream");

    av_free(pbuf.s);

    fflush(stdout);

}


static void spapr_cpu_reset(void *opaque)

{

    PowerPCCPU *cpu = opaque;

    CPUState *cs = CPU(cpu);

    CPUPPCState *env = &cpu->env;

    cpu_reset(cs);

    /* All CPUs start halted.  CPU0 is unhalted from the machine level

     * reset code and the rest are explicitly started up by the guest

     * using an RTAS call */

    cs->halted = 1;

    env->spr[SPR_HIOR] = 0;

    env->external_htab = (uint8_t *)spapr->htab;

    if (kvm_enabled() && !env->external_htab) {

        /*

         * HV KVM, set external_htab to 1 so our ppc_hash64_load_hpte*

         * functions do the right thing.

         */

        env->external_htab = (void *)1;

    }

    env->htab_base = -1;

    env->htab_mask = HTAB_SIZE(spapr) - 1;

    env->spr[SPR_SDR1] = (target_ulong)(uintptr_t)spapr->htab |

        (spapr->htab_shift - 18);

}


static void exynos4210_fimd_update(void *opaque)

{

    Exynos4210fimdState *s = (Exynos4210fimdState *)opaque;

    DisplaySurface *surface = qemu_console_surface(s->console);

    Exynos4210fimdWindow *w;

    int i, line;

    hwaddr fb_line_addr, inc_size;

    int scrn_height;

    int first_line = -1, last_line = -1, scrn_width;

    bool blend = false;

    uint8_t *host_fb_addr;

    bool is_dirty = false;

    const int global_width = (s->vidtcon[2] & FIMD_VIDTCON2_SIZE_MASK) + 1;

    const int global_height = ((s->vidtcon[2] >> FIMD_VIDTCON2_VER_SHIFT) &

            FIMD_VIDTCON2_SIZE_MASK) + 1;

    if (!s || !s->console || !surface_bits_per_pixel(surface) ||

            !s->enabled) {

        return;

    }

    exynos4210_update_resolution(s);

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

        w = &s->window[i];

        if ((w->wincon & FIMD_WINCON_ENWIN) && w->host_fb_addr) {

            scrn_height = w->rightbot_y - w->lefttop_y + 1;

            scrn_width = w->virtpage_width;

            /* Total width of virtual screen page in bytes */

            inc_size = scrn_width + w->virtpage_offsize;

            memory_region_sync_dirty_bitmap(w->mem_section.mr);

            host_fb_addr = w->host_fb_addr;

            fb_line_addr = w->mem_section.offset_within_region;

            for (line = 0; line < scrn_height; line++) {

                is_dirty = memory_region_get_dirty(w->mem_section.mr,

                            fb_line_addr, scrn_width, DIRTY_MEMORY_VGA);

                if (s->invalidate || is_dirty) {

                    if (first_line == -1) {

                        first_line = line;

                    }

                    last_line = line;

                    w->draw_line(w, host_fb_addr, s->ifb +

                        w->lefttop_x * RGBA_SIZE + (w->lefttop_y + line) *

                        global_width * RGBA_SIZE, blend);

                }

                host_fb_addr += inc_size;

                fb_line_addr += inc_size;

                is_dirty = false;

            }

            memory_region_reset_dirty(w->mem_section.mr,

                w->mem_section.offset_within_region,

                w->fb_len, DIRTY_MEMORY_VGA);

            blend = true;

        }

    }

    /* Copy resulting image to QEMU_CONSOLE. */

    if (first_line >= 0) {

        uint8_t *d;

        int bpp;

        bpp = surface_bits_per_pixel(surface);

        fimd_update_putpix_qemu(bpp);

        bpp = (bpp + 1) >> 3;

        d = surface_data(surface);

        for (line = first_line; line <= last_line; line++) {

            fimd_copy_line_toqemu(global_width, s->ifb + global_width * line *

                    RGBA_SIZE, d + global_width * line * bpp);

        }

        dpy_gfx_update(s->console, 0, 0, global_width, global_height);

    }

    s->invalidate = false;

    s->vidintcon[1] |= FIMD_VIDINT_INTFRMPEND;

    if ((s->vidcon[0] & FIMD_VIDCON0_ENVID_F) == 0) {

        exynos4210_fimd_enable(s, false);

    }

    exynos4210_fimd_update_irq(s);

}


static void gen_waiti(DisasContext *dc, uint32_t imm4)

{

    TCGv_i32 pc = tcg_const_i32(dc->next_pc);

    TCGv_i32 intlevel = tcg_const_i32(imm4);

    if (dc->tb->cflags & CF_USE_ICOUNT) {

        gen_io_start();

    }

    gen_helper_waiti(cpu_env, pc, intlevel);

    if (dc->tb->cflags & CF_USE_ICOUNT) {

        gen_io_end();

    }

    tcg_temp_free(pc);

    tcg_temp_free(intlevel);

    gen_jumpi_check_loop_end(dc, 0);

}


static void spr_read_hdecr(DisasContext *ctx, int gprn, int sprn)

{

    if (ctx->tb->cflags & CF_USE_ICOUNT) {

        gen_io_start();

    }

    gen_helper_load_hdecr(cpu_gpr[gprn], cpu_env);

    if (ctx->tb->cflags & CF_USE_ICOUNT) {

        gen_io_end();

        gen_stop_exception(ctx);

    }

}


static int get_physical_address (CPUState *env, target_ulong *physical,

                                int *prot, target_ulong address,

                                int rw, int access_type)

{

    /* User mode can only access useg/xuseg */

    int user_mode = (env->hflags & MIPS_HFLAG_MODE) == MIPS_HFLAG_UM;

    int supervisor_mode = (env->hflags & MIPS_HFLAG_MODE) == MIPS_HFLAG_SM;

    int kernel_mode = !user_mode && !supervisor_mode;

#if defined(TARGET_MIPS64)

    int UX = (env->CP0_Status & (1 << CP0St_UX)) != 0;

    int SX = (env->CP0_Status & (1 << CP0St_SX)) != 0;

    int KX = (env->CP0_Status & (1 << CP0St_KX)) != 0;

#endif

    int ret = TLBRET_MATCH;

#if 0

    if (logfile) {

        fprintf(logfile, "user mode %d h %08x\n",

                user_mode, env->hflags);

    }

#endif

    if (address <= (int32_t)0x7FFFFFFFUL) {

        /* useg */

        if (env->CP0_Status & (1 << CP0St_ERL)) {

            *physical = address & 0xFFFFFFFF;

            *prot = PAGE_READ | PAGE_WRITE;

        } else {

            ret = env->tlb->map_address(env, physical, prot, address, rw, access_type);

        }

#if defined(TARGET_MIPS64)

    } else if (address < 0x4000000000000000ULL) {

        /* xuseg */

	if (UX && address < (0x3FFFFFFFFFFFFFFFULL & env->SEGMask)) {

            ret = env->tlb->map_address(env, physical, prot, address, rw, access_type);

	} else {

	    ret = TLBRET_BADADDR;

        }

    } else if (address < 0x8000000000000000ULL) {

        /* xsseg */

	if ((supervisor_mode || kernel_mode) &&

	    SX && address < (0x7FFFFFFFFFFFFFFFULL & env->SEGMask)) {

            ret = env->tlb->map_address(env, physical, prot, address, rw, access_type);

	} else {

	    ret = TLBRET_BADADDR;

        }

    } else if (address < 0xC000000000000000ULL) {

        /* xkphys */

        /* XXX: Assumes PABITS = 36 (correct for MIPS64R1) */

        if (kernel_mode && KX &&

            (address & 0x07FFFFFFFFFFFFFFULL) < 0x0000000FFFFFFFFFULL) {

            *physical = address & 0x0000000FFFFFFFFFULL;

            *prot = PAGE_READ | PAGE_WRITE;

	} else {

	    ret = TLBRET_BADADDR;

	}

    } else if (address < 0xFFFFFFFF80000000ULL) {

        /* xkseg */

	if (kernel_mode && KX &&

	    address < (0xFFFFFFFF7FFFFFFFULL & env->SEGMask)) {

            ret = env->tlb->map_address(env, physical, prot, address, rw, access_type);

	} else {

	    ret = TLBRET_BADADDR;

	}

#endif

    } else if (address < (int32_t)0xA0000000UL) {

        /* kseg0 */

        if (kernel_mode) {

            *physical = address - (int32_t)0x80000000UL;

            *prot = PAGE_READ | PAGE_WRITE;

        } else {

            ret = TLBRET_BADADDR;

        }

    } else if (address < (int32_t)0xC0000000UL) {

        /* kseg1 */

        if (kernel_mode) {

            *physical = address - (int32_t)0xA0000000UL;

            *prot = PAGE_READ | PAGE_WRITE;

        } else {

            ret = TLBRET_BADADDR;

        }

    } else if (address < (int32_t)0xE0000000UL) {

        /* sseg (kseg2) */

        if (supervisor_mode || kernel_mode) {

            ret = env->tlb->map_address(env, physical, prot, address, rw, access_type);

        } else {

            ret = TLBRET_BADADDR;

        }

    } else {

        /* kseg3 */

        /* XXX: debug segment is not emulated */

        if (kernel_mode) {

            ret = env->tlb->map_address(env, physical, prot, address, rw, access_type);

        } else {

            ret = TLBRET_BADADDR;

        }

    }

#if 0

    if (logfile) {

        fprintf(logfile, TARGET_FMT_lx " %d %d => " TARGET_FMT_lx " %d (%d)\n",

		address, rw, access_type, *physical, *prot, ret);

    }

#endif

    return ret;

}


void palette8tobgr32(const uint8_t *src, uint8_t *dst, unsigned num_pixels, const uint8_t *palette)

{

	unsigned i;

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

	{

		#ifdef WORDS_BIGENDIAN

		dst[3]= palette[ src[i]*4+0 ];

		dst[2]= palette[ src[i]*4+1 ];

		dst[1]= palette[ src[i]*4+2 ];

		#else

		//FIXME slow?

		dst[0]= palette[ src[i]*4+0 ];

		dst[1]= palette[ src[i]*4+1 ];

		dst[2]= palette[ src[i]*4+2 ];

//		dst[3]= 0; /* do we need this cleansing? */

		#endif

		dst+= 4;

	}

}


int av_seek_frame_binary(AVFormatContext *s, int stream_index, int64_t target_ts, int flags){

    AVInputFormat *avif= s->iformat;

    int64_t av_uninit(pos_min), av_uninit(pos_max), pos, pos_limit;

    int64_t ts_min, ts_max, ts;

    int index;

    AVStream *st;

    if (stream_index < 0)

        return -1;

#ifdef DEBUG_SEEK

    av_log(s, AV_LOG_DEBUG, "read_seek: %d %"PRId64"\n", stream_index, target_ts);

#endif

    ts_max=

    ts_min= AV_NOPTS_VALUE;

    pos_limit= -1; //gcc falsely says it may be uninitialized

    st= s->streams[stream_index];

    if(st->index_entries){

        AVIndexEntry *e;

        index= av_index_search_timestamp(st, target_ts, flags | AVSEEK_FLAG_BACKWARD); //FIXME whole func must be checked for non-keyframe entries in index case, especially read_timestamp()

        index= FFMAX(index, 0);

        e= &st->index_entries[index];

        if(e->timestamp <= target_ts || e->pos == e->min_distance){

            pos_min= e->pos;

            ts_min= e->timestamp;

#ifdef DEBUG_SEEK

            av_log(s, AV_LOG_DEBUG, "using cached pos_min=0x%"PRIx64" dts_min=%"PRId64"\n",

                   pos_min,ts_min);

#endif

        }else{

            assert(index==0);

        }

        index= av_index_search_timestamp(st, target_ts, flags & ~AVSEEK_FLAG_BACKWARD);

        assert(index < st->nb_index_entries);

        if(index >= 0){

            e= &st->index_entries[index];

            assert(e->timestamp >= target_ts);

            pos_max= e->pos;

            ts_max= e->timestamp;

            pos_limit= pos_max - e->min_distance;

#ifdef DEBUG_SEEK

            av_log(s, AV_LOG_DEBUG, "using cached pos_max=0x%"PRIx64" pos_limit=0x%"PRIx64" dts_max=%"PRId64"\n",

                   pos_max,pos_limit, ts_max);

#endif

        }

    }

    pos= av_gen_search(s, stream_index, target_ts, pos_min, pos_max, pos_limit, ts_min, ts_max, flags, &ts, avif->read_timestamp);

    if(pos<0)

        return -1;

    /* do the seek */

    url_fseek(s->pb, pos, SEEK_SET);

    av_update_cur_dts(s, st, ts);

    return 0;

}


static abi_long do_ipc(unsigned int call, abi_long first,

                       abi_long second, abi_long third,

                       abi_long ptr, abi_long fifth)

{

    int version;

    abi_long ret = 0;

    version = call >> 16;

    call &= 0xffff;

    switch (call) {

    case IPCOP_semop:

        ret = do_semop(first, ptr, second);

        break;

    case IPCOP_semget:

        ret = get_errno(semget(first, second, third));

        break;

    case IPCOP_semctl: {

        /* The semun argument to semctl is passed by value, so dereference the

         * ptr argument. */

        abi_ulong atptr;

        get_user_ual(atptr, ptr);

        ret = do_semctl(first, second, third, atptr);

        break;

    }

    case IPCOP_msgget:

        ret = get_errno(msgget(first, second));

        break;

    case IPCOP_msgsnd:

        ret = do_msgsnd(first, ptr, second, third);

        break;

    case IPCOP_msgctl:

        ret = do_msgctl(first, second, ptr);

        break;

    case IPCOP_msgrcv:

        switch (version) {

        case 0:

            {

                struct target_ipc_kludge {

                    abi_long msgp;

                    abi_long msgtyp;

                } *tmp;

                if (!lock_user_struct(VERIFY_READ, tmp, ptr, 1)) {

                    ret = -TARGET_EFAULT;

                    break;

                }

                ret = do_msgrcv(first, tswapal(tmp->msgp), second, tswapal(tmp->msgtyp), third);

                unlock_user_struct(tmp, ptr, 0);

                break;

            }

        default:

            ret = do_msgrcv(first, ptr, second, fifth, third);

        }

        break;

    case IPCOP_shmat:

        switch (version) {

        default:

        {

            abi_ulong raddr;

            raddr = do_shmat(first, ptr, second);

            if (is_error(raddr))

                return get_errno(raddr);

            if (put_user_ual(raddr, third))

                return -TARGET_EFAULT;

            break;

        }

        case 1:

            ret = -TARGET_EINVAL;

            break;

        }

	break;

    case IPCOP_shmdt:

        ret = do_shmdt(ptr);

	break;

    case IPCOP_shmget:

	/* IPC_* flag values are the same on all linux platforms */

	ret = get_errno(shmget(first, second, third));

	break;

	/* IPC_* and SHM_* command values are the same on all linux platforms */

    case IPCOP_shmctl:

        ret = do_shmctl(first, second, ptr);

        break;

    default:

	gemu_log("Unsupported ipc call: %d (version %d)\n", call, version);

	ret = -TARGET_ENOSYS;

	break;

    }

    return ret;

}


static int virtcon_parse(const char *devname)

{

    QemuOptsList *device = qemu_find_opts("device");

    static int index = 0;

    char label[32];

    QemuOpts *bus_opts, *dev_opts;

    if (strcmp(devname, "none") == 0)

        return 0;

    if (index == MAX_VIRTIO_CONSOLES) {

        fprintf(stderr, "qemu: too many virtio consoles\n");

        exit(1);

    }

    bus_opts = qemu_opts_create(device, NULL, 0, &error_abort);

    if (arch_type == QEMU_ARCH_S390X) {

        qemu_opt_set(bus_opts, "driver", "virtio-serial-s390", &error_abort);

    } else {

        qemu_opt_set(bus_opts, "driver", "virtio-serial-pci", &error_abort);

    }

    dev_opts = qemu_opts_create(device, NULL, 0, &error_abort);

    qemu_opt_set(dev_opts, "driver", "virtconsole", &error_abort);

    snprintf(label, sizeof(label), "virtcon%d", index);

    virtcon_hds[index] = qemu_chr_new(label, devname, NULL);

    if (!virtcon_hds[index]) {

        fprintf(stderr, "qemu: could not connect virtio console"

                " to character backend '%s'\n", devname);

        return -1;

    }

    qemu_opt_set(dev_opts, "chardev", label, &error_abort);

    index++;

    return 0;

}


void helper_lcall_protected(int new_cs, target_ulong new_eip,

                            int shift, int next_eip_addend)

{

    int new_stack, i;

    uint32_t e1, e2, cpl, dpl, rpl, selector, offset, param_count;

    uint32_t ss = 0, ss_e1 = 0, ss_e2 = 0, sp, type, ss_dpl, sp_mask;

    uint32_t val, limit, old_sp_mask;

    target_ulong ssp, old_ssp, next_eip;

    next_eip = env->eip + next_eip_addend;

    LOG_PCALL("lcall %04x:%08x s=%d\n", new_cs, (uint32_t)new_eip, shift);

    LOG_PCALL_STATE(env);

    if ((new_cs & 0xfffc) == 0)

        raise_exception_err(EXCP0D_GPF, 0);

    if (load_segment(&e1, &e2, new_cs) != 0)

        raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);

    cpl = env->hflags & HF_CPL_MASK;

    LOG_PCALL("desc=%08x:%08x\n", e1, e2);

    if (e2 & DESC_S_MASK) {

        if (!(e2 & DESC_CS_MASK))

            raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);

        dpl = (e2 >> DESC_DPL_SHIFT) & 3;

        if (e2 & DESC_C_MASK) {

            /* conforming code segment */

            if (dpl > cpl)

                raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);

        } else {

            /* non conforming code segment */

            rpl = new_cs & 3;

            if (rpl > cpl)

                raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);

            if (dpl != cpl)

                raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);

        }

        if (!(e2 & DESC_P_MASK))

            raise_exception_err(EXCP0B_NOSEG, new_cs & 0xfffc);

#ifdef TARGET_X86_64

        /* XXX: check 16/32 bit cases in long mode */

        if (shift == 2) {

            target_ulong rsp;

            /* 64 bit case */

            rsp = ESP;

            PUSHQ(rsp, env->segs[R_CS].selector);

            PUSHQ(rsp, next_eip);

            /* from this point, not restartable */

            ESP = rsp;

            cpu_x86_load_seg_cache(env, R_CS, (new_cs & 0xfffc) | cpl,

                                   get_seg_base(e1, e2),

                                   get_seg_limit(e1, e2), e2);

            EIP = new_eip;

        } else

#endif

        {

            sp = ESP;

            sp_mask = get_sp_mask(env->segs[R_SS].flags);

            ssp = env->segs[R_SS].base;

            if (shift) {

                PUSHL(ssp, sp, sp_mask, env->segs[R_CS].selector);

                PUSHL(ssp, sp, sp_mask, next_eip);

            } else {

                PUSHW(ssp, sp, sp_mask, env->segs[R_CS].selector);

                PUSHW(ssp, sp, sp_mask, next_eip);

            }

            limit = get_seg_limit(e1, e2);

            if (new_eip > limit)

                raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);

            /* from this point, not restartable */

            SET_ESP(sp, sp_mask);

            cpu_x86_load_seg_cache(env, R_CS, (new_cs & 0xfffc) | cpl,

                                   get_seg_base(e1, e2), limit, e2);

            EIP = new_eip;

        }

    } else {

        /* check gate type */

        type = (e2 >> DESC_TYPE_SHIFT) & 0x1f;

        dpl = (e2 >> DESC_DPL_SHIFT) & 3;

        rpl = new_cs & 3;

        switch(type) {

        case 1: /* available 286 TSS */

        case 9: /* available 386 TSS */

        case 5: /* task gate */

            if (dpl < cpl || dpl < rpl)

                raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);

            switch_tss(new_cs, e1, e2, SWITCH_TSS_CALL, next_eip);

            CC_OP = CC_OP_EFLAGS;

            return;

        case 4: /* 286 call gate */

        case 12: /* 386 call gate */

            break;

        default:

            raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);

            break;

        }

        shift = type >> 3;

        if (dpl < cpl || dpl < rpl)

            raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);

        /* check valid bit */

        if (!(e2 & DESC_P_MASK))

            raise_exception_err(EXCP0B_NOSEG,  new_cs & 0xfffc);

        selector = e1 >> 16;

        offset = (e2 & 0xffff0000) | (e1 & 0x0000ffff);

        param_count = e2 & 0x1f;

        if ((selector & 0xfffc) == 0)

            raise_exception_err(EXCP0D_GPF, 0);

        if (load_segment(&e1, &e2, selector) != 0)

            raise_exception_err(EXCP0D_GPF, selector & 0xfffc);

        if (!(e2 & DESC_S_MASK) || !(e2 & (DESC_CS_MASK)))

            raise_exception_err(EXCP0D_GPF, selector & 0xfffc);

        dpl = (e2 >> DESC_DPL_SHIFT) & 3;

        if (dpl > cpl)

            raise_exception_err(EXCP0D_GPF, selector & 0xfffc);

        if (!(e2 & DESC_P_MASK))

            raise_exception_err(EXCP0B_NOSEG, selector & 0xfffc);

        if (!(e2 & DESC_C_MASK) && dpl < cpl) {

            /* to inner privilege */

            get_ss_esp_from_tss(&ss, &sp, dpl);

            LOG_PCALL("new ss:esp=%04x:%08x param_count=%d ESP=" TARGET_FMT_lx "\n",

                        ss, sp, param_count, ESP);

            if ((ss & 0xfffc) == 0)

                raise_exception_err(EXCP0A_TSS, ss & 0xfffc);

            if ((ss & 3) != dpl)

                raise_exception_err(EXCP0A_TSS, ss & 0xfffc);

            if (load_segment(&ss_e1, &ss_e2, ss) != 0)

                raise_exception_err(EXCP0A_TSS, ss & 0xfffc);

            ss_dpl = (ss_e2 >> DESC_DPL_SHIFT) & 3;

            if (ss_dpl != dpl)

                raise_exception_err(EXCP0A_TSS, ss & 0xfffc);

            if (!(ss_e2 & DESC_S_MASK) ||

                (ss_e2 & DESC_CS_MASK) ||

                !(ss_e2 & DESC_W_MASK))

                raise_exception_err(EXCP0A_TSS, ss & 0xfffc);

            if (!(ss_e2 & DESC_P_MASK))

                raise_exception_err(EXCP0A_TSS, ss & 0xfffc);

            //            push_size = ((param_count * 2) + 8) << shift;

            old_sp_mask = get_sp_mask(env->segs[R_SS].flags);

            old_ssp = env->segs[R_SS].base;

            sp_mask = get_sp_mask(ss_e2);

            ssp = get_seg_base(ss_e1, ss_e2);

            if (shift) {

                PUSHL(ssp, sp, sp_mask, env->segs[R_SS].selector);

                PUSHL(ssp, sp, sp_mask, ESP);

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

                    val = ldl_kernel(old_ssp + ((ESP + i * 4) & old_sp_mask));

                    PUSHL(ssp, sp, sp_mask, val);

                }

            } else {

                PUSHW(ssp, sp, sp_mask, env->segs[R_SS].selector);

                PUSHW(ssp, sp, sp_mask, ESP);

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

                    val = lduw_kernel(old_ssp + ((ESP + i * 2) & old_sp_mask));

                    PUSHW(ssp, sp, sp_mask, val);

                }

            }

            new_stack = 1;

        } else {

            /* to same privilege */

            sp = ESP;

            sp_mask = get_sp_mask(env->segs[R_SS].flags);

            ssp = env->segs[R_SS].base;

            //            push_size = (4 << shift);

            new_stack = 0;

        }

        if (shift) {

            PUSHL(ssp, sp, sp_mask, env->segs[R_CS].selector);

            PUSHL(ssp, sp, sp_mask, next_eip);

        } else {

            PUSHW(ssp, sp, sp_mask, env->segs[R_CS].selector);

            PUSHW(ssp, sp, sp_mask, next_eip);

        }

        /* from this point, not restartable */

        if (new_stack) {

            ss = (ss & ~3) | dpl;

            cpu_x86_load_seg_cache(env, R_SS, ss,

                                   ssp,

                                   get_seg_limit(ss_e1, ss_e2),

                                   ss_e2);

        }

        selector = (selector & ~3) | dpl;

        cpu_x86_load_seg_cache(env, R_CS, selector,

                       get_seg_base(e1, e2),

                       get_seg_limit(e1, e2),

                       e2);

        cpu_x86_set_cpl(env, dpl);

        SET_ESP(sp, sp_mask);

        EIP = offset;

    }

#ifdef CONFIG_KQEMU

    if (kqemu_is_ok(env)) {

        env->exception_index = -1;

        cpu_loop_exit();

    }

#endif

}


static void raw_reopen_abort(BDRVReopenState *state)

{

    g_free(state->opaque);

    state->opaque = NULL;

}


void err (const char *s)

{

  perror (s);

  abort ();

}


static void hda_audio_command(HDACodecDevice *hda, uint32_t nid, uint32_t data)

{

    HDAAudioState *a = HDA_AUDIO(hda);

    HDAAudioStream *st;

    const desc_node *node = NULL;

    const desc_param *param;

    uint32_t verb, payload, response, count, shift;

    if ((data & 0x70000) == 0x70000) {

        /* 12/8 id/payload */

        verb = (data >> 8) & 0xfff;

        payload = data & 0x00ff;

    } else {

        /* 4/16 id/payload */

        verb = (data >> 8) & 0xf00;

        payload = data & 0xffff;

    }

    node = hda_codec_find_node(a->desc, nid);

    if (node == NULL) {

        goto fail;

    }

    dprint(a, 2, "%s: nid %d (%s), verb 0x%x, payload 0x%x\n",

           __FUNCTION__, nid, node->name, verb, payload);

    switch (verb) {

    /* all nodes */

    case AC_VERB_PARAMETERS:

        param = hda_codec_find_param(node, payload);

        if (param == NULL) {

            goto fail;

        }

        hda_codec_response(hda, true, param->val);

        break;

    case AC_VERB_GET_SUBSYSTEM_ID:

        hda_codec_response(hda, true, a->desc->iid);

        break;

    /* all functions */

    case AC_VERB_GET_CONNECT_LIST:

        param = hda_codec_find_param(node, AC_PAR_CONNLIST_LEN);

        count = param ? param->val : 0;

        response = 0;

        shift = 0;

        while (payload < count && shift < 32) {

            response |= node->conn[payload] << shift;

            payload++;

            shift += 8;

        }

        hda_codec_response(hda, true, response);

        break;

    /* pin widget */

    case AC_VERB_GET_CONFIG_DEFAULT:

        hda_codec_response(hda, true, node->config);

        break;

    case AC_VERB_GET_PIN_WIDGET_CONTROL:

        hda_codec_response(hda, true, node->pinctl);

        break;

    case AC_VERB_SET_PIN_WIDGET_CONTROL:

        if (node->pinctl != payload) {

            dprint(a, 1, "unhandled pin control bit\n");

        }

        hda_codec_response(hda, true, 0);

        break;

    /* audio in/out widget */

    case AC_VERB_SET_CHANNEL_STREAMID:

        st = a->st + node->stindex;

        if (st->node == NULL) {

            goto fail;

        }

        hda_audio_set_running(st, false);

        st->stream = (payload >> 4) & 0x0f;

        st->channel = payload & 0x0f;

        dprint(a, 2, "%s: stream %d, channel %d\n",

               st->node->name, st->stream, st->channel);

        hda_audio_set_running(st, a->running_real[st->output * 16 + st->stream]);

        hda_codec_response(hda, true, 0);

        break;

    case AC_VERB_GET_CONV:

        st = a->st + node->stindex;

        if (st->node == NULL) {

            goto fail;

        }

        response = st->stream << 4 | st->channel;

        hda_codec_response(hda, true, response);

        break;

    case AC_VERB_SET_STREAM_FORMAT:

        st = a->st + node->stindex;

        if (st->node == NULL) {

            goto fail;

        }

        st->format = payload;

        hda_codec_parse_fmt(st->format, &st->as);

        hda_audio_setup(st);

        hda_codec_response(hda, true, 0);

        break;

    case AC_VERB_GET_STREAM_FORMAT:

        st = a->st + node->stindex;

        if (st->node == NULL) {

            goto fail;

        }

        hda_codec_response(hda, true, st->format);

        break;

    case AC_VERB_GET_AMP_GAIN_MUTE:

        st = a->st + node->stindex;

        if (st->node == NULL) {

            goto fail;

        }

        if (payload & AC_AMP_GET_LEFT) {

            response = st->gain_left | (st->mute_left ? AC_AMP_MUTE : 0);

        } else {

            response = st->gain_right | (st->mute_right ? AC_AMP_MUTE : 0);

        }

        hda_codec_response(hda, true, response);

        break;

    case AC_VERB_SET_AMP_GAIN_MUTE:

        st = a->st + node->stindex;

        if (st->node == NULL) {

            goto fail;

        }

        dprint(a, 1, "amp (%s): %s%s%s%s index %d  gain %3d %s\n",

               st->node->name,

               (payload & AC_AMP_SET_OUTPUT) ? "o" : "-",

               (payload & AC_AMP_SET_INPUT)  ? "i" : "-",

               (payload & AC_AMP_SET_LEFT)   ? "l" : "-",

               (payload & AC_AMP_SET_RIGHT)  ? "r" : "-",

               (payload & AC_AMP_SET_INDEX) >> AC_AMP_SET_INDEX_SHIFT,

               (payload & AC_AMP_GAIN),

               (payload & AC_AMP_MUTE) ? "muted" : "");

        if (payload & AC_AMP_SET_LEFT) {

            st->gain_left = payload & AC_AMP_GAIN;

            st->mute_left = payload & AC_AMP_MUTE;

        }

        if (payload & AC_AMP_SET_RIGHT) {

            st->gain_right = payload & AC_AMP_GAIN;

            st->mute_right = payload & AC_AMP_MUTE;

        }

        hda_audio_set_amp(st);

        hda_codec_response(hda, true, 0);

        break;

    /* not supported */

    case AC_VERB_SET_POWER_STATE:

    case AC_VERB_GET_POWER_STATE:

    case AC_VERB_GET_SDI_SELECT:

        hda_codec_response(hda, true, 0);

        break;

    default:

        goto fail;

    }

    return;

fail:

    dprint(a, 1, "%s: not handled: nid %d (%s), verb 0x%x, payload 0x%x\n",

           __FUNCTION__, nid, node ? node->name : "?", verb, payload);

    hda_codec_response(hda, true, 0);

}


static void sdp_parse_fmtp_config(AVCodecContext * codec, void *ctx,

                                  char *attr, char *value)

{

    switch (codec->codec_id) {

        case CODEC_ID_MPEG4:

        case CODEC_ID_AAC:

            if (!strcmp(attr, "config")) {

                /* decode the hexa encoded parameter */

                int len = hex_to_data(NULL, value);

                if (codec->extradata)

                    av_free(codec->extradata);

                codec->extradata = av_mallocz(len + FF_INPUT_BUFFER_PADDING_SIZE);

                if (!codec->extradata)

                    return;

                codec->extradata_size = len;

                hex_to_data(codec->extradata, value);

            }

            break;

        case CODEC_ID_VORBIS:

            ff_vorbis_parse_fmtp_config(codec, ctx, attr, value);

            break;

        default:

            break;

    }

    return;

}


static void mux_print_help(CharDriverState *chr)

{

    int i, j;

    char ebuf[15] = "Escape-Char";

    char cbuf[50] = "\n\r";

    if (term_escape_char > 0 && term_escape_char < 26) {

        snprintf(cbuf, sizeof(cbuf), "\n\r");

        snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');

    } else {

        snprintf(cbuf, sizeof(cbuf),

                 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",

                 term_escape_char);

    }

    qemu_chr_fe_write(chr, (uint8_t *)cbuf, strlen(cbuf));

    for (i = 0; mux_help[i] != NULL; i++) {

        for (j=0; mux_help[i][j] != '\0'; j++) {

            if (mux_help[i][j] == '%')

                qemu_chr_fe_write(chr, (uint8_t *)ebuf, strlen(ebuf));

            else

                qemu_chr_fe_write(chr, (uint8_t *)&mux_help[i][j], 1);

        }

    }

}


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

{

    struct in_addr host_addr = { .s_addr = INADDR_ANY };

    int host_port;

    char buf[256] = "";

    const char *src_str, *p;

    SlirpState *s;

    int is_udp = 0;

    int err;

    const char *arg1 = qdict_get_str(qdict, "arg1");

    const char *arg2 = qdict_get_try_str(qdict, "arg2");

    const char *arg3 = qdict_get_try_str(qdict, "arg3");

    if (arg2) {

        s = slirp_lookup(mon, arg1, arg2);

        src_str = arg3;

    } else {

        s = slirp_lookup(mon, NULL, NULL);

        src_str = arg1;

    }

    if (!s) {

        return;

    }

    if (!src_str || !src_str[0])

        goto fail_syntax;

    p = src_str;

    get_str_sep(buf, sizeof(buf), &p, ':');

    if (!strcmp(buf, "tcp") || buf[0] == '\0') {

        is_udp = 0;

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

        is_udp = 1;

    } else {

        goto fail_syntax;

    }

    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0) {

        goto fail_syntax;

    }

    if (buf[0] != '\0' && !inet_aton(buf, &host_addr)) {

        goto fail_syntax;

    }

    host_port = atoi(p);

    err = slirp_remove_hostfwd(TAILQ_FIRST(&slirp_stacks)->slirp, is_udp,

                               host_addr, host_port);

    monitor_printf(mon, "host forwarding rule for %s %s\n", src_str,

                   err ? "removed" : "not found");

    return;

 fail_syntax:

    monitor_printf(mon, "invalid format\n");

}


static QObject *parse_object(JSONParserContext *ctxt, va_list *ap)

{

    QDict *dict = NULL;

    QObject *token, *peek;

    JSONParserContext saved_ctxt = parser_context_save(ctxt);

    token = parser_context_pop_token(ctxt);

    if (token == NULL) {

        goto out;

    }

    if (!token_is_operator(token, '{')) {

        goto out;

    }

    dict = qdict_new();

    peek = parser_context_peek_token(ctxt);

    if (peek == NULL) {

        parse_error(ctxt, NULL, "premature EOI");

        goto out;

    }

    if (!token_is_operator(peek, '}')) {

        if (parse_pair(ctxt, dict, ap) == -1) {

            goto out;

        }

        token = parser_context_pop_token(ctxt);

        if (token == NULL) {

            parse_error(ctxt, NULL, "premature EOI");

            goto out;

        }

        while (!token_is_operator(token, '}')) {

            if (!token_is_operator(token, ',')) {

                parse_error(ctxt, token, "expected separator in dict");

                goto out;

            }

            if (parse_pair(ctxt, dict, ap) == -1) {

                goto out;

            }

            token = parser_context_pop_token(ctxt);

            if (token == NULL) {

                parse_error(ctxt, NULL, "premature EOI");

                goto out;

            }

        }

    } else {

        (void)parser_context_pop_token(ctxt);

    }

    return QOBJECT(dict);

out:

    parser_context_restore(ctxt, saved_ctxt);

    QDECREF(dict);

    return NULL;

}


static void qemu_chr_parse_mux(QemuOpts *opts, ChardevBackend *backend,

                               Error **errp)

{

    const char *chardev = qemu_opt_get(opts, "chardev");

    ChardevMux *mux;

    if (chardev == NULL) {

        error_setg(errp, "chardev: mux: no chardev given");

        return;

    }

    mux = backend->u.mux = g_new0(ChardevMux, 1);

    qemu_chr_parse_common(opts, qapi_ChardevMux_base(mux));

    mux->chardev = g_strdup(chardev);

}


static void do_flush_queued_data(VirtIOSerialPort *port, VirtQueue *vq,

                                 VirtIODevice *vdev)

{

    VirtIOSerialPortClass *vsc;

    assert(port);

    assert(virtio_queue_ready(vq));

    vsc = VIRTIO_SERIAL_PORT_GET_CLASS(port);

    while (!port->throttled) {

        unsigned int i;

        /* Pop an elem only if we haven't left off a previous one mid-way */

        if (!port->elem.out_num) {

            if (!virtqueue_pop(vq, &port->elem)) {

                break;

            }

            port->iov_idx = 0;

            port->iov_offset = 0;

        }

        for (i = port->iov_idx; i < port->elem.out_num; i++) {

            size_t buf_size;

            ssize_t ret;

            buf_size = port->elem.out_sg[i].iov_len - port->iov_offset;

            ret = vsc->have_data(port,

                                  port->elem.out_sg[i].iov_base

                                  + port->iov_offset,

                                  buf_size);

            if (port->throttled) {

                port->iov_idx = i;

                if (ret > 0) {

                    port->iov_offset += ret;

                }

                break;

            }

            port->iov_offset = 0;

        }

        if (port->throttled) {

            break;

        }

        virtqueue_push(vq, &port->elem, 0);

        port->elem.out_num = 0;

    }

    virtio_notify(vdev, vq);

}


static void l2cap_command(struct l2cap_instance_s *l2cap, int code, int id,

                const uint8_t *params, int len)

{

    int err;

#if 0

    /* TODO: do the IDs really have to be in sequence?  */

    if (!id || (id != l2cap->last_id && id != l2cap->next_id)) {

        fprintf(stderr, "%s: out of sequence command packet ignored.\n",

                        __func__);

        return;

    }

#else

    l2cap->next_id = id;

#endif

    if (id == l2cap->next_id) {

        l2cap->last_id = l2cap->next_id;

        l2cap->next_id = l2cap->next_id == 255 ? 1 : l2cap->next_id + 1;

    } else {

        /* TODO: Need to re-send the same response, without re-executing

         * the corresponding command!  */

    }

    switch (code) {

    case L2CAP_COMMAND_REJ:

        if (unlikely(len != 2 && len != 4 && len != 6)) {

            err = L2CAP_REJ_CMD_NOT_UNDERSTOOD;

            goto reject;

        }

        /* We never issue commands other than Command Reject currently.  */

        fprintf(stderr, "%s: stray Command Reject (%02x, %04x) "

                        "packet, ignoring.\n", __func__, id,

                        le16_to_cpu(((l2cap_cmd_rej *) params)->reason));

        break;

    case L2CAP_CONN_REQ:

        if (unlikely(len != L2CAP_CONN_REQ_SIZE)) {

            err = L2CAP_REJ_CMD_NOT_UNDERSTOOD;

            goto reject;

        }

        l2cap_channel_open_req_msg(l2cap,

                        le16_to_cpu(((l2cap_conn_req *) params)->psm),

                        le16_to_cpu(((l2cap_conn_req *) params)->scid));

        break;

    case L2CAP_CONN_RSP:

        if (unlikely(len != L2CAP_CONN_RSP_SIZE)) {

            err = L2CAP_REJ_CMD_NOT_UNDERSTOOD;

            goto reject;

        }

        /* We never issue Connection Requests currently. TODO  */

        fprintf(stderr, "%s: unexpected Connection Response (%02x) "

                        "packet, ignoring.\n", __func__, id);

        break;

    case L2CAP_CONF_REQ:

        if (unlikely(len < L2CAP_CONF_REQ_SIZE(0))) {

            err = L2CAP_REJ_CMD_NOT_UNDERSTOOD;

            goto reject;

        }

        l2cap_channel_config_req_msg(l2cap,

                        le16_to_cpu(((l2cap_conf_req *) params)->flags) & 1,

                        le16_to_cpu(((l2cap_conf_req *) params)->dcid),

                        ((l2cap_conf_req *) params)->data,

                        len - L2CAP_CONF_REQ_SIZE(0));

        break;

    case L2CAP_CONF_RSP:

        if (unlikely(len < L2CAP_CONF_RSP_SIZE(0))) {

            err = L2CAP_REJ_CMD_NOT_UNDERSTOOD;

            goto reject;

        }

        if (l2cap_channel_config_rsp_msg(l2cap,

                        le16_to_cpu(((l2cap_conf_rsp *) params)->result),

                        le16_to_cpu(((l2cap_conf_rsp *) params)->flags) & 1,

                        le16_to_cpu(((l2cap_conf_rsp *) params)->scid),

                        ((l2cap_conf_rsp *) params)->data,

                        len - L2CAP_CONF_RSP_SIZE(0)))

            fprintf(stderr, "%s: unexpected Configure Response (%02x) "

                            "packet, ignoring.\n", __func__, id);

        break;

    case L2CAP_DISCONN_REQ:

        if (unlikely(len != L2CAP_DISCONN_REQ_SIZE)) {

            err = L2CAP_REJ_CMD_NOT_UNDERSTOOD;

            goto reject;

        }

        l2cap_channel_close(l2cap,

                        le16_to_cpu(((l2cap_disconn_req *) params)->dcid),

                        le16_to_cpu(((l2cap_disconn_req *) params)->scid));

        break;

    case L2CAP_DISCONN_RSP:

        if (unlikely(len != L2CAP_DISCONN_RSP_SIZE)) {

            err = L2CAP_REJ_CMD_NOT_UNDERSTOOD;

            goto reject;

        }

        /* We never issue Disconnection Requests currently. TODO  */

        fprintf(stderr, "%s: unexpected Disconnection Response (%02x) "

                        "packet, ignoring.\n", __func__, id);

        break;

    case L2CAP_ECHO_REQ:

        l2cap_echo_response(l2cap, params, len);

        break;

    case L2CAP_ECHO_RSP:

        /* We never issue Echo Requests currently. TODO  */

        fprintf(stderr, "%s: unexpected Echo Response (%02x) "

                        "packet, ignoring.\n", __func__, id);

        break;

    case L2CAP_INFO_REQ:

        if (unlikely(len != L2CAP_INFO_REQ_SIZE)) {

            err = L2CAP_REJ_CMD_NOT_UNDERSTOOD;

            goto reject;

        }

        l2cap_info(l2cap, le16_to_cpu(((l2cap_info_req *) params)->type));

        break;

    case L2CAP_INFO_RSP:

        if (unlikely(len != L2CAP_INFO_RSP_SIZE)) {

            err = L2CAP_REJ_CMD_NOT_UNDERSTOOD;

            goto reject;

        }

        /* We never issue Information Requests currently. TODO  */

        fprintf(stderr, "%s: unexpected Information Response (%02x) "

                        "packet, ignoring.\n", __func__, id);

        break;

    default:

        err = L2CAP_REJ_CMD_NOT_UNDERSTOOD;

    reject:

        l2cap_command_reject(l2cap, id, err, 0, 0);

        break;

    }

}


static int curl_aio_flush(void *opaque)

{

    BDRVCURLState *s = opaque;

    int i, j;

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

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

            if (s->states[i].acb[j]) {

                return 1;

            }

        }

    }

    return 0;

}


static void test_dynamic_globalprop_subprocess(void)

{

    MyType *mt;

    static GlobalProperty props[] = {

        { TYPE_DYNAMIC_PROPS, "prop1", "101", true },

        { TYPE_DYNAMIC_PROPS, "prop2", "102", true },

        { TYPE_DYNAMIC_PROPS"-bad", "prop3", "103", true },

        /* .not_used=false to emulate what qdev_add_one_global() does: */

        { TYPE_UNUSED_HOTPLUG, "prop4", "104", false },

        { TYPE_UNUSED_NOHOTPLUG, "prop5", "105", true },

        { TYPE_NONDEVICE, "prop6", "106", true },

        {}

    };

    int all_used;

    qdev_prop_register_global_list(props);

    mt = DYNAMIC_TYPE(object_new(TYPE_DYNAMIC_PROPS));

    qdev_init_nofail(DEVICE(mt));

    g_assert_cmpuint(mt->prop1, ==, 101);

    g_assert_cmpuint(mt->prop2, ==, 102);

    all_used = qdev_prop_check_globals();

    g_assert_cmpuint(all_used, ==, 1);

    g_assert(!props[0].not_used);

    g_assert(!props[1].not_used);

    g_assert(props[2].not_used);

    g_assert(!props[3].not_used);

    g_assert(props[4].not_used);

    g_assert(props[5].not_used);

}


void bdrv_aio_cancel(BlockDriverAIOCB *acb)

{

    if (acb->cb == bdrv_aio_rw_vector_cb) {

        VectorTranslationState *s = acb->opaque;

        acb = s->aiocb;

    }

    acb->pool->cancel(acb);

}


static void omap_mcbsp_writeh(void *opaque, hwaddr addr,

                uint32_t value)

{

    struct omap_mcbsp_s *s = (struct omap_mcbsp_s *) opaque;

    int offset = addr & OMAP_MPUI_REG_MASK;

    switch (offset) {

    case 0x00:	/* DRR2 */

    case 0x02:	/* DRR1 */

        OMAP_RO_REG(addr);

        return;

    case 0x04:	/* DXR2 */

        if (((s->xcr[0] >> 5) & 7) < 3)			/* XWDLEN1 */

            return;

        /* Fall through.  */

    case 0x06:	/* DXR1 */

        if (s->tx_req > 1) {

            s->tx_req -= 2;

            if (s->codec && s->codec->cts) {

                s->codec->out.fifo[s->codec->out.len ++] = (value >> 8) & 0xff;

                s->codec->out.fifo[s->codec->out.len ++] = (value >> 0) & 0xff;

            }

            if (s->tx_req < 2)

                omap_mcbsp_tx_done(s);

        } else

            printf("%s: Tx FIFO overrun\n", __FUNCTION__);

        return;

    case 0x08:	/* SPCR2 */

        s->spcr[1] &= 0x0002;

        s->spcr[1] |= 0x03f9 & value;

        s->spcr[1] |= 0x0004 & (value << 2);		/* XEMPTY := XRST */

        if (~value & 1)					/* XRST */

            s->spcr[1] &= ~6;

        omap_mcbsp_req_update(s);

        return;

    case 0x0a:	/* SPCR1 */

        s->spcr[0] &= 0x0006;

        s->spcr[0] |= 0xf8f9 & value;

        if (value & (1 << 15))				/* DLB */

            printf("%s: Digital Loopback mode enable attempt\n", __FUNCTION__);

        if (~value & 1) {				/* RRST */

            s->spcr[0] &= ~6;

            s->rx_req = 0;

            omap_mcbsp_rx_done(s);

        }

        omap_mcbsp_req_update(s);

        return;

    case 0x0c:	/* RCR2 */

        s->rcr[1] = value & 0xffff;

        return;

    case 0x0e:	/* RCR1 */

        s->rcr[0] = value & 0x7fe0;

        return;

    case 0x10:	/* XCR2 */

        s->xcr[1] = value & 0xffff;

        return;

    case 0x12:	/* XCR1 */

        s->xcr[0] = value & 0x7fe0;

        return;

    case 0x14:	/* SRGR2 */

        s->srgr[1] = value & 0xffff;

        omap_mcbsp_req_update(s);

        return;

    case 0x16:	/* SRGR1 */

        s->srgr[0] = value & 0xffff;

        omap_mcbsp_req_update(s);

        return;

    case 0x18:	/* MCR2 */

        s->mcr[1] = value & 0x03e3;

        if (value & 3)					/* XMCM */

            printf("%s: Tx channel selection mode enable attempt\n",

                            __FUNCTION__);

        return;

    case 0x1a:	/* MCR1 */

        s->mcr[0] = value & 0x03e1;

        if (value & 1)					/* RMCM */

            printf("%s: Rx channel selection mode enable attempt\n",

                            __FUNCTION__);

        return;

    case 0x1c:	/* RCERA */

        s->rcer[0] = value & 0xffff;

        return;

    case 0x1e:	/* RCERB */

        s->rcer[1] = value & 0xffff;

        return;

    case 0x20:	/* XCERA */

        s->xcer[0] = value & 0xffff;

        return;

    case 0x22:	/* XCERB */

        s->xcer[1] = value & 0xffff;

        return;

    case 0x24:	/* PCR0 */

        s->pcr = value & 0x7faf;

        return;

    case 0x26:	/* RCERC */

        s->rcer[2] = value & 0xffff;

        return;

    case 0x28:	/* RCERD */

        s->rcer[3] = value & 0xffff;

        return;

    case 0x2a:	/* XCERC */

        s->xcer[2] = value & 0xffff;

        return;

    case 0x2c:	/* XCERD */

        s->xcer[3] = value & 0xffff;

        return;

    case 0x2e:	/* RCERE */

        s->rcer[4] = value & 0xffff;

        return;

    case 0x30:	/* RCERF */

        s->rcer[5] = value & 0xffff;

        return;

    case 0x32:	/* XCERE */

        s->xcer[4] = value & 0xffff;

        return;

    case 0x34:	/* XCERF */

        s->xcer[5] = value & 0xffff;

        return;

    case 0x36:	/* RCERG */

        s->rcer[6] = value & 0xffff;

        return;

    case 0x38:	/* RCERH */

        s->rcer[7] = value & 0xffff;

        return;

    case 0x3a:	/* XCERG */

        s->xcer[6] = value & 0xffff;

        return;

    case 0x3c:	/* XCERH */

        s->xcer[7] = value & 0xffff;

        return;

    }

    OMAP_BAD_REG(addr);

}


BlockDriverAIOCB *paio_ioctl(BlockDriverState *bs, int fd,

        unsigned long int req, void *buf,

        BlockDriverCompletionFunc *cb, void *opaque)

{

    struct qemu_paiocb *acb;

    acb = qemu_aio_get(&raw_aio_pool, bs, cb, opaque);

    if (!acb)

        return NULL;

    acb->aio_type = QEMU_AIO_IOCTL;

    acb->aio_fildes = fd;

    acb->ev_signo = SIGUSR2;

    acb->async_context_id = get_async_context_id();

    acb->aio_offset = 0;

    acb->aio_ioctl_buf = buf;

    acb->aio_ioctl_cmd = req;

    acb->next = posix_aio_state->first_aio;

    posix_aio_state->first_aio = acb;

    qemu_paio_submit(acb);

    return &acb->common;

}


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

                                     const char *name, Error **errp)

{

    Object **child = opaque;

    gchar *path;

    if (*child) {

        path = object_get_canonical_path(*child);

        visit_type_str(v, &path, name, errp);

        g_free(path);

    } else {

        path = (gchar *)"";

        visit_type_str(v, &path, name, errp);

    }

}


void FUNCC(ff_h264_idct_dc_add)(uint8_t *_dst, DCTELEM *block, int stride){

    int i, j;

    int dc = (((dctcoef*)block)[0] + 32) >> 6;

    INIT_CLIP

    pixel *dst = (pixel*)_dst;

    stride /= sizeof(pixel);

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

    {

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

            dst[i] = CLIP( dst[i] + dc );

        dst += stride;

    }

}


int av_read_frame(AVFormatContext *s, AVPacket *pkt)

{

    const int genpts = s->flags & AVFMT_FLAG_GENPTS;

    int          eof = 0;

    int ret;

    AVStream *st;

    if (!genpts) {

        ret = s->packet_buffer ?

            read_from_packet_buffer(&s->packet_buffer, &s->packet_buffer_end, pkt) :

            read_frame_internal(s, pkt);

        if (ret < 0)

            return ret;

        goto return_packet;

    }

    for (;;) {

        AVPacketList *pktl = s->packet_buffer;

        if (pktl) {

            AVPacket *next_pkt = &pktl->pkt;

            if (next_pkt->dts != AV_NOPTS_VALUE) {

                int wrap_bits = s->streams[next_pkt->stream_index]->pts_wrap_bits;

                // last dts seen for this stream. if any of packets following

                // current one had no dts, we will set this to AV_NOPTS_VALUE.

                int64_t last_dts = next_pkt->dts;

                while (pktl && next_pkt->pts == AV_NOPTS_VALUE) {

                    if (pktl->pkt.stream_index == next_pkt->stream_index &&

                        (av_compare_mod(next_pkt->dts, pktl->pkt.dts, 2LL << (wrap_bits - 1)) < 0)) {

                        if (av_compare_mod(pktl->pkt.pts, pktl->pkt.dts, 2LL << (wrap_bits - 1))) { //not b frame

                            next_pkt->pts = pktl->pkt.dts;

                        }

                        if (last_dts != AV_NOPTS_VALUE) {

                            // Once last dts was set to AV_NOPTS_VALUE, we don't change it.

                            last_dts = pktl->pkt.dts;

                        }

                    }

                    pktl = pktl->next;

                }

                if (eof && next_pkt->pts == AV_NOPTS_VALUE && last_dts != AV_NOPTS_VALUE) {

                    // Fixing the last reference frame had none pts issue (For MXF etc).

                    // We only do this when

                    // 1. eof.

                    // 2. we are not able to resolve a pts value for current packet.

                    // 3. the packets for this stream at the end of the files had valid dts.

                    next_pkt->pts = last_dts + next_pkt->duration;

                }

                pktl = s->packet_buffer;

            }

            /* read packet from packet buffer, if there is data */

            if (!(next_pkt->pts == AV_NOPTS_VALUE &&

                  next_pkt->dts != AV_NOPTS_VALUE && !eof)) {

                ret = read_from_packet_buffer(&s->packet_buffer,

                                               &s->packet_buffer_end, pkt);

                goto return_packet;

            }

        }

        ret = read_frame_internal(s, pkt);

        if (ret < 0) {

            if (pktl && ret != AVERROR(EAGAIN)) {

                eof = 1;

                continue;

            } else

                return ret;

        }

        if (av_dup_packet(add_to_pktbuf(&s->packet_buffer, pkt,

                          &s->packet_buffer_end)) < 0)

            return AVERROR(ENOMEM);

    }

return_packet:

    st = s->streams[pkt->stream_index];

    if (st->skip_samples) {

        uint8_t *p = av_packet_new_side_data(pkt, AV_PKT_DATA_SKIP_SAMPLES, 10);

        AV_WL32(p, st->skip_samples);

        av_log(s, AV_LOG_DEBUG, "demuxer injecting skip %d\n", st->skip_samples);

        st->skip_samples = 0;

    }

    if ((s->iformat->flags & AVFMT_GENERIC_INDEX) && pkt->flags & AV_PKT_FLAG_KEY) {

        ff_reduce_index(s, st->index);

        av_add_index_entry(st, pkt->pos, pkt->dts, 0, 0, AVINDEX_KEYFRAME);

    }

    if (is_relative(pkt->dts))

        pkt->dts -= RELATIVE_TS_BASE;

    if (is_relative(pkt->pts))

        pkt->pts -= RELATIVE_TS_BASE;

    return ret;

}


static int buf_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)

{

    QEMUBuffer *s = opaque;

    ssize_t len = qsb_get_length(s->qsb) - pos;

    if (len <= 0) {

        return 0;

    }

    if (len > size) {

        len = size;

    }

    return qsb_get_buffer(s->qsb, pos, len, buf);

}


int unix_listen(const char *str, char *ostr, int olen)

{

    QemuOpts *opts;

    char *path, *optstr;

    int sock, len;

    opts = qemu_opts_create(&dummy_opts, NULL, 0);

    optstr = strchr(str, ',');

    if (optstr) {

        len = optstr - str;

        if (len) {

            path = g_malloc(len+1);

            snprintf(path, len+1, "%.*s", len, str);

            qemu_opt_set(opts, "path", path);

            g_free(path);

        }

    } else {

        qemu_opt_set(opts, "path", str);

    }

    sock = unix_listen_opts(opts);

    if (sock != -1 && ostr)

        snprintf(ostr, olen, "%s%s", qemu_opt_get(opts, "path"), optstr ? optstr : "");

    qemu_opts_del(opts);

    return sock;

}


static void render_fragments(Vp3DecodeContext *s,

                             int first_fragment,

                             int width,

                             int height,

                             int plane /* 0 = Y, 1 = U, 2 = V */)

{

    int x, y;

    int m, n;

    int i = first_fragment;

    int j;

    int16_t *dequantizer;

    DCTELEM dequant_block[64];

    unsigned char *output_plane;

    unsigned char *last_plane;

    unsigned char *golden_plane;

    int stride;

    int motion_x, motion_y;

    int motion_x_limit, motion_y_limit;

    int motion_halfpel_index;

    unsigned int motion_source;

    debug_vp3("  vp3: rendering final fragments for %s\n",

        (plane == 0) ? "Y plane" : (plane == 1) ? "U plane" : "V plane");

    /* set up plane-specific parameters */

    if (plane == 0) {

        dequantizer = s->intra_y_dequant;

        output_plane = s->current_frame.data[0];

        last_plane = s->last_frame.data[0];

        golden_plane = s->golden_frame.data[0];

        stride = -s->current_frame.linesize[0];

    } else if (plane == 1) {

        dequantizer = s->intra_c_dequant;

        output_plane = s->current_frame.data[1];

        last_plane = s->last_frame.data[1];

        golden_plane = s->golden_frame.data[1];

        stride = -s->current_frame.linesize[1];

    } else {

        dequantizer = s->intra_c_dequant;

        output_plane = s->current_frame.data[2];

        last_plane = s->last_frame.data[2];

        golden_plane = s->golden_frame.data[2];

        stride = -s->current_frame.linesize[2];

    }

    motion_x_limit = width - 8;

    motion_y_limit = height - 8;

    /* for each fragment row... */

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

        /* for each fragment in a row... */

        for (x = 0; x < width; x += 8, i++) {

            /* transform if this block was coded */

            if (s->all_fragments[i].coding_method != MODE_COPY) {

                /* sort out the motion vector */

                motion_x = s->all_fragments[i].motion_x;

                motion_y = s->all_fragments[i].motion_y;

                motion_halfpel_index = s->all_fragments[i].motion_halfpel_index;

/*

                if (motion_x < 0)

                    motion_x = 0;

                if (motion_y < 0)

                    motion_y = 0;

                if (motion_x > motion_x_limit)

                    motion_x = motion_x_limit;

                if (motion_y > motion_y_limit)

                    motion_y = motion_y_limit;

*/

                motion_source = s->all_fragments[i].first_pixel;

                motion_source += motion_x;

                motion_source += (motion_y * stride);

                /* first, take care of copying a block from either the

                 * previous or the golden frame */

                if ((s->all_fragments[i].coding_method == MODE_USING_GOLDEN) ||

                    (s->all_fragments[i].coding_method == MODE_GOLDEN_MV)) {

                    s->dsp.put_pixels_tab[1][motion_halfpel_index](

                        output_plane + s->all_fragments[i].first_pixel,

                        golden_plane + motion_source,

                        stride, 8);

                } else

                if (s->all_fragments[i].coding_method != MODE_INTRA) {

                    s->dsp.put_pixels_tab[1][motion_halfpel_index](

                        output_plane + s->all_fragments[i].first_pixel,

                        last_plane + motion_source,

                        stride, 8);

                }

                /* dequantize the DCT coefficients */

                debug_idct("fragment %d, coding mode %d, DC = %d, dequant = %d:\n",

                    i, s->all_fragments[i].coding_method,

                    s->all_fragments[i].coeffs[0], dequantizer[0]);

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

                    dequant_block[dequant_index[j]] =

                        s->all_fragments[i].coeffs[j] *

                        dequantizer[j];

                debug_idct("dequantized block:\n");

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

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

                        debug_idct(" %5d", dequant_block[m * 8 + n]);

                    }

                    debug_idct("\n");

                }

                debug_idct("\n");

                /* invert DCT and place (or add) in final output */

                if (s->all_fragments[i].coding_method == MODE_INTRA) {

                    dequant_block[0] += 1024;

                    s->dsp.idct_put(

                        output_plane + s->all_fragments[i].first_pixel,

                        stride, dequant_block);

                } else {

                    s->dsp.idct_add(

                        output_plane + s->all_fragments[i].first_pixel,

                        stride, dequant_block);

                }

                debug_idct("block after idct_%s():\n",

                    (s->all_fragments[i].coding_method == MODE_INTRA)?

                    "put" : "add");

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

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

                        debug_idct(" %3d", *(output_plane +

                            s->all_fragments[i].first_pixel + (m * stride + n)));

                    }

                    debug_idct("\n");

                }

                debug_idct("\n");

            } else {

                /* copy directly from the previous frame */

                s->dsp.put_pixels_tab[1][0](

                    output_plane + s->all_fragments[i].first_pixel,

                    last_plane + s->all_fragments[i].first_pixel,

                    stride, 8);

            }

        }

    }

    emms_c();

}


static av_cold int color_init(AVFilterContext *ctx, const char *args, void *opaque)

{

    ColorContext *color = ctx->priv;

    char color_string[128] = "black";

    char frame_size  [128] = "320x240";

    char frame_rate  [128] = "25";

    AVRational frame_rate_q;

    char *colon = 0, *equal = 0;

    int ret = 0;

    color->class = &color_class;

    if (args) {

        colon = strchr(args, ':');

        equal = strchr(args, '=');

    }

    if (!args || (equal && (!colon || equal < colon))) {

        av_opt_set_defaults(color);

        if ((ret = av_set_options_string(color, args, "=", ":")) < 0) {

            av_log(ctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);

            goto end;

        }

        if (av_parse_video_rate(&frame_rate_q, color->rate_str) < 0 ||

                frame_rate_q.den <= 0 || frame_rate_q.num <= 0) {

            av_log(ctx, AV_LOG_ERROR, "Invalid frame rate: %s\n", color->rate_str);

            ret = AVERROR(EINVAL);

            goto end;

        }

        if (av_parse_color(color->color_rgba, color->color_str, -1, ctx) < 0) {

            ret = AVERROR(EINVAL);

            goto end;

        }

    } else {

        av_log(ctx, AV_LOG_WARNING, "Flat options syntax is deprecated, use key=value pairs.\n");

        sscanf(args, "%127[^:]:%127[^:]:%127s", color_string, frame_size, frame_rate);

        if (av_parse_video_size(&color->w, &color->h, frame_size) < 0) {

            av_log(ctx, AV_LOG_ERROR, "Invalid frame size: %s\n", frame_size);

            return AVERROR(EINVAL);

        }

        if (av_parse_video_rate(&frame_rate_q, frame_rate) < 0 ||

                frame_rate_q.den <= 0 || frame_rate_q.num <= 0) {

            av_log(ctx, AV_LOG_ERROR, "Invalid frame rate: %s\n", frame_rate);

            return AVERROR(EINVAL);

        }

        if (av_parse_color(color->color_rgba, color_string, -1, ctx) < 0)

            return AVERROR(EINVAL);

    }

    color->time_base.num = frame_rate_q.den;

    color->time_base.den = frame_rate_q.num;

end:

    av_opt_free(color);

    return ret;

}