static void pmac_ide_transfer_cb(void *opaque, int ret)

{

    DBDMA_io *io = opaque;

    MACIOIDEState *m = io->opaque;

    IDEState *s = idebus_active_if(&m->bus);

    int64_t sector_num;

    int nsector, remainder;

    int64_t offset;

    MACIO_DPRINTF("pmac_ide_transfer_cb\n");

    if (ret < 0) {

        MACIO_DPRINTF("DMA error\n");

        m->aiocb = NULL;

        ide_dma_error(s);

        io->remainder_len = 0;

        goto done;

    }

    if (!m->dma_active) {

        MACIO_DPRINTF("waiting for data (%#x - %#x - %x)\n",

                      s->nsector, io->len, s->status);

        /* data not ready yet, wait for the channel to get restarted */

        io->processing = false;

        return;

    }

    if (s->io_buffer_size <= 0) {

        MACIO_DPRINTF("end of transfer\n");

        s->status = READY_STAT | SEEK_STAT;

        ide_set_irq(s->bus);

        m->dma_active = false;

        goto done;

    }

    if (io->len == 0) {

        MACIO_DPRINTF("End of DMA transfer\n");

        goto done;

    }

    /* Calculate number of sectors */

    sector_num = ide_get_sector(s) + (s->io_buffer_index >> 9);

    offset = (ide_get_sector(s) << 9) + s->io_buffer_index;

    nsector = (io->len + 0x1ff) >> 9;

    remainder = io->len & 0x1ff;

    s->nsector -= nsector;

    MACIO_DPRINTF("nsector: %d   remainder: %x\n", nsector, remainder);

    MACIO_DPRINTF("sector: %"PRIx64"   %x\n", sector_num, nsector);

    switch (s->dma_cmd) {

    case IDE_DMA_READ:

        pmac_dma_read(s->blk, offset, io->len, pmac_ide_transfer_cb, io);

        break;

    case IDE_DMA_WRITE:

        pmac_dma_write(s->blk, sector_num, nsector, pmac_ide_transfer_cb, io);

        break;

    case IDE_DMA_TRIM:

        MACIO_DPRINTF("TRIM command issued!");

        break;

    }

    return;

done:

    if (s->dma_cmd == IDE_DMA_READ || s->dma_cmd == IDE_DMA_WRITE) {

        block_acct_done(blk_get_stats(s->blk), &s->acct);

    }

    io->dma_end(opaque);

}


static inline void RENAME(rgb16to32)(const uint8_t *src, uint8_t *dst, unsigned src_size)

{

	const uint16_t *end;

#ifdef HAVE_MMX

	const uint16_t *mm_end;

#endif

	uint8_t *d = (uint8_t *)dst;

	const uint16_t *s = (uint16_t *)src;

	end = s + src_size/2;

#ifdef HAVE_MMX

	__asm __volatile(PREFETCH"	%0"::"m"(*s):"memory");

	__asm __volatile("pxor	%%mm7,%%mm7\n\t":::"memory");

	mm_end = end - 3;

	while(s < mm_end)

	{

	    __asm __volatile(

		PREFETCH" 32%1\n\t"

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

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

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

		"pand	%2, %%mm0\n\t"

		"pand	%3, %%mm1\n\t"

		"pand	%4, %%mm2\n\t"

		"psllq	$3, %%mm0\n\t"

		"psrlq	$3, %%mm1\n\t"

		"psrlq	$8, %%mm2\n\t"

		"movq	%%mm0, %%mm3\n\t"

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

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

		"punpcklwd %%mm7, %%mm0\n\t"

		"punpcklwd %%mm7, %%mm1\n\t"

		"punpcklwd %%mm7, %%mm2\n\t"

		"punpckhwd %%mm7, %%mm3\n\t"

		"punpckhwd %%mm7, %%mm4\n\t"

		"punpckhwd %%mm7, %%mm5\n\t"

		"psllq	$8, %%mm1\n\t"

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

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

		"por	%%mm2, %%mm0\n\t"

		"psllq	$8, %%mm4\n\t"

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

		"por	%%mm4, %%mm3\n\t"

		"por	%%mm5, %%mm3\n\t"

		MOVNTQ"	%%mm0, %0\n\t"

		MOVNTQ"	%%mm3, 8%0\n\t"

		:"=m"(*d)

		:"m"(*s),"m"(mask16b),"m"(mask16g),"m"(mask16r)

		:"memory");

		d += 16;

		s += 4;

	}

	__asm __volatile(SFENCE:::"memory");

	__asm __volatile(EMMS:::"memory");

#endif

	while(s < end)

	{

		register uint16_t bgr;

		bgr = *s++;

#ifdef WORDS_BIGENDIAN

		*d++ = 0;

		*d++ = (bgr&0x1F)<<3;

		*d++ = (bgr&0x7E0)>>3;

		*d++ = (bgr&0xF800)>>8;

#else

		*d++ = (bgr&0x1F)<<3;

		*d++ = (bgr&0x7E0)>>3;

		*d++ = (bgr&0xF800)>>8;

		*d++ = 0;

#endif

	}

}


static void celt_search_for_dual_stereo(OpusPsyContext *s, CeltFrame *f)
{
    float td1, td2;
    f->dual_stereo = 0;
    bands_dist(s, f, &td1);
    f->dual_stereo = 1;
    bands_dist(s, f, &td2);
    f->dual_stereo = td2 < td1;
    s->dual_stereo_used += td2 < td1;
}


void pci_default_write_config(PCIDevice *d, uint32_t addr, uint32_t val, int l)

{

    int i, was_irq_disabled = pci_irq_disabled(d);

    uint32_t config_size = pci_config_size(d);

    for (i = 0; i < l && addr + i < config_size; val >>= 8, ++i) {

        uint8_t wmask = d->wmask[addr + i];

        uint8_t w1cmask = d->w1cmask[addr + i];

        assert(!(wmask & w1cmask));

        d->config[addr + i] = (d->config[addr + i] & ~wmask) | (val & wmask);

        d->config[addr + i] &= ~(val & w1cmask); /* W1C: Write 1 to Clear */

    }

    if (ranges_overlap(addr, l, PCI_BASE_ADDRESS_0, 24) ||

        ranges_overlap(addr, l, PCI_ROM_ADDRESS, 4) ||

        ranges_overlap(addr, l, PCI_ROM_ADDRESS1, 4) ||

        range_covers_byte(addr, l, PCI_COMMAND))

        pci_update_mappings(d);

    if (range_covers_byte(addr, l, PCI_COMMAND))

        pci_update_irq_disabled(d, was_irq_disabled);

}


static inline int check_fit_i32(uint32_t val, unsigned int bits)

{

    return ((val << (32 - bits)) >> (32 - bits)) == val;

}


static void v9fs_getattr(void *opaque)

{

    int32_t fid;

    size_t offset = 7;

    ssize_t retval = 0;

    struct stat stbuf;

    V9fsFidState *fidp;

    uint64_t request_mask;

    V9fsStatDotl v9stat_dotl;

    V9fsPDU *pdu = opaque;

    V9fsState *s = pdu->s;

    pdu_unmarshal(pdu, offset, "dq", &fid, &request_mask);

    trace_v9fs_getattr(pdu->tag, pdu->id, fid, request_mask);

    fidp = get_fid(pdu, fid);

    if (fidp == NULL) {

        retval = -ENOENT;

        goto out_nofid;

    }

    /*

     * Currently we only support BASIC fields in stat, so there is no

     * need to look at request_mask.

     */

    retval = v9fs_co_lstat(pdu, &fidp->path, &stbuf);

    if (retval < 0) {

        goto out;

    }

    stat_to_v9stat_dotl(s, &stbuf, &v9stat_dotl);

    /*  fill st_gen if requested and supported by underlying fs */

    if (request_mask & P9_STATS_GEN) {

        retval = v9fs_co_st_gen(pdu, &fidp->path, stbuf.st_mode, &v9stat_dotl);

        if (retval < 0) {

            goto out;

        }

        v9stat_dotl.st_result_mask |= P9_STATS_GEN;

    }

    retval = offset;

    retval += pdu_marshal(pdu, offset, "A", &v9stat_dotl);

    trace_v9fs_getattr_return(pdu->tag, pdu->id, v9stat_dotl.st_result_mask,

                              v9stat_dotl.st_mode, v9stat_dotl.st_uid,

                              v9stat_dotl.st_gid);

out:

    put_fid(pdu, fidp);

out_nofid:

    complete_pdu(s, pdu, retval);

}


int qemu_timeout_ns_to_ms(int64_t ns)

{

    int64_t ms;

    if (ns < 0) {

        return -1;

    }

    if (!ns) {

        return 0;

    }

    /* Always round up, because it's better to wait too long than to wait too

     * little and effectively busy-wait

     */

    ms = DIV_ROUND_UP(ns, SCALE_MS);

    /* To avoid overflow problems, limit this to 2^31, i.e. approx 25 days */

    if (ms > (int64_t) INT32_MAX) {

        ms = INT32_MAX;

    }

    return (int) ms;

}


void ff_er_frame_end(MpegEncContext *s){

    int i, mb_x, mb_y, error, error_type, dc_error, mv_error, ac_error;

    int distance;

    int threshold_part[4]= {100,100,100};

    int threshold= 50;

    int is_intra_likely;

    int size = s->b8_stride * 2 * s->mb_height;

    Picture *pic= s->current_picture_ptr;

    if(!s->error_recognition || s->error_count==0 || s->avctx->lowres ||

       s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU ||

       s->error_count==3*s->mb_width*(s->avctx->skip_top + s->avctx->skip_bottom)) return;

    if(s->current_picture.motion_val[0] == NULL){

        av_log(s->avctx, AV_LOG_ERROR, "Warning MVs not available\n");

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

            pic->ref_index[i]= av_mallocz(size * sizeof(uint8_t));

            pic->motion_val_base[i]= av_mallocz((size+4) * 2 * sizeof(uint16_t));

            pic->motion_val[i]= pic->motion_val_base[i]+4;

        }

        pic->motion_subsample_log2= 3;

        s->current_picture= *s->current_picture_ptr;

    }

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

        if(pic->ref_index[i])

            memset(pic->ref_index[i], 0, size * sizeof(uint8_t));

    }

    if(s->avctx->debug&FF_DEBUG_ER){

        for(mb_y=0; mb_y<s->mb_height; mb_y++){

            for(mb_x=0; mb_x<s->mb_width; mb_x++){

                int status= s->error_status_table[mb_x + mb_y*s->mb_stride];

                av_log(s->avctx, AV_LOG_DEBUG, "%2X ", status);

            }

            av_log(s->avctx, AV_LOG_DEBUG, "\n");

        }

    }

#if 1

    /* handle overlapping slices */

    for(error_type=1; error_type<=3; error_type++){

        int end_ok=0;

        for(i=s->mb_num-1; i>=0; i--){

            const int mb_xy= s->mb_index2xy[i];

            int error= s->error_status_table[mb_xy];

            if(error&(1<<error_type))

                end_ok=1;

            if(error&(8<<error_type))

                end_ok=1;

            if(!end_ok)

                s->error_status_table[mb_xy]|= 1<<error_type;

            if(error&VP_START)

                end_ok=0;

        }

    }

#endif

#if 1

    /* handle slices with partitions of different length */

    if(s->partitioned_frame){

        int end_ok=0;

        for(i=s->mb_num-1; i>=0; i--){

            const int mb_xy= s->mb_index2xy[i];

            int error= s->error_status_table[mb_xy];

            if(error&AC_END)

                end_ok=0;

            if((error&MV_END) || (error&DC_END) || (error&AC_ERROR))

                end_ok=1;

            if(!end_ok)

                s->error_status_table[mb_xy]|= AC_ERROR;

            if(error&VP_START)

                end_ok=0;

        }

    }

#endif

    /* handle missing slices */

    if(s->error_recognition>=4){

        int end_ok=1;

        for(i=s->mb_num-2; i>=s->mb_width+100; i--){ //FIXME +100 hack

            const int mb_xy= s->mb_index2xy[i];

            int error1= s->error_status_table[mb_xy  ];

            int error2= s->error_status_table[s->mb_index2xy[i+1]];

            if(error1&VP_START)

                end_ok=1;

            if(   error2==(VP_START|DC_ERROR|AC_ERROR|MV_ERROR|AC_END|DC_END|MV_END)

               && error1!=(VP_START|DC_ERROR|AC_ERROR|MV_ERROR|AC_END|DC_END|MV_END)

               && ((error1&AC_END) || (error1&DC_END) || (error1&MV_END))){ //end & uninit

                end_ok=0;

            }

            if(!end_ok)

                s->error_status_table[mb_xy]|= DC_ERROR|AC_ERROR|MV_ERROR;

        }

    }

#if 1

    /* backward mark errors */

    distance=9999999;

    for(error_type=1; error_type<=3; error_type++){

        for(i=s->mb_num-1; i>=0; i--){

            const int mb_xy= s->mb_index2xy[i];

            int error= s->error_status_table[mb_xy];

            if(!s->mbskip_table[mb_xy]) //FIXME partition specific

                distance++;

            if(error&(1<<error_type))

                distance= 0;

            if(s->partitioned_frame){

                if(distance < threshold_part[error_type-1])

                    s->error_status_table[mb_xy]|= 1<<error_type;

            }else{

                if(distance < threshold)

                    s->error_status_table[mb_xy]|= 1<<error_type;

            }

            if(error&VP_START)

                distance= 9999999;

        }

    }

#endif

    /* forward mark errors */

    error=0;

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

        const int mb_xy= s->mb_index2xy[i];

        int old_error= s->error_status_table[mb_xy];

        if(old_error&VP_START)

            error= old_error& (DC_ERROR|AC_ERROR|MV_ERROR);

        else{

            error|= old_error& (DC_ERROR|AC_ERROR|MV_ERROR);

            s->error_status_table[mb_xy]|= error;

        }

    }

