static void kmvc_decode_inter_8x8(KmvcContext * ctx, const uint8_t * src, int w, int h)

{

    BitBuf bb;

    int res, val;

    int i, j;

    int bx, by;

    int l0x, l1x, l0y, l1y;

    int mx, my;

    kmvc_init_getbits(bb, src);

    for (by = 0; by < h; by += 8)

        for (bx = 0; bx < w; bx += 8) {

            kmvc_getbit(bb, src, res);

            if (!res) {

                kmvc_getbit(bb, src, res);

                if (!res) {     // fill whole 8x8 block

                    val = *src++;

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

                        BLK(ctx->cur, bx + (i & 0x7), by + (i >> 3)) = val;

                } else {        // copy block from previous frame

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

                        BLK(ctx->cur, bx + (i & 0x7), by + (i >> 3)) =

                            BLK(ctx->prev, bx + (i & 0x7), by + (i >> 3));

                }

            } else {            // handle four 4x4 subblocks

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

                    l0x = bx + (i & 1) * 4;

                    l0y = by + (i & 2) * 2;

                    kmvc_getbit(bb, src, res);

                    if (!res) {

                        kmvc_getbit(bb, src, res);

                        if (!res) {     // fill whole 4x4 block

                            val = *src++;

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

                                BLK(ctx->cur, l0x + (j & 3), l0y + (j >> 2)) = val;

                        } else {        // copy block

                            val = *src++;

                            mx = (val & 0xF) - 8;

                            my = (val >> 4) - 8;

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

                                BLK(ctx->cur, l0x + (j & 3), l0y + (j >> 2)) =

                                    BLK(ctx->prev, l0x + (j & 3) + mx, l0y + (j >> 2) + my);

                        }

                    } else {    // descend to 2x2 sub-sub-blocks

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

                            l1x = l0x + (j & 1) * 2;

                            l1y = l0y + (j & 2);

                            kmvc_getbit(bb, src, res);

                            if (!res) {

                                kmvc_getbit(bb, src, res);

                                if (!res) {     // fill whole 2x2 block

                                    val = *src++;

                                    BLK(ctx->cur, l1x, l1y) = val;

                                    BLK(ctx->cur, l1x + 1, l1y) = val;

                                    BLK(ctx->cur, l1x, l1y + 1) = val;

                                    BLK(ctx->cur, l1x + 1, l1y + 1) = val;

                                } else {        // copy block

                                    val = *src++;

                                    mx = (val & 0xF) - 8;

                                    my = (val >> 4) - 8;

                                    BLK(ctx->cur, l1x, l1y) = BLK(ctx->prev, l1x + mx, l1y + my);

                                    BLK(ctx->cur, l1x + 1, l1y) =

                                        BLK(ctx->prev, l1x + 1 + mx, l1y + my);

                                    BLK(ctx->cur, l1x, l1y + 1) =

                                        BLK(ctx->prev, l1x + mx, l1y + 1 + my);

                                    BLK(ctx->cur, l1x + 1, l1y + 1) =

                                        BLK(ctx->prev, l1x + 1 + mx, l1y + 1 + my);

                                }

                            } else {    // read values for block

                                BLK(ctx->cur, l1x, l1y) = *src++;

                                BLK(ctx->cur, l1x + 1, l1y) = *src++;

                                BLK(ctx->cur, l1x, l1y + 1) = *src++;

                                BLK(ctx->cur, l1x + 1, l1y + 1) = *src++;

                            }

                        }

                    }

                }

            }

        }

}


static void tlb_flush_by_mmuidx_async_work(CPUState *cpu, run_on_cpu_data data)

{

    CPUArchState *env = cpu->env_ptr;

    unsigned long mmu_idx_bitmask = data.host_int;

    int mmu_idx;

    assert_cpu_is_self(cpu);

    tb_lock();

    tlb_debug("start: mmu_idx:0x%04lx\n", mmu_idx_bitmask);

    for (mmu_idx = 0; mmu_idx < NB_MMU_MODES; mmu_idx++) {

        if (test_bit(mmu_idx, &mmu_idx_bitmask)) {

            tlb_debug("%d\n", mmu_idx);

            memset(env->tlb_table[mmu_idx], -1, sizeof(env->tlb_table[0]));

            memset(env->tlb_v_table[mmu_idx], -1, sizeof(env->tlb_v_table[0]));

        }

    }

    memset(cpu->tb_jmp_cache, 0, sizeof(cpu->tb_jmp_cache));

    tlb_debug("done\n");

    tb_unlock();

}


static int encode_hq_slice(AVCodecContext *avctx, void *arg)

{

    SliceArgs *slice_dat = arg;

    VC2EncContext *s = slice_dat->ctx;

    PutBitContext *pb = &slice_dat->pb;

    const int slice_x = slice_dat->x;

    const int slice_y = slice_dat->y;

    const int quant_idx = slice_dat->quant_idx;

    const int slice_bytes_max = slice_dat->bytes;

    uint8_t quants[MAX_DWT_LEVELS][4];

    int p, level, orientation;

    /* The reference decoder ignores it, and its typical length is 0 */

    memset(put_bits_ptr(pb), 0, s->prefix_bytes);

    skip_put_bytes(pb, s->prefix_bytes);

    put_bits(pb, 8, quant_idx);

    /* Slice quantization (slice_quantizers() in the specs) */

    for (level = 0; level < s->wavelet_depth; level++)

        for (orientation = !!level; orientation < 4; orientation++)

            quants[level][orientation] = FFMAX(quant_idx - s->quant[level][orientation], 0);

    /* Luma + 2 Chroma planes */

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

        int bytes_start, bytes_len, pad_s, pad_c;

        bytes_start = put_bits_count(pb) >> 3;

        put_bits(pb, 8, 0);

        for (level = 0; level < s->wavelet_depth; level++) {

            for (orientation = !!level; orientation < 4; orientation++) {

                encode_subband(s, pb, slice_x, slice_y,

                               &s->plane[p].band[level][orientation],

                               quants[level][orientation]);

            }

        }

        avpriv_align_put_bits(pb);

        bytes_len = (put_bits_count(pb) >> 3) - bytes_start - 1;

        if (p == 2) {

            int len_diff = slice_bytes_max - (put_bits_count(pb) >> 3);

            pad_s = FFALIGN((bytes_len + len_diff), s->size_scaler)/s->size_scaler;

            pad_c = (pad_s*s->size_scaler) - bytes_len;

        } else {

            pad_s = FFALIGN(bytes_len, s->size_scaler)/s->size_scaler;

            pad_c = (pad_s*s->size_scaler) - bytes_len;

        }

        pb->buf[bytes_start] = pad_s;

        flush_put_bits(pb);

        skip_put_bytes(pb, pad_c);

    }

    return 0;

}


int ff_rtsp_setup_output_streams(AVFormatContext *s, const char *addr)

{

    RTSPState *rt = s->priv_data;

    RTSPMessageHeader reply1, *reply = &reply1;

    int i;

    char *sdp;

    AVFormatContext sdp_ctx, *ctx_array[1];

    s->start_time_realtime = av_gettime();

    /* Announce the stream */

    sdp = av_mallocz(SDP_MAX_SIZE);

    if (sdp == NULL)

        return AVERROR(ENOMEM);

    /* We create the SDP based on the RTSP AVFormatContext where we

     * aren't allowed to change the filename field. (We create the SDP

     * based on the RTSP context since the contexts for the RTP streams

     * don't exist yet.) In order to specify a custom URL with the actual

     * peer IP instead of the originally specified hostname, we create

     * a temporary copy of the AVFormatContext, where the custom URL is set.

     *

     * FIXME: Create the SDP without copying the AVFormatContext.

     * This either requires setting up the RTP stream AVFormatContexts

     * already here (complicating things immensely) or getting a more

     * flexible SDP creation interface.

     */

    sdp_ctx = *s;

    ff_url_join(sdp_ctx.filename, sizeof(sdp_ctx.filename),

                "rtsp", NULL, addr, -1, NULL);

    ctx_array[0] = &sdp_ctx;

    if (avf_sdp_create(ctx_array, 1, sdp, SDP_MAX_SIZE)) {

        av_free(sdp);

        return AVERROR_INVALIDDATA;

    }

    av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", sdp);

    ff_rtsp_send_cmd_with_content(s, "ANNOUNCE", rt->control_uri,

                                  "Content-Type: application/sdp\r\n",

                                  reply, NULL, sdp, strlen(sdp));

    av_free(sdp);

    if (reply->status_code != RTSP_STATUS_OK)

        return AVERROR_INVALIDDATA;

    /* Set up the RTSPStreams for each AVStream */

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

        RTSPStream *rtsp_st;

        AVStream *st = s->streams[i];

        rtsp_st = av_mallocz(sizeof(RTSPStream));

        if (!rtsp_st)

            return AVERROR(ENOMEM);

        dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);

        st->priv_data = rtsp_st;

        rtsp_st->stream_index = i;

        av_strlcpy(rtsp_st->control_url, rt->control_uri, sizeof(rtsp_st->control_url));

        /* Note, this must match the relative uri set in the sdp content */

        av_strlcatf(rtsp_st->control_url, sizeof(rtsp_st->control_url),

                    "/streamid=%d", i);

    }

    return 0;

}


static int smjpeg_read_packet(AVFormatContext *s, AVPacket *pkt)

{

    SMJPEGContext *sc = s->priv_data;

    uint32_t dtype, ret, size, timestamp;

    int64_t pos;

    if (s->pb->eof_reached)

        return AVERROR_EOF;

    pos   = avio_tell(s->pb);

    dtype = avio_rl32(s->pb);

    switch (dtype) {

    case SMJPEG_SNDD:

        timestamp = avio_rb32(s->pb);

        size = avio_rb32(s->pb);

        ret = av_get_packet(s->pb, pkt, size);

        pkt->stream_index = sc->audio_stream_index;

        pkt->pts = timestamp;

        pkt->pos = pos;

        break;

    case SMJPEG_VIDD:

        timestamp = avio_rb32(s->pb);

        size = avio_rb32(s->pb);

        ret = av_get_packet(s->pb, pkt, size);

        pkt->stream_index = sc->video_stream_index;

        pkt->pts = timestamp;

        pkt->pos = pos;

        break;

    case SMJPEG_DONE:

        ret = AVERROR_EOF;

        break;

    default:

        av_log(s, AV_LOG_ERROR, "unknown chunk %x\n", dtype);

        ret = AVERROR_INVALIDDATA;

        break;

    }

    return ret;

}


static void apic_mem_writeb(void *opaque, target_phys_addr_t addr, uint32_t val)

{

}


static void write_dt(void *ptr, unsigned long addr, unsigned long limit,

                     int flags)

{

    unsigned int e1, e2;

    uint32_t *p;

    e1 = (addr << 16) | (limit & 0xffff);

    e2 = ((addr >> 16) & 0xff) | (addr & 0xff000000) | (limit & 0x000f0000);

    e2 |= flags;

    p = ptr;

    p[0] = tswapl(e1);

    p[1] = tswapl(e2);

}


static int vdi_co_write(BlockDriverState *bs,

        int64_t sector_num, const uint8_t *buf, int nb_sectors)

{

    BDRVVdiState *s = bs->opaque;

    uint32_t bmap_entry;

    uint32_t block_index;

    uint32_t sector_in_block;

    uint32_t n_sectors;

    uint32_t bmap_first = VDI_UNALLOCATED;

    uint32_t bmap_last = VDI_UNALLOCATED;

    uint8_t *block = NULL;

    int ret;

    logout("\n");

restart:

    block_index = sector_num / s->block_sectors;

    sector_in_block = sector_num % s->block_sectors;

    n_sectors = s->block_sectors - sector_in_block;

    if (n_sectors > nb_sectors) {

        n_sectors = nb_sectors;

    }

    logout("will write %u sectors starting at sector %" PRIu64 "\n",

           n_sectors, sector_num);

    /* prepare next AIO request */

    bmap_entry = le32_to_cpu(s->bmap[block_index]);

    if (!VDI_IS_ALLOCATED(bmap_entry)) {

        /* Allocate new block and write to it. */

        uint64_t offset;

        bmap_entry = s->header.blocks_allocated;

        s->bmap[block_index] = cpu_to_le32(bmap_entry);

        s->header.blocks_allocated++;

        offset = s->header.offset_data / SECTOR_SIZE +

                 (uint64_t)bmap_entry * s->block_sectors;

        if (block == NULL) {

            block = g_malloc(s->block_size);

            bmap_first = block_index;

        }

        bmap_last = block_index;

        /* Copy data to be written to new block and zero unused parts. */

        memset(block, 0, sector_in_block * SECTOR_SIZE);

        memcpy(block + sector_in_block * SECTOR_SIZE,

               buf, n_sectors * SECTOR_SIZE);

        memset(block + (sector_in_block + n_sectors) * SECTOR_SIZE, 0,

               (s->block_sectors - n_sectors - sector_in_block) * SECTOR_SIZE);

        ret = bdrv_write(bs->file, offset, block, s->block_sectors);

    } else {

        uint64_t offset = s->header.offset_data / SECTOR_SIZE +

                          (uint64_t)bmap_entry * s->block_sectors +

                          sector_in_block;

        ret = bdrv_write(bs->file, offset, buf, n_sectors);

    }

    nb_sectors -= n_sectors;

    sector_num += n_sectors;

    buf += n_sectors * SECTOR_SIZE;

    logout("%u sectors written\n", n_sectors);

    if (ret >= 0 && nb_sectors > 0) {

        goto restart;

    }

    logout("finished data write\n");

    if (ret < 0) {

        return ret;

    }

    if (block) {

        /* One or more new blocks were allocated. */

        VdiHeader *header = (VdiHeader *) block;

        uint8_t *base;

        uint64_t offset;

        logout("now writing modified header\n");

        assert(VDI_IS_ALLOCATED(bmap_first));

        *header = s->header;

        vdi_header_to_le(header);

        ret = bdrv_write(bs->file, 0, block, 1);

        g_free(block);

        block = NULL;

        if (ret < 0) {

            return ret;

        }

        logout("now writing modified block map entry %u...%u\n",

               bmap_first, bmap_last);

        /* Write modified sectors from block map. */

        bmap_first /= (SECTOR_SIZE / sizeof(uint32_t));

        bmap_last /= (SECTOR_SIZE / sizeof(uint32_t));

        n_sectors = bmap_last - bmap_first + 1;

        offset = s->bmap_sector + bmap_first;

        base = ((uint8_t *)&s->bmap[0]) + bmap_first * SECTOR_SIZE;

        logout("will write %u block map sectors starting from entry %u\n",

               n_sectors, bmap_first);

        ret = bdrv_write(bs->file, offset, base, n_sectors);

    }

    return ret;

}


static void vga_screen_dump(void *opaque, const char *filename, bool cswitch,

                            Error **errp)

{

    VGACommonState *s = opaque;

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

    if (cswitch) {

        vga_invalidate_display(s);

    }

    graphic_hw_update(s->con);

    ppm_save(filename, surface, errp);

}


static uint64_t omap_tcmi_read(void *opaque, target_phys_addr_t addr,

                               unsigned size)

{

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

    uint32_t ret;

    if (size != 4) {

        return omap_badwidth_read32(opaque, addr);

    }

    switch (addr) {

    case 0x00:	/* IMIF_PRIO */

    case 0x04:	/* EMIFS_PRIO */

    case 0x08:	/* EMIFF_PRIO */

    case 0x0c:	/* EMIFS_CONFIG */

    case 0x10:	/* EMIFS_CS0_CONFIG */

    case 0x14:	/* EMIFS_CS1_CONFIG */

    case 0x18:	/* EMIFS_CS2_CONFIG */

    case 0x1c:	/* EMIFS_CS3_CONFIG */

    case 0x24:	/* EMIFF_MRS */

    case 0x28:	/* TIMEOUT1 */

    case 0x2c:	/* TIMEOUT2 */

    case 0x30:	/* TIMEOUT3 */

    case 0x3c:	/* EMIFF_SDRAM_CONFIG_2 */

    case 0x40:	/* EMIFS_CFG_DYN_WAIT */

        return s->tcmi_regs[addr >> 2];

    case 0x20:	/* EMIFF_SDRAM_CONFIG */

        ret = s->tcmi_regs[addr >> 2];

        s->tcmi_regs[addr >> 2] &= ~1; /* XXX: Clear SLRF on SDRAM access */

        /* XXX: We can try using the VGA_DIRTY flag for this */

        return ret;

    }

    OMAP_BAD_REG(addr);

    return 0;

}


static int vc1_decode_p_mb(VC1Context *v)

{

    MpegEncContext *s = &v->s;

    GetBitContext *gb = &s->gb;

    int i, j;

    int mb_pos = s->mb_x + s->mb_y * s->mb_stride;

    int cbp; /* cbp decoding stuff */

    int mqdiff, mquant; /* MB quantization */

    int ttmb = v->ttfrm; /* MB Transform type */

    int mb_has_coeffs = 1; /* last_flag */

    int dmv_x, dmv_y; /* Differential MV components */

    int index, index1; /* LUT indexes */

    int val, sign; /* temp values */

    int first_block = 1;

    int dst_idx, off;

    int skipped, fourmv;

    int block_cbp = 0, pat;

    int apply_loop_filter;

    mquant = v->pq; /* Loosy initialization */

    if (v->mv_type_is_raw)

        fourmv = get_bits1(gb);

    else

        fourmv = v->mv_type_mb_plane[mb_pos];

    if (v->skip_is_raw)

        skipped = get_bits1(gb);

    else

        skipped = v->s.mbskip_table[mb_pos];

    s->dsp.clear_blocks(s->block[0]);

    apply_loop_filter = s->loop_filter && !(s->avctx->skip_loop_filter >= AVDISCARD_NONKEY);

    if (!fourmv) /* 1MV mode */

    {

        if (!skipped)

        {

            GET_MVDATA(dmv_x, dmv_y);

            if (s->mb_intra) {

                s->current_picture.motion_val[1][s->block_index[0]][0] = 0;

                s->current_picture.motion_val[1][s->block_index[0]][1] = 0;

            }

            s->current_picture.mb_type[mb_pos] = s->mb_intra ? MB_TYPE_INTRA : MB_TYPE_16x16;

            vc1_pred_mv(s, 0, dmv_x, dmv_y, 1, v->range_x, v->range_y, v->mb_type[0]);

            /* FIXME Set DC val for inter block ? */

            if (s->mb_intra && !mb_has_coeffs)

            {

                GET_MQUANT();

                s->ac_pred = get_bits1(gb);

                cbp = 0;

            }

            else if (mb_has_coeffs)

            {

                if (s->mb_intra) s->ac_pred = get_bits1(gb);

                cbp = get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2);

                GET_MQUANT();

            }

            else

            {

                mquant = v->pq;

                cbp = 0;

            }

            s->current_picture.qscale_table[mb_pos] = mquant;

            if (!v->ttmbf && !s->mb_intra && mb_has_coeffs)

                ttmb = get_vlc2(gb, ff_vc1_ttmb_vlc[v->tt_index].table,

                                VC1_TTMB_VLC_BITS, 2);

            if(!s->mb_intra) vc1_mc_1mv(v, 0);

            dst_idx = 0;

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

            {

                s->dc_val[0][s->block_index[i]] = 0;

                dst_idx += i >> 2;

                val = ((cbp >> (5 - i)) & 1);

                off = (i & 4) ? 0 : ((i & 1) * 8 + (i & 2) * 4 * s->linesize);

                v->mb_type[0][s->block_index[i]] = s->mb_intra;

                if(s->mb_intra) {

                    /* check if prediction blocks A and C are available */

                    v->a_avail = v->c_avail = 0;

                    if(i == 2 || i == 3 || !s->first_slice_line)

                        v->a_avail = v->mb_type[0][s->block_index[i] - s->block_wrap[i]];

                    if(i == 1 || i == 3 || s->mb_x)

                        v->c_avail = v->mb_type[0][s->block_index[i] - 1];

                    vc1_decode_intra_block(v, s->block[i], i, val, mquant, (i&4)?v->codingset2:v->codingset);

                    if((i>3) && (s->flags & CODEC_FLAG_GRAY)) continue;

                    s->dsp.vc1_inv_trans_8x8(s->block[i]);

                    if(v->rangeredfrm) for(j = 0; j < 64; j++) s->block[i][j] <<= 1;

                    s->dsp.put_signed_pixels_clamped(s->block[i], s->dest[dst_idx] + off, s->linesize >> ((i & 4) >> 2));

                    if(v->pq >= 9 && v->overlap) {

                        if(v->c_avail)

                            s->dsp.vc1_h_overlap(s->dest[dst_idx] + off, s->linesize >> ((i & 4) >> 2));

                        if(v->a_avail)

                            s->dsp.vc1_v_overlap(s->dest[dst_idx] + off, s->linesize >> ((i & 4) >> 2));

                    }

                    if(apply_loop_filter && s->mb_x && s->mb_x != (s->mb_width - 1) && s->mb_y && s->mb_y != (s->mb_height - 1)){

                        int left_cbp, top_cbp;

                        if(i & 4){

                            left_cbp = v->cbp[s->mb_x - 1]            >> (i * 4);

                            top_cbp  = v->cbp[s->mb_x - s->mb_stride] >> (i * 4);

                        }else{

                            left_cbp = (i & 1) ? (cbp >> ((i-1)*4)) : (v->cbp[s->mb_x - 1]           >> ((i+1)*4));

                            top_cbp  = (i & 2) ? (cbp >> ((i-2)*4)) : (v->cbp[s->mb_x - s->mb_stride] >> ((i+2)*4));

                        }

                        if(left_cbp & 0xC)

                            s->dsp.vc1_loop_filter(s->dest[dst_idx] + off, 1, i & 4 ? s->uvlinesize : s->linesize, 8, mquant);

                        if(top_cbp  & 0xA)

                            s->dsp.vc1_loop_filter(s->dest[dst_idx] + off, i & 4 ? s->uvlinesize : s->linesize, 1, 8, mquant);

                    }

                    block_cbp |= 0xF << (i << 2);

                } else if(val) {

                    int left_cbp = 0, top_cbp = 0, filter = 0;

                    if(apply_loop_filter && s->mb_x && s->mb_x != (s->mb_width - 1) && s->mb_y && s->mb_y != (s->mb_height - 1)){

                        filter = 1;

                        if(i & 4){

                            left_cbp = v->cbp[s->mb_x - 1]            >> (i * 4);

                            top_cbp  = v->cbp[s->mb_x - s->mb_stride] >> (i * 4);

                        }else{

                            left_cbp = (i & 1) ? (cbp >> ((i-1)*4)) : (v->cbp[s->mb_x - 1]           >> ((i+1)*4));

                            top_cbp  = (i & 2) ? (cbp >> ((i-2)*4)) : (v->cbp[s->mb_x - s->mb_stride] >> ((i+2)*4));

                        }

                        if(left_cbp & 0xC)

                            s->dsp.vc1_loop_filter(s->dest[dst_idx] + off, 1, i & 4 ? s->uvlinesize : s->linesize, 8, mquant);

                        if(top_cbp  & 0xA)

                            s->dsp.vc1_loop_filter(s->dest[dst_idx] + off, i & 4 ? s->uvlinesize : s->linesize, 1, 8, mquant);

                    }

                    pat = vc1_decode_p_block(v, s->block[i], i, mquant, ttmb, first_block, s->dest[dst_idx] + off, (i&4)?s->uvlinesize:s->linesize, (i&4) && (s->flags & CODEC_FLAG_GRAY), filter, left_cbp, top_cbp);

                    block_cbp |= pat << (i << 2);

                    if(!v->ttmbf && ttmb < 8) ttmb = -1;

                    first_block = 0;

                }

            }

        }

        else //Skipped

        {

            s->mb_intra = 0;

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

                v->mb_type[0][s->block_index[i]] = 0;

                s->dc_val[0][s->block_index[i]] = 0;

            }

            s->current_picture.mb_type[mb_pos] = MB_TYPE_SKIP;

            s->current_picture.qscale_table[mb_pos] = 0;

            vc1_pred_mv(s, 0, 0, 0, 1, v->range_x, v->range_y, v->mb_type[0]);

            vc1_mc_1mv(v, 0);

            return 0;

        }

    } //1MV mode

    else //4MV mode

    {

        if (!skipped /* unskipped MB */)

        {

            int intra_count = 0, coded_inter = 0;

            int is_intra[6], is_coded[6];

            /* Get CBPCY */

            cbp = get_vlc2(&v->s.gb, v->cbpcy_vlc->table, VC1_CBPCY_P_VLC_BITS, 2);

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

            {

                val = ((cbp >> (5 - i)) & 1);

                s->dc_val[0][s->block_index[i]] = 0;

                s->mb_intra = 0;

                if(i < 4) {

                    dmv_x = dmv_y = 0;

                    s->mb_intra = 0;

                    mb_has_coeffs = 0;

                    if(val) {

                        GET_MVDATA(dmv_x, dmv_y);

                    }

                    vc1_pred_mv(s, i, dmv_x, dmv_y, 0, v->range_x, v->range_y, v->mb_type[0]);

                    if(!s->mb_intra) vc1_mc_4mv_luma(v, i);

                    intra_count += s->mb_intra;

                    is_intra[i] = s->mb_intra;

                    is_coded[i] = mb_has_coeffs;

                }

                if(i&4){

                    is_intra[i] = (intra_count >= 3);

                    is_coded[i] = val;

                }

                if(i == 4) vc1_mc_4mv_chroma(v);

                v->mb_type[0][s->block_index[i]] = is_intra[i];

                if(!coded_inter) coded_inter = !is_intra[i] & is_coded[i];

            }

            // if there are no coded blocks then don't do anything more

            if(!intra_count && !coded_inter) return 0;

            dst_idx = 0;

            GET_MQUANT();

            s->current_picture.qscale_table[mb_pos] = mquant;

            /* test if block is intra and has pred */

            {

                int intrapred = 0;

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

                    if(is_intra[i]) {

                        if(((!s->first_slice_line || (i==2 || i==3)) && v->mb_type[0][s->block_index[i] - s->block_wrap[i]])

                            || ((s->mb_x || (i==1 || i==3)) && v->mb_type[0][s->block_index[i] - 1])) {

                            intrapred = 1;

                            break;

                        }

                    }

                if(intrapred)s->ac_pred = get_bits1(gb);

                else s->ac_pred = 0;

            }

            if (!v->ttmbf && coded_inter)

                ttmb = get_vlc2(gb, ff_vc1_ttmb_vlc[v->tt_index].table, VC1_TTMB_VLC_BITS, 2);

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

            {

                dst_idx += i >> 2;

                off = (i & 4) ? 0 : ((i & 1) * 8 + (i & 2) * 4 * s->linesize);

                s->mb_intra = is_intra[i];

                if (is_intra[i]) {

                    /* check if prediction blocks A and C are available */

                    v->a_avail = v->c_avail = 0;

                    if(i == 2 || i == 3 || !s->first_slice_line)

                        v->a_avail = v->mb_type[0][s->block_index[i] - s->block_wrap[i]];

                    if(i == 1 || i == 3 || s->mb_x)

                        v->c_avail = v->mb_type[0][s->block_index[i] - 1];

                    vc1_decode_intra_block(v, s->block[i], i, is_coded[i], mquant, (i&4)?v->codingset2:v->codingset);

                    if((i>3) && (s->flags & CODEC_FLAG_GRAY)) continue;

                    s->dsp.vc1_inv_trans_8x8(s->block[i]);

                    if(v->rangeredfrm) for(j = 0; j < 64; j++) s->block[i][j] <<= 1;

                    s->dsp.put_signed_pixels_clamped(s->block[i], s->dest[dst_idx] + off, (i&4)?s->uvlinesize:s->linesize);

                    if(v->pq >= 9 && v->overlap) {

                        if(v->c_avail)

                            s->dsp.vc1_h_overlap(s->dest[dst_idx] + off, s->linesize >> ((i & 4) >> 2));

                        if(v->a_avail)

                            s->dsp.vc1_v_overlap(s->dest[dst_idx] + off, s->linesize >> ((i & 4) >> 2));

                    }

                    if(v->s.loop_filter && s->mb_x && s->mb_x != (s->mb_width - 1) && s->mb_y && s->mb_y != (s->mb_height - 1)){

                        int left_cbp, top_cbp;

                        if(i & 4){

                            left_cbp = v->cbp[s->mb_x - 1]            >> (i * 4);

                            top_cbp  = v->cbp[s->mb_x - s->mb_stride] >> (i * 4);

                        }else{

                            left_cbp = (i & 1) ? (cbp >> ((i-1)*4)) : (v->cbp[s->mb_x - 1]           >> ((i+1)*4));

                            top_cbp  = (i & 2) ? (cbp >> ((i-2)*4)) : (v->cbp[s->mb_x - s->mb_stride] >> ((i+2)*4));

                        }

                        if(left_cbp & 0xC)

                            s->dsp.vc1_loop_filter(s->dest[dst_idx] + off, 1, i & 4 ? s->uvlinesize : s->linesize, 8, mquant);

                        if(top_cbp  & 0xA)

                            s->dsp.vc1_loop_filter(s->dest[dst_idx] + off, i & 4 ? s->uvlinesize : s->linesize, 1, 8, mquant);

                    }

                    block_cbp |= 0xF << (i << 2);

                } else if(is_coded[i]) {

                    int left_cbp = 0, top_cbp = 0, filter = 0;

                    if(v->s.loop_filter && s->mb_x && s->mb_x != (s->mb_width - 1) && s->mb_y && s->mb_y != (s->mb_height - 1)){

                        filter = 1;

                        if(i & 4){

                            left_cbp = v->cbp[s->mb_x - 1]            >> (i * 4);

                            top_cbp  = v->cbp[s->mb_x - s->mb_stride] >> (i * 4);

                        }else{

                            left_cbp = (i & 1) ? (cbp >> ((i-1)*4)) : (v->cbp[s->mb_x - 1]           >> ((i+1)*4));

                            top_cbp  = (i & 2) ? (cbp >> ((i-2)*4)) : (v->cbp[s->mb_x - s->mb_stride] >> ((i+2)*4));

                        }

                        if(left_cbp & 0xC)

                            s->dsp.vc1_loop_filter(s->dest[dst_idx] + off, 1, i & 4 ? s->uvlinesize : s->linesize, 8, mquant);

                        if(top_cbp  & 0xA)

                            s->dsp.vc1_loop_filter(s->dest[dst_idx] + off, i & 4 ? s->uvlinesize : s->linesize, 1, 8, mquant);

                    }

                    pat = vc1_decode_p_block(v, s->block[i], i, mquant, ttmb, first_block, s->dest[dst_idx] + off, (i&4)?s->uvlinesize:s->linesize, (i&4) && (s->flags & CODEC_FLAG_GRAY), filter, left_cbp, top_cbp);

                    block_cbp |= pat << (i << 2);

                    if(!v->ttmbf && ttmb < 8) ttmb = -1;

                    first_block = 0;

                }

            }

            return 0;

        }

        else //Skipped MB

        {

            s->mb_intra = 0;

            s->current_picture.qscale_table[mb_pos] = 0;

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

                v->mb_type[0][s->block_index[i]] = 0;

                s->dc_val[0][s->block_index[i]] = 0;

            }

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

            {

                vc1_pred_mv(s, i, 0, 0, 0, v->range_x, v->range_y, v->mb_type[0]);

                vc1_mc_4mv_luma(v, i);

            }

            vc1_mc_4mv_chroma(v);

            s->current_picture.qscale_table[mb_pos] = 0;

            return 0;

        }

    }

    v->cbp[s->mb_x] = block_cbp;

    /* Should never happen */

    return -1;

}