#if 1

    /* handle not partitioned case */

    if(!s->partitioned_frame){

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

            const int mb_xy= s->mb_index2xy[i];

            error= s->error_status_table[mb_xy];

            if(error&(AC_ERROR|DC_ERROR|MV_ERROR))

                error|= AC_ERROR|DC_ERROR|MV_ERROR;

            s->error_status_table[mb_xy]= error;

        }

    }

#endif

    dc_error= ac_error= mv_error=0;

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

        const int mb_xy= s->mb_index2xy[i];

        error= s->error_status_table[mb_xy];

        if(error&DC_ERROR) dc_error ++;

        if(error&AC_ERROR) ac_error ++;

        if(error&MV_ERROR) mv_error ++;

    }

    av_log(s->avctx, AV_LOG_INFO, "concealing %d DC, %d AC, %d MV errors\n", dc_error, ac_error, mv_error);

    is_intra_likely= is_intra_more_likely(s);

    /* set unknown mb-type to most likely */

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

        const int mb_xy= s->mb_index2xy[i];

        error= s->error_status_table[mb_xy];

        if(!((error&DC_ERROR) && (error&MV_ERROR)))

            continue;

        if(is_intra_likely)

            s->current_picture.mb_type[mb_xy]= MB_TYPE_INTRA4x4;

        else

            s->current_picture.mb_type[mb_xy]= MB_TYPE_16x16 | MB_TYPE_L0;

    }

    /* handle inter blocks with damaged AC */

    for(mb_y=0; mb_y<s->mb_height; mb_y++){

        for(mb_x=0; mb_x<s->mb_width; mb_x++){

            const int mb_xy= mb_x + mb_y * s->mb_stride;

            const int mb_type= s->current_picture.mb_type[mb_xy];

            error= s->error_status_table[mb_xy];

            if(IS_INTRA(mb_type)) continue; //intra

            if(error&MV_ERROR) continue;              //inter with damaged MV

            if(!(error&AC_ERROR)) continue;           //undamaged inter

            s->mv_dir = MV_DIR_FORWARD;

            s->mb_intra=0;

            s->mb_skipped=0;

            if(IS_8X8(mb_type)){

                int mb_index= mb_x*2 + mb_y*2*s->b8_stride;

                int j;

                s->mv_type = MV_TYPE_8X8;

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

                    s->mv[0][j][0] = s->current_picture.motion_val[0][ mb_index + (j&1) + (j>>1)*s->b8_stride ][0];

                    s->mv[0][j][1] = s->current_picture.motion_val[0][ mb_index + (j&1) + (j>>1)*s->b8_stride ][1];

                }

            }else{

                s->mv_type = MV_TYPE_16X16;

                s->mv[0][0][0] = s->current_picture.motion_val[0][ mb_x*2 + mb_y*2*s->b8_stride ][0];

                s->mv[0][0][1] = s->current_picture.motion_val[0][ mb_x*2 + mb_y*2*s->b8_stride ][1];

            }

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

            s->mb_x= mb_x;

            s->mb_y= mb_y;

            decode_mb(s);

        }

    }

    /* guess MVs */

    if(s->pict_type==FF_B_TYPE){

        for(mb_y=0; mb_y<s->mb_height; mb_y++){

            for(mb_x=0; mb_x<s->mb_width; mb_x++){

                int xy= mb_x*2 + mb_y*2*s->b8_stride;

                const int mb_xy= mb_x + mb_y * s->mb_stride;

                const int mb_type= s->current_picture.mb_type[mb_xy];

                error= s->error_status_table[mb_xy];

                if(IS_INTRA(mb_type)) continue;

                if(!(error&MV_ERROR)) continue;           //inter with undamaged MV

                if(!(error&AC_ERROR)) continue;           //undamaged inter

                s->mv_dir = MV_DIR_FORWARD|MV_DIR_BACKWARD;

                s->mb_intra=0;

                s->mv_type = MV_TYPE_16X16;

                s->mb_skipped=0;

                if(s->pp_time){

                    int time_pp= s->pp_time;

                    int time_pb= s->pb_time;

                    s->mv[0][0][0] = s->next_picture.motion_val[0][xy][0]*time_pb/time_pp;

                    s->mv[0][0][1] = s->next_picture.motion_val[0][xy][1]*time_pb/time_pp;

                    s->mv[1][0][0] = s->next_picture.motion_val[0][xy][0]*(time_pb - time_pp)/time_pp;

                    s->mv[1][0][1] = s->next_picture.motion_val[0][xy][1]*(time_pb - time_pp)/time_pp;

                }else{

                    s->mv[0][0][0]= 0;

                    s->mv[0][0][1]= 0;

                    s->mv[1][0][0]= 0;

                    s->mv[1][0][1]= 0;

                }

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

                s->mb_x= mb_x;

                s->mb_y= mb_y;

                decode_mb(s);

            }

        }

    }else

        guess_mv(s);

#if CONFIG_MPEG_XVMC_DECODER

    /* the filters below are not XvMC compatible, skip them */

    if(s->avctx->xvmc_acceleration) goto ec_clean;

#endif

    /* fill DC for inter blocks */

    for(mb_y=0; mb_y<s->mb_height; mb_y++){

        for(mb_x=0; mb_x<s->mb_width; mb_x++){

            int dc, dcu, dcv, y, n;

            int16_t *dc_ptr;

            uint8_t *dest_y, *dest_cb, *dest_cr;

            const int mb_xy= mb_x + mb_y * s->mb_stride;

            const int mb_type= s->current_picture.mb_type[mb_xy];

            error= s->error_status_table[mb_xy];

            if(IS_INTRA(mb_type) && s->partitioned_frame) continue;

//            if(error&MV_ERROR) continue; //inter data damaged FIXME is this good?

            dest_y = s->current_picture.data[0] + mb_x*16 + mb_y*16*s->linesize;

            dest_cb= s->current_picture.data[1] + mb_x*8  + mb_y*8 *s->uvlinesize;

            dest_cr= s->current_picture.data[2] + mb_x*8  + mb_y*8 *s->uvlinesize;

            dc_ptr= &s->dc_val[0][mb_x*2 + mb_y*2*s->b8_stride];

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

                dc=0;

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

                    int x;

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

                       dc+= dest_y[x + (n&1)*8 + (y + (n>>1)*8)*s->linesize];

                    }

                }

                dc_ptr[(n&1) + (n>>1)*s->b8_stride]= (dc+4)>>3;

            }

            dcu=dcv=0;

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

                int x;

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

                    dcu+=dest_cb[x + y*(s->uvlinesize)];

                    dcv+=dest_cr[x + y*(s->uvlinesize)];

                }

            }

            s->dc_val[1][mb_x + mb_y*s->mb_stride]= (dcu+4)>>3;

            s->dc_val[2][mb_x + mb_y*s->mb_stride]= (dcv+4)>>3;

        }

    }

#if 1

    /* guess DC for damaged blocks */

    guess_dc(s, s->dc_val[0], s->mb_width*2, s->mb_height*2, s->b8_stride, 1);

    guess_dc(s, s->dc_val[1], s->mb_width  , s->mb_height  , s->mb_stride, 0);

    guess_dc(s, s->dc_val[2], s->mb_width  , s->mb_height  , s->mb_stride, 0);

#endif

    /* filter luma DC */

    filter181(s->dc_val[0], s->mb_width*2, s->mb_height*2, s->b8_stride);

#if 1

    /* render DC only intra */

    for(mb_y=0; mb_y<s->mb_height; mb_y++){

        for(mb_x=0; mb_x<s->mb_width; mb_x++){

            uint8_t *dest_y, *dest_cb, *dest_cr;

            const int mb_xy= mb_x + mb_y * s->mb_stride;

            const int mb_type= s->current_picture.mb_type[mb_xy];

            error= s->error_status_table[mb_xy];

            if(IS_INTER(mb_type)) continue;

            if(!(error&AC_ERROR)) continue;              //undamaged

            dest_y = s->current_picture.data[0] + mb_x*16 + mb_y*16*s->linesize;

            dest_cb= s->current_picture.data[1] + mb_x*8  + mb_y*8 *s->uvlinesize;

            dest_cr= s->current_picture.data[2] + mb_x*8  + mb_y*8 *s->uvlinesize;

            put_dc(s, dest_y, dest_cb, dest_cr, mb_x, mb_y);

        }

    }

#endif

    if(s->avctx->error_concealment&FF_EC_DEBLOCK){

        /* filter horizontal block boundaries */

        h_block_filter(s, s->current_picture.data[0], s->mb_width*2, s->mb_height*2, s->linesize  , 1);

        h_block_filter(s, s->current_picture.data[1], s->mb_width  , s->mb_height  , s->uvlinesize, 0);

        h_block_filter(s, s->current_picture.data[2], s->mb_width  , s->mb_height  , s->uvlinesize, 0);

        /* filter vertical block boundaries */

        v_block_filter(s, s->current_picture.data[0], s->mb_width*2, s->mb_height*2, s->linesize  , 1);

        v_block_filter(s, s->current_picture.data[1], s->mb_width  , s->mb_height  , s->uvlinesize, 0);

        v_block_filter(s, s->current_picture.data[2], s->mb_width  , s->mb_height  , s->uvlinesize, 0);

    }

#if CONFIG_MPEG_XVMC_DECODER

ec_clean:

#endif

    /* clean a few tables */

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

        const int mb_xy= s->mb_index2xy[i];

        int error= s->error_status_table[mb_xy];

        if(s->pict_type!=FF_B_TYPE && (error&(DC_ERROR|MV_ERROR|AC_ERROR))){

            s->mbskip_table[mb_xy]=0;

        }

        s->mbintra_table[mb_xy]=1;

    }

}


static void qxl_init_ramsize(PCIQXLDevice *qxl, uint32_t ram_min_mb)

{

    /* vga ram (bar 0) */

    if (qxl->ram_size_mb != -1) {

        qxl->vga.vram_size = qxl->ram_size_mb * 1024 * 1024;

    }

    if (qxl->vga.vram_size < ram_min_mb * 1024 * 1024) {

        qxl->vga.vram_size = ram_min_mb * 1024 * 1024;

    }

    /* vram32 (surfaces, 32bit, bar 1) */

    if (qxl->vram32_size_mb != -1) {

        qxl->vram32_size = qxl->vram32_size_mb * 1024 * 1024;

    }

    if (qxl->vram32_size < 4096) {

        qxl->vram32_size = 4096;

    }

    /* vram (surfaces, 64bit, bar 4+5) */

    if (qxl->vram_size_mb != -1) {

        qxl->vram_size = qxl->vram_size_mb * 1024 * 1024;

    }

    if (qxl->vram_size < qxl->vram32_size) {

        qxl->vram_size = qxl->vram32_size;

    }

    if (qxl->revision == 1) {

        qxl->vram32_size = 4096;

        qxl->vram_size = 4096;

    }

    qxl->vga.vram_size = msb_mask(qxl->vga.vram_size * 2 - 1);

    qxl->vram32_size = msb_mask(qxl->vram32_size * 2 - 1);

    qxl->vram_size = msb_mask(qxl->vram_size * 2 - 1);

}


void ff_mspel_motion(MpegEncContext *s,

                               uint8_t *dest_y, uint8_t *dest_cb, uint8_t *dest_cr,

                               uint8_t **ref_picture, op_pixels_func (*pix_op)[4],

                               int motion_x, int motion_y, int h)

{

    Wmv2Context * const w= (Wmv2Context*)s;

    uint8_t *ptr;

    int dxy, offset, mx, my, src_x, src_y, v_edge_pos, linesize, uvlinesize;

    int emu=0;

    dxy = ((motion_y & 1) << 1) | (motion_x & 1);

    dxy = 2*dxy + w->hshift;

    src_x = s->mb_x * 16 + (motion_x >> 1);

    src_y = s->mb_y * 16 + (motion_y >> 1);

    /* WARNING: do no forget half pels */

    v_edge_pos = s->v_edge_pos;

    src_x = av_clip(src_x, -16, s->width);

    src_y = av_clip(src_y, -16, s->height);

    if(src_x<=-16 || src_x >= s->width)

        dxy &= ~3;

    if(src_y<=-16 || src_y >= s->height)

        dxy &= ~4;

    linesize   = s->linesize;

    uvlinesize = s->uvlinesize;

    ptr = ref_picture[0] + (src_y * linesize) + src_x;

    if(s->flags&CODEC_FLAG_EMU_EDGE){

        if(src_x<1 || src_y<1 || src_x + 17  >= s->h_edge_pos

                              || src_y + h+1 >= v_edge_pos){

            s->vdsp.emulated_edge_mc(s->edge_emu_buffer, ptr - 1 - s->linesize, s->linesize, 19, 19,

                             src_x-1, src_y-1, s->h_edge_pos, s->v_edge_pos);

            ptr= s->edge_emu_buffer + 1 + s->linesize;

            emu=1;

        }

    }

    s->dsp.put_mspel_pixels_tab[dxy](dest_y             , ptr             , linesize);

    s->dsp.put_mspel_pixels_tab[dxy](dest_y+8           , ptr+8           , linesize);

    s->dsp.put_mspel_pixels_tab[dxy](dest_y  +8*linesize, ptr  +8*linesize, linesize);

    s->dsp.put_mspel_pixels_tab[dxy](dest_y+8+8*linesize, ptr+8+8*linesize, linesize);

    if(s->flags&CODEC_FLAG_GRAY) return;

    if (s->out_format == FMT_H263) {

        dxy = 0;

        if ((motion_x & 3) != 0)

            dxy |= 1;

        if ((motion_y & 3) != 0)

            dxy |= 2;

        mx = motion_x >> 2;

        my = motion_y >> 2;

    } else {

        mx = motion_x / 2;

        my = motion_y / 2;

        dxy = ((my & 1) << 1) | (mx & 1);

        mx >>= 1;

        my >>= 1;

    }

    src_x = s->mb_x * 8 + mx;

    src_y = s->mb_y * 8 + my;

    src_x = av_clip(src_x, -8, s->width >> 1);

    if (src_x == (s->width >> 1))

        dxy &= ~1;

    src_y = av_clip(src_y, -8, s->height >> 1);

    if (src_y == (s->height >> 1))

        dxy &= ~2;

    offset = (src_y * uvlinesize) + src_x;

    ptr = ref_picture[1] + offset;

    if(emu){

        s->vdsp.emulated_edge_mc(s->edge_emu_buffer, ptr, s->uvlinesize, 9, 9,

                         src_x, src_y, s->h_edge_pos>>1, s->v_edge_pos>>1);

        ptr= s->edge_emu_buffer;

    }

    pix_op[1][dxy](dest_cb, ptr, uvlinesize, h >> 1);

    ptr = ref_picture[2] + offset;

    if(emu){

        s->vdsp.emulated_edge_mc(s->edge_emu_buffer, ptr, s->uvlinesize, 9, 9,

                         src_x, src_y, s->h_edge_pos>>1, s->v_edge_pos>>1);

        ptr= s->edge_emu_buffer;

    }

    pix_op[1][dxy](dest_cr, ptr, uvlinesize, h >> 1);

}