static void s390_pcihost_init_as(S390pciState *s)

{

    int i;

    S390PCIBusDevice *pbdev;

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

        pbdev = &s->pbdev[i];

        memory_region_init(&pbdev->mr, OBJECT(s),

                           "iommu-root-s390", UINT64_MAX);

        address_space_init(&pbdev->as, &pbdev->mr, "iommu-pci");

    }

    memory_region_init_io(&s->msix_notify_mr, OBJECT(s),

                          &s390_msi_ctrl_ops, s, "msix-s390", UINT64_MAX);

    address_space_init(&s->msix_notify_as, &s->msix_notify_mr, "msix-pci");

}


static uint64_t tmu2_read(void *opaque, target_phys_addr_t addr,

                          unsigned size)

{

    MilkymistTMU2State *s = opaque;

    uint32_t r = 0;

    addr >>= 2;

    switch (addr) {

    case R_CTL:

    case R_HMESHLAST:

    case R_VMESHLAST:

    case R_BRIGHTNESS:

    case R_CHROMAKEY:

    case R_VERTICESADDR:

    case R_TEXFBUF:

    case R_TEXHRES:

    case R_TEXVRES:

    case R_TEXHMASK:

    case R_TEXVMASK:

    case R_DSTFBUF:

    case R_DSTHRES:

    case R_DSTVRES:

    case R_DSTHOFFSET:

    case R_DSTVOFFSET:

    case R_DSTSQUAREW:

    case R_DSTSQUAREH:

    case R_ALPHA:

        r = s->regs[addr];

        break;

    default:

        error_report("milkymist_tmu2: read access to unknown register 0x"

                TARGET_FMT_plx, addr << 2);

        break;

    }

    trace_milkymist_tmu2_memory_read(addr << 2, r);

    return r;

}


static void icount_adjust_vm(void *opaque)

{

    timer_mod(icount_vm_timer,

                   qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +

                   NANOSECONDS_PER_SECOND / 10);

    icount_adjust();

}


static int qcow_is_allocated(BlockDriverState *bs, int64_t sector_num,

                             int nb_sectors, int *pnum)

{

    BDRVQcowState *s = bs->opaque;

    int index_in_cluster, n;

    uint64_t cluster_offset;

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

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

    n = s->cluster_sectors - index_in_cluster;

    if (n > nb_sectors)

        n = nb_sectors;

    *pnum = n;

    return (cluster_offset != 0);

}


static uint64_t mv88w8618_eth_read(void *opaque, target_phys_addr_t offset,

                                   unsigned size)

{

    mv88w8618_eth_state *s = opaque;

    switch (offset) {

    case MP_ETH_SMIR:

        if (s->smir & MP_ETH_SMIR_OPCODE) {

            switch (s->smir & MP_ETH_SMIR_ADDR) {

            case MP_ETH_PHY1_BMSR:

                return MP_PHY_BMSR_LINK | MP_PHY_BMSR_AUTONEG |

                       MP_ETH_SMIR_RDVALID;

            case MP_ETH_PHY1_PHYSID1:

                return (MP_PHY_88E3015 >> 16) | MP_ETH_SMIR_RDVALID;

            case MP_ETH_PHY1_PHYSID2:

                return (MP_PHY_88E3015 & 0xFFFF) | MP_ETH_SMIR_RDVALID;

            default:

                return MP_ETH_SMIR_RDVALID;

            }

        }

        return 0;

    case MP_ETH_ICR:

        return s->icr;

    case MP_ETH_IMR:

        return s->imr;

    case MP_ETH_FRDP0 ... MP_ETH_FRDP3:

        return s->frx_queue[(offset - MP_ETH_FRDP0)/4];

    case MP_ETH_CRDP0 ... MP_ETH_CRDP3:

        return s->rx_queue[(offset - MP_ETH_CRDP0)/4];

    case MP_ETH_CTDP0 ... MP_ETH_CTDP3:

        return s->tx_queue[(offset - MP_ETH_CTDP0)/4];

    default:

        return 0;

    }

}


static void blockdev_backup_prepare(BlkActionState *common, Error **errp)

{

    BlockdevBackupState *state = DO_UPCAST(BlockdevBackupState, common, common);

    BlockdevBackup *backup;

    BlockBackend *blk, *target;

    Error *local_err = NULL;

    assert(common->action->type == TRANSACTION_ACTION_KIND_BLOCKDEV_BACKUP);

    backup = common->action->u.blockdev_backup;

    blk = blk_by_name(backup->device);

    if (!blk) {

        error_setg(errp, "Device '%s' not found", backup->device);

        return;

    }

    if (!blk_is_available(blk)) {

        error_setg(errp, QERR_DEVICE_HAS_NO_MEDIUM, backup->device);

        return;

    }

    target = blk_by_name(backup->target);

    if (!target) {

        error_setg(errp, "Device '%s' not found", backup->target);

        return;

    }

    /* AioContext is released in .clean() */

    state->aio_context = blk_get_aio_context(blk);

    if (state->aio_context != blk_get_aio_context(target)) {

        state->aio_context = NULL;

        error_setg(errp, "Backup between two IO threads is not implemented");

        return;

    }

    aio_context_acquire(state->aio_context);

    state->bs = blk_bs(blk);

    bdrv_drained_begin(state->bs);

    do_blockdev_backup(backup->device, backup->target,

                       backup->sync,

                       backup->has_speed, backup->speed,

                       backup->has_on_source_error, backup->on_source_error,

                       backup->has_on_target_error, backup->on_target_error,

                       common->block_job_txn, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        return;

    }

    state->job = state->bs->job;

}