static void register_types(void)

{

    register_char_driver("null", CHARDEV_BACKEND_KIND_NULL, NULL,

                         qemu_chr_open_null);

    register_char_driver("socket", CHARDEV_BACKEND_KIND_SOCKET,

                         qemu_chr_parse_socket, qmp_chardev_open_socket);

    register_char_driver("udp", CHARDEV_BACKEND_KIND_UDP, qemu_chr_parse_udp,

                         qmp_chardev_open_udp);

    register_char_driver("ringbuf", CHARDEV_BACKEND_KIND_RINGBUF,

                         qemu_chr_parse_ringbuf, qemu_chr_open_ringbuf);

    register_char_driver("file", CHARDEV_BACKEND_KIND_FILE,

                         qemu_chr_parse_file_out, qmp_chardev_open_file);

    register_char_driver("stdio", CHARDEV_BACKEND_KIND_STDIO,

                         qemu_chr_parse_stdio, qemu_chr_open_stdio);

#if defined HAVE_CHARDEV_SERIAL

    register_char_driver("serial", CHARDEV_BACKEND_KIND_SERIAL,

                         qemu_chr_parse_serial, qmp_chardev_open_serial);

    register_char_driver("tty", CHARDEV_BACKEND_KIND_SERIAL,

                         qemu_chr_parse_serial, qmp_chardev_open_serial);

#endif

#ifdef HAVE_CHARDEV_PARPORT

    register_char_driver("parallel", CHARDEV_BACKEND_KIND_PARALLEL,

                         qemu_chr_parse_parallel, qmp_chardev_open_parallel);

    register_char_driver("parport", CHARDEV_BACKEND_KIND_PARALLEL,

                         qemu_chr_parse_parallel, qmp_chardev_open_parallel);

#endif

#ifdef HAVE_CHARDEV_PTY

    register_char_driver("pty", CHARDEV_BACKEND_KIND_PTY, NULL,

                         qemu_chr_open_pty);

#endif

#ifdef _WIN32

    register_char_driver("console", CHARDEV_BACKEND_KIND_CONSOLE, NULL,

                         qemu_chr_open_win_con);

#endif

    register_char_driver("pipe", CHARDEV_BACKEND_KIND_PIPE,

                         qemu_chr_parse_pipe, qemu_chr_open_pipe);

    register_char_driver("mux", CHARDEV_BACKEND_KIND_MUX, qemu_chr_parse_mux,

                         qemu_chr_open_mux);

    /* Bug-compatibility: */

    register_char_driver("memory", CHARDEV_BACKEND_KIND_MEMORY,

                         qemu_chr_parse_ringbuf, qemu_chr_open_ringbuf);

    /* this must be done after machine init, since we register FEs with muxes

     * as part of realize functions like serial_isa_realizefn when -nographic

     * is specified

     */

    qemu_add_machine_init_done_notifier(&muxes_realize_notify);

    atexit(qemu_chr_cleanup);

}


static int scaling_list_data(HEVCContext *s, ScalingList *sl)

{

    GetBitContext *gb = &s->HEVClc.gb;

    uint8_t scaling_list_pred_mode_flag[4][6];

    int32_t scaling_list_dc_coef[2][6];

    int size_id, matrix_id, i, pos, delta;

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

        for (matrix_id = 0; matrix_id < (size_id == 3 ? 2 : 6); matrix_id++) {

            scaling_list_pred_mode_flag[size_id][matrix_id] = get_bits1(gb);

            if (!scaling_list_pred_mode_flag[size_id][matrix_id]) {

                delta = get_ue_golomb_long(gb);

                /* Only need to handle non-zero delta. Zero means default,

                 * which should already be in the arrays. */

                if (delta) {

                    // Copy from previous array.

                    if (matrix_id - delta < 0) {

                        av_log(s->avctx, AV_LOG_ERROR,

                               "Invalid delta in scaling list data: %d.\n", delta);

                        return AVERROR_INVALIDDATA;

                    }

                    memcpy(sl->sl[size_id][matrix_id],

                           sl->sl[size_id][matrix_id - delta],

                           size_id > 0 ? 64 : 16);

                    if (size_id > 1)

                        sl->sl_dc[size_id - 2][matrix_id] = sl->sl_dc[size_id - 2][matrix_id - delta];

                }

            } else {

                int next_coef, coef_num;

                int32_t scaling_list_delta_coef;

                next_coef = 8;

                coef_num  = FFMIN(64, 1 << (4 + (size_id << 1)));

                if (size_id > 1) {

                    scaling_list_dc_coef[size_id - 2][matrix_id] = get_se_golomb(gb) + 8;

                    next_coef = scaling_list_dc_coef[size_id - 2][matrix_id];

                    sl->sl_dc[size_id - 2][matrix_id] = next_coef;

                }

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

                    if (size_id == 0)

                        pos = 4 * ff_hevc_diag_scan4x4_y[i] +

                                  ff_hevc_diag_scan4x4_x[i];

                    else

                        pos = 8 * ff_hevc_diag_scan8x8_y[i] +

                                  ff_hevc_diag_scan8x8_x[i];

                    scaling_list_delta_coef = get_se_golomb(gb);

                    next_coef = (next_coef + scaling_list_delta_coef + 256) % 256;

                    sl->sl[size_id][matrix_id][pos] = next_coef;

                }

            }

        }

    return 0;

}


static int nvdec_mpeg12_start_frame(AVCodecContext *avctx, const uint8_t *buffer, uint32_t size)

{

    MpegEncContext *s = avctx->priv_data;

    NVDECContext      *ctx = avctx->internal->hwaccel_priv_data;

    CUVIDPICPARAMS     *pp = &ctx->pic_params;

    CUVIDMPEG2PICPARAMS *ppc = &pp->CodecSpecific.mpeg2;

    FrameDecodeData *fdd;

    NVDECFrame *cf;

    AVFrame *cur_frame = s->current_picture.f;

    int ret, i;

    ret = ff_nvdec_start_frame(avctx, cur_frame);

    if (ret < 0)

        return ret;

    fdd = (FrameDecodeData*)cur_frame->private_ref->data;

    cf  = (NVDECFrame*)fdd->hwaccel_priv;

    *pp = (CUVIDPICPARAMS) {

        .PicWidthInMbs     = (cur_frame->width  + 15) / 16,

        .FrameHeightInMbs  = (cur_frame->height + 15) / 16,

        .CurrPicIdx        = cf->idx,

        .intra_pic_flag    = s->pict_type == AV_PICTURE_TYPE_I,

        .ref_pic_flag      = s->pict_type == AV_PICTURE_TYPE_I ||

                             s->pict_type == AV_PICTURE_TYPE_P,

        .CodecSpecific.mpeg2 = {

            .ForwardRefIdx     = get_ref_idx(s->last_picture.f),

            .BackwardRefIdx    = get_ref_idx(s->next_picture.f),

            .picture_coding_type        = s->pict_type,

            .full_pel_forward_vector    = s->full_pel[0],

            .full_pel_backward_vector   = s->full_pel[1],

            .f_code                     = { { s->mpeg_f_code[0][0],

                                              s->mpeg_f_code[0][1] },

                                            { s->mpeg_f_code[1][0],

                                              s->mpeg_f_code[1][1] } },

            .intra_dc_precision         = s->intra_dc_precision,

            .frame_pred_frame_dct       = s->frame_pred_frame_dct,

            .concealment_motion_vectors = s->concealment_motion_vectors,

            .q_scale_type               = s->q_scale_type,

            .intra_vlc_format           = s->intra_vlc_format,

            .alternate_scan             = s->alternate_scan,

            .top_field_first            = s->top_field_first,

        }

    };

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

        ppc->QuantMatrixIntra[i] = s->intra_matrix[i];

        ppc->QuantMatrixInter[i] = s->inter_matrix[i];

    }

    return 0;

}


static void on_vcpu(CPUState *env, void (*func)(void *data), void *data)

{

    if (env == cpu_single_env) {

        func(data);

        return;

    }

    abort();

}


static int svq1_decode_frame(AVCodecContext *avctx,
                             void *data, int *data_size,
                             AVPacket *avpkt)
{
  const uint8_t *buf = avpkt->data;
  int buf_size = avpkt->size;
  MpegEncContext *s=avctx->priv_data;
  uint8_t        *current, *previous;
  int             result, i, x, y, width, height;
  AVFrame *pict = data;
  svq1_pmv *pmv;
  /* initialize bit buffer */
  init_get_bits(&s->gb,buf,buf_size*8);
  /* decode frame header */
  s->f_code = get_bits (&s->gb, 22);
  if ((s->f_code & ~0x70) || !(s->f_code & 0x60))
    return -1;
  /* swap some header bytes (why?) */
  if (s->f_code != 0x20) {
    uint32_t *src = (uint32_t *) (buf + 4);
    for (i=0; i < 4; i++) {
      src[i] = ((src[i] << 16) | (src[i] >> 16)) ^ src[7 - i];
    }
  }
  result = svq1_decode_frame_header (&s->gb, s);
  if (result != 0)
  {
    av_dlog(s->avctx, "Error in svq1_decode_frame_header %i\n",result);
    return result;
  }
  avcodec_set_dimensions(avctx, s->width, s->height);
  //FIXME this avoids some confusion for "B frames" without 2 references
  //this should be removed after libavcodec can handle more flexible picture types & ordering
  if(s->pict_type==AV_PICTURE_TYPE_B && s->last_picture_ptr==NULL) return buf_size;
  if(  (avctx->skip_frame >= AVDISCARD_NONREF && s->pict_type==AV_PICTURE_TYPE_B)
     ||(avctx->skip_frame >= AVDISCARD_NONKEY && s->pict_type!=AV_PICTURE_TYPE_I)
     || avctx->skip_frame >= AVDISCARD_ALL)
      return buf_size;
  if(ff_MPV_frame_start(s, avctx) < 0)
      return -1;
  pmv = av_malloc((FFALIGN(s->width, 16)/8 + 3) * sizeof(*pmv));
  if (!pmv)
      return -1;
  /* decode y, u and v components */
  for (i=0; i < 3; i++) {
    int linesize;
    if (i == 0) {
      width  = FFALIGN(s->width, 16);
      height = FFALIGN(s->height, 16);
      linesize= s->linesize;
    } else {
      if(s->flags&CODEC_FLAG_GRAY) break;
      width  = FFALIGN(s->width/4, 16);
      height = FFALIGN(s->height/4, 16);
      linesize= s->uvlinesize;
    }
    current = s->current_picture.f.data[i];
    if(s->pict_type==AV_PICTURE_TYPE_B){
        previous = s->next_picture.f.data[i];
    }else{
        previous = s->last_picture.f.data[i];
    }
    if (s->pict_type == AV_PICTURE_TYPE_I) {
      /* keyframe */
      for (y=0; y < height; y+=16) {
        for (x=0; x < width; x+=16) {
          result = svq1_decode_block_intra (&s->gb, &current[x], linesize);
          if (result != 0)
          {
            av_log(s->avctx, AV_LOG_ERROR, "Error in svq1_decode_block %i (keyframe)\n",result);
            goto err;
          }
        }
        current += 16*linesize;
      }
    } else {
      /* delta frame */
      memset (pmv, 0, ((width / 8) + 3) * sizeof(svq1_pmv));
      for (y=0; y < height; y+=16) {
        for (x=0; x < width; x+=16) {
          result = svq1_decode_delta_block (s, &s->gb, &current[x], previous,
                                            linesize, pmv, x, y);
          if (result != 0)
          {
            av_dlog(s->avctx, "Error in svq1_decode_delta_block %i\n",result);
            goto err;
          }
        }
        pmv[0].x =
        pmv[0].y = 0;
        current += 16*linesize;
      }
    }
  }
  *pict = s->current_picture.f;
  ff_MPV_frame_end(s);
  *data_size=sizeof(AVFrame);
  result = buf_size;
err:
  av_free(pmv);
  return result;
}


static void ogg_free(AVFormatContext *s)

{

    int i;

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

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

        OGGStreamContext *oggstream = st->priv_data;

        if (st->codecpar->codec_id == AV_CODEC_ID_FLAC ||

            st->codecpar->codec_id == AV_CODEC_ID_SPEEX ||

            st->codecpar->codec_id == AV_CODEC_ID_OPUS ||

            st->codecpar->codec_id == AV_CODEC_ID_VP8) {

            av_freep(&oggstream->header[0]);

        }

        av_freep(&oggstream->header[1]);

        av_freep(&st->priv_data);

    }

}


static void bdrv_drain_recurse(BlockDriverState *bs)

{

    BdrvChild *child;

    if (bs->drv && bs->drv->bdrv_drain) {

        bs->drv->bdrv_drain(bs);

    }

    QLIST_FOREACH(child, &bs->children, next) {

        bdrv_drain_recurse(child->bs);

    }

}