static ExitStatus gen_call_pal(DisasContext *ctx, int palcode)

{

    /* We're emulating OSF/1 PALcode.  Many of these are trivial access

       to internal cpu registers.  */

    /* Unprivileged PAL call */

    if (palcode >= 0x80 && palcode < 0xC0) {

        switch (palcode) {

        case 0x86:

            /* IMB */

            /* No-op inside QEMU.  */

            break;

        case 0x9E:

            /* RDUNIQUE */

            tcg_gen_mov_i64(cpu_ir[IR_V0], cpu_unique);

            break;

        case 0x9F:

            /* WRUNIQUE */

            tcg_gen_mov_i64(cpu_unique, cpu_ir[IR_A0]);

            break;

        default:

            return gen_excp(ctx, EXCP_CALL_PAL, palcode & 0xbf);

        }

        return NO_EXIT;

    }

#ifndef CONFIG_USER_ONLY

    /* Privileged PAL code */

    if (palcode < 0x40 && (ctx->tb->flags & TB_FLAGS_USER_MODE) == 0) {

        switch (palcode) {

        case 0x01:

            /* CFLUSH */

            /* No-op inside QEMU.  */

            break;

        case 0x02:

            /* DRAINA */

            /* No-op inside QEMU.  */

            break;

        case 0x2D:

            /* WRVPTPTR */

            tcg_gen_st_i64(cpu_ir[IR_A0], cpu_env, offsetof(CPUAlphaState, vptptr));

            break;

        case 0x31:

            /* WRVAL */

            tcg_gen_mov_i64(cpu_sysval, cpu_ir[IR_A0]);

            break;

        case 0x32:

            /* RDVAL */

            tcg_gen_mov_i64(cpu_ir[IR_V0], cpu_sysval);

            break;

        case 0x35: {

            /* SWPIPL */

            TCGv tmp;

            /* Note that we already know we're in kernel mode, so we know

               that PS only contains the 3 IPL bits.  */

            tcg_gen_ld8u_i64(cpu_ir[IR_V0], cpu_env, offsetof(CPUAlphaState, ps));

            /* But make sure and store only the 3 IPL bits from the user.  */

            tmp = tcg_temp_new();

            tcg_gen_andi_i64(tmp, cpu_ir[IR_A0], PS_INT_MASK);

            tcg_gen_st8_i64(tmp, cpu_env, offsetof(CPUAlphaState, ps));

            tcg_temp_free(tmp);

            break;

        }

        case 0x36:

            /* RDPS */

            tcg_gen_ld8u_i64(cpu_ir[IR_V0], cpu_env, offsetof(CPUAlphaState, ps));

            break;

        case 0x38:

            /* WRUSP */

            tcg_gen_mov_i64(cpu_usp, cpu_ir[IR_A0]);

            break;

        case 0x3A:

            /* RDUSP */

            tcg_gen_mov_i64(cpu_ir[IR_V0], cpu_usp);

            break;

        case 0x3C:

            /* WHAMI */

            tcg_gen_ld32s_i64(cpu_ir[IR_V0], cpu_env,

                -offsetof(AlphaCPU, env) + offsetof(CPUState, cpu_index));

            break;

        default:

            return gen_excp(ctx, EXCP_CALL_PAL, palcode & 0x3f);

        }

        return NO_EXIT;

    }

#endif

    return gen_invalid(ctx);

}


static void tcg_out_ri32(TCGContext *s, int const_arg, TCGArg arg)

{

    if (const_arg) {

        assert(const_arg == 1);

        tcg_out8(s, TCG_CONST);

        tcg_out32(s, arg);

    } else {

        tcg_out_r(s, arg);

    }

}


static int qsort_strcmp(const void *a, const void *b)

{

    return strcmp(a, b);

}


static uint32_t mb_add_cmdline(MultibootState *s, const char *cmdline)

{

    target_phys_addr_t p = s->offset_cmdlines;

    char *b = (char *)s->mb_buf + p;

    get_opt_value(b, strlen(cmdline) + 1, cmdline);

    s->offset_cmdlines += strlen(b) + 1;

    return s->mb_buf_phys + p;

}


static void RENAME(yuv2yuv1)(SwsContext *c, const int16_t *lumSrc,

                             const int16_t *chrUSrc, const int16_t *chrVSrc,

                             const int16_t *alpSrc,

                             uint8_t *dest, uint8_t *uDest, uint8_t *vDest,

                             uint8_t *aDest, int dstW, int chrDstW)

{

    int p= 4;

    const int16_t *src[4]= { alpSrc + dstW, lumSrc + dstW, chrUSrc + chrDstW, chrVSrc + chrDstW };

    uint8_t *dst[4]= { aDest, dest, uDest, vDest };

    x86_reg counter[4]= { dstW, dstW, chrDstW, chrDstW };

    while (p--) {

        if (dst[p]) {

            __asm__ volatile(

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

                ".p2align               4             \n\t" /* FIXME Unroll? */

                "1:                                   \n\t"

                "movq  (%0, %%"REG_a", 2), %%mm0      \n\t"

                "movq 8(%0, %%"REG_a", 2), %%mm1      \n\t"

                "psraw                 $7, %%mm0      \n\t"

                "psraw                 $7, %%mm1      \n\t"

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

                MOVNTQ(%%mm0, (%1, %%REGa))

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

                "jnc                   1b             \n\t"

                :: "r" (src[p]), "r" (dst[p] + counter[p]),

                   "g" (-counter[p])

                : "%"REG_a

            );

        }

    }

}


static int vp3_decode_frame(AVCodecContext *avctx,

                            void *data, int *data_size,

                            const uint8_t *buf, int buf_size)

{

    Vp3DecodeContext *s = avctx->priv_data;

    GetBitContext gb;

    static int counter = 0;

    int i;

    init_get_bits(&gb, buf, buf_size * 8);

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

    {

        av_log(avctx, AV_LOG_ERROR, "Header packet passed to frame decoder, skipping\n");

        return -1;

    }

    s->keyframe = !get_bits1(&gb);

    if (!s->theora)

        skip_bits(&gb, 1);

    s->last_quality_index = s->quality_index;

    s->nqis=0;

    do{

        s->qis[s->nqis++]= get_bits(&gb, 6);

    } while(s->theora >= 0x030200 && s->nqis<3 && get_bits1(&gb));

    s->quality_index= s->qis[0];

    if (s->avctx->debug & FF_DEBUG_PICT_INFO)

        av_log(s->avctx, AV_LOG_INFO, " VP3 %sframe #%d: Q index = %d\n",

            s->keyframe?"key":"", counter, s->quality_index);

    counter++;

    if (s->quality_index != s->last_quality_index) {

        init_dequantizer(s);

        init_loop_filter(s);

    }

    if (s->keyframe) {

        if (!s->theora)

        {

            skip_bits(&gb, 4); /* width code */

            skip_bits(&gb, 4); /* height code */

            if (s->version)

            {

                s->version = get_bits(&gb, 5);

                if (counter == 1)

                    av_log(s->avctx, AV_LOG_DEBUG, "VP version: %d\n", s->version);

            }

        }

        if (s->version || s->theora)

        {

                if (get_bits1(&gb))

                    av_log(s->avctx, AV_LOG_ERROR, "Warning, unsupported keyframe coding type?!\n");

            skip_bits(&gb, 2); /* reserved? */

        }

        if (s->last_frame.data[0] == s->golden_frame.data[0]) {

            if (s->golden_frame.data[0])

                avctx->release_buffer(avctx, &s->golden_frame);

            s->last_frame= s->golden_frame; /* ensure that we catch any access to this released frame */

        } else {

            if (s->golden_frame.data[0])

                avctx->release_buffer(avctx, &s->golden_frame);

            if (s->last_frame.data[0])

                avctx->release_buffer(avctx, &s->last_frame);

        }

        s->golden_frame.reference = 3;

        if(avctx->get_buffer(avctx, &s->golden_frame) < 0) {

            av_log(s->avctx, AV_LOG_ERROR, "vp3: get_buffer() failed\n");

            return -1;

        }

        /* golden frame is also the current frame */

        s->current_frame= s->golden_frame;

        /* time to figure out pixel addresses? */

        if (!s->pixel_addresses_inited)

        {

            if (!s->flipped_image)

                vp3_calculate_pixel_addresses(s);

            else

                theora_calculate_pixel_addresses(s);

            s->pixel_addresses_inited = 1;

        }

    } else {

        /* allocate a new current frame */

        s->current_frame.reference = 3;

        if (!s->pixel_addresses_inited) {

            av_log(s->avctx, AV_LOG_ERROR, "vp3: first frame not a keyframe\n");

            return -1;

        }

        if(avctx->get_buffer(avctx, &s->current_frame) < 0) {

            av_log(s->avctx, AV_LOG_ERROR, "vp3: get_buffer() failed\n");

            return -1;

        }

    }

    s->current_frame.qscale_table= s->qscale_table; //FIXME allocate individual tables per AVFrame

    s->current_frame.qstride= 0;

    {START_TIMER

    init_frame(s, &gb);

    STOP_TIMER("init_frame")}

#if KEYFRAMES_ONLY

if (!s->keyframe) {

    memcpy(s->current_frame.data[0], s->golden_frame.data[0],

        s->current_frame.linesize[0] * s->height);

    memcpy(s->current_frame.data[1], s->golden_frame.data[1],

        s->current_frame.linesize[1] * s->height / 2);

    memcpy(s->current_frame.data[2], s->golden_frame.data[2],

        s->current_frame.linesize[2] * s->height / 2);

} else {

#endif

    {START_TIMER

    if (unpack_superblocks(s, &gb)){

        av_log(s->avctx, AV_LOG_ERROR, "error in unpack_superblocks\n");

        return -1;

    }

    STOP_TIMER("unpack_superblocks")}

    {START_TIMER

    if (unpack_modes(s, &gb)){

        av_log(s->avctx, AV_LOG_ERROR, "error in unpack_modes\n");

        return -1;

    }

    STOP_TIMER("unpack_modes")}

    {START_TIMER

    if (unpack_vectors(s, &gb)){

        av_log(s->avctx, AV_LOG_ERROR, "error in unpack_vectors\n");

        return -1;

    }

    STOP_TIMER("unpack_vectors")}

    {START_TIMER

    if (unpack_dct_coeffs(s, &gb)){

        av_log(s->avctx, AV_LOG_ERROR, "error in unpack_dct_coeffs\n");

        return -1;

    }

    STOP_TIMER("unpack_dct_coeffs")}

    {START_TIMER

    reverse_dc_prediction(s, 0, s->fragment_width, s->fragment_height);

    if ((avctx->flags & CODEC_FLAG_GRAY) == 0) {

        reverse_dc_prediction(s, s->fragment_start[1],

            s->fragment_width / 2, s->fragment_height / 2);

        reverse_dc_prediction(s, s->fragment_start[2],

            s->fragment_width / 2, s->fragment_height / 2);

    }

    STOP_TIMER("reverse_dc_prediction")}

    {START_TIMER

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

        render_slice(s, i);

    STOP_TIMER("render_fragments")}

    {START_TIMER

    apply_loop_filter(s);

    STOP_TIMER("apply_loop_filter")}

#if KEYFRAMES_ONLY

}

#endif

    *data_size=sizeof(AVFrame);

    *(AVFrame*)data= s->current_frame;

    /* release the last frame, if it is allocated and if it is not the

     * golden frame */

    if ((s->last_frame.data[0]) &&

        (s->last_frame.data[0] != s->golden_frame.data[0]))

        avctx->release_buffer(avctx, &s->last_frame);

    /* shuffle frames (last = current) */

    s->last_frame= s->current_frame;

    s->current_frame.data[0]= NULL; /* ensure that we catch any access to this released frame */

    return buf_size;

}