static void dump_qobject(fprintf_function func_fprintf, void *f,

                         int comp_indent, QObject *obj)

{

    switch (qobject_type(obj)) {

        case QTYPE_QINT: {

            QInt *value = qobject_to_qint(obj);

            func_fprintf(f, "%" PRId64, qint_get_int(value));

            break;

        }

        case QTYPE_QSTRING: {

            QString *value = qobject_to_qstring(obj);

            func_fprintf(f, "%s", qstring_get_str(value));

            break;

        }

        case QTYPE_QDICT: {

            QDict *value = qobject_to_qdict(obj);

            dump_qdict(func_fprintf, f, comp_indent, value);

            break;

        }

        case QTYPE_QLIST: {

            QList *value = qobject_to_qlist(obj);

            dump_qlist(func_fprintf, f, comp_indent, value);

            break;

        }

        case QTYPE_QFLOAT: {

            QFloat *value = qobject_to_qfloat(obj);

            func_fprintf(f, "%g", qfloat_get_double(value));

            break;

        }

        case QTYPE_QBOOL: {

            QBool *value = qobject_to_qbool(obj);

            func_fprintf(f, "%s", qbool_get_int(value) ? "true" : "false");

            break;

        }

        case QTYPE_QERROR: {

            QString *value = qerror_human((QError *)obj);

            func_fprintf(f, "%s", qstring_get_str(value));

            QDECREF(value);

            break;

        }

        case QTYPE_NONE:

            break;

        case QTYPE_MAX:

        default:

            abort();

    }

}


vmxnet3_dump_tx_descr(struct Vmxnet3_TxDesc *descr)

{

    VMW_PKPRN("TX DESCR: "

              "addr %" PRIx64 ", len: %d, gen: %d, rsvd: %d, "

              "dtype: %d, ext1: %d, msscof: %d, hlen: %d, om: %d, "

              "eop: %d, cq: %d, ext2: %d, ti: %d, tci: %d",

              le64_to_cpu(descr->addr), descr->len, descr->gen, descr->rsvd,

              descr->dtype, descr->ext1, descr->msscof, descr->hlen, descr->om,

              descr->eop, descr->cq, descr->ext2, descr->ti, descr->tci);

}


build_dsdt(GArray *table_data, GArray *linker,

           AcpiCpuInfo *cpu, AcpiPmInfo *pm, AcpiMiscInfo *misc,

           PcPciInfo *pci)

{

    CrsRangeEntry *entry;

    Aml *dsdt, *sb_scope, *scope, *dev, *method, *field, *pkg, *crs;

    GPtrArray *mem_ranges = g_ptr_array_new_with_free_func(crs_range_free);

    GPtrArray *io_ranges = g_ptr_array_new_with_free_func(crs_range_free);

    MachineState *machine = MACHINE(qdev_get_machine());

    PCMachineState *pcms = PC_MACHINE(machine);

    uint32_t nr_mem = machine->ram_slots;

    int root_bus_limit = 0xFF;

    PCIBus *bus = NULL;

    int i;

    dsdt = init_aml_allocator();

    /* Reserve space for header */

    acpi_data_push(dsdt->buf, sizeof(AcpiTableHeader));

    build_dbg_aml(dsdt);

    if (misc->is_piix4) {

        sb_scope = aml_scope("_SB");

        dev = aml_device("PCI0");

        aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0A03")));

        aml_append(dev, aml_name_decl("_ADR", aml_int(0)));

        aml_append(dev, aml_name_decl("_UID", aml_int(1)));

        aml_append(sb_scope, dev);

        aml_append(dsdt, sb_scope);

        build_hpet_aml(dsdt);

        build_piix4_pm(dsdt);

        build_piix4_isa_bridge(dsdt);

        build_isa_devices_aml(dsdt);

        build_piix4_pci_hotplug(dsdt);

        build_piix4_pci0_int(dsdt);

    } else {

        sb_scope = aml_scope("_SB");

        aml_append(sb_scope,

            aml_operation_region("PCST", AML_SYSTEM_IO, 0xae00, 0x0c));

        aml_append(sb_scope,

            aml_operation_region("PCSB", AML_SYSTEM_IO, 0xae0c, 0x01));

        field = aml_field("PCSB", AML_ANY_ACC, AML_NOLOCK, AML_WRITE_AS_ZEROS);

        aml_append(field, aml_named_field("PCIB", 8));

        aml_append(sb_scope, field);

        aml_append(dsdt, sb_scope);

        sb_scope = aml_scope("_SB");

        dev = aml_device("PCI0");

        aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0A08")));

        aml_append(dev, aml_name_decl("_CID", aml_eisaid("PNP0A03")));

        aml_append(dev, aml_name_decl("_ADR", aml_int(0)));

        aml_append(dev, aml_name_decl("_UID", aml_int(1)));

        aml_append(dev, aml_name_decl("SUPP", aml_int(0)));

        aml_append(dev, aml_name_decl("CTRL", aml_int(0)));

        aml_append(dev, build_q35_osc_method());

        aml_append(sb_scope, dev);

        aml_append(dsdt, sb_scope);

        build_hpet_aml(dsdt);

        build_q35_isa_bridge(dsdt);

        build_isa_devices_aml(dsdt);

        build_q35_pci0_int(dsdt);

    }

    build_cpu_hotplug_aml(dsdt);

    build_memory_hotplug_aml(dsdt, nr_mem, pm->mem_hp_io_base,

                             pm->mem_hp_io_len);

    scope =  aml_scope("_GPE");

    {

        aml_append(scope, aml_name_decl("_HID", aml_string("ACPI0006")));

        aml_append(scope, aml_method("_L00", 0, AML_NOTSERIALIZED));

        if (misc->is_piix4) {

            method = aml_method("_E01", 0, AML_NOTSERIALIZED);

            aml_append(method,

                aml_acquire(aml_name("\\_SB.PCI0.BLCK"), 0xFFFF));

            aml_append(method, aml_call0("\\_SB.PCI0.PCNT"));

            aml_append(method, aml_release(aml_name("\\_SB.PCI0.BLCK")));

            aml_append(scope, method);

        } else {

            aml_append(scope, aml_method("_L01", 0, AML_NOTSERIALIZED));

        }

        method = aml_method("_E02", 0, AML_NOTSERIALIZED);

        aml_append(method, aml_call0("\\_SB." CPU_SCAN_METHOD));

        aml_append(scope, method);

        method = aml_method("_E03", 0, AML_NOTSERIALIZED);

        aml_append(method, aml_call0(MEMORY_HOTPLUG_HANDLER_PATH));

        aml_append(scope, method);

        aml_append(scope, aml_method("_L04", 0, AML_NOTSERIALIZED));

        aml_append(scope, aml_method("_L05", 0, AML_NOTSERIALIZED));

        aml_append(scope, aml_method("_L06", 0, AML_NOTSERIALIZED));

        aml_append(scope, aml_method("_L07", 0, AML_NOTSERIALIZED));

        aml_append(scope, aml_method("_L08", 0, AML_NOTSERIALIZED));

        aml_append(scope, aml_method("_L09", 0, AML_NOTSERIALIZED));

        aml_append(scope, aml_method("_L0A", 0, AML_NOTSERIALIZED));

        aml_append(scope, aml_method("_L0B", 0, AML_NOTSERIALIZED));

        aml_append(scope, aml_method("_L0C", 0, AML_NOTSERIALIZED));

        aml_append(scope, aml_method("_L0D", 0, AML_NOTSERIALIZED));

        aml_append(scope, aml_method("_L0E", 0, AML_NOTSERIALIZED));

        aml_append(scope, aml_method("_L0F", 0, AML_NOTSERIALIZED));

    }

    aml_append(dsdt, scope);

    bus = PC_MACHINE(machine)->bus;

    if (bus) {

        QLIST_FOREACH(bus, &bus->child, sibling) {

            uint8_t bus_num = pci_bus_num(bus);

            uint8_t numa_node = pci_bus_numa_node(bus);

            /* look only for expander root buses */

            if (!pci_bus_is_root(bus)) {

                continue;

            }

            if (bus_num < root_bus_limit) {

                root_bus_limit = bus_num - 1;

            }

            scope = aml_scope("\\_SB");

            dev = aml_device("PC%.02X", bus_num);

            aml_append(dev, aml_name_decl("_UID", aml_int(bus_num)));

            aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0A03")));

            aml_append(dev, aml_name_decl("_BBN", aml_int(bus_num)));

            if (numa_node != NUMA_NODE_UNASSIGNED) {

                aml_append(dev, aml_name_decl("_PXM", aml_int(numa_node)));

            }

            aml_append(dev, build_prt(false));

            crs = build_crs(PCI_HOST_BRIDGE(BUS(bus)->parent),

                            io_ranges, mem_ranges);

            aml_append(dev, aml_name_decl("_CRS", crs));

            aml_append(scope, dev);

            aml_append(dsdt, scope);

        }

    }

    scope = aml_scope("\\_SB.PCI0");

    /* build PCI0._CRS */

    crs = aml_resource_template();

    aml_append(crs,

        aml_word_bus_number(AML_MIN_FIXED, AML_MAX_FIXED, AML_POS_DECODE,

                            0x0000, 0x0, root_bus_limit,

                            0x0000, root_bus_limit + 1));

    aml_append(crs, aml_io(AML_DECODE16, 0x0CF8, 0x0CF8, 0x01, 0x08));

    aml_append(crs,

        aml_word_io(AML_MIN_FIXED, AML_MAX_FIXED,

                    AML_POS_DECODE, AML_ENTIRE_RANGE,

                    0x0000, 0x0000, 0x0CF7, 0x0000, 0x0CF8));

    crs_replace_with_free_ranges(io_ranges, 0x0D00, 0xFFFF);

    for (i = 0; i < io_ranges->len; i++) {

        entry = g_ptr_array_index(io_ranges, i);

        aml_append(crs,

            aml_word_io(AML_MIN_FIXED, AML_MAX_FIXED,

                        AML_POS_DECODE, AML_ENTIRE_RANGE,

                        0x0000, entry->base, entry->limit,

                        0x0000, entry->limit - entry->base + 1));

    }

    aml_append(crs,

        aml_dword_memory(AML_POS_DECODE, AML_MIN_FIXED, AML_MAX_FIXED,

                         AML_CACHEABLE, AML_READ_WRITE,

                         0, 0x000A0000, 0x000BFFFF, 0, 0x00020000));

    crs_replace_with_free_ranges(mem_ranges, pci->w32.begin, pci->w32.end - 1);

    for (i = 0; i < mem_ranges->len; i++) {

        entry = g_ptr_array_index(mem_ranges, i);

        aml_append(crs,

            aml_dword_memory(AML_POS_DECODE, AML_MIN_FIXED, AML_MAX_FIXED,

                             AML_NON_CACHEABLE, AML_READ_WRITE,

                             0, entry->base, entry->limit,

                             0, entry->limit - entry->base + 1));

    }

    if (pci->w64.begin) {

        aml_append(crs,

            aml_qword_memory(AML_POS_DECODE, AML_MIN_FIXED, AML_MAX_FIXED,

                             AML_CACHEABLE, AML_READ_WRITE,

                             0, pci->w64.begin, pci->w64.end - 1, 0,

                             pci->w64.end - pci->w64.begin));

    }

    aml_append(scope, aml_name_decl("_CRS", crs));

    /* reserve GPE0 block resources */

    dev = aml_device("GPE0");

    aml_append(dev, aml_name_decl("_HID", aml_string("PNP0A06")));

    aml_append(dev, aml_name_decl("_UID", aml_string("GPE0 resources")));

    /* device present, functioning, decoding, not shown in UI */

    aml_append(dev, aml_name_decl("_STA", aml_int(0xB)));

    crs = aml_resource_template();

    aml_append(crs,

        aml_io(AML_DECODE16, pm->gpe0_blk, pm->gpe0_blk, 1, pm->gpe0_blk_len)

    );

    aml_append(dev, aml_name_decl("_CRS", crs));

    aml_append(scope, dev);

    g_ptr_array_free(io_ranges, true);

    g_ptr_array_free(mem_ranges, true);

    /* reserve PCIHP resources */

    if (pm->pcihp_io_len) {

        dev = aml_device("PHPR");

        aml_append(dev, aml_name_decl("_HID", aml_string("PNP0A06")));

        aml_append(dev,

            aml_name_decl("_UID", aml_string("PCI Hotplug resources")));

        /* device present, functioning, decoding, not shown in UI */

        aml_append(dev, aml_name_decl("_STA", aml_int(0xB)));

        crs = aml_resource_template();

        aml_append(crs,

            aml_io(AML_DECODE16, pm->pcihp_io_base, pm->pcihp_io_base, 1,

                   pm->pcihp_io_len)

        );

        aml_append(dev, aml_name_decl("_CRS", crs));

        aml_append(scope, dev);

    }

    aml_append(dsdt, scope);

    /*  create S3_ / S4_ / S5_ packages if necessary */

    scope = aml_scope("\\");

    if (!pm->s3_disabled) {

        pkg = aml_package(4);

        aml_append(pkg, aml_int(1)); /* PM1a_CNT.SLP_TYP */

        aml_append(pkg, aml_int(1)); /* PM1b_CNT.SLP_TYP, FIXME: not impl. */

        aml_append(pkg, aml_int(0)); /* reserved */

        aml_append(pkg, aml_int(0)); /* reserved */

        aml_append(scope, aml_name_decl("_S3", pkg));

    }

    if (!pm->s4_disabled) {

        pkg = aml_package(4);

        aml_append(pkg, aml_int(pm->s4_val)); /* PM1a_CNT.SLP_TYP */

        /* PM1b_CNT.SLP_TYP, FIXME: not impl. */

        aml_append(pkg, aml_int(pm->s4_val));

        aml_append(pkg, aml_int(0)); /* reserved */

        aml_append(pkg, aml_int(0)); /* reserved */

        aml_append(scope, aml_name_decl("_S4", pkg));

    }

    pkg = aml_package(4);

    aml_append(pkg, aml_int(0)); /* PM1a_CNT.SLP_TYP */

    aml_append(pkg, aml_int(0)); /* PM1b_CNT.SLP_TYP not impl. */

    aml_append(pkg, aml_int(0)); /* reserved */

    aml_append(pkg, aml_int(0)); /* reserved */

    aml_append(scope, aml_name_decl("_S5", pkg));

    aml_append(dsdt, scope);

    if (misc->applesmc_io_base) {

        scope = aml_scope("\\_SB.PCI0.ISA");

        dev = aml_device("SMC");

        aml_append(dev, aml_name_decl("_HID", aml_eisaid("APP0001")));

        /* device present, functioning, decoding, not shown in UI */

        aml_append(dev, aml_name_decl("_STA", aml_int(0xB)));

        crs = aml_resource_template();

        aml_append(crs,

            aml_io(AML_DECODE16, misc->applesmc_io_base, misc->applesmc_io_base,

                   0x01, APPLESMC_MAX_DATA_LENGTH)

        );

        aml_append(crs, aml_irq_no_flags(6));

        aml_append(dev, aml_name_decl("_CRS", crs));

        aml_append(scope, dev);

        aml_append(dsdt, scope);

    }

    if (misc->pvpanic_port) {

        scope = aml_scope("\\_SB.PCI0.ISA");

        dev = aml_device("PEVT");

        aml_append(dev, aml_name_decl("_HID", aml_string("QEMU0001")));

        crs = aml_resource_template();

        aml_append(crs,

            aml_io(AML_DECODE16, misc->pvpanic_port, misc->pvpanic_port, 1, 1)

        );

        aml_append(dev, aml_name_decl("_CRS", crs));

        aml_append(dev, aml_operation_region("PEOR", AML_SYSTEM_IO,

                                              misc->pvpanic_port, 1));

        field = aml_field("PEOR", AML_BYTE_ACC, AML_NOLOCK, AML_PRESERVE);

        aml_append(field, aml_named_field("PEPT", 8));

        aml_append(dev, field);

        /* device present, functioning, decoding, shown in UI */

        aml_append(dev, aml_name_decl("_STA", aml_int(0xF)));

        method = aml_method("RDPT", 0, AML_NOTSERIALIZED);

        aml_append(method, aml_store(aml_name("PEPT"), aml_local(0)));

        aml_append(method, aml_return(aml_local(0)));

        aml_append(dev, method);

        method = aml_method("WRPT", 1, AML_NOTSERIALIZED);

        aml_append(method, aml_store(aml_arg(0), aml_name("PEPT")));

        aml_append(dev, method);

        aml_append(scope, dev);

        aml_append(dsdt, scope);

    }

    sb_scope = aml_scope("\\_SB");

    {

        build_processor_devices(sb_scope, pcms->apic_id_limit, cpu, pm);

        build_memory_devices(sb_scope, nr_mem, pm->mem_hp_io_base,

                             pm->mem_hp_io_len);

        {

            Object *pci_host;

            PCIBus *bus = NULL;

            pci_host = acpi_get_i386_pci_host();

            if (pci_host) {

                bus = PCI_HOST_BRIDGE(pci_host)->bus;

            }

            if (bus) {

                Aml *scope = aml_scope("PCI0");

                /* Scan all PCI buses. Generate tables to support hotplug. */

                build_append_pci_bus_devices(scope, bus, pm->pcihp_bridge_en);

                if (misc->tpm_version != TPM_VERSION_UNSPEC) {

                    dev = aml_device("ISA.TPM");

                    aml_append(dev, aml_name_decl("_HID", aml_eisaid("PNP0C31")));

                    aml_append(dev, aml_name_decl("_STA", aml_int(0xF)));

                    crs = aml_resource_template();

                    aml_append(crs, aml_memory32_fixed(TPM_TIS_ADDR_BASE,

                               TPM_TIS_ADDR_SIZE, AML_READ_WRITE));

                    aml_append(crs, aml_irq_no_flags(TPM_TIS_IRQ));

                    aml_append(dev, aml_name_decl("_CRS", crs));

                    aml_append(scope, dev);

                }

                aml_append(sb_scope, scope);

            }

        }

        aml_append(dsdt, sb_scope);

    }

    /* copy AML table into ACPI tables blob and patch header there */

    g_array_append_vals(table_data, dsdt->buf->data, dsdt->buf->len);

    build_header(linker, table_data,

        (void *)(table_data->data + table_data->len - dsdt->buf->len),

        "DSDT", dsdt->buf->len, 1, NULL);

    free_aml_allocator();

}