static char *ts_value_string (char *buf, int buf_size, int64_t ts)

{

    if (ts == AV_NOPTS_VALUE) {

        snprintf(buf, buf_size, "N/A");

    } else {

        snprintf(buf, buf_size, "%"PRId64, ts);

    }

    return buf;

}


void pci_ne2000_init(PCIBus *bus, NICInfo *nd)

{

    PCINE2000State *d;

    NE2000State *s;

    uint8_t *pci_conf;

    d = (PCINE2000State *)pci_register_device(bus,

                                              "NE2000", sizeof(PCINE2000State),

                                              -1,

                                              NULL, NULL);

    pci_conf = d->dev.config;

    pci_conf[0x00] = 0xec; // Realtek 8029

    pci_conf[0x01] = 0x10;

    pci_conf[0x02] = 0x29;

    pci_conf[0x03] = 0x80;

    pci_conf[0x0a] = 0x00; // ethernet network controller

    pci_conf[0x0b] = 0x02;

    pci_conf[0x0e] = 0x00; // header_type

    pci_conf[0x3d] = 1; // interrupt pin 0

    pci_register_io_region(&d->dev, 0, 0x100,

                           PCI_ADDRESS_SPACE_IO, ne2000_map);

    s = &d->ne2000;

    s->irq = 16; // PCI interrupt

    s->pci_dev = (PCIDevice *)d;

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

    ne2000_reset(s);

    s->vc = qemu_new_vlan_client(nd->vlan, ne2000_receive, s);

    snprintf(s->vc->info_str, sizeof(s->vc->info_str),

             "ne2000 pci macaddr=%02x:%02x:%02x:%02x:%02x:%02x",

             s->macaddr[0],

             s->macaddr[1],

             s->macaddr[2],

             s->macaddr[3],

             s->macaddr[4],

             s->macaddr[5]);

    /* XXX: instance number ? */

    register_savevm("ne2000", 0, 2, ne2000_save, ne2000_load, s);

    register_savevm("ne2000_pci", 0, 1, generic_pci_save, generic_pci_load,

                    &d->dev);

}


static int decode_bdlt(uint8_t *frame, int width, int height,

                       const uint8_t *src, const uint8_t *src_end)

{

    const uint8_t *frame_end = frame + width * height;

    uint8_t *line_ptr;

    int count, lines, segments;

    count = bytestream_get_le16(&src);

    if (count >= height || width * count < 0)

        return -1;

    frame += width * count;

    lines = bytestream_get_le16(&src);

    if (frame + lines * width > frame_end || src >= src_end)

        return -1;

    while (lines--) {

        line_ptr = frame;

        frame += width;

        segments = *src++;

        while (segments--) {

            if (src_end - src < 3)

                return -1;

            line_ptr += *src++;

            if (line_ptr >= frame)

                return -1;

            count = (int8_t)*src++;

            if (count >= 0) {

                if (line_ptr + count > frame || src_end - src < count)

                    return -1;

                bytestream_get_buffer(&src, line_ptr, count);

            } else {

                count = -count;

                if (line_ptr + count > frame || src >= src_end)

                    return -1;

                memset(line_ptr, *src++, count);

            }

            line_ptr += count;

        }

    }

    return 0;

}


gdb_handlesig (CPUState *env, int sig)

{

  GDBState *s;

  char buf[256];

  int n;

  s = gdbserver_state;

  if (gdbserver_fd < 0 || s->fd < 0)

    return sig;

  /* disable single step if it was enabled */

  cpu_single_step(env, 0);

  tb_flush(env);

  if (sig != 0)

    {

      snprintf(buf, sizeof(buf), "S%02x", target_signal_to_gdb (sig));

      put_packet(s, buf);

    }

  /* put_packet() might have detected that the peer terminated the

     connection.  */

  if (s->fd < 0)

      return sig;

  sig = 0;

  s->state = RS_IDLE;

  s->running_state = 0;

  while (s->running_state == 0) {

      n = read (s->fd, buf, 256);

      if (n > 0)

        {

          int i;

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

            gdb_read_byte (s, buf[i]);

        }

      else if (n == 0 || errno != EAGAIN)

        {

          /* XXX: Connection closed.  Should probably wait for annother

             connection before continuing.  */

          return sig;

        }

  }

  sig = s->signal;

  s->signal = 0;

  return sig;

}


int spapr_h_cas_compose_response(target_ulong addr, target_ulong size)

{

    void *fdt, *fdt_skel;

    sPAPRDeviceTreeUpdateHeader hdr = { .version_id = 1 };

    size -= sizeof(hdr);

    /* Create sceleton */

    fdt_skel = g_malloc0(size);

    _FDT((fdt_create(fdt_skel, size)));

    _FDT((fdt_begin_node(fdt_skel, "")));

    _FDT((fdt_end_node(fdt_skel)));

    _FDT((fdt_finish(fdt_skel)));

    fdt = g_malloc0(size);

    _FDT((fdt_open_into(fdt_skel, fdt, size)));

    g_free(fdt_skel);

    /* Place to make changes to the tree */

    /* Pack resulting tree */

    _FDT((fdt_pack(fdt)));

    if (fdt_totalsize(fdt) + sizeof(hdr) > size) {

        trace_spapr_cas_failed(size);

        return -1;

    }

    cpu_physical_memory_write(addr, &hdr, sizeof(hdr));

    cpu_physical_memory_write(addr + sizeof(hdr), fdt, fdt_totalsize(fdt));

    trace_spapr_cas_continue(fdt_totalsize(fdt) + sizeof(hdr));

    g_free(fdt);

    return 0;

}


int do_snapshot_blkdev(Monitor *mon, const QDict *qdict, QObject **ret_data)

{

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

    const char *filename = qdict_get_try_str(qdict, "snapshot_file");

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

    BlockDriverState *bs;

    BlockDriver *drv, *proto_drv;

    int ret = 0;

    int flags;

    if (!filename) {

        qerror_report(QERR_MISSING_PARAMETER, "snapshot_file");

        ret = -1;

        goto out;

    }

    bs = bdrv_find(device);

    if (!bs) {

        qerror_report(QERR_DEVICE_NOT_FOUND, device);

        ret = -1;

        goto out;

    }

    if (!format) {

        format = "qcow2";

    }

    drv = bdrv_find_format(format);

    if (!drv) {

        qerror_report(QERR_INVALID_BLOCK_FORMAT, format);

        ret = -1;

        goto out;

    }

    proto_drv = bdrv_find_protocol(filename);

    if (!proto_drv) {

        qerror_report(QERR_INVALID_BLOCK_FORMAT, format);

        ret = -1;

        goto out;

    }

    ret = bdrv_img_create(filename, format, bs->filename,

                          bs->drv->format_name, NULL, -1, bs->open_flags);

    if (ret) {

        goto out;

    }

    qemu_aio_flush();

    bdrv_flush(bs);

    flags = bs->open_flags;

    bdrv_close(bs);

    ret = bdrv_open(bs, filename, flags, drv);

    /*

     * If reopening the image file we just created fails, we really

     * are in trouble :(

     */

    if (ret != 0) {

        abort();

    }

out:

    if (ret) {

        ret = -1;

    }

    return ret;

}


static int decode_sequence_header(AVCodecContext *avctx, GetBitContext *gb)

{

    VC9Context *v = avctx->priv_data;

    v->profile = get_bits(gb, 2);

    av_log(avctx, AV_LOG_DEBUG, "Profile: %i\n", v->profile);

#if HAS_ADVANCED_PROFILE

    if (v->profile > PROFILE_MAIN)

    {

        v->level = get_bits(gb, 3);

        v->chromaformat = get_bits(gb, 2);

        if (v->chromaformat != 1)

        {

            av_log(avctx, AV_LOG_ERROR,

                   "Only 4:2:0 chroma format supported\n");

            return -1;

        }

    }

    else

#endif

    {

        v->res_sm = get_bits(gb, 2); //reserved

        if (v->res_sm)

        {

            av_log(avctx, AV_LOG_ERROR,

                   "Reserved RES_SM=%i is forbidden\n", v->res_sm);

            //return -1;

        }

    }

    // (fps-2)/4 (->30)

    v->frmrtq_postproc = get_bits(gb, 3); //common

    // (bitrate-32kbps)/64kbps

    v->bitrtq_postproc = get_bits(gb, 5); //common

    v->s.loop_filter = get_bits(gb, 1); //common

#if HAS_ADVANCED_PROFILE

    if (v->profile <= PROFILE_MAIN)

#endif

    {

        v->res_x8 = get_bits(gb, 1); //reserved

        if (v->res_x8)

        {

            av_log(avctx, AV_LOG_ERROR,

                   "1 for reserved RES_X8 is forbidden\n");

            //return -1;

        }

        v->multires = get_bits(gb, 1);

        v->res_fasttx = get_bits(gb, 1);

        if (!v->res_fasttx)

        {

            av_log(avctx, AV_LOG_ERROR,

                   "0 for reserved RES_FASTTX is forbidden\n");

            //return -1;

        }

    }

    v->fastuvmc =  get_bits(gb, 1); //common

    if (!v->profile && !v->fastuvmc)

    {

        av_log(avctx, AV_LOG_ERROR,

               "FASTUVMC unavailable in Simple Profile\n");

        return -1;

    }

    v->extended_mv =  get_bits(gb, 1); //common

    if (!v->profile && v->extended_mv)

    {

        av_log(avctx, AV_LOG_ERROR,

               "Extended MVs unavailable in Simple Profile\n");

        return -1;

    }

    v->dquant =  get_bits(gb, 2); //common

    v->vstransform =  get_bits(gb, 1); //common

#if HAS_ADVANCED_PROFILE

    if (v->profile <= PROFILE_MAIN)

#endif

    {

        v->res_transtab = get_bits(gb, 1);

        if (v->res_transtab)

        {

            av_log(avctx, AV_LOG_ERROR,

                   "1 for reserved RES_TRANSTAB is forbidden\n");

            return -1;

        }

    }

    v->overlap = get_bits(gb, 1); //common

#if HAS_ADVANCED_PROFILE

    if (v->profile <= PROFILE_MAIN)

#endif

    {

        v->s.resync_marker = get_bits(gb, 1);

        v->rangered = get_bits(gb, 1);

    }

    v->s.max_b_frames = avctx->max_b_frames = get_bits(gb, 3); //common

    v->quantizer_mode = get_bits(gb, 2); //common

#if HAS_ADVANCED_PROFILE

    if (v->profile <= PROFILE_MAIN)

#endif

    {

        v->finterpflag = get_bits(gb, 1); //common

        v->res_rtm_flag = get_bits(gb, 1); //reserved

        if (!v->res_rtm_flag)

        {

            av_log(avctx, AV_LOG_ERROR,

                   "0 for reserved RES_RTM_FLAG is forbidden\n");

            //return -1;

        }

#if TRACE

        av_log(avctx, AV_LOG_INFO,

               "Profile %i:\nfrmrtq_postproc=%i, bitrtq_postproc=%i\n"

               "LoopFilter=%i, MultiRes=%i, FastUVMV=%i, Extended MV=%i\n"

               "Rangered=%i, VSTransform=%i, Overlap=%i, SyncMarker=%i\n"

               "DQuant=%i, Quantizer mode=%i, Max B frames=%i\n",

               v->profile, v->frmrtq_postproc, v->bitrtq_postproc,

               v->s.loop_filter, v->multires, v->fastuvmc, v->extended_mv,

               v->rangered, v->vstransform, v->overlap, v->s.resync_marker,

               v->dquant, v->quantizer_mode, avctx->max_b_frames

               );

        return 0;

#endif

    }

#if HAS_ADVANCED_PROFILE

    else return decode_advanced_sequence_header(avctx, gb);

#endif

}


static void rdma_accept_incoming_migration(void *opaque)