INLINE bits64 extractFloat64Frac( float64 a )

{

    return a & LIT64( 0x000FFFFFFFFFFFFF );

}


setup_sigcontext(struct target_sigcontext *sc, struct target_fpstate *fpstate,

		 CPUX86State *env, unsigned long mask)

{

	int err = 0;

	err |= __put_user(env->segs[R_GS], (unsigned int *)&sc->gs);

	err |= __put_user(env->segs[R_FS], (unsigned int *)&sc->fs);

	err |= __put_user(env->segs[R_ES], (unsigned int *)&sc->es);

	err |= __put_user(env->segs[R_DS], (unsigned int *)&sc->ds);

	err |= __put_user(env->regs[R_EDI], &sc->edi);

	err |= __put_user(env->regs[R_ESI], &sc->esi);

	err |= __put_user(env->regs[R_EBP], &sc->ebp);

	err |= __put_user(env->regs[R_ESP], &sc->esp);

	err |= __put_user(env->regs[R_EBX], &sc->ebx);

	err |= __put_user(env->regs[R_EDX], &sc->edx);

	err |= __put_user(env->regs[R_ECX], &sc->ecx);

	err |= __put_user(env->regs[R_EAX], &sc->eax);

	err |= __put_user(env->exception_index, &sc->trapno);

	err |= __put_user(env->error_code, &sc->err);

	err |= __put_user(env->eip, &sc->eip);

	err |= __put_user(env->segs[R_CS], (unsigned int *)&sc->cs);

	err |= __put_user(env->eflags, &sc->eflags);

	err |= __put_user(env->regs[R_ESP], &sc->esp_at_signal);

	err |= __put_user(env->segs[R_SS], (unsigned int *)&sc->ss);

#if 0

	tmp = save_i387(fpstate);

	if (tmp < 0)

	  err = 1;

	else

	  err |= __put_user(tmp ? fpstate : NULL, &sc->fpstate);

#else

        err |= __put_user(0, &sc->fpstate);

#endif

	/* non-iBCS2 extensions.. */

	err |= __put_user(mask, &sc->oldmask);

	err |= __put_user(/*current->thread.cr2*/ 0, &sc->cr2);

	return err;

}


static void esp_command_complete(SCSIBus *bus, int reason, uint32_t tag,

                                 uint32_t arg)

{

    ESPState *s = DO_UPCAST(ESPState, busdev.qdev, bus->qbus.parent);

    if (reason == SCSI_REASON_DONE) {

        DPRINTF("SCSI Command complete\n");

        if (s->ti_size != 0)

            DPRINTF("SCSI command completed unexpectedly\n");

        s->ti_size = 0;

        s->dma_left = 0;

        s->async_len = 0;

        if (arg)

            DPRINTF("Command failed\n");

        s->sense = arg;

        s->rregs[ESP_RSTAT] = STAT_ST;

        esp_dma_done(s);

        s->current_dev = NULL;

    } else {

        DPRINTF("transfer %d/%d\n", s->dma_left, s->ti_size);

        s->async_len = arg;

        s->async_buf = s->current_dev->info->get_buf(s->current_dev, 0);

        if (s->dma_left) {

            esp_do_dma(s);

        } else if (s->dma_counter != 0 && s->ti_size <= 0) {

            /* If this was the last part of a DMA transfer then the

               completion interrupt is deferred to here.  */

            esp_dma_done(s);

        }

    }

}


static inline CopyRet receive_frame(AVCodecContext *avctx,

                                    void *data, int *data_size,

                                    uint8_t second_field)

{

    BC_STATUS ret;

    BC_DTS_PROC_OUT output = {

        .PicInfo.width  = avctx->width,

        .PicInfo.height = avctx->height,

    };

    CHDContext *priv = avctx->priv_data;

    HANDLE dev       = priv->dev;

    *data_size = 0;

    // Request decoded data from the driver

    ret = DtsProcOutputNoCopy(dev, OUTPUT_PROC_TIMEOUT, &output);

    if (ret == BC_STS_FMT_CHANGE) {

        av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Initial format change\n");

        avctx->width  = output.PicInfo.width;

        avctx->height = output.PicInfo.height;

        return RET_COPY_AGAIN;

    } else if (ret == BC_STS_SUCCESS) {

        int copy_ret = -1;

        if (output.PoutFlags & BC_POUT_FLAGS_PIB_VALID) {

            if (priv->last_picture == -1) {

                /*

                 * Init to one less, so that the incrementing code doesn't

                 * need to be special-cased.

                 */

                priv->last_picture = output.PicInfo.picture_number - 1;

            }

            if (avctx->codec->id == CODEC_ID_MPEG4 &&

                output.PicInfo.timeStamp == 0) {

                av_log(avctx, AV_LOG_VERBOSE,

                       "CrystalHD: Not returning packed frame twice.\n");

                priv->last_picture++;

                DtsReleaseOutputBuffs(dev, NULL, FALSE);

                return RET_COPY_AGAIN;

            }

            print_frame_info(priv, &output);

            if (priv->last_picture + 1 < output.PicInfo.picture_number) {

                av_log(avctx, AV_LOG_WARNING,

                       "CrystalHD: Picture Number discontinuity\n");

                /*

                 * Have we lost frames? If so, we need to shrink the

                 * pipeline length appropriately.

                 *

                 * XXX: I have no idea what the semantics of this situation

                 * are so I don't even know if we've lost frames or which

                 * ones.

                 *

                 * In any case, only warn the first time.

                 */

               priv->last_picture = output.PicInfo.picture_number - 1;

            }

            copy_ret = copy_frame(avctx, &output, data, data_size, second_field);

            if (*data_size > 0) {

                avctx->has_b_frames--;

                priv->last_picture++;

                av_log(avctx, AV_LOG_VERBOSE, "CrystalHD: Pipeline length: %u\n",

                       avctx->has_b_frames);

            }

        } else {

            /*

             * An invalid frame has been consumed.

             */

            av_log(avctx, AV_LOG_ERROR, "CrystalHD: ProcOutput succeeded with "

                                        "invalid PIB\n");

            avctx->has_b_frames--;

            copy_ret = RET_OK;

        }

        DtsReleaseOutputBuffs(dev, NULL, FALSE);

        return copy_ret;

    } else if (ret == BC_STS_BUSY) {

        return RET_COPY_AGAIN;

    } else {

        av_log(avctx, AV_LOG_ERROR, "CrystalHD: ProcOutput failed %d\n", ret);

        return RET_ERROR;

    }

}


static int encode_frame(AVCodecContext *avctx, QSVEncContext *q,

                        const AVFrame *frame)

{

    AVPacket new_pkt = { 0 };

    mfxBitstream *bs;

    mfxFrameSurface1 *surf = NULL;

    mfxSyncPoint sync      = NULL;

    int ret;

    if (frame) {

        ret = submit_frame(q, frame, &surf);

        if (ret < 0) {

            av_log(avctx, AV_LOG_ERROR, "Error submitting the frame for encoding.\n");

            return ret;

        }

    }

    ret = av_new_packet(&new_pkt, q->packet_size);

    if (ret < 0) {

        av_log(avctx, AV_LOG_ERROR, "Error allocating the output packet\n");

        return ret;

    }

    bs = av_mallocz(sizeof(*bs));

    if (!bs) {

        av_packet_unref(&new_pkt);

        return AVERROR(ENOMEM);

    }

    bs->Data      = new_pkt.data;

    bs->MaxLength = new_pkt.size;

    do {

        ret = MFXVideoENCODE_EncodeFrameAsync(q->session, NULL, surf, bs, &sync);

        if (ret == MFX_WRN_DEVICE_BUSY)

            av_usleep(1);

    } while (ret > 0);

    if (ret < 0) {

        av_packet_unref(&new_pkt);

        av_freep(&bs);

        return (ret == MFX_ERR_MORE_DATA) ? 0 : ff_qsv_error(ret);

    }

    if (ret == MFX_WRN_INCOMPATIBLE_VIDEO_PARAM && frame->interlaced_frame)

        print_interlace_msg(avctx, q);

    if (sync) {

        av_fifo_generic_write(q->async_fifo, &new_pkt, sizeof(new_pkt), NULL);

        av_fifo_generic_write(q->async_fifo, &sync,    sizeof(sync),    NULL);

        av_fifo_generic_write(q->async_fifo, &bs,      sizeof(bs),    NULL);

    } else {

        av_packet_unref(&new_pkt);

        av_freep(&bs);

    }

    return 0;

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);

    EHCIPCIInfo *i = data;

    k->init = usb_ehci_pci_initfn;

    k->vendor_id = i->vendor_id;

    k->device_id = i->device_id;

    k->revision = i->revision;

    k->class_id = PCI_CLASS_SERIAL_USB;

    k->config_write = usb_ehci_pci_write_config;

    dc->vmsd = &vmstate_ehci_pci;

    dc->props = ehci_pci_properties;

}


static void curses_refresh(DisplayChangeListener *dcl)

{

    int chr, nextchr, keysym, keycode, keycode_alt;

    curses_winch_check();

    if (invalidate) {

        clear();

        refresh();

        curses_calc_pad();

        graphic_hw_invalidate(NULL);

        invalidate = 0;

    }

    graphic_hw_text_update(NULL, screen);

    nextchr = ERR;

    while (1) {

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

        if (nextchr == ERR)

            chr = getch();

        else {

            chr = nextchr;

            nextchr = ERR;

        }

        if (chr == ERR)

            break;

#ifdef KEY_RESIZE

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

        if (chr == KEY_RESIZE) {

            clear();

            refresh();

            curses_calc_pad();

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

            continue;

        }

#endif

        keycode = curses2keycode[chr];

        keycode_alt = 0;

        /* alt key */

        if (keycode == 1) {

            nextchr = getch();

            if (nextchr != ERR) {

                chr = nextchr;

                keycode_alt = ALT;

                keycode = curses2keycode[nextchr];

                nextchr = ERR;

                if (keycode != -1) {

                    keycode |= ALT;

                    /* process keys reserved for qemu */

                    if (keycode >= QEMU_KEY_CONSOLE0 &&

                            keycode < QEMU_KEY_CONSOLE0 + 9) {

                        erase();

                        wnoutrefresh(stdscr);

                        console_select(keycode - QEMU_KEY_CONSOLE0);

                        invalidate = 1;

                        continue;

                    }

                }

            }

        }

        if (kbd_layout) {

            keysym = -1;

            if (chr < CURSES_KEYS)

                keysym = curses2keysym[chr];

            if (keysym == -1) {

                if (chr < ' ') {

                    keysym = chr + '@';

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

                        keysym += 'a' - 'A';

                    keysym |= KEYSYM_CNTRL;

                } else

                    keysym = chr;

            }

            keycode = keysym2scancode(kbd_layout, keysym & KEYSYM_MASK);

            if (keycode == 0)

                continue;

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

            keycode |= keycode_alt;

        }

        if (keycode == -1)

            continue;

        if (qemu_console_is_graphic(NULL)) {

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

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

            if (keycode & SHIFT) {

                qemu_input_event_send_key_number(NULL, SHIFT_CODE, true);

                qemu_input_event_send_key_delay(0);

            }

            if (keycode & CNTRL) {

                qemu_input_event_send_key_number(NULL, CNTRL_CODE, true);

                qemu_input_event_send_key_delay(0);

            }

            if (keycode & ALT) {

                qemu_input_event_send_key_number(NULL, ALT_CODE, true);

                qemu_input_event_send_key_delay(0);

            }

            if (keycode & ALTGR) {

                qemu_input_event_send_key_number(NULL, GREY | ALT_CODE, true);

                qemu_input_event_send_key_delay(0);

            }

            qemu_input_event_send_key_number(NULL, keycode & KEY_MASK, true);

            qemu_input_event_send_key_delay(0);

            qemu_input_event_send_key_number(NULL, keycode & KEY_MASK, false);

            qemu_input_event_send_key_delay(0);

            if (keycode & ALTGR) {

                qemu_input_event_send_key_number(NULL, GREY | ALT_CODE, false);

                qemu_input_event_send_key_delay(0);

            }

            if (keycode & ALT) {

                qemu_input_event_send_key_number(NULL, ALT_CODE, false);

                qemu_input_event_send_key_delay(0);

            }

            if (keycode & CNTRL) {

                qemu_input_event_send_key_number(NULL, CNTRL_CODE, false);

                qemu_input_event_send_key_delay(0);

            }

            if (keycode & SHIFT) {

                qemu_input_event_send_key_number(NULL, SHIFT_CODE, false);

                qemu_input_event_send_key_delay(0);

            }

        } else {

            keysym = -1;

            if (chr < CURSES_KEYS) {

                keysym = curses2qemu[chr];

            }

            if (keysym == -1)

                keysym = chr;

            kbd_put_keysym(keysym);

        }

    }

}


static ssize_t proxy_lgetxattr(FsContext *ctx, V9fsPath *fs_path,

                               const char *name, void *value, size_t size)

{

    int retval;

    V9fsString xname;

    v9fs_string_init(&xname);

    v9fs_string_sprintf(&xname, "%s", name);

    retval = v9fs_request(ctx->private, T_LGETXATTR, value, "dss", size,

                          fs_path, &xname);

    v9fs_string_free(&xname);

    if (retval < 0) {

        errno = -retval;

    }

    return retval;

}


static void cadence_timer_sync(CadenceTimerState *s)

{

    int i;

    int64_t r, x;

    int64_t interval = ((s->reg_count & COUNTER_CTRL_INT) ?

            (int64_t)s->reg_interval + 1 : 0x10000ULL) << 16;

    uint64_t old_time = s->cpu_time;

    s->cpu_time = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);

    DB_PRINT("cpu time: %lld ns\n", (long long)old_time);

    if (!s->cpu_time_valid || old_time == s->cpu_time) {

        s->cpu_time_valid = 1;

        return;

    }

    r = (int64_t)cadence_timer_get_steps(s, s->cpu_time - old_time);

    x = (int64_t)s->reg_value + ((s->reg_count & COUNTER_CTRL_DEC) ? -r : r);

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

        int64_t m = (int64_t)s->reg_match[i] << 16;

        if (m > interval) {

            continue;

        }

        /* check to see if match event has occurred. check m +/- interval

         * to account for match events in wrap around cases */

        if (is_between(m, s->reg_value, x) ||

            is_between(m + interval, s->reg_value, x) ||

            is_between(m - interval, s->reg_value, x)) {

            s->reg_intr |= (2 << i);

        }

    }

    while (x < 0) {

        x += interval;

    }

    s->reg_value = (uint32_t)(x % interval);

    if (s->reg_value != x) {

        s->reg_intr |= (s->reg_count & COUNTER_CTRL_INT) ?

            COUNTER_INTR_IV : COUNTER_INTR_OV;

    }

    cadence_timer_update(s);

}


static void tcg_out_brcond_i64(TCGContext *s, TCGCond cond, TCGReg arg1,

                               int32_t arg2, int const_arg2, int label)

{

    /* For 64-bit signed comparisons vs zero, we can avoid the compare.  */

    if (arg2 == 0 && !is_unsigned_cond(cond)) {

        TCGLabel *l = &s->labels[label];

        int off16;

        if (l->has_value) {

            off16 = INSN_OFF16(tcg_pcrel_diff(s, l->u.value_ptr));

        } else {

            /* Make sure to preserve destinations during retranslation.  */

            off16 = *s->code_ptr & INSN_OFF16(-1);

            tcg_out_reloc(s, s->code_ptr, R_SPARC_WDISP16, label, 0);

        }

        tcg_out32(s, INSN_OP(0) | INSN_OP2(3) | BPR_PT | INSN_RS1(arg1)

                  | INSN_COND(tcg_cond_to_rcond[cond]) | off16);

    } else {

        tcg_out_cmp(s, arg1, arg2, const_arg2);

        tcg_out_bpcc(s, tcg_cond_to_bcond[cond], BPCC_XCC | BPCC_PT, label);

    }

    tcg_out_nop(s);

}


int pci_bridge_initfn(PCIDevice *dev)

{

    PCIBus *parent = dev->bus;

    PCIBridge *br = DO_UPCAST(PCIBridge, dev, dev);

    PCIBus *sec_bus = &br->sec_bus;

    pci_set_word(dev->config + PCI_STATUS,

                 PCI_STATUS_66MHZ | PCI_STATUS_FAST_BACK);

    pci_config_set_class(dev->config, PCI_CLASS_BRIDGE_PCI);

    dev->config[PCI_HEADER_TYPE] =

        (dev->config[PCI_HEADER_TYPE] & PCI_HEADER_TYPE_MULTI_FUNCTION) |

        PCI_HEADER_TYPE_BRIDGE;

    pci_set_word(dev->config + PCI_SEC_STATUS,

                 PCI_STATUS_66MHZ | PCI_STATUS_FAST_BACK);

    qbus_create_inplace(&sec_bus->qbus, &pci_bus_info, &dev->qdev,

                        br->bus_name);

    sec_bus->parent_dev = dev;

    sec_bus->map_irq = br->map_irq;

    sec_bus->address_space_mem = &br->address_space_mem;

    memory_region_init(&br->address_space_mem, "pci_bridge_pci", INT64_MAX);

    sec_bus->address_space_io = &br->address_space_io;

    memory_region_init(&br->address_space_io, "pci_bridge_io", 65536);

    pci_bridge_region_init(br);

    QLIST_INIT(&sec_bus->child);

    QLIST_INSERT_HEAD(&parent->child, sec_bus, sibling);

    return 0;

}


static void clear_sdr_rep(IPMIBmcSim *ibs,

                          uint8_t *cmd, unsigned int cmd_len,

                          uint8_t *rsp, unsigned int *rsp_len,

                          unsigned int max_rsp_len)

{

    IPMI_CHECK_CMD_LEN(8);

    IPMI_CHECK_RESERVATION(2, ibs->sdr.reservation);

    if (cmd[4] != 'C' || cmd[5] != 'L' || cmd[6] != 'R') {

        rsp[2] = IPMI_CC_INVALID_DATA_FIELD;

        return;

    }

    if (cmd[7] == 0xaa) {

        ibs->sdr.next_free = 0;

        ibs->sdr.overflow = 0;

        set_timestamp(ibs, ibs->sdr.last_clear);

        IPMI_ADD_RSP_DATA(1); /* Erasure complete */

        sdr_inc_reservation(&ibs->sdr);

    } else if (cmd[7] == 0) {

        IPMI_ADD_RSP_DATA(1); /* Erasure complete */

    } else {

        rsp[2] = IPMI_CC_INVALID_DATA_FIELD;

        return;

    }

}


static inline void RENAME(initFilter)(int16_t *dstFilter, int16_t *filterPos, int *filterSize, int xInc,

				      int srcW, int dstW, int filterAlign, int one)

{

	int i;

	double filter[8000];

#ifdef HAVE_MMX

	asm volatile("emms\n\t"::: "memory"); //FIXME this shouldnt be required but it IS (even for non mmx versions)

#endif

	if(ABS(xInc - 0x10000) <10) // unscaled

	{

		int i;

		*filterSize= (1 +(filterAlign-1)) & (~(filterAlign-1)); // 1 or 4 normaly

		for(i=0; i<dstW*(*filterSize); i++) filter[i]=0;

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

		{

			filter[i*(*filterSize)]=1;

			filterPos[i]=i;

		}

	}

	else if(xInc <= (1<<16) || sws_flags==SWS_FAST_BILINEAR) // upscale

	{

		int i;

		int xDstInSrc;

		if(sws_flags==SWS_BICUBIC) *filterSize= 4;

		else			   *filterSize= 2;

//		printf("%d %d %d\n", filterSize, srcW, dstW);

		*filterSize= (*filterSize +(filterAlign-1)) & (~(filterAlign-1));

		xDstInSrc= xInc/2 - 0x8000;

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

		{

			int xx= (xDstInSrc>>16) - (*filterSize>>1) + 1;

			int j;

			filterPos[i]= xx;

			if(sws_flags == SWS_BICUBIC)

			{

				double d= ABS(((xx+1)<<16) - xDstInSrc)/(double)(1<<16);

				double y1,y2,y3,y4;

				double A= -0.75;

					// Equation is from VirtualDub

				y1 = (        +     A*d -       2.0*A*d*d +       A*d*d*d);

				y2 = (+ 1.0             -     (A+3.0)*d*d + (A+2.0)*d*d*d);

				y3 = (        -     A*d + (2.0*A+3.0)*d*d - (A+2.0)*d*d*d);

				y4 = (                  +           A*d*d -       A*d*d*d);

//				printf("%d %d %d \n", coeff, (int)d, xDstInSrc);

				filter[i*(*filterSize) + 0]= y1;

				filter[i*(*filterSize) + 1]= y2;

				filter[i*(*filterSize) + 2]= y3;

				filter[i*(*filterSize) + 3]= y4;

//				printf("%1.3f %d, %d, %d, %d\n",d , y1, y2, y3, y4);

			}

			else

			{

				for(j=0; j<*filterSize; j++)

				{

					double d= ABS((xx<<16) - xDstInSrc)/(double)(1<<16);

					double coeff= 1.0 - d;

					if(coeff<0) coeff=0;

	//				printf("%d %d %d \n", coeff, (int)d, xDstInSrc);

					filter[i*(*filterSize) + j]= coeff;

					xx++;

				}

			}

			xDstInSrc+= xInc;

		}

	}

	else // downscale

	{

		int xDstInSrc;

		if(sws_flags==SWS_BICUBIC) *filterSize= (int)ceil(1 + 4.0*srcW / (double)dstW);

		else			   *filterSize= (int)ceil(1 + 2.0*srcW / (double)dstW);

//		printf("%d %d %d\n", *filterSize, srcW, dstW);

		*filterSize= (*filterSize +(filterAlign-1)) & (~(filterAlign-1));

		xDstInSrc= xInc/2 - 0x8000;

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

		{

			int xx= (int)((double)xDstInSrc/(double)(1<<16) - ((*filterSize)-1)*0.5 + 0.5);

			int j;

			filterPos[i]= xx;

			for(j=0; j<*filterSize; j++)

			{

				double d= ABS((xx<<16) - xDstInSrc)/(double)xInc;

				double coeff;

				if(sws_flags == SWS_BICUBIC)

				{

					double A= -0.75;

//					d*=2;

					// Equation is from VirtualDub

					if(d<1.0)

						coeff = (1.0 - (A+3.0)*d*d + (A+2.0)*d*d*d);

					else if(d<2.0)

						coeff = (-4.0*A + 8.0*A*d - 5.0*A*d*d + A*d*d*d);

					else

						coeff=0.0;

				}

				else

				{

					coeff= 1.0 - d;

					if(coeff<0) coeff=0;

				}

//				if(filterAlign==1) printf("%d %d %d \n", coeff, (int)d, xDstInSrc);

				filter[i*(*filterSize) + j]= coeff;

				xx++;

			}

			xDstInSrc+= xInc;

		}

	}

	//fix borders

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

	{

		int j;

		if(filterPos[i] < 0)

		{

			// Move filter coeffs left to compensate for filterPos

			for(j=1; j<*filterSize; j++)

			{

				int left= MAX(j + filterPos[i], 0);

				filter[i*(*filterSize) + left] += filter[i*(*filterSize) + j];

				filter[i*(*filterSize) + j]=0;

			}

			filterPos[i]= 0;

		}

		if(filterPos[i] + (*filterSize) > srcW)

		{

			int shift= filterPos[i] + (*filterSize) - srcW;

			// Move filter coeffs right to compensate for filterPos

			for(j=(*filterSize)-2; j>=0; j--)

			{

				int right= MIN(j + shift, (*filterSize)-1);

				filter[i*(*filterSize) +right] += filter[i*(*filterSize) +j];

				filter[i*(*filterSize) +j]=0;

			}

			filterPos[i]= srcW - (*filterSize);

		}

	}

	//FIXME try to align filterpos if possible / try to shift filterpos to put zeros at the end

	// and skip these than later

	//Normalize

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

	{

		int j;

		double sum=0;

		double scale= one;

		for(j=0; j<*filterSize; j++)

		{

			sum+= filter[i*(*filterSize) + j];

		}

		scale/= sum;

		for(j=0; j<*filterSize; j++)

		{

			dstFilter[i*(*filterSize) + j]= (int)(filter[i*(*filterSize) + j]*scale);

		}

	}

}