{

    RDMAContext *rdma = opaque;

    int ret;

    QEMUFile *f;

    Error *local_err = NULL, **errp = &local_err;

    DPRINTF("Accepting rdma connection...\n");

    ret = qemu_rdma_accept(rdma);

    if (ret) {

        ERROR(errp, "RDMA Migration initialization failed!");

        return;

    }

    DPRINTF("Accepted migration\n");

    f = qemu_fopen_rdma(rdma, "rb");

    if (f == NULL) {

        ERROR(errp, "could not qemu_fopen_rdma!");

        qemu_rdma_cleanup(rdma);

        return;

    }

    rdma->migration_started_on_destination = 1;

    process_incoming_migration(f);

}


static int extract_header(AVCodecContext *const avctx,

                          const AVPacket *const avpkt) {

    const uint8_t *buf;

    unsigned buf_size;

    IffContext *s = avctx->priv_data;

    int palette_size;

    if (avctx->extradata_size < 2) {

        av_log(avctx, AV_LOG_ERROR, "not enough extradata\n");

        return AVERROR_INVALIDDATA;

    palette_size = avctx->extradata_size - AV_RB16(avctx->extradata);

    if (avpkt) {

        int image_size;

        if (avpkt->size < 2)

            return AVERROR_INVALIDDATA;

        image_size = avpkt->size - AV_RB16(avpkt->data);

        buf = avpkt->data;

        buf_size = bytestream_get_be16(&buf);

        if (buf_size <= 1 || image_size <= 1) {

            av_log(avctx, AV_LOG_ERROR,

                   "Invalid image size received: %u -> image data offset: %d\n",

                   buf_size, image_size);

            return AVERROR_INVALIDDATA;

    } else {

        buf = avctx->extradata;

        buf_size = bytestream_get_be16(&buf);

        if (buf_size <= 1 || palette_size < 0) {

            av_log(avctx, AV_LOG_ERROR,

                   "Invalid palette size received: %u -> palette data offset: %d\n",

                   buf_size, palette_size);

            return AVERROR_INVALIDDATA;

    if (buf_size > 8) {

        s->compression  = bytestream_get_byte(&buf);

        s->bpp          = bytestream_get_byte(&buf);

        s->ham          = bytestream_get_byte(&buf);

        s->flags        = bytestream_get_byte(&buf);

        s->transparency = bytestream_get_be16(&buf);

        s->masking      = bytestream_get_byte(&buf);

        if (s->masking == MASK_HAS_MASK) {

            if (s->bpp >= 8) {

                avctx->pix_fmt = PIX_FMT_RGB32;

                av_freep(&s->mask_palbuf);

                s->mask_buf = av_malloc((s->planesize * 32) + FF_INPUT_BUFFER_PADDING_SIZE);

                if (!s->mask_buf)

                s->mask_palbuf = av_malloc((2 << s->bpp) * sizeof(uint32_t) + FF_INPUT_BUFFER_PADDING_SIZE);

                if (!s->mask_palbuf) {

            s->bpp++;

        } else if (s->masking != MASK_NONE && s->masking != MASK_HAS_TRANSPARENT_COLOR) {

            av_log(avctx, AV_LOG_ERROR, "Masking not supported\n");

            return AVERROR_PATCHWELCOME;

        if (!s->bpp || s->bpp > 32) {

            av_log(avctx, AV_LOG_ERROR, "Invalid number of bitplanes: %u\n", s->bpp);

            return AVERROR_INVALIDDATA;

        } else if (s->ham >= 8) {

            av_log(avctx, AV_LOG_ERROR, "Invalid number of hold bits for HAM: %u\n", s->ham);

            return AVERROR_INVALIDDATA;

        av_freep(&s->ham_buf);

        av_freep(&s->ham_palbuf);

        if (s->ham) {

            int i, count = FFMIN(palette_size / 3, 1 << s->ham);

            int ham_count;

            const uint8_t *const palette = avctx->extradata + AV_RB16(avctx->extradata);

            s->ham_buf = av_malloc((s->planesize * 8) + FF_INPUT_BUFFER_PADDING_SIZE);

            if (!s->ham_buf)

            ham_count = 8 * (1 << s->ham);

            s->ham_palbuf = av_malloc((ham_count << !!(s->masking == MASK_HAS_MASK)) * sizeof (uint32_t) + FF_INPUT_BUFFER_PADDING_SIZE);

            if (!s->ham_palbuf) {

                av_freep(&s->ham_buf);

            if (count) { // HAM with color palette attached

                // prefill with black and palette and set HAM take direct value mask to zero

                memset(s->ham_palbuf, 0, (1 << s->ham) * 2 * sizeof (uint32_t));

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

                    s->ham_palbuf[i*2+1] = 0xFF000000 | AV_RL24(palette + i*3);

                count = 1 << s->ham;

            } else { // HAM with grayscale color palette

                count = 1 << s->ham;

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

                    s->ham_palbuf[i*2]   = 0xFF000000; // take direct color value from palette

                    s->ham_palbuf[i*2+1] = 0xFF000000 | av_le2ne32(gray2rgb((i * 255) >> s->ham));

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

                uint32_t tmp = i << (8 - s->ham);

                tmp |= tmp >> s->ham;

                s->ham_palbuf[(i+count)*2]     = 0xFF00FFFF; // just modify blue color component

                s->ham_palbuf[(i+count*2)*2]   = 0xFFFFFF00; // just modify red color component

                s->ham_palbuf[(i+count*3)*2]   = 0xFFFF00FF; // just modify green color component

                s->ham_palbuf[(i+count)*2+1]   = 0xFF000000 | tmp << 16;

                s->ham_palbuf[(i+count*2)*2+1] = 0xFF000000 | tmp;

                s->ham_palbuf[(i+count*3)*2+1] = 0xFF000000 | tmp << 8;

            if (s->masking == MASK_HAS_MASK) {

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

                    s->ham_palbuf[(1 << s->bpp) + i] = s->ham_palbuf[i] | 0xFF000000;

    return 0;


static void handle_output(VirtIODevice *vdev, VirtQueue *vq)

{

    VirtIOSerial *vser;

    VirtIOSerialPort *port;

    VirtIOSerialPortInfo *info;

    vser = DO_UPCAST(VirtIOSerial, vdev, vdev);

    port = find_port_by_vq(vser, vq);

    info = port ? DO_UPCAST(VirtIOSerialPortInfo, qdev, port->dev.info) : NULL;

    if (!port || !port->host_connected || !info->have_data) {

        discard_vq_data(vq, vdev);

        return;

    }

    if (!port->throttled) {

        do_flush_queued_data(port, vq, vdev);

        return;

    }

}


static abi_long do_getsockname(int fd, abi_ulong target_addr,

                               abi_ulong target_addrlen_addr)

{

    socklen_t addrlen;

    void *addr;

    abi_long ret;

    if (target_addr == 0)

       return get_errno(accept(fd, NULL, NULL));

    if (get_user_u32(addrlen, target_addrlen_addr))

        return -TARGET_EFAULT;

    if (addrlen < 0)

        return -TARGET_EINVAL;

    addr = alloca(addrlen);

    ret = get_errno(getsockname(fd, addr, &addrlen));

    if (!is_error(ret)) {

        host_to_target_sockaddr(target_addr, addr, addrlen);

        if (put_user_u32(addrlen, target_addrlen_addr))

            ret = -TARGET_EFAULT;

    }

    return ret;

}


static int pc_rec_cmp(const void *p1, const void *p2)

{

    PCRecord *r1 = *(PCRecord **)p1;

    PCRecord *r2 = *(PCRecord **)p2;

    if (r1->count < r2->count)

        return 1;

    else if (r1->count == r2->count)

        return 0;

    else

        return -1;

}


static int64_t coroutine_fn bdrv_co_get_block_status(BlockDriverState *bs,

                                                     bool want_zero,

                                                     int64_t sector_num,

                                                     int nb_sectors, int *pnum,

                                                     BlockDriverState **file)

{

    int64_t total_sectors;

    int64_t n;

    int64_t ret, ret2;

    BlockDriverState *local_file = NULL;

    assert(pnum);

    *pnum = 0;

    total_sectors = bdrv_nb_sectors(bs);

    if (total_sectors < 0) {

        ret = total_sectors;

        goto early_out;

    }

    if (sector_num >= total_sectors) {

        ret = BDRV_BLOCK_EOF;

        goto early_out;

    }

    if (!nb_sectors) {

        ret = 0;

        goto early_out;

    }

    n = total_sectors - sector_num;

    if (n < nb_sectors) {

        nb_sectors = n;

    }

    if (!bs->drv->bdrv_co_get_block_status) {

        *pnum = nb_sectors;

        ret = BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED;

        if (sector_num + nb_sectors == total_sectors) {

            ret |= BDRV_BLOCK_EOF;

        }

        if (bs->drv->protocol_name) {

            ret |= BDRV_BLOCK_OFFSET_VALID | (sector_num * BDRV_SECTOR_SIZE);

            local_file = bs;

        }

        goto early_out;

    }

    bdrv_inc_in_flight(bs);

    ret = bs->drv->bdrv_co_get_block_status(bs, sector_num, nb_sectors, pnum,

                                            &local_file);

    if (ret < 0) {

        *pnum = 0;

        goto out;

    }

    if (ret & BDRV_BLOCK_RAW) {

        assert(ret & BDRV_BLOCK_OFFSET_VALID && local_file);

        ret = bdrv_co_get_block_status(local_file, want_zero,

                                       ret >> BDRV_SECTOR_BITS,

                                       *pnum, pnum, &local_file);

        goto out;

    }

    if (ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ZERO)) {

        ret |= BDRV_BLOCK_ALLOCATED;

    } else if (want_zero) {

        if (bdrv_unallocated_blocks_are_zero(bs)) {

            ret |= BDRV_BLOCK_ZERO;

        } else if (bs->backing) {

            BlockDriverState *bs2 = bs->backing->bs;

            int64_t nb_sectors2 = bdrv_nb_sectors(bs2);

            if (nb_sectors2 >= 0 && sector_num >= nb_sectors2) {

                ret |= BDRV_BLOCK_ZERO;

            }

        }

    }

    if (want_zero && local_file && local_file != bs &&

        (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) &&

        (ret & BDRV_BLOCK_OFFSET_VALID)) {

        int file_pnum;

        ret2 = bdrv_co_get_block_status(local_file, want_zero,

                                        ret >> BDRV_SECTOR_BITS,

                                        *pnum, &file_pnum, NULL);

        if (ret2 >= 0) {

            /* Ignore errors.  This is just providing extra information, it

             * is useful but not necessary.

             */

            if (ret2 & BDRV_BLOCK_EOF &&

                (!file_pnum || ret2 & BDRV_BLOCK_ZERO)) {

                /*

                 * It is valid for the format block driver to read

                 * beyond the end of the underlying file's current

                 * size; such areas read as zero.

                 */

                ret |= BDRV_BLOCK_ZERO;

            } else {

                /* Limit request to the range reported by the protocol driver */

                *pnum = file_pnum;

                ret |= (ret2 & BDRV_BLOCK_ZERO);

            }

        }

    }

out:

    bdrv_dec_in_flight(bs);

    if (ret >= 0 && sector_num + *pnum == total_sectors) {

        ret |= BDRV_BLOCK_EOF;

    }

early_out:

    if (file) {

        *file = local_file;

    }

    return ret;

}


static void usbredir_bulk_packet(void *priv, uint32_t id,

    struct usb_redir_bulk_packet_header *bulk_packet,

    uint8_t *data, int data_len)

{

    USBRedirDevice *dev = priv;

    uint8_t ep = bulk_packet->endpoint;

    int len = bulk_packet->length;

    AsyncURB *aurb;

    DPRINTF("bulk-in status %d ep %02X len %d id %u\n", bulk_packet->status,

            ep, len, id);

    aurb = async_find(dev, id);

    if (!aurb) {

        free(data);

        return;

    }

    if (aurb->bulk_packet.endpoint != bulk_packet->endpoint ||

            aurb->bulk_packet.stream_id != bulk_packet->stream_id) {

        ERROR("return bulk packet mismatch, please report this!\n");

        len = USB_RET_NAK;

    }

    if (aurb->packet) {

        len = usbredir_handle_status(dev, bulk_packet->status, len);

        if (len > 0) {

            usbredir_log_data(dev, "bulk data in:", data, data_len);

            if (data_len <= aurb->packet->iov.size) {

                usb_packet_copy(aurb->packet, data, data_len);

            } else {

                ERROR("bulk buffer too small (%d > %zd)\n", data_len,

                      aurb->packet->iov.size);

                len = USB_RET_STALL;

            }

        }

        aurb->packet->result = len;

        usb_packet_complete(&dev->dev, aurb->packet);

    }

    async_free(dev, aurb);

    free(data);

}


static inline void gen_op_eval_fbu(TCGv dst, TCGv src,

                                    unsigned int fcc_offset)

{

    gen_mov_reg_FCC0(dst, src, fcc_offset);

    gen_mov_reg_FCC1(cpu_tmp0, src, fcc_offset);

    tcg_gen_and_tl(dst, dst, cpu_tmp0);

}


static void virtio_pci_device_plugged(DeviceState *d)

{

    VirtIOPCIProxy *proxy = VIRTIO_PCI(d);

    VirtioBusState *bus = &proxy->bus;

    uint8_t *config;

    uint32_t size;

    config = proxy->pci_dev.config;

    if (proxy->class_code) {

        pci_config_set_class(config, proxy->class_code);

    }

    pci_set_word(config + PCI_SUBSYSTEM_VENDOR_ID,

                 pci_get_word(config + PCI_VENDOR_ID));

    pci_set_word(config + PCI_SUBSYSTEM_ID, virtio_bus_get_vdev_id(bus));

    config[PCI_INTERRUPT_PIN] = 1;

    if (proxy->nvectors &&

        msix_init_exclusive_bar(&proxy->pci_dev, proxy->nvectors, 1)) {

        error_report("unable to init msix vectors to %" PRIu32,

                     proxy->nvectors);

        proxy->nvectors = 0;

    }

    proxy->pci_dev.config_write = virtio_write_config;

    size = VIRTIO_PCI_REGION_SIZE(&proxy->pci_dev)

         + virtio_bus_get_vdev_config_len(bus);

    if (size & (size - 1)) {

        size = 1 << qemu_fls(size);

    }

    memory_region_init_io(&proxy->bar, OBJECT(proxy), &virtio_pci_config_ops,

                          proxy, "virtio-pci", size);

    pci_register_bar(&proxy->pci_dev, 0, PCI_BASE_ADDRESS_SPACE_IO,

                     &proxy->bar);

    if (!kvm_has_many_ioeventfds()) {

        proxy->flags &= ~VIRTIO_PCI_FLAG_USE_IOEVENTFD;

    }

    proxy->host_features |= 0x1 << VIRTIO_F_NOTIFY_ON_EMPTY;

    proxy->host_features |= 0x1 << VIRTIO_F_BAD_FEATURE;

    proxy->host_features = virtio_bus_get_vdev_features(bus,

                                                      proxy->host_features);

}


void ff_xvmc_pack_pblocks(MpegEncContext *s, int cbp)

{

    int i, j = 0;

    const int mb_block_count = 4 + (1 << s->chroma_format);

    cbp <<= 12-mb_block_count;

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

        if (cbp & (1 << 11))

            s->pblocks[i] = &s->block[j++];

        else

            s->pblocks[i] = NULL;

        cbp += cbp;

    }

}


static void cpu_print_cc(FILE *f,

                         int (*cpu_fprintf)(FILE *f, const char *fmt, ...),

                         uint32_t cc)

{

    cpu_fprintf(f, "%c%c%c%c", cc & PSR_NEG? 'N' : '-',

                cc & PSR_ZERO? 'Z' : '-', cc & PSR_OVF? 'V' : '-',

                cc & PSR_CARRY? 'C' : '-');

}


static int cpu_restore_state_from_tb(CPUState *cpu, TranslationBlock *tb,

                                     uintptr_t searched_pc)

{

    CPUArchState *env = cpu->env_ptr;

    TCGContext *s = &tcg_ctx;

    int j;

    uintptr_t tc_ptr;

#ifdef CONFIG_PROFILER

    int64_t ti;

#endif

#ifdef CONFIG_PROFILER

    ti = profile_getclock();

#endif

    tcg_func_start(s);

    gen_intermediate_code_pc(env, tb);

    if (use_icount) {

        /* Reset the cycle counter to the start of the block.  */

        cpu->icount_decr.u16.low += tb->icount;

        /* Clear the IO flag.  */

        cpu->can_do_io = 0;

    }

    /* find opc index corresponding to search_pc */

    tc_ptr = (uintptr_t)tb->tc_ptr;

    if (searched_pc < tc_ptr)

        return -1;

    s->tb_next_offset = tb->tb_next_offset;

#ifdef USE_DIRECT_JUMP

    s->tb_jmp_offset = tb->tb_jmp_offset;

    s->tb_next = NULL;

#else

    s->tb_jmp_offset = NULL;

    s->tb_next = tb->tb_next;

#endif

    j = tcg_gen_code_search_pc(s, (tcg_insn_unit *)tc_ptr,

                               searched_pc - tc_ptr);

    if (j < 0)

        return -1;

    /* now find start of instruction before */

    while (s->gen_opc_instr_start[j] == 0) {

        j--;

    }

    cpu->icount_decr.u16.low -= s->gen_opc_icount[j];

    restore_state_to_opc(env, tb, j);

#ifdef CONFIG_PROFILER

    s->restore_time += profile_getclock() - ti;

    s->restore_count++;

#endif

    return 0;

}


static uint8_t virtio_scsi_do_command(QVirtIOSCSI *vs, const uint8_t *cdb,

                                      const uint8_t *data_in,

                                      size_t data_in_len,

                                      uint8_t *data_out, size_t data_out_len)

{

    QVirtQueue *vq;

    QVirtIOSCSICmdReq req = { { 0 } };

    QVirtIOSCSICmdResp resp = { .response = 0xff, .status = 0xff };

    uint64_t req_addr, resp_addr, data_in_addr = 0, data_out_addr = 0;

    uint8_t response;

    uint32_t free_head;

    vq = vs->vq[2];

    req.lun[0] = 1; /* Select LUN */

    req.lun[1] = 1; /* Select target 1 */

    memcpy(req.cdb, cdb, CDB_SIZE);

    /* XXX: Fix endian if any multi-byte field in req/resp is used */

    /* Add request header */

    req_addr = qvirtio_scsi_alloc(vs, sizeof(req), &req);

    free_head = qvirtqueue_add(vq, req_addr, sizeof(req), false, true);

    if (data_out_len) {

        data_out_addr = qvirtio_scsi_alloc(vs, data_out_len, data_out);

        qvirtqueue_add(vq, data_out_addr, data_out_len, false, true);

    }

    /* Add response header */

    resp_addr = qvirtio_scsi_alloc(vs, sizeof(resp), &resp);

    qvirtqueue_add(vq, resp_addr, sizeof(resp), true, !!data_in_len);

    if (data_in_len) {

        data_in_addr = qvirtio_scsi_alloc(vs, data_in_len, data_in);

        qvirtqueue_add(vq, data_in_addr, data_in_len, true, false);

    }

    qvirtqueue_kick(&qvirtio_pci, vs->dev, vq, free_head);

    qvirtio_wait_queue_isr(&qvirtio_pci, vs->dev, vq, QVIRTIO_SCSI_TIMEOUT_US);

    response = readb(resp_addr + offsetof(QVirtIOSCSICmdResp, response));

    guest_free(vs->alloc, req_addr);

    guest_free(vs->alloc, resp_addr);

    guest_free(vs->alloc, data_in_addr);

    guest_free(vs->alloc, data_out_addr);

    return response;

}


static uint64_t pic_read(void *opaque, target_phys_addr_t addr,

                         unsigned size)

{

    HeathrowPICS *s = opaque;

    HeathrowPIC *pic;

    unsigned int n;

    uint32_t value;

    n = ((addr & 0xfff) - 0x10) >> 4;

    if (n >= 2) {

        value = 0;

    } else {

        pic = &s->pics[n];

        switch(addr & 0xf) {

        case 0x0:

            value = pic->events;

            break;

        case 0x4:

            value = pic->mask;

            break;

        case 0xc:

            value = pic->levels;

            break;

        default:

            value = 0;

            break;

        }

    }

    PIC_DPRINTF("readl: " TARGET_FMT_plx " %u: %08x\n", addr, n, value);

    return value;

}


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

{

    PCDIMMDevice *dimm = PC_DIMM(dev);

    if (!dimm->hostmem) {

        error_setg(errp, "'" PC_DIMM_MEMDEV_PROP "' property is not set");

        return;

    }

    if (dimm->node >= nb_numa_nodes) {

        error_setg(errp, "'DIMM property " PC_DIMM_NODE_PROP " has value %"

                   PRIu32 "' which exceeds the number of numa nodes: %d",

                   dimm->node, nb_numa_nodes);

        return;

    }

}


static void vtd_reset_context_cache(IntelIOMMUState *s)

{

    VTDAddressSpace **pvtd_as;

    VTDAddressSpace *vtd_as;

    uint32_t bus_it;

    uint32_t devfn_it;

    VTD_DPRINTF(CACHE, "global context_cache_gen=1");

    for (bus_it = 0; bus_it < VTD_PCI_BUS_MAX; ++bus_it) {

        pvtd_as = s->address_spaces[bus_it];

        if (!pvtd_as) {

            continue;

        }

        for (devfn_it = 0; devfn_it < VTD_PCI_DEVFN_MAX; ++devfn_it) {

            vtd_as = pvtd_as[devfn_it];

            if (!vtd_as) {

                continue;

            }

            vtd_as->context_cache_entry.context_cache_gen = 0;

        }

    }

    s->context_cache_gen = 1;

}


static void virtio_write_config(PCIDevice *pci_dev, uint32_t address,

                                uint32_t val, int len)

{

    VirtIOPCIProxy *proxy = DO_UPCAST(VirtIOPCIProxy, pci_dev, pci_dev);

    if (PCI_COMMAND == address) {

        if (!(val & PCI_COMMAND_MASTER)) {

            proxy->vdev->status &= !VIRTIO_CONFIG_S_DRIVER_OK;

        }

    }

    pci_default_write_config(pci_dev, address, val, len);

    if(proxy->vdev->nvectors)

        msix_write_config(pci_dev, address, val, len);

}


void fpu_clear_exceptions(void)

{

    struct __attribute__((packed)) {

        uint16_t fpuc;

        uint16_t dummy1;

        uint16_t fpus;

        uint16_t dummy2;

        uint16_t fptag;

        uint16_t dummy3;

        uint32_t ignored[4];

        long double fpregs[8];

    } float_env32;

    asm volatile ("fnstenv %0\n" : : "m" (float_env32));

    float_env32.fpus &= ~0x7f;

    asm volatile ("fldenv %0\n" : : "m" (float_env32));

}


static unsigned int dec_movs_r(DisasContext *dc)

{

	TCGv t0;

	int size = memsize_z(dc);

	DIS(fprintf (logfile, "movs.%c $r%u, $r%u\n",

		    memsize_char(size),

		    dc->op1, dc->op2));

	cris_cc_mask(dc, CC_MASK_NZ);

	t0 = tcg_temp_new(TCG_TYPE_TL);

	/* Size can only be qi or hi.  */

	t_gen_sext(t0, cpu_R[dc->op1], size);

	cris_alu(dc, CC_OP_MOVE,

		    cpu_R[dc->op2], cpu_R[dc->op1], t0, 4);

	tcg_temp_free(t0);

	return 2;

}


void hpet_pit_disable(void) {

    PITChannelState *s;

    s = &pit_state.channels[0];

    qemu_del_timer(s->irq_timer);

}


void ff_h264_h_lpf_luma_inter_msa(uint8_t *data, int img_width,

                                  int alpha, int beta, int8_t *tc)

{

    uint8_t bs0 = 1;

    uint8_t bs1 = 1;

    uint8_t bs2 = 1;

    uint8_t bs3 = 1;

    if (tc[0] < 0)

        bs0 = 0;

    if (tc[1] < 0)

        bs1 = 0;

    if (tc[2] < 0)

        bs2 = 0;

    if (tc[3] < 0)

        bs3 = 0;

    avc_loopfilter_luma_inter_edge_ver_msa(data,

                                           bs0, bs1, bs2, bs3,

                                           tc[0], tc[1], tc[2], tc[3],

                                           alpha, beta, img_width);

}


void bdrv_attach_aio_context(BlockDriverState *bs,

                             AioContext *new_context)

{

    BdrvAioNotifier *ban;

    if (!bs->drv) {

        return;

    }

    bs->aio_context = new_context;

    if (bs->backing) {

        bdrv_attach_aio_context(bs->backing->bs, new_context);

    }

    if (bs->file) {

        bdrv_attach_aio_context(bs->file->bs, new_context);

    }

    if (bs->drv->bdrv_attach_aio_context) {

        bs->drv->bdrv_attach_aio_context(bs, new_context);

    }

    if (bs->io_limits_enabled) {

        throttle_timers_attach_aio_context(&bs->throttle_timers, new_context);

    }

    QLIST_FOREACH(ban, &bs->aio_notifiers, list) {

        ban->attached_aio_context(new_context, ban->opaque);

    }

}


uint32_t HELPER(mvcp)(CPUS390XState *env, uint64_t l, uint64_t a1, uint64_t a2)

{

    HELPER_LOG("%s: %16" PRIx64 " %16" PRIx64 " %16" PRIx64 "\n",

               __func__, l, a1, a2);

    return mvc_asc(env, l, a1, PSW_ASC_PRIMARY, a2, PSW_ASC_SECONDARY);

}


ssize_t nbd_wr_syncv(QIOChannel *ioc,

                     struct iovec *iov,

                     size_t niov,

                     size_t length,

                     bool do_read,

                     Error **errp)

{

    ssize_t done = 0;

    struct iovec *local_iov = g_new(struct iovec, niov);

    struct iovec *local_iov_head = local_iov;

    unsigned int nlocal_iov = niov;

    nlocal_iov = iov_copy(local_iov, nlocal_iov, iov, niov, 0, length);

    while (nlocal_iov > 0) {

        ssize_t len;

        if (do_read) {

            len = qio_channel_readv(ioc, local_iov, nlocal_iov, errp);

        } else {

            len = qio_channel_writev(ioc, local_iov, nlocal_iov, errp);

        }

        if (len == QIO_CHANNEL_ERR_BLOCK) {

            /* errp should not be set */

            assert(qemu_in_coroutine());

            qio_channel_yield(ioc, do_read ? G_IO_IN : G_IO_OUT);

            continue;

        }

        if (len < 0) {

            done = -EIO;

            goto cleanup;

        }

        if (do_read && len == 0) {

            break;

        }

        iov_discard_front(&local_iov, &nlocal_iov, len);

        done += len;

    }

 cleanup:

    g_free(local_iov_head);

    return done;

}


void qemu_init_vcpu(void *_env)

{

    CPUState *env = _env;

    if (kvm_enabled())

        kvm_init_vcpu(env);

    env->nr_cores = smp_cores;

    env->nr_threads = smp_threads;

    return;

}


void kvm_inject_x86_mce(CPUState *cenv, int bank, uint64_t status,

                        uint64_t mcg_status, uint64_t addr, uint64_t misc,

                        int flag)

{

#ifdef KVM_CAP_MCE

    struct kvm_x86_mce mce = {

        .bank = bank,

        .status = status,

        .mcg_status = mcg_status,

        .addr = addr,

        .misc = misc,

    };

    if (flag & MCE_BROADCAST) {

        kvm_mce_broadcast_rest(cenv);

    }

    kvm_inject_x86_mce_on(cenv, &mce, flag);

#else /* !KVM_CAP_MCE*/

    if (flag & ABORT_ON_ERROR) {

        abort();

    }

#endif /* !KVM_CAP_MCE*/

}


readv_f(int argc, char **argv)

{

	struct timeval t1, t2;

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

	int c, cnt;

	char *buf;

	int64_t offset;

	int total;

	int nr_iov;

	QEMUIOVector qiov;

	int pattern = 0;

	int Pflag = 0;

	while ((c = getopt(argc, argv, "CP:qv")) != EOF) {

		switch (c) {

		case 'C':

			Cflag = 1;

			break;

		case 'P':

			Pflag = 1;

			pattern = atoi(optarg);

			break;

		case 'q':

			qflag = 1;

			break;

		case 'v':

			vflag = 1;

			break;

		default:

			return command_usage(&readv_cmd);

		}

	}

	if (optind > argc - 2)

		return command_usage(&readv_cmd);

	offset = cvtnum(argv[optind]);

	if (offset < 0) {

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

		return 0;

	}

	optind++;

	if (offset & 0x1ff) {

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

			(long long)offset);

		return 0;

	}

	nr_iov = argc - optind;

	buf = create_iovec(&qiov, &argv[optind], nr_iov, 0xab);

	gettimeofday(&t1, NULL);

	cnt = do_aio_readv(&qiov, offset, &total);

	gettimeofday(&t2, NULL);

	if (cnt < 0) {

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

		goto out;

	}

	if (Pflag) {

		void* cmp_buf = malloc(qiov.size);

		memset(cmp_buf, pattern, qiov.size);

		if (memcmp(buf, cmp_buf, qiov.size)) {

			printf("Pattern verification failed at offset %lld, "

				"%zd bytes\n",

				(long long) offset, qiov.size);

		}

		free(cmp_buf);

	}

	if (qflag)

		goto out;

        if (vflag)

		dump_buffer(buf, offset, qiov.size);

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

	t2 = tsub(t2, t1);

	print_report("read", &t2, offset, qiov.size, total, cnt, Cflag);

out:

	qemu_io_free(buf);

	return 0;

}


static int init_directories(BDRVVVFATState* s,

                            const char *dirname, int heads, int secs)

{

    bootsector_t* bootsector;

    mapping_t* mapping;

    unsigned int i;

    unsigned int cluster;

    memset(&(s->first_sectors[0]),0,0x40*0x200);

    s->cluster_size=s->sectors_per_cluster*0x200;

    s->cluster_buffer=g_malloc(s->cluster_size);

    /*

     * The formula: sc = spf+1+spf*spc*(512*8/fat_type),

     * where sc is sector_count,

     * spf is sectors_per_fat,

     * spc is sectors_per_clusters, and

     * fat_type = 12, 16 or 32.

     */

    i = 1+s->sectors_per_cluster*0x200*8/s->fat_type;

    s->sectors_per_fat=(s->sector_count+i)/i; /* round up */

    array_init(&(s->mapping),sizeof(mapping_t));

    array_init(&(s->directory),sizeof(direntry_t));

    /* add volume label */

    {

	direntry_t* entry=array_get_next(&(s->directory));

	entry->attributes=0x28; /* archive | volume label */

	memcpy(entry->name,"QEMU VVF",8);

	memcpy(entry->extension,"AT ",3);

    }

    /* Now build FAT, and write back information into directory */

    init_fat(s);

    s->faked_sectors=s->first_sectors_number+s->sectors_per_fat*2;

    s->cluster_count=sector2cluster(s, s->sector_count);

    mapping = array_get_next(&(s->mapping));

    mapping->begin = 0;

    mapping->dir_index = 0;

    mapping->info.dir.parent_mapping_index = -1;

    mapping->first_mapping_index = -1;

    mapping->path = g_strdup(dirname);

    i = strlen(mapping->path);

    if (i > 0 && mapping->path[i - 1] == '/')

	mapping->path[i - 1] = '\0';

    mapping->mode = MODE_DIRECTORY;

    mapping->read_only = 0;

    s->path = mapping->path;

    for (i = 0, cluster = 0; i < s->mapping.next; i++) {

	/* MS-DOS expects the FAT to be 0 for the root directory

	 * (except for the media byte). */

	/* LATER TODO: still true for FAT32? */

	int fix_fat = (i != 0);

	mapping = array_get(&(s->mapping), i);

        if (mapping->mode & MODE_DIRECTORY) {

	    mapping->begin = cluster;

	    if(read_directory(s, i)) {

		fprintf(stderr, "Could not read directory %s\n",

			mapping->path);

		return -1;

	    }

	    mapping = array_get(&(s->mapping), i);

	} else {

	    assert(mapping->mode == MODE_UNDEFINED);

	    mapping->mode=MODE_NORMAL;

	    mapping->begin = cluster;

	    if (mapping->end > 0) {

		direntry_t* direntry = array_get(&(s->directory),

			mapping->dir_index);

		mapping->end = cluster + 1 + (mapping->end-1)/s->cluster_size;

		set_begin_of_direntry(direntry, mapping->begin);

	    } else {

		mapping->end = cluster + 1;

		fix_fat = 0;

	    }

	}

	assert(mapping->begin < mapping->end);

	/* next free cluster */

	cluster = mapping->end;

	if(cluster > s->cluster_count) {

	    fprintf(stderr,"Directory does not fit in FAT%d (capacity %.2f MB)\n",

		    s->fat_type, s->sector_count / 2000.0);

	    return -EINVAL;

	}

	/* fix fat for entry */

	if (fix_fat) {

	    int j;

	    for(j = mapping->begin; j < mapping->end - 1; j++)

		fat_set(s, j, j+1);

	    fat_set(s, mapping->end - 1, s->max_fat_value);

	}

    }

    mapping = array_get(&(s->mapping), 0);

    s->sectors_of_root_directory = mapping->end * s->sectors_per_cluster;

    s->last_cluster_of_root_directory = mapping->end;

    /* the FAT signature */

    fat_set(s,0,s->max_fat_value);

    fat_set(s,1,s->max_fat_value);

    s->current_mapping = NULL;

    bootsector=(bootsector_t*)(s->first_sectors+(s->first_sectors_number-1)*0x200);

    bootsector->jump[0]=0xeb;

    bootsector->jump[1]=0x3e;

    bootsector->jump[2]=0x90;

    memcpy(bootsector->name,"QEMU    ",8);

    bootsector->sector_size=cpu_to_le16(0x200);

    bootsector->sectors_per_cluster=s->sectors_per_cluster;

    bootsector->reserved_sectors=cpu_to_le16(1);

    bootsector->number_of_fats=0x2; /* number of FATs */

    bootsector->root_entries=cpu_to_le16(s->sectors_of_root_directory*0x10);

    bootsector->total_sectors16=s->sector_count>0xffff?0:cpu_to_le16(s->sector_count);

    bootsector->media_type=(s->first_sectors_number>1?0xf8:0xf0); /* media descriptor (f8=hd, f0=3.5 fd)*/

    s->fat.pointer[0] = bootsector->media_type;

    bootsector->sectors_per_fat=cpu_to_le16(s->sectors_per_fat);

    bootsector->sectors_per_track = cpu_to_le16(secs);

    bootsector->number_of_heads = cpu_to_le16(heads);

    bootsector->hidden_sectors=cpu_to_le32(s->first_sectors_number==1?0:0x3f);

    bootsector->total_sectors=cpu_to_le32(s->sector_count>0xffff?s->sector_count:0);

    /* LATER TODO: if FAT32, this is wrong */

    bootsector->u.fat16.drive_number=s->first_sectors_number==1?0:0x80; /* fda=0, hda=0x80 */

    bootsector->u.fat16.current_head=0;

    bootsector->u.fat16.signature=0x29;

    bootsector->u.fat16.id=cpu_to_le32(0xfabe1afd);

    memcpy(bootsector->u.fat16.volume_label,"QEMU VVFAT ",11);

    memcpy(bootsector->fat_type,(s->fat_type==12?"FAT12   ":s->fat_type==16?"FAT16   ":"FAT32   "),8);

    bootsector->magic[0]=0x55; bootsector->magic[1]=0xaa;

    return 0;

}


int kvm_vcpu_ioctl(CPUState *env, int type, ...)

{

    int ret;

    void *arg;

    va_list ap;

    va_start(ap, type);

    arg = va_arg(ap, void *);

    va_end(ap);

    ret = ioctl(env->kvm_fd, type, arg);

    if (ret == -1)

        ret = -errno;

    return ret;

}


ssize_t qemu_put_compression_data(QEMUFile *f, const uint8_t *p, size_t size,

                                  int level)

{

    ssize_t blen = IO_BUF_SIZE - f->buf_index - sizeof(int32_t);

    if (blen < compressBound(size)) {

        return 0;

    }

    if (compress2(f->buf + f->buf_index + sizeof(int32_t), (uLongf *)&blen,

                  (Bytef *)p, size, level) != Z_OK) {

        error_report("Compress Failed!");

        return 0;

    }

    qemu_put_be32(f, blen);

    f->buf_index += blen;

    return blen + sizeof(int32_t);

}