static CharDriverState *qmp_chardev_open_file(const char *id,

                                              ChardevBackend *backend,

                                              ChardevReturn *ret,

                                              Error **errp)

{

    ChardevFile *file = backend->u.file;

    ChardevCommon *common = qapi_ChardevFile_base(file);

    HANDLE out;

    if (file->has_in) {

        error_setg(errp, "input file not supported");

        return NULL;

    }

    out = CreateFile(file->out, GENERIC_WRITE, FILE_SHARE_READ, NULL,

                     OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

    if (out == INVALID_HANDLE_VALUE) {

        error_setg(errp, "open %s failed", file->out);

        return NULL;

    }

    return qemu_chr_open_win_file(out, common, errp);

}


void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)

{

    if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {

        return;

    }

    bs->drv->bdrv_debug_event(bs, event);

}


static bool pc_machine_get_aligned_dimm(Object *obj, Error **errp)

{

    PCMachineState *pcms = PC_MACHINE(obj);

    return pcms->enforce_aligned_dimm;

}


static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)

{

    BlockDriver *drv = bs->drv;

    /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */

    if (bs->sg)

        return 0;

    /* query actual device if possible, otherwise just trust the hint */

    if (drv->bdrv_getlength) {

        int64_t length = drv->bdrv_getlength(bs);

        if (length < 0) {

            return length;

        }

        hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);

    }

    bs->total_sectors = hint;

    return 0;

}


BlockStatsList *qmp_query_blockstats(Error **errp)
{
    BlockStatsList *head = NULL, **p_next = &head;
    BlockDriverState *bs = NULL;
     while ((bs = bdrv_next(bs))) {
        BlockStatsList *info = g_malloc0(sizeof(*info));
        info->value = bdrv_query_stats(bs);
        *p_next = info;
        p_next = &info->next;
    }
    return head;
}


static void opt_pad_color(const char *arg) {

    /* Input is expected to be six hex digits similar to

       how colors are expressed in html tags (but without the #) */

    int rgb = strtol(arg, NULL, 16);

    int r,g,b;

    r = (rgb >> 16);

    g = ((rgb >> 8) & 255);

    b = (rgb & 255);

    padcolor[0] = RGB_TO_Y(r,g,b);

    padcolor[1] = RGB_TO_U(r,g,b,0);

    padcolor[2] = RGB_TO_V(r,g,b,0);

}


static void gen_spr_74xx (CPUPPCState *env)

{

    /* Processor identification */

    spr_register(env, SPR_PIR, "PIR",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_pir,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_MMCR2, "MMCR2",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_UMMCR2, "UMMCR2",

                 &spr_read_ureg, SPR_NOACCESS,

                 &spr_read_ureg, SPR_NOACCESS,

                 0x00000000);

    /* XXX: not implemented */

    spr_register(env, SPR_BAMR, "BAMR",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_MSSCR0, "MSSCR0",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* Hardware implementation registers */

    /* XXX : not implemented */

    spr_register(env, SPR_HID0, "HID0",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_HID1, "HID1",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* Altivec */

    spr_register(env, SPR_VRSAVE, "VRSAVE",

                 &spr_read_generic, &spr_write_generic,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_L2CR, "L2CR",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, NULL,

                 0x00000000);

    /* Not strictly an SPR */

    vscr_init(env, 0x00010000);

}


static int read_channels(AVFilterContext *ctx, int channels, uint8_t *item_str, int *nb, double **c, double **cache)

{

    char *p, *arg, *old_str, *prev_arg = NULL, *saveptr = NULL;

    int i, ret;

    p = old_str = av_strdup(item_str);

    if (!p)

        return AVERROR(ENOMEM);

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

        if (!(arg = av_strtok(p, "|", &saveptr)))

            arg = prev_arg;

        p = NULL;

        count_coefficients(arg, &nb[i]);

        cache[i] = av_calloc(nb[i], sizeof(cache[i]));

        c[i] = av_calloc(nb[i], sizeof(c[i]));

        if (!c[i] || !cache[i])

            return AVERROR(ENOMEM);

        ret = read_coefficients(ctx, arg, nb[i], c[i]);

        if (ret < 0)

            return ret;

        prev_arg = arg;

    }

    av_freep(&old_str);

    return 0;

}


av_cold void ff_ac3dsp_init_x86(AC3DSPContext *c, int bit_exact)

{

#if HAVE_YASM

    int mm_flags = av_get_cpu_flags();

    if (mm_flags & AV_CPU_FLAG_MMX) {

        c->ac3_exponent_min = ff_ac3_exponent_min_mmx;

        c->ac3_max_msb_abs_int16 = ff_ac3_max_msb_abs_int16_mmx;

        c->ac3_lshift_int16 = ff_ac3_lshift_int16_mmx;

        c->ac3_rshift_int32 = ff_ac3_rshift_int32_mmx;

    }

    if (mm_flags & AV_CPU_FLAG_3DNOW && HAVE_AMD3DNOW) {

        c->extract_exponents = ff_ac3_extract_exponents_3dnow;

        if (!bit_exact) {

            c->float_to_fixed24 = ff_float_to_fixed24_3dnow;

        }

    }

    if (mm_flags & AV_CPU_FLAG_MMX2 && HAVE_MMX2) {

        c->ac3_exponent_min = ff_ac3_exponent_min_mmxext;

        c->ac3_max_msb_abs_int16 = ff_ac3_max_msb_abs_int16_mmxext;

    }

    if (mm_flags & AV_CPU_FLAG_SSE && HAVE_SSE) {

        c->float_to_fixed24 = ff_float_to_fixed24_sse;

    }

    if (mm_flags & AV_CPU_FLAG_SSE2 && HAVE_SSE) {

        c->ac3_exponent_min = ff_ac3_exponent_min_sse2;

        c->ac3_max_msb_abs_int16 = ff_ac3_max_msb_abs_int16_sse2;

        c->float_to_fixed24 = ff_float_to_fixed24_sse2;

        c->compute_mantissa_size = ff_ac3_compute_mantissa_size_sse2;

        c->extract_exponents = ff_ac3_extract_exponents_sse2;

        if (!(mm_flags & AV_CPU_FLAG_SSE2SLOW)) {

            c->ac3_lshift_int16 = ff_ac3_lshift_int16_sse2;

            c->ac3_rshift_int32 = ff_ac3_rshift_int32_sse2;

        }

    }

    if (mm_flags & AV_CPU_FLAG_SSSE3 && HAVE_SSSE3) {

        c->ac3_max_msb_abs_int16 = ff_ac3_max_msb_abs_int16_ssse3;

        if (!(mm_flags & AV_CPU_FLAG_ATOM)) {

            c->extract_exponents = ff_ac3_extract_exponents_ssse3;

        }

    }

#endif

}


static int xan_decode_end(AVCodecContext *avctx)

{

    XanContext *s = avctx->priv_data;

    /* release the last frame */

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

    av_free(s->buffer1);

    av_free(s->buffer2);

    return 0;

}


static abi_long do_sendrecvmsg_locked(int fd, struct target_msghdr *msgp,

                                      int flags, int send)

{

    abi_long ret, len;

    struct msghdr msg;

    int count;

    struct iovec *vec;

    abi_ulong target_vec;

    if (msgp->msg_name) {

        msg.msg_namelen = tswap32(msgp->msg_namelen);

        msg.msg_name = alloca(msg.msg_namelen+1);

        ret = target_to_host_sockaddr(fd, msg.msg_name,

                                      tswapal(msgp->msg_name),

                                      msg.msg_namelen);

        if (ret) {

            goto out2;

        }

    } else {

        msg.msg_name = NULL;

        msg.msg_namelen = 0;

    }

    msg.msg_controllen = 2 * tswapal(msgp->msg_controllen);

    msg.msg_control = alloca(msg.msg_controllen);

    msg.msg_flags = tswap32(msgp->msg_flags);

    count = tswapal(msgp->msg_iovlen);

    target_vec = tswapal(msgp->msg_iov);

    vec = lock_iovec(send ? VERIFY_READ : VERIFY_WRITE,

                     target_vec, count, send);

    if (vec == NULL) {

        ret = -host_to_target_errno(errno);

        goto out2;

    }

    msg.msg_iovlen = count;

    msg.msg_iov = vec;

    if (send) {

        ret = target_to_host_cmsg(&msg, msgp);

        if (ret == 0)

            ret = get_errno(sendmsg(fd, &msg, flags));

    } else {

        ret = get_errno(recvmsg(fd, &msg, flags));

        if (!is_error(ret)) {

            len = ret;

            ret = host_to_target_cmsg(msgp, &msg);

            if (!is_error(ret)) {

                msgp->msg_namelen = tswap32(msg.msg_namelen);

                if (msg.msg_name != NULL) {

                    ret = host_to_target_sockaddr(tswapal(msgp->msg_name),

                                    msg.msg_name, msg.msg_namelen);

                    if (ret) {

                        goto out;

                    }

                }

                ret = len;

            }

        }

    }

out:

    unlock_iovec(vec, target_vec, count, !send);

out2:

    return ret;

}


static void omap_clkm_write(void *opaque, hwaddr addr,

                            uint64_t value, unsigned size)

{

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

    uint16_t diff;

    omap_clk clk;

    static const char *clkschemename[8] = {

        "fully synchronous", "fully asynchronous", "synchronous scalable",

        "mix mode 1", "mix mode 2", "bypass mode", "mix mode 3", "mix mode 4",

    };

    if (size != 2) {

        omap_badwidth_write16(opaque, addr, value);

        return;

    }

    switch (addr) {

    case 0x00:	/* ARM_CKCTL */

        diff = s->clkm.arm_ckctl ^ value;

        s->clkm.arm_ckctl = value & 0x7fff;

        omap_clkm_ckctl_update(s, diff, value);

        return;

    case 0x04:	/* ARM_IDLECT1 */

        diff = s->clkm.arm_idlect1 ^ value;

        s->clkm.arm_idlect1 = value & 0x0fff;

        omap_clkm_idlect1_update(s, diff, value);

        return;

    case 0x08:	/* ARM_IDLECT2 */

        diff = s->clkm.arm_idlect2 ^ value;

        s->clkm.arm_idlect2 = value & 0x07ff;

        omap_clkm_idlect2_update(s, diff, value);

        return;

    case 0x0c:	/* ARM_EWUPCT */

        s->clkm.arm_ewupct = value & 0x003f;

        return;

    case 0x10:	/* ARM_RSTCT1 */

        diff = s->clkm.arm_rstct1 ^ value;

        s->clkm.arm_rstct1 = value & 0x0007;

        if (value & 9) {

            qemu_system_reset_request(SHUTDOWN_CAUSE_GUEST_RESET);

            s->clkm.cold_start = 0xa;

        }

        if (diff & ~value & 4) {				/* DSP_RST */

            omap_mpui_reset(s);

            omap_tipb_bridge_reset(s->private_tipb);

            omap_tipb_bridge_reset(s->public_tipb);

        }

        if (diff & 2) {						/* DSP_EN */

            clk = omap_findclk(s, "dsp_ck");

            omap_clk_canidle(clk, (~value >> 1) & 1);

        }

        return;

    case 0x14:	/* ARM_RSTCT2 */

        s->clkm.arm_rstct2 = value & 0x0001;

        return;

    case 0x18:	/* ARM_SYSST */

        if ((s->clkm.clocking_scheme ^ (value >> 11)) & 7) {

            s->clkm.clocking_scheme = (value >> 11) & 7;

            printf("%s: clocking scheme set to %s\n", __FUNCTION__,

                            clkschemename[s->clkm.clocking_scheme]);

        }

        s->clkm.cold_start &= value & 0x3f;

        return;

    case 0x1c:	/* ARM_CKOUT1 */

        diff = s->clkm.arm_ckout1 ^ value;

        s->clkm.arm_ckout1 = value & 0x003f;

        omap_clkm_ckout1_update(s, diff, value);

        return;

    case 0x20:	/* ARM_CKOUT2 */

    default:

        OMAP_BAD_REG(addr);

    }

}


static void ppce500_reset_device_tree(void *opaque)

{

    DeviceTreeParams *p = opaque;

    ppce500_load_device_tree(p->machine, &p->params, p->addr, p->initrd_base,

                             p->initrd_size, false);

}


iscsi_aio_write16_cb(struct iscsi_context *iscsi, int status,

                     void *command_data, void *opaque)

{

    IscsiAIOCB *acb = opaque;

    trace_iscsi_aio_write16_cb(iscsi, status, acb, acb->canceled);

    g_free(acb->buf);

    if (acb->canceled != 0) {

        qemu_aio_release(acb);

        scsi_free_scsi_task(acb->task);

        acb->task = NULL;

        return;

    }

    acb->status = 0;

    if (status < 0) {

        error_report("Failed to write16 data to iSCSI lun. %s",

                     iscsi_get_error(iscsi));

        acb->status = -EIO;

    }

    iscsi_schedule_bh(acb);

    scsi_free_scsi_task(acb->task);

    acb->task = NULL;

}


static int apc_probe(AVProbeData *p)

{

    if (p->buf_size < 8)

        return 0;

    if (!strncmp(p->buf, "CRYO_APC", 8))

        return AVPROBE_SCORE_MAX;

    return 0;

}


static int hnm_decode_frame(AVCodecContext *avctx, void *data,
                            int *got_frame, AVPacket *avpkt)
{
    AVFrame *frame = data;
    Hnm4VideoContext *hnm = avctx->priv_data;
    int ret;
    uint16_t chunk_id;
    if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
        return ret;
    chunk_id = AV_RL16(avpkt->data + 4);
    if (chunk_id == HNM4_CHUNK_ID_PL) {
        hnm_update_palette(avctx, avpkt->data, avpkt->size);
        frame->palette_has_changed = 1;
    } else if (chunk_id == HNM4_CHUNK_ID_IZ) {
        unpack_intraframe(avctx, avpkt->data + 12, avpkt->size - 12);
        memcpy(hnm->previous, hnm->current, hnm->width * hnm->height);
        if (hnm->version == 0x4a)
            memcpy(hnm->processed, hnm->current, hnm->width * hnm->height);
        else
            postprocess_current_frame(avctx);
        copy_processed_frame(avctx, frame);
        frame->pict_type = AV_PICTURE_TYPE_I;
        frame->key_frame = 1;
        memcpy(frame->data[1], hnm->palette, 256 * 4);
        *got_frame = 1;
    } else if (chunk_id == HNM4_CHUNK_ID_IU) {
        if (hnm->version == 0x4a) {
            decode_interframe_v4a(avctx, avpkt->data + 8, avpkt->size - 8);
            memcpy(hnm->processed, hnm->current, hnm->width * hnm->height);
        } else {
            decode_interframe_v4(avctx, avpkt->data + 8, avpkt->size - 8);
            postprocess_current_frame(avctx);
        copy_processed_frame(avctx, frame);
        frame->pict_type = AV_PICTURE_TYPE_P;
        frame->key_frame = 0;
        memcpy(frame->data[1], hnm->palette, 256 * 4);
        *got_frame = 1;
        hnm_flip_buffers(hnm);
    } else {
        av_log(avctx, AV_LOG_ERROR, "invalid chunk id: %d\n", chunk_id);
    return avpkt->size;


int vp78_decode_frame(AVCodecContext *avctx, void *data, int *got_frame,

                      AVPacket *avpkt, int is_vp7)

{

    VP8Context *s = avctx->priv_data;

    int ret, i, referenced, num_jobs;

    enum AVDiscard skip_thresh;

    VP8Frame *av_uninit(curframe), *prev_frame;

    if (is_vp7)

        ret = vp7_decode_frame_header(s, avpkt->data, avpkt->size);

    else

        ret = vp8_decode_frame_header(s, avpkt->data, avpkt->size);

    if (ret < 0)

        goto err;

    if (!is_vp7 && s->pix_fmt == AV_PIX_FMT_NONE) {

        enum AVPixelFormat pix_fmts[] = {

#if CONFIG_VP8_VAAPI_HWACCEL

            AV_PIX_FMT_VAAPI,

#endif

            AV_PIX_FMT_YUV420P,

            AV_PIX_FMT_NONE,

        };

        s->pix_fmt = ff_get_format(s->avctx, pix_fmts);

        if (s->pix_fmt < 0) {

            ret = AVERROR(EINVAL);

            goto err;

        }

        avctx->pix_fmt = s->pix_fmt;

    }

    prev_frame = s->framep[VP56_FRAME_CURRENT];

    referenced = s->update_last || s->update_golden == VP56_FRAME_CURRENT ||

                 s->update_altref == VP56_FRAME_CURRENT;

    skip_thresh = !referenced ? AVDISCARD_NONREF

                              : !s->keyframe ? AVDISCARD_NONKEY

                                             : AVDISCARD_ALL;

    if (avctx->skip_frame >= skip_thresh) {

        s->invisible = 1;

        memcpy(&s->next_framep[0], &s->framep[0], sizeof(s->framep[0]) * 4);

        goto skip_decode;

    }

    s->deblock_filter = s->filter.level && avctx->skip_loop_filter < skip_thresh;

    // release no longer referenced frames

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

        if (s->frames[i].tf.f->data[0] &&

            &s->frames[i] != prev_frame &&

            &s->frames[i] != s->framep[VP56_FRAME_PREVIOUS] &&

            &s->frames[i] != s->framep[VP56_FRAME_GOLDEN]   &&

            &s->frames[i] != s->framep[VP56_FRAME_GOLDEN2])

            vp8_release_frame(s, &s->frames[i]);

    curframe = s->framep[VP56_FRAME_CURRENT] = vp8_find_free_buffer(s);

    if (!s->colorspace)

        avctx->colorspace = AVCOL_SPC_BT470BG;

    if (s->fullrange)

        avctx->color_range = AVCOL_RANGE_JPEG;

    else

        avctx->color_range = AVCOL_RANGE_MPEG;

    /* Given that arithmetic probabilities are updated every frame, it's quite

     * likely that the values we have on a random interframe are complete

     * junk if we didn't start decode on a keyframe. So just don't display

     * anything rather than junk. */

    if (!s->keyframe && (!s->framep[VP56_FRAME_PREVIOUS] ||

                         !s->framep[VP56_FRAME_GOLDEN]   ||

                         !s->framep[VP56_FRAME_GOLDEN2])) {

        av_log(avctx, AV_LOG_WARNING,

               "Discarding interframe without a prior keyframe!\n");

        ret = AVERROR_INVALIDDATA;

        goto err;

    }

    curframe->tf.f->key_frame = s->keyframe;

    curframe->tf.f->pict_type = s->keyframe ? AV_PICTURE_TYPE_I

                                            : AV_PICTURE_TYPE_P;

    if ((ret = vp8_alloc_frame(s, curframe, referenced))) {

        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed!\n");

        goto err;

    }

    // check if golden and altref are swapped

    if (s->update_altref != VP56_FRAME_NONE)

        s->next_framep[VP56_FRAME_GOLDEN2] = s->framep[s->update_altref];

    else

        s->next_framep[VP56_FRAME_GOLDEN2] = s->framep[VP56_FRAME_GOLDEN2];

    if (s->update_golden != VP56_FRAME_NONE)

        s->next_framep[VP56_FRAME_GOLDEN] = s->framep[s->update_golden];

    else

        s->next_framep[VP56_FRAME_GOLDEN] = s->framep[VP56_FRAME_GOLDEN];

    if (s->update_last)

        s->next_framep[VP56_FRAME_PREVIOUS] = curframe;

    else

        s->next_framep[VP56_FRAME_PREVIOUS] = s->framep[VP56_FRAME_PREVIOUS];

    s->next_framep[VP56_FRAME_CURRENT] = curframe;

    ff_thread_finish_setup(avctx);

    if (avctx->hwaccel) {

        ret = avctx->hwaccel->start_frame(avctx, avpkt->data, avpkt->size);

        if (ret < 0)

            goto err;

        ret = avctx->hwaccel->decode_slice(avctx, avpkt->data, avpkt->size);

        if (ret < 0)

            goto err;

        ret = avctx->hwaccel->end_frame(avctx);

        if (ret < 0)

            goto err;

    } else {

        s->linesize   = curframe->tf.f->linesize[0];

        s->uvlinesize = curframe->tf.f->linesize[1];

        memset(s->top_nnz, 0, s->mb_width * sizeof(*s->top_nnz));

        /* Zero macroblock structures for top/top-left prediction

         * from outside the frame. */

        if (!s->mb_layout)

            memset(s->macroblocks + s->mb_height * 2 - 1, 0,

                   (s->mb_width + 1) * sizeof(*s->macroblocks));

        if (!s->mb_layout && s->keyframe)

            memset(s->intra4x4_pred_mode_top, DC_PRED, s->mb_width * 4);

        memset(s->ref_count, 0, sizeof(s->ref_count));

        if (s->mb_layout == 1) {

            // Make sure the previous frame has read its segmentation map,

            // if we re-use the same map.

            if (prev_frame && s->segmentation.enabled &&

                !s->segmentation.update_map)

                ff_thread_await_progress(&prev_frame->tf, 1, 0);

            if (is_vp7)

                vp7_decode_mv_mb_modes(avctx, curframe, prev_frame);

            else

                vp8_decode_mv_mb_modes(avctx, curframe, prev_frame);

        }

        if (avctx->active_thread_type == FF_THREAD_FRAME)

            num_jobs = 1;

        else

            num_jobs = FFMIN(s->num_coeff_partitions, avctx->thread_count);

        s->num_jobs   = num_jobs;

        s->curframe   = curframe;

        s->prev_frame = prev_frame;

        s->mv_min.y   = -MARGIN;

        s->mv_max.y   = ((s->mb_height - 1) << 6) + MARGIN;

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

            s->thread_data[i].thread_mb_pos = 0;

            s->thread_data[i].wait_mb_pos   = INT_MAX;

        }

        if (is_vp7)

            avctx->execute2(avctx, vp7_decode_mb_row_sliced, s->thread_data, NULL,

                            num_jobs);

        else

            avctx->execute2(avctx, vp8_decode_mb_row_sliced, s->thread_data, NULL,

                            num_jobs);

    }

    ff_thread_report_progress(&curframe->tf, INT_MAX, 0);

    memcpy(&s->framep[0], &s->next_framep[0], sizeof(s->framep[0]) * 4);

skip_decode:

    // if future frames don't use the updated probabilities,

    // reset them to the values we saved

    if (!s->update_probabilities)

        s->prob[0] = s->prob[1];

    if (!s->invisible) {

        if ((ret = av_frame_ref(data, curframe->tf.f)) < 0)

            return ret;

        *got_frame = 1;

    }

    return avpkt->size;

err:

    memcpy(&s->next_framep[0], &s->framep[0], sizeof(s->framep[0]) * 4);

    return ret;

}


NBDExport *nbd_export_new(BlockDriverState *bs, off_t dev_offset,

                          off_t size, uint32_t nbdflags,

                          void (*close)(NBDExport *))

{

    NBDExport *exp = g_malloc0(sizeof(NBDExport));

    exp->refcount = 1;

    QTAILQ_INIT(&exp->clients);

    exp->bs = bs;

    exp->dev_offset = dev_offset;

    exp->nbdflags = nbdflags;

    exp->size = size == -1 ? bdrv_getlength(bs) : size;

    exp->close = close;

    exp->ctx = bdrv_get_aio_context(bs);

    bdrv_ref(bs);

    bdrv_add_aio_context_notifier(bs, bs_aio_attached, bs_aio_detach, exp);

    return exp;

}


static int qemu_reset_requested(void)

{

    int r = reset_requested;

    if (r && replay_checkpoint(CHECKPOINT_RESET_REQUESTED)) {

        reset_requested = 0;

        return r;

    }

    return false;

}


static int add_calxeda_midway_xgmac_fdt_node(SysBusDevice *sbdev, void *opaque)

{

    PlatformBusFDTData *data = opaque;

    PlatformBusDevice *pbus = data->pbus;

    void *fdt = data->fdt;

    const char *parent_node = data->pbus_node_name;

    int compat_str_len, i, ret = -1;

    char *nodename;

    uint32_t *irq_attr, *reg_attr;

    uint64_t mmio_base, irq_number;

    VFIOPlatformDevice *vdev = VFIO_PLATFORM_DEVICE(sbdev);

    VFIODevice *vbasedev = &vdev->vbasedev;

    mmio_base = platform_bus_get_mmio_addr(pbus, sbdev, 0);

    nodename = g_strdup_printf("%s/%s@%" PRIx64, parent_node,

                               vbasedev->name, mmio_base);

    qemu_fdt_add_subnode(fdt, nodename);

    compat_str_len = strlen(vdev->compat) + 1;

    qemu_fdt_setprop(fdt, nodename, "compatible",

                          vdev->compat, compat_str_len);

    qemu_fdt_setprop(fdt, nodename, "dma-coherent", "", 0);

    reg_attr = g_new(uint32_t, vbasedev->num_regions * 2);

    for (i = 0; i < vbasedev->num_regions; i++) {

        mmio_base = platform_bus_get_mmio_addr(pbus, sbdev, i);

        reg_attr[2 * i] = cpu_to_be32(mmio_base);

        reg_attr[2 * i + 1] = cpu_to_be32(

                                memory_region_size(&vdev->regions[i]->mem));

    }

    ret = qemu_fdt_setprop(fdt, nodename, "reg", reg_attr,

                           vbasedev->num_regions * 2 * sizeof(uint32_t));

    if (ret) {

        error_report("could not set reg property of node %s", nodename);

        goto fail_reg;

    }

    irq_attr = g_new(uint32_t, vbasedev->num_irqs * 3);

    for (i = 0; i < vbasedev->num_irqs; i++) {

        irq_number = platform_bus_get_irqn(pbus, sbdev , i)

                         + data->irq_start;

        irq_attr[3 * i] = cpu_to_be32(GIC_FDT_IRQ_TYPE_SPI);

        irq_attr[3 * i + 1] = cpu_to_be32(irq_number);

        irq_attr[3 * i + 2] = cpu_to_be32(GIC_FDT_IRQ_FLAGS_LEVEL_HI);

    }

    ret = qemu_fdt_setprop(fdt, nodename, "interrupts",

                     irq_attr, vbasedev->num_irqs * 3 * sizeof(uint32_t));

    if (ret) {

        error_report("could not set interrupts property of node %s",

                     nodename);

    }

    g_free(irq_attr);

fail_reg:

    g_free(reg_attr);

    g_free(nodename);

    return ret;

}