void ff_h264_filter_mb(H264Context *h, H264SliceContext *sl,

                       int mb_x, int mb_y,

                       uint8_t *img_y, uint8_t *img_cb, uint8_t *img_cr,

                       unsigned int linesize, unsigned int uvlinesize)

{

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

    const int mb_type = h->cur_pic.mb_type[mb_xy];

    const int mvy_limit = IS_INTERLACED(mb_type) ? 2 : 4;

    int first_vertical_edge_done = 0;

    int chroma = !(CONFIG_GRAY && (h->flags&CODEC_FLAG_GRAY));

    int qp_bd_offset = 6 * (h->sps.bit_depth_luma - 8);

    int a = 52 + h->slice_alpha_c0_offset - qp_bd_offset;

    int b = 52 + h->slice_beta_offset - qp_bd_offset;

    if (FRAME_MBAFF(h)

            // and current and left pair do not have the same interlaced type

            && IS_INTERLACED(mb_type ^ sl->left_type[LTOP])

            // and left mb is in available to us

            && sl->left_type[LTOP]) {

        /* First vertical edge is different in MBAFF frames

         * There are 8 different bS to compute and 2 different Qp

         */

        DECLARE_ALIGNED(8, int16_t, bS)[8];

        int qp[2];

        int bqp[2];

        int rqp[2];

        int mb_qp, mbn0_qp, mbn1_qp;

        int i;

        first_vertical_edge_done = 1;

        if( IS_INTRA(mb_type) ) {

            AV_WN64A(&bS[0], 0x0004000400040004ULL);

            AV_WN64A(&bS[4], 0x0004000400040004ULL);

        } else {

            static const uint8_t offset[2][2][8]={

                {

                    {3+4*0, 3+4*0, 3+4*0, 3+4*0, 3+4*1, 3+4*1, 3+4*1, 3+4*1},

                    {3+4*2, 3+4*2, 3+4*2, 3+4*2, 3+4*3, 3+4*3, 3+4*3, 3+4*3},

                },{

                    {3+4*0, 3+4*1, 3+4*2, 3+4*3, 3+4*0, 3+4*1, 3+4*2, 3+4*3},

                    {3+4*0, 3+4*1, 3+4*2, 3+4*3, 3+4*0, 3+4*1, 3+4*2, 3+4*3},

                }

            };

            const uint8_t *off= offset[MB_FIELD(h)][mb_y&1];

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

                int j= MB_FIELD(h) ? i>>2 : i&1;

                int mbn_xy = sl->left_mb_xy[LEFT(j)];

                int mbn_type = sl->left_type[LEFT(j)];

                if( IS_INTRA( mbn_type ) )

                    bS[i] = 4;

                else{

                    bS[i] = 1 + !!(sl->non_zero_count_cache[12+8*(i>>1)] |

                         ((!h->pps.cabac && IS_8x8DCT(mbn_type)) ?

                            (h->cbp_table[mbn_xy] & (((MB_FIELD(h) ? (i&2) : (mb_y&1)) ? 8 : 2) << 12))

                                                                       :

                            h->non_zero_count[mbn_xy][ off[i] ]));

                }

            }

        }

        mb_qp   = h->cur_pic.qscale_table[mb_xy];

        mbn0_qp = h->cur_pic.qscale_table[sl->left_mb_xy[0]];

        mbn1_qp = h->cur_pic.qscale_table[sl->left_mb_xy[1]];

        qp[0] = ( mb_qp + mbn0_qp + 1 ) >> 1;

        bqp[0] = ( get_chroma_qp( h, 0, mb_qp ) +

                   get_chroma_qp( h, 0, mbn0_qp ) + 1 ) >> 1;

        rqp[0] = ( get_chroma_qp( h, 1, mb_qp ) +

                   get_chroma_qp( h, 1, mbn0_qp ) + 1 ) >> 1;

        qp[1] = ( mb_qp + mbn1_qp + 1 ) >> 1;

        bqp[1] = ( get_chroma_qp( h, 0, mb_qp ) +

                   get_chroma_qp( h, 0, mbn1_qp ) + 1 ) >> 1;

        rqp[1] = ( get_chroma_qp( h, 1, mb_qp ) +

                   get_chroma_qp( h, 1, mbn1_qp ) + 1 ) >> 1;

        /* Filter edge */

        tprintf(h->avctx, "filter mb:%d/%d MBAFF, QPy:%d/%d, QPb:%d/%d QPr:%d/%d ls:%d uvls:%d", mb_x, mb_y, qp[0], qp[1], bqp[0], bqp[1], rqp[0], rqp[1], linesize, uvlinesize);

        { int i; for (i = 0; i < 8; i++) tprintf(h->avctx, " bS[%d]:%d", i, bS[i]); tprintf(h->avctx, "\n"); }

        if (MB_FIELD(h)) {

            filter_mb_mbaff_edgev ( h, img_y                ,   linesize, bS  , 1, qp [0], a, b, 1 );

            filter_mb_mbaff_edgev ( h, img_y  + 8*  linesize,   linesize, bS+4, 1, qp [1], a, b, 1 );

            if (chroma){

                if (CHROMA444(h)) {

                    filter_mb_mbaff_edgev ( h, img_cb,                uvlinesize, bS  , 1, bqp[0], a, b, 1 );

                    filter_mb_mbaff_edgev ( h, img_cb + 8*uvlinesize, uvlinesize, bS+4, 1, bqp[1], a, b, 1 );

                    filter_mb_mbaff_edgev ( h, img_cr,                uvlinesize, bS  , 1, rqp[0], a, b, 1 );

                    filter_mb_mbaff_edgev ( h, img_cr + 8*uvlinesize, uvlinesize, bS+4, 1, rqp[1], a, b, 1 );

                } else if (CHROMA422(h)) {

                    filter_mb_mbaff_edgecv(h, img_cb,                uvlinesize, bS  , 1, bqp[0], a, b, 1);

                    filter_mb_mbaff_edgecv(h, img_cb + 8*uvlinesize, uvlinesize, bS+4, 1, bqp[1], a, b, 1);

                    filter_mb_mbaff_edgecv(h, img_cr,                uvlinesize, bS  , 1, rqp[0], a, b, 1);

                    filter_mb_mbaff_edgecv(h, img_cr + 8*uvlinesize, uvlinesize, bS+4, 1, rqp[1], a, b, 1);

                }else{

                    filter_mb_mbaff_edgecv( h, img_cb,                uvlinesize, bS  , 1, bqp[0], a, b, 1 );

                    filter_mb_mbaff_edgecv( h, img_cb + 4*uvlinesize, uvlinesize, bS+4, 1, bqp[1], a, b, 1 );

                    filter_mb_mbaff_edgecv( h, img_cr,                uvlinesize, bS  , 1, rqp[0], a, b, 1 );

                    filter_mb_mbaff_edgecv( h, img_cr + 4*uvlinesize, uvlinesize, bS+4, 1, rqp[1], a, b, 1 );

                }

            }

        }else{

            filter_mb_mbaff_edgev ( h, img_y              , 2*  linesize, bS  , 2, qp [0], a, b, 1 );

            filter_mb_mbaff_edgev ( h, img_y  +   linesize, 2*  linesize, bS+1, 2, qp [1], a, b, 1 );

            if (chroma){

                if (CHROMA444(h)) {

                    filter_mb_mbaff_edgev ( h, img_cb,              2*uvlinesize, bS  , 2, bqp[0], a, b, 1 );

                    filter_mb_mbaff_edgev ( h, img_cb + uvlinesize, 2*uvlinesize, bS+1, 2, bqp[1], a, b, 1 );

                    filter_mb_mbaff_edgev ( h, img_cr,              2*uvlinesize, bS  , 2, rqp[0], a, b, 1 );

                    filter_mb_mbaff_edgev ( h, img_cr + uvlinesize, 2*uvlinesize, bS+1, 2, rqp[1], a, b, 1 );

                }else{

                    filter_mb_mbaff_edgecv( h, img_cb,              2*uvlinesize, bS  , 2, bqp[0], a, b, 1 );

                    filter_mb_mbaff_edgecv( h, img_cb + uvlinesize, 2*uvlinesize, bS+1, 2, bqp[1], a, b, 1 );

                    filter_mb_mbaff_edgecv( h, img_cr,              2*uvlinesize, bS  , 2, rqp[0], a, b, 1 );

                    filter_mb_mbaff_edgecv( h, img_cr + uvlinesize, 2*uvlinesize, bS+1, 2, rqp[1], a, b, 1 );

                }

            }

        }

    }

#if CONFIG_SMALL

    {

        int dir;

        for (dir = 0; dir < 2; dir++)

            filter_mb_dir(h, sl, mb_x, mb_y, img_y, img_cb, img_cr, linesize,

                          uvlinesize, mb_xy, mb_type, mvy_limit,

                          dir ? 0 : first_vertical_edge_done, a, b,

                          chroma, dir);

    }

#else

    filter_mb_dir(h, sl, mb_x, mb_y, img_y, img_cb, img_cr, linesize, uvlinesize, mb_xy, mb_type, mvy_limit, first_vertical_edge_done, a, b, chroma, 0);

    filter_mb_dir(h, sl, mb_x, mb_y, img_y, img_cb, img_cr, linesize, uvlinesize, mb_xy, mb_type, mvy_limit, 0,                        a, b, chroma, 1);

#endif

}


e1000_set_link_status(VLANClientState *nc)

{

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

    uint32_t old_status = s->mac_reg[STATUS];

    if (nc->link_down)

        s->mac_reg[STATUS] &= ~E1000_STATUS_LU;

    else

        s->mac_reg[STATUS] |= E1000_STATUS_LU;

    if (s->mac_reg[STATUS] != old_status)

        set_ics(s, 0, E1000_ICR_LSC);

}


static void tcx_initfn(Object *obj)

{

    SysBusDevice *sbd = SYS_BUS_DEVICE(obj);

    TCXState *s = TCX(obj);

    memory_region_init_ram(&s->rom, NULL, "tcx.prom", FCODE_MAX_ROM_SIZE,

                           &error_abort);

    memory_region_set_readonly(&s->rom, true);

    sysbus_init_mmio(sbd, &s->rom);

    /* 2/STIP : Stippler */

    memory_region_init_io(&s->stip, OBJECT(s), &tcx_stip_ops, s, "tcx.stip",

                          TCX_STIP_NREGS);

    sysbus_init_mmio(sbd, &s->stip);

    /* 3/BLIT : Blitter */

    memory_region_init_io(&s->blit, OBJECT(s), &tcx_blit_ops, s, "tcx.blit",

                          TCX_BLIT_NREGS);

    sysbus_init_mmio(sbd, &s->blit);

    /* 5/RSTIP : Raw Stippler */

    memory_region_init_io(&s->rstip, OBJECT(s), &tcx_rstip_ops, s, "tcx.rstip",

                          TCX_RSTIP_NREGS);

    sysbus_init_mmio(sbd, &s->rstip);

    /* 6/RBLIT : Raw Blitter */

    memory_region_init_io(&s->rblit, OBJECT(s), &tcx_rblit_ops, s, "tcx.rblit",

                          TCX_RBLIT_NREGS);

    sysbus_init_mmio(sbd, &s->rblit);

    /* 7/TEC : ??? */

    memory_region_init_io(&s->tec, OBJECT(s), &tcx_dummy_ops, s,

                          "tcx.tec", TCX_TEC_NREGS);

    sysbus_init_mmio(sbd, &s->tec);

    /* 8/CMAP : DAC */

    memory_region_init_io(&s->dac, OBJECT(s), &tcx_dac_ops, s,

                          "tcx.dac", TCX_DAC_NREGS);

    sysbus_init_mmio(sbd, &s->dac);

    /* 9/THC : Cursor */

    memory_region_init_io(&s->thc, OBJECT(s), &tcx_thc_ops, s, "tcx.thc",

                          TCX_THC_NREGS);

    sysbus_init_mmio(sbd, &s->thc);

    /* 11/DHC : ??? */

    memory_region_init_io(&s->dhc, OBJECT(s), &tcx_dummy_ops, s, "tcx.dhc",

                          TCX_DHC_NREGS);

    sysbus_init_mmio(sbd, &s->dhc);

    /* 12/ALT : ??? */

    memory_region_init_io(&s->alt, OBJECT(s), &tcx_dummy_ops, s, "tcx.alt",

                          TCX_ALT_NREGS);

    sysbus_init_mmio(sbd, &s->alt);

    return;

}


static int alloc_buffer(AVCodecContext *s, InputStream *ist, FrameBuffer **pbuf)

{

    FrameBuffer  *buf = av_mallocz(sizeof(*buf));

    int i, ret;

    const int pixel_size = av_pix_fmt_descriptors[s->pix_fmt].comp[0].step_minus1+1;

    int h_chroma_shift, v_chroma_shift;

    int edge = 32; // XXX should be avcodec_get_edge_width(), but that fails on svq1

    int w = s->width, h = s->height;

    if (!buf)

        return AVERROR(ENOMEM);

    if (!(s->flags & CODEC_FLAG_EMU_EDGE)) {

        w += 2*edge;

        h += 2*edge;

    }

    avcodec_align_dimensions(s, &w, &h);

    if ((ret = av_image_alloc(buf->base, buf->linesize, w, h,

                              s->pix_fmt, 32)) < 0) {

        av_freep(&buf);

        return ret;

    }

    /* XXX this shouldn't be needed, but some tests break without this line

     * those decoders are buggy and need to be fixed.

     * the following tests fail:

     * bethsoft-vid, cdgraphics, ansi, aasc, fraps-v1, qtrle-1bit

     */

    memset(buf->base[0], 128, ret);

    avcodec_get_chroma_sub_sample(s->pix_fmt, &h_chroma_shift, &v_chroma_shift);

    for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {

        const int h_shift = i==0 ? 0 : h_chroma_shift;

        const int v_shift = i==0 ? 0 : v_chroma_shift;

        if (s->flags & CODEC_FLAG_EMU_EDGE)

            buf->data[i] = buf->base[i];

        else

            buf->data[i] = buf->base[i] +

                           FFALIGN((buf->linesize[i]*edge >> v_shift) +

                                   (pixel_size*edge >> h_shift), 32);

    }

    buf->w       = s->width;

    buf->h       = s->height;

    buf->pix_fmt = s->pix_fmt;

    buf->ist     = ist;

    *pbuf = buf;

    return 0;

}


static void x86_cpu_initfn(Object *obj)
{
    CPUState *cs = CPU(obj);
    X86CPU *cpu = X86_CPU(obj);
    X86CPUClass *xcc = X86_CPU_GET_CLASS(obj);
    CPUX86State *env = &cpu->env;
    FeatureWord w;
    cs->env_ptr = env;
    object_property_add(obj, "family", "int",
                        x86_cpuid_version_get_family,
                        x86_cpuid_version_set_family, NULL, NULL, NULL);
    object_property_add(obj, "model", "int",
                        x86_cpuid_version_get_model,
                        x86_cpuid_version_set_model, NULL, NULL, NULL);
    object_property_add(obj, "stepping", "int",
                        x86_cpuid_version_get_stepping,
                        x86_cpuid_version_set_stepping, NULL, NULL, NULL);
    object_property_add_str(obj, "vendor",
                            x86_cpuid_get_vendor,
                            x86_cpuid_set_vendor, NULL);
    object_property_add_str(obj, "model-id",
                            x86_cpuid_get_model_id,
                            x86_cpuid_set_model_id, NULL);
    object_property_add(obj, "tsc-frequency", "int",
                        x86_cpuid_get_tsc_freq,
                        x86_cpuid_set_tsc_freq, NULL, NULL, NULL);
    object_property_add(obj, "feature-words", "X86CPUFeatureWordInfo",
                        x86_cpu_get_feature_words,
                        NULL, NULL, (void *)env->features, NULL);
    object_property_add(obj, "filtered-features", "X86CPUFeatureWordInfo",
                        x86_cpu_get_feature_words,
                        NULL, NULL, (void *)cpu->filtered_features, NULL);
    cpu->hyperv_spinlock_attempts = HYPERV_SPINLOCK_NEVER_RETRY;
    for (w = 0; w < FEATURE_WORDS; w++) {
        int bitnr;
        for (bitnr = 0; bitnr < 32; bitnr++) {
            x86_cpu_register_feature_bit_props(cpu, w, bitnr);
        }
    }
    object_property_add_alias(obj, "sse3", obj, "pni", &error_abort);
    object_property_add_alias(obj, "pclmuldq", obj, "pclmulqdq", &error_abort);
    object_property_add_alias(obj, "sse4-1", obj, "sse4.1", &error_abort);
    object_property_add_alias(obj, "sse4-2", obj, "sse4.2", &error_abort);
    object_property_add_alias(obj, "xd", obj, "nx", &error_abort);
    object_property_add_alias(obj, "ffxsr", obj, "fxsr-opt", &error_abort);
    object_property_add_alias(obj, "i64", obj, "lm", &error_abort);
    object_property_add_alias(obj, "ds_cpl", obj, "ds-cpl", &error_abort);
    object_property_add_alias(obj, "tsc_adjust", obj, "tsc-adjust", &error_abort);
    object_property_add_alias(obj, "fxsr_opt", obj, "fxsr-opt", &error_abort);
    object_property_add_alias(obj, "lahf_lm", obj, "lahf-lm", &error_abort);
    object_property_add_alias(obj, "cmp_legacy", obj, "cmp-legacy", &error_abort);
    object_property_add_alias(obj, "nodeid_msr", obj, "nodeid-msr", &error_abort);
    object_property_add_alias(obj, "perfctr_core", obj, "perfctr-core", &error_abort);
    object_property_add_alias(obj, "perfctr_nb", obj, "perfctr-nb", &error_abort);
    object_property_add_alias(obj, "kvm_nopiodelay", obj, "kvm-nopiodelay", &error_abort);
    object_property_add_alias(obj, "kvm_mmu", obj, "kvm-mmu", &error_abort);
    object_property_add_alias(obj, "kvm_asyncpf", obj, "kvm-asyncpf", &error_abort);
    object_property_add_alias(obj, "kvm_steal_time", obj, "kvm-steal-time", &error_abort);
    object_property_add_alias(obj, "kvm_pv_eoi", obj, "kvm-pv-eoi", &error_abort);
    object_property_add_alias(obj, "kvm_pv_unhalt", obj, "kvm-pv-unhalt", &error_abort);
    object_property_add_alias(obj, "svm_lock", obj, "svm-lock", &error_abort);
    object_property_add_alias(obj, "nrip_save", obj, "nrip-save", &error_abort);
    object_property_add_alias(obj, "tsc_scale", obj, "tsc-scale", &error_abort);
    object_property_add_alias(obj, "vmcb_clean", obj, "vmcb-clean", &error_abort);
    object_property_add_alias(obj, "pause_filter", obj, "pause-filter", &error_abort);
    object_property_add_alias(obj, "sse4_1", obj, "sse4.1", &error_abort);
    object_property_add_alias(obj, "sse4_2", obj, "sse4.2", &error_abort);
    x86_cpu_load_def(cpu, xcc->cpu_def, &error_abort);
}


static void video_refresh_timer(void *opaque)

{

    VideoState *is = opaque;

    VideoPicture *vp;

    SubPicture *sp, *sp2;

    if (is->video_st) {

        if (is->pictq_size == 0) {

            /* if no picture, need to wait */

            schedule_refresh(is, 1);

        } else {

            /* dequeue the picture */

            vp = &is->pictq[is->pictq_rindex];

            /* update current video pts */

            is->video_current_pts = vp->pts;

            is->video_current_pts_time = av_gettime();

            /* launch timer for next picture */

            schedule_refresh(is, (int)(compute_frame_delay(vp->pts, is) * 1000 + 0.5));

            if(is->subtitle_st) {

                if (is->subtitle_stream_changed) {

                    SDL_LockMutex(is->subpq_mutex);

                    while (is->subpq_size) {

                        free_subpicture(&is->subpq[is->subpq_rindex]);

                        /* update queue size and signal for next picture */

                        if (++is->subpq_rindex == SUBPICTURE_QUEUE_SIZE)

                            is->subpq_rindex = 0;

                        is->subpq_size--;

                    }

                    is->subtitle_stream_changed = 0;

                    SDL_CondSignal(is->subpq_cond);

                    SDL_UnlockMutex(is->subpq_mutex);

                } else {

                    if (is->subpq_size > 0) {

                        sp = &is->subpq[is->subpq_rindex];

                        if (is->subpq_size > 1)

                            sp2 = &is->subpq[(is->subpq_rindex + 1) % SUBPICTURE_QUEUE_SIZE];

                        else

                            sp2 = NULL;

                        if ((is->video_current_pts > (sp->pts + ((float) sp->sub.end_display_time / 1000)))

                                || (sp2 && is->video_current_pts > (sp2->pts + ((float) sp2->sub.start_display_time / 1000))))

                        {

                            free_subpicture(sp);

                            /* update queue size and signal for next picture */

                            if (++is->subpq_rindex == SUBPICTURE_QUEUE_SIZE)

                                is->subpq_rindex = 0;

                            SDL_LockMutex(is->subpq_mutex);

                            is->subpq_size--;

                            SDL_CondSignal(is->subpq_cond);

                            SDL_UnlockMutex(is->subpq_mutex);

                        }

                    }

                }

            }

            /* display picture */

            video_display(is);

            /* update queue size and signal for next picture */

            if (++is->pictq_rindex == VIDEO_PICTURE_QUEUE_SIZE)

                is->pictq_rindex = 0;

            SDL_LockMutex(is->pictq_mutex);

            is->pictq_size--;

            SDL_CondSignal(is->pictq_cond);

            SDL_UnlockMutex(is->pictq_mutex);

        }

    } else if (is->audio_st) {

        /* draw the next audio frame */

        schedule_refresh(is, 40);

        /* if only audio stream, then display the audio bars (better

           than nothing, just to test the implementation */

        /* display picture */

        video_display(is);

    } else {

        schedule_refresh(is, 100);

    }

    if (show_status) {

        static int64_t last_time;

        int64_t cur_time;

        int aqsize, vqsize, sqsize;

        double av_diff;

        cur_time = av_gettime();

        if (!last_time || (cur_time - last_time) >= 30000) {

            aqsize = 0;

            vqsize = 0;

            sqsize = 0;

            if (is->audio_st)

                aqsize = is->audioq.size;

            if (is->video_st)

                vqsize = is->videoq.size;

            if (is->subtitle_st)

                sqsize = is->subtitleq.size;

            av_diff = 0;

            if (is->audio_st && is->video_st)

                av_diff = get_audio_clock(is) - get_video_clock(is);

            printf("%7.2f A-V:%7.3f aq=%5dKB vq=%5dKB sq=%5dB f=%Ld/%Ld   \r",

                   get_master_clock(is), av_diff, aqsize / 1024, vqsize / 1024, sqsize, is->faulty_dts, is->faulty_pts);

            fflush(stdout);

            last_time = cur_time;

        }

    }

}


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

{

    USBNetState *s = (USBNetState *) dev;

    int ret = 0;

    switch(p->pid) {

    case USB_TOKEN_IN:

        switch (p->devep) {

        case 1:

            ret = usb_net_handle_statusin(s, p);

            break;

        case 2:

            ret = usb_net_handle_datain(s, p);

            break;

        default:

            goto fail;

        }

        break;

    case USB_TOKEN_OUT:

        switch (p->devep) {

        case 2:

            ret = usb_net_handle_dataout(s, p);

            break;

        default:

            goto fail;

        }

        break;

    default:

    fail:

        ret = USB_RET_STALL;

        break;

    }

    if (ret == USB_RET_STALL)

        fprintf(stderr, "usbnet: failed data transaction: "

                        "pid 0x%x ep 0x%x len 0x%x\n",

                        p->pid, p->devep, p->len);

    return ret;

}


int net_init_bridge(QemuOpts *opts, const char *name, VLANState *vlan)

{

    TAPState *s;

    int fd, vnet_hdr;

    if (!qemu_opt_get(opts, "br")) {

        qemu_opt_set(opts, "br", DEFAULT_BRIDGE_INTERFACE);

    }

    if (!qemu_opt_get(opts, "helper")) {

        qemu_opt_set(opts, "helper", DEFAULT_BRIDGE_HELPER);

    }

    fd = net_bridge_run_helper(qemu_opt_get(opts, "helper"),

                               qemu_opt_get(opts, "br"));

    if (fd == -1) {

        return -1;

    }

    fcntl(fd, F_SETFL, O_NONBLOCK);

    vnet_hdr = tap_probe_vnet_hdr(fd);

    s = net_tap_fd_init(vlan, "bridge", name, fd, vnet_hdr);

    if (!s) {

        close(fd);

        return -1;

    }

    snprintf(s->nc.info_str, sizeof(s->nc.info_str), "helper=%s,br=%s",

             qemu_opt_get(opts, "helper"), qemu_opt_get(opts, "br"));

    return 0;

}


static int vfio_setup_pcie_cap(VFIOPCIDevice *vdev, int pos, uint8_t size,
                               Error **errp)
{
    uint16_t flags;
    uint8_t type;
    flags = pci_get_word(vdev->pdev.config + pos + PCI_CAP_FLAGS);
    type = (flags & PCI_EXP_FLAGS_TYPE) >> 4;
    if (type != PCI_EXP_TYPE_ENDPOINT &&
        type != PCI_EXP_TYPE_LEG_END &&
        type != PCI_EXP_TYPE_RC_END) {
        error_setg(errp, "assignment of PCIe type 0x%x "
                   "devices is not currently supported", type);
        return -EINVAL;
    if (!pci_bus_is_express(vdev->pdev.bus)) {
        PCIBus *bus = vdev->pdev.bus;
        PCIDevice *bridge;
         * Traditionally PCI device assignment exposes the PCIe capability
         * as-is on non-express buses.  The reason being that some drivers
         * simply assume that it's there, for example tg3.  However when
         * we're running on a native PCIe machine type, like Q35, we need
         * to hide the PCIe capability.  The reason for this is twofold;
         * first Windows guests get a Code 10 error when the PCIe capability
         * is exposed in this configuration.  Therefore express devices won't
         * work at all unless they're attached to express buses in the VM.
         * Second, a native PCIe machine introduces the possibility of fine
         * granularity IOMMUs supporting both translation and isolation.
         * Guest code to discover the IOMMU visibility of a device, such as
         * IOMMU grouping code on Linux, is very aware of device types and
         * valid transitions between bus types.  An express device on a non-
         * express bus is not a valid combination on bare metal systems.
         *
         * Drivers that require a PCIe capability to make the device
         * functional are simply going to need to have their devices placed
         * on a PCIe bus in the VM.
        while (!pci_bus_is_root(bus)) {
            bridge = pci_bridge_get_device(bus);
            bus = bridge->bus;
        if (pci_bus_is_express(bus)) {
            return 0;
    } else if (pci_bus_is_root(vdev->pdev.bus)) {
         * On a Root Complex bus Endpoints become Root Complex Integrated
         * Endpoints, which changes the type and clears the LNK & LNK2 fields.
        if (type == PCI_EXP_TYPE_ENDPOINT) {
                                   PCI_EXP_TYPE_RC_END << 4,
                                   PCI_EXP_FLAGS_TYPE);
            /* Link Capabilities, Status, and Control goes away */
            if (size > PCI_EXP_LNKCTL) {
                vfio_add_emulated_long(vdev, pos + PCI_EXP_LNKCAP, 0, ~0);
                vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKCTL, 0, ~0);
                vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKSTA, 0, ~0);
#ifndef PCI_EXP_LNKCAP2
#define PCI_EXP_LNKCAP2 44
#endif
#ifndef PCI_EXP_LNKSTA2
#define PCI_EXP_LNKSTA2 50
#endif
                /* Link 2 Capabilities, Status, and Control goes away */
                if (size > PCI_EXP_LNKCAP2) {
                    vfio_add_emulated_long(vdev, pos + PCI_EXP_LNKCAP2, 0, ~0);
                    vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKCTL2, 0, ~0);
                    vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKSTA2, 0, ~0);
        } else if (type == PCI_EXP_TYPE_LEG_END) {
             * Legacy endpoints don't belong on the root complex.  Windows
             * seems to be happier with devices if we skip the capability.
            return 0;
    } else {
         * Convert Root Complex Integrated Endpoints to regular endpoints.
         * These devices don't support LNK/LNK2 capabilities, so make them up.
        if (type == PCI_EXP_TYPE_RC_END) {
                                   PCI_EXP_TYPE_ENDPOINT << 4,
                                   PCI_EXP_FLAGS_TYPE);
            vfio_add_emulated_long(vdev, pos + PCI_EXP_LNKCAP,
                                   PCI_EXP_LNK_MLW_1 | PCI_EXP_LNK_LS_25, ~0);
            vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKCTL, 0, ~0);
        /* Mark the Link Status bits as emulated to allow virtual negotiation */
        vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKSTA,
                               pci_get_word(vdev->pdev.config + pos +
                                            PCI_EXP_LNKSTA),
                               PCI_EXP_LNKCAP_MLW | PCI_EXP_LNKCAP_SLS);
    pos = pci_add_capability(&vdev->pdev, PCI_CAP_ID_EXP, pos, size,
                             errp);
    if (pos < 0) {
        return pos;
    vdev->pdev.exp.exp_cap = pos;
    return pos;


static int nsv_read_close(AVFormatContext *s)

{

/*     int i; */

    NSVContext *nsv = s->priv_data;

    av_freep(&nsv->nsvs_file_offset);

    av_freep(&nsv->nsvs_timestamps);

#if 0

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

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

        NSVStream *ast = st->priv_data;

        if(ast){

            av_free(ast->index_entries);

            av_free(ast);

        }

        av_free(st->codec->palctrl);

    }

#endif

    return 0;

}


static int create_vorbis_context(vorbis_enc_context *venc,

                                 AVCodecContext *avctx)

{

    vorbis_enc_floor   *fc;

    vorbis_enc_residue *rc;

    vorbis_enc_mapping *mc;

    int i, book, ret;

    venc->channels    = avctx->channels;

    venc->sample_rate = avctx->sample_rate;

    venc->log2_blocksize[0] = venc->log2_blocksize[1] = 11;

    venc->ncodebooks = FF_ARRAY_ELEMS(cvectors);

    venc->codebooks  = av_malloc(sizeof(vorbis_enc_codebook) * venc->ncodebooks);

    if (!venc->codebooks)

        return AVERROR(ENOMEM);

    // codebook 0..14 - floor1 book, values 0..255

    // codebook 15 residue masterbook

    // codebook 16..29 residue

    for (book = 0; book < venc->ncodebooks; book++) {

        vorbis_enc_codebook *cb = &venc->codebooks[book];

        int vals;

        cb->ndimensions = cvectors[book].dim;

        cb->nentries    = cvectors[book].real_len;

        cb->min         = cvectors[book].min;

        cb->delta       = cvectors[book].delta;

        cb->lookup      = cvectors[book].lookup;

        cb->seq_p       = 0;

        cb->lens      = av_malloc_array(cb->nentries, sizeof(uint8_t));

        cb->codewords = av_malloc_array(cb->nentries, sizeof(uint32_t));

        if (!cb->lens || !cb->codewords)

            return AVERROR(ENOMEM);

        memcpy(cb->lens, cvectors[book].clens, cvectors[book].len);

        memset(cb->lens + cvectors[book].len, 0, cb->nentries - cvectors[book].len);

        if (cb->lookup) {

            vals = cb_lookup_vals(cb->lookup, cb->ndimensions, cb->nentries);

            cb->quantlist = av_malloc_array(vals, sizeof(int));

            if (!cb->quantlist)

                return AVERROR(ENOMEM);

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

                cb->quantlist[i] = cvectors[book].quant[i];

        } else {

            cb->quantlist = NULL;

        }

        if ((ret = ready_codebook(cb)) < 0)

            return ret;

    }

    venc->nfloors = 1;

    venc->floors  = av_malloc(sizeof(vorbis_enc_floor) * venc->nfloors);

    if (!venc->floors)

        return AVERROR(ENOMEM);

    // just 1 floor

    fc = &venc->floors[0];

    fc->partitions         = NUM_FLOOR_PARTITIONS;

    fc->partition_to_class = av_malloc(sizeof(int) * fc->partitions);

    if (!fc->partition_to_class)

        return AVERROR(ENOMEM);

    fc->nclasses           = 0;

    for (i = 0; i < fc->partitions; i++) {

        static const int a[] = {0, 1, 2, 2, 3, 3, 4, 4};

        fc->partition_to_class[i] = a[i];

        fc->nclasses = FFMAX(fc->nclasses, fc->partition_to_class[i]);

    }

    fc->nclasses++;

    fc->classes = av_malloc_array(fc->nclasses, sizeof(vorbis_enc_floor_class));

    if (!fc->classes)

        return AVERROR(ENOMEM);

    for (i = 0; i < fc->nclasses; i++) {

        vorbis_enc_floor_class * c = &fc->classes[i];

        int j, books;

        c->dim        = floor_classes[i].dim;

        c->subclass   = floor_classes[i].subclass;

        c->masterbook = floor_classes[i].masterbook;

        books         = (1 << c->subclass);

        c->books      = av_malloc_array(books, sizeof(int));

        if (!c->books)

            return AVERROR(ENOMEM);

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

            c->books[j] = floor_classes[i].nbooks[j];

    }

    fc->multiplier = 2;

    fc->rangebits  = venc->log2_blocksize[0] - 1;

    fc->values = 2;

    for (i = 0; i < fc->partitions; i++)

        fc->values += fc->classes[fc->partition_to_class[i]].dim;

    fc->list = av_malloc_array(fc->values, sizeof(vorbis_floor1_entry));

    if (!fc->list)

        return AVERROR(ENOMEM);

    fc->list[0].x = 0;

    fc->list[1].x = 1 << fc->rangebits;

    for (i = 2; i < fc->values; i++) {

        static const int a[] = {

             93, 23,372,  6, 46,186,750, 14, 33, 65,

            130,260,556,  3, 10, 18, 28, 39, 55, 79,

            111,158,220,312,464,650,850

        };

        fc->list[i].x = a[i - 2];

    }

    if (ff_vorbis_ready_floor1_list(avctx, fc->list, fc->values))

        return AVERROR_BUG;

    venc->nresidues = 1;

    venc->residues  = av_malloc(sizeof(vorbis_enc_residue) * venc->nresidues);

    if (!venc->residues)

        return AVERROR(ENOMEM);

    // single residue

    rc = &venc->residues[0];

    rc->type            = 2;

    rc->begin           = 0;

    rc->end             = 1600;

    rc->partition_size  = 32;

    rc->classifications = 10;

    rc->classbook       = 15;

    rc->books           = av_malloc(sizeof(*rc->books) * rc->classifications);

    if (!rc->books)

        return AVERROR(ENOMEM);

    {

        static const int8_t a[10][8] = {

            { -1, -1, -1, -1, -1, -1, -1, -1, },

            { -1, -1, 16, -1, -1, -1, -1, -1, },

            { -1, -1, 17, -1, -1, -1, -1, -1, },

            { -1, -1, 18, -1, -1, -1, -1, -1, },

            { -1, -1, 19, -1, -1, -1, -1, -1, },

            { -1, -1, 20, -1, -1, -1, -1, -1, },

            { -1, -1, 21, -1, -1, -1, -1, -1, },

            { 22, 23, -1, -1, -1, -1, -1, -1, },

            { 24, 25, -1, -1, -1, -1, -1, -1, },

            { 26, 27, 28, -1, -1, -1, -1, -1, },

        };

        memcpy(rc->books, a, sizeof a);

    }

    if ((ret = ready_residue(rc, venc)) < 0)

        return ret;

    venc->nmappings = 1;

    venc->mappings  = av_malloc(sizeof(vorbis_enc_mapping) * venc->nmappings);

    if (!venc->mappings)

        return AVERROR(ENOMEM);

    // single mapping

    mc = &venc->mappings[0];

    mc->submaps = 1;

    mc->mux     = av_malloc(sizeof(int) * venc->channels);

    if (!mc->mux)

        return AVERROR(ENOMEM);

    for (i = 0; i < venc->channels; i++)

        mc->mux[i] = 0;

    mc->floor   = av_malloc(sizeof(int) * mc->submaps);

    mc->residue = av_malloc(sizeof(int) * mc->submaps);

    if (!mc->floor || !mc->residue)

        return AVERROR(ENOMEM);

    for (i = 0; i < mc->submaps; i++) {

        mc->floor[i]   = 0;

        mc->residue[i] = 0;

    }

    mc->coupling_steps = venc->channels == 2 ? 1 : 0;

    mc->magnitude      = av_malloc(sizeof(int) * mc->coupling_steps);

    mc->angle          = av_malloc(sizeof(int) * mc->coupling_steps);

    if (!mc->magnitude || !mc->angle)

        return AVERROR(ENOMEM);

    if (mc->coupling_steps) {

        mc->magnitude[0] = 0;

        mc->angle[0]     = 1;

    }

    venc->nmodes = 1;

    venc->modes  = av_malloc(sizeof(vorbis_enc_mode) * venc->nmodes);

    if (!venc->modes)

        return AVERROR(ENOMEM);

    // single mode

    venc->modes[0].blockflag = 0;

    venc->modes[0].mapping   = 0;

    venc->have_saved = 0;

    venc->saved      = av_malloc_array(sizeof(float) * venc->channels, (1 << venc->log2_blocksize[1]) / 2);

    venc->samples    = av_malloc_array(sizeof(float) * venc->channels, (1 << venc->log2_blocksize[1]));

    venc->floor      = av_malloc_array(sizeof(float) * venc->channels, (1 << venc->log2_blocksize[1]) / 2);

    venc->coeffs     = av_malloc_array(sizeof(float) * venc->channels, (1 << venc->log2_blocksize[1]) / 2);

    if (!venc->saved || !venc->samples || !venc->floor || !venc->coeffs)

        return AVERROR(ENOMEM);

    if ((ret = dsp_init(avctx, venc)) < 0)

        return ret;

    return 0;

}


static void assert_codec_experimental(AVCodecContext *c, int encoder)

{

    const char *codec_string = encoder ? "encoder" : "decoder";

    AVCodec *codec;

    if (c->codec->capabilities & CODEC_CAP_EXPERIMENTAL &&

        c->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {

        av_log(NULL, AV_LOG_ERROR, "%s '%s' is experimental and might produce bad "

                "results.\nAdd '-strict experimental' if you want to use it.\n",

                codec_string, c->codec->name);

        codec = encoder ? avcodec_find_encoder(codec->id) : avcodec_find_decoder(codec->id);

        if (!(codec->capabilities & CODEC_CAP_EXPERIMENTAL))

            av_log(NULL, AV_LOG_ERROR, "Or use the non experimental %s '%s'.\n",

                   codec_string, codec->name);

        ffmpeg_exit(1);

    }

}


static void vnc_display_close(DisplayState *ds)

{

    VncDisplay *vs = ds ? (VncDisplay *)ds->opaque : vnc_display;

    if (!vs)

        return;

    if (vs->display) {

        g_free(vs->display);

        vs->display = NULL;

    }

    if (vs->lsock != -1) {

        qemu_set_fd_handler2(vs->lsock, NULL, NULL, NULL, NULL);

        close(vs->lsock);

        vs->lsock = -1;

    }

#ifdef CONFIG_VNC_WS

    g_free(vs->ws_display);

    vs->ws_display = NULL;

    if (vs->lwebsock != -1) {

        qemu_set_fd_handler2(vs->lwebsock, NULL, NULL, NULL, NULL);

        close(vs->lwebsock);

        vs->lwebsock = -1;

    }

#endif /* CONFIG_VNC_WS */

    vs->auth = VNC_AUTH_INVALID;

#ifdef CONFIG_VNC_TLS

    vs->subauth = VNC_AUTH_INVALID;

    vs->tls.x509verify = 0;

#endif

}


static void device_set_realized(Object *obj, bool value, Error **errp)
{
    DeviceState *dev = DEVICE(obj);
    DeviceClass *dc = DEVICE_GET_CLASS(dev);
    HotplugHandler *hotplug_ctrl;
    BusState *bus;
    Error *local_err = NULL;
    bool unattached_parent = false;
    static int unattached_count;
    int ret;
    if (dev->hotplugged && !dc->hotpluggable) {
        error_setg(errp, QERR_DEVICE_NO_HOTPLUG, object_get_typename(obj));
        return;
    if (value && !dev->realized) {
        if (!obj->parent) {
            gchar *name = g_strdup_printf("device[%d]", unattached_count++);
            object_property_add_child(container_get(qdev_get_machine(),
                                                    "/unattached"),
                                      name, obj, &error_abort);
            unattached_parent = true;
            g_free(name);
        hotplug_ctrl = qdev_get_hotplug_handler(dev);
        if (hotplug_ctrl) {
            hotplug_handler_pre_plug(hotplug_ctrl, dev, &local_err);
            if (local_err != NULL) {
        if (dc->realize) {
            dc->realize(dev, &local_err);
        if (local_err != NULL) {
        DEVICE_LISTENER_CALL(realize, Forward, dev);
        if (hotplug_ctrl) {
            hotplug_handler_plug(hotplug_ctrl, dev, &local_err);
        if (local_err != NULL) {
            goto post_realize_fail;
        if (qdev_get_vmsd(dev)) {
            if (vmstate_register_with_alias_id(dev, -1, qdev_get_vmsd(dev), dev,
                                               dev->instance_id_alias,
                                               dev->alias_required_for_version,
                                               &local_err) < 0) {
                goto post_realize_fail;
        QLIST_FOREACH(bus, &dev->child_bus, sibling) {
            object_property_set_bool(OBJECT(bus), true, "realized",
                                         &local_err);
            if (local_err != NULL) {
                goto child_realize_fail;
        if (dev->hotplugged) {
            device_reset(dev);
        dev->pending_deleted_event = false;
    } else if (!value && dev->realized) {
        Error **local_errp = NULL;
        QLIST_FOREACH(bus, &dev->child_bus, sibling) {
            local_errp = local_err ? NULL : &local_err;
            object_property_set_bool(OBJECT(bus), false, "realized",
                                     local_errp);
        if (qdev_get_vmsd(dev)) {
            vmstate_unregister(dev, qdev_get_vmsd(dev), dev);
        if (dc->unrealize) {
            local_errp = local_err ? NULL : &local_err;
            dc->unrealize(dev, local_errp);
        dev->pending_deleted_event = true;
        DEVICE_LISTENER_CALL(unrealize, Reverse, dev);
    if (local_err != NULL) {
    dev->realized = value;
    return;
child_realize_fail:
    QLIST_FOREACH(bus, &dev->child_bus, sibling) {
        object_property_set_bool(OBJECT(bus), false, "realized",
                                 NULL);
    if (qdev_get_vmsd(dev)) {
        vmstate_unregister(dev, qdev_get_vmsd(dev), dev);
post_realize_fail:
    if (dc->unrealize) {
        dc->unrealize(dev, NULL);
fail:
    error_propagate(errp, local_err);
    if (unattached_parent) {
        object_unparent(OBJECT(dev));
        unattached_count--;


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

{

    DriveInfo *dinfo;

    BlockDriverState *bs, *bs1;

    int ret;

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

    bs = get_bs_snapshots();

    if (!bs) {

        monitor_printf(mon, "No block device supports snapshots\n");

        return;

    }

    QTAILQ_FOREACH(dinfo, &drives, next) {

        bs1 = dinfo->bdrv;

        if (bdrv_has_snapshot(bs1)) {

            ret = bdrv_snapshot_delete(bs1, name);

            if (ret < 0) {

                if (ret == -ENOTSUP)

                    monitor_printf(mon,

                                   "Snapshots not supported on device '%s'\n",

                                   bdrv_get_device_name(bs1));

                else

                    monitor_printf(mon, "Error %d while deleting snapshot on "

                                   "'%s'\n", ret, bdrv_get_device_name(bs1));

            }

        }

    }

}


static void bit_prop_set(DeviceState *dev, Property *props, bool val)

{

    uint32_t *p = qdev_get_prop_ptr(dev, props);

    uint32_t mask = qdev_get_prop_mask(props);

    if (val)

        *p |= ~mask;

    else

        *p &= ~mask;

}


static void vmxnet3_adjust_by_guest_type(VMXNET3State *s)

{

    struct Vmxnet3_GOSInfo gos;

    VMXNET3_READ_DRV_SHARED(s->drv_shmem, devRead.misc.driverInfo.gos,

                            &gos, sizeof(gos));

    s->rx_packets_compound =

        (gos.gosType == VMXNET3_GOS_TYPE_WIN) ? false : true;

    VMW_CFPRN("Guest type specifics: RXCOMPOUND: %d", s->rx_packets_compound);

}


int av_grow_packet(AVPacket *pkt, int grow_by)

{

    int new_size;

    av_assert0((unsigned)pkt->size <= INT_MAX - AV_INPUT_BUFFER_PADDING_SIZE);

    if ((unsigned)grow_by >

        INT_MAX - (pkt->size + AV_INPUT_BUFFER_PADDING_SIZE))

        return -1;

    new_size = pkt->size + grow_by + AV_INPUT_BUFFER_PADDING_SIZE;

    if (pkt->buf) {

        size_t data_offset;

        uint8_t *old_data = pkt->data;

        if (pkt->data == NULL) {

            data_offset = 0;

            pkt->data = pkt->buf->data;

        } else {

            data_offset = pkt->data - pkt->buf->data;

            if (data_offset > INT_MAX - new_size)

                return -1;

        }

        if (new_size + data_offset > pkt->buf->size) {

            int ret = av_buffer_realloc(&pkt->buf, new_size + data_offset);

            if (ret < 0) {

                pkt->data = old_data;

                return ret;

            }

            pkt->data = pkt->buf->data + data_offset;

        }

    } else {

        pkt->buf = av_buffer_alloc(new_size);

        if (!pkt->buf)

            return AVERROR(ENOMEM);

        memcpy(pkt->buf->data, pkt->data, pkt->size);

        pkt->data = pkt->buf->data;

    }

    pkt->size += grow_by;

    memset(pkt->data + pkt->size, 0, AV_INPUT_BUFFER_PADDING_SIZE);

    return 0;

}


static inline void IRQ_resetbit(IRQ_queue_t *q, int n_IRQ)

{

    q->pending--;

    reset_bit(q->queue, n_IRQ);

}


static void *nbd_client_thread(void *arg)

{

    char *device = arg;

    off_t size;

    size_t blocksize;

    uint32_t nbdflags;

    int fd, sock;

    int ret;

    pthread_t show_parts_thread;

    sock = unix_socket_outgoing(sockpath);

    if (sock < 0) {

        goto out;

    }

    ret = nbd_receive_negotiate(sock, NULL, &nbdflags,

                                &size, &blocksize);

    if (ret < 0) {

        goto out;

    }

    fd = open(device, O_RDWR);

    if (fd < 0) {

        /* Linux-only, we can use %m in printf.  */

        fprintf(stderr, "Failed to open %s: %m", device);

        goto out;

    }

    ret = nbd_init(fd, sock, nbdflags, size, blocksize);

    if (ret < 0) {

        goto out;

    }

    /* update partition table */

    pthread_create(&show_parts_thread, NULL, show_parts, device);

    if (verbose) {

        fprintf(stderr, "NBD device %s is now connected to %s\n",

                device, srcpath);

    } else {

        /* Close stderr so that the qemu-nbd process exits.  */

        dup2(STDOUT_FILENO, STDERR_FILENO);

    }

    ret = nbd_client(fd);

    if (ret) {

        goto out;

    }

    close(fd);

    kill(getpid(), SIGTERM);

    return (void *) EXIT_SUCCESS;

out:

    kill(getpid(), SIGTERM);

    return (void *) EXIT_FAILURE;

}


bool migration_in_setup(MigrationState *s)

{

    return s->state == MIG_STATE_SETUP;

}


static int64_t guest_file_handle_add(HANDLE fh, Error **errp)

{

    GuestFileHandle *gfh;

    int64_t handle;

    handle = ga_get_fd_handle(ga_state, errp);

    if (handle < 0) {

        return -1;

    }

    gfh = g_malloc0(sizeof(GuestFileHandle));

    gfh->id = handle;

    gfh->fh = fh;

    QTAILQ_INSERT_TAIL(&guest_file_state.filehandles, gfh, next);

    return handle;

}


static void pm_reset(void *opaque)
{
    ICH9LPCPMRegs *pm = opaque;
    ich9_pm_iospace_update(pm, 0);
    acpi_pm1_evt_reset(&pm->acpi_regs);
    acpi_pm1_cnt_reset(&pm->acpi_regs);
    acpi_pm_tmr_reset(&pm->acpi_regs);
    acpi_gpe_reset(&pm->acpi_regs);
    pm_update_sci(pm);


static void get_pixels_altivec(int16_t *restrict block, const uint8_t *pixels,

                               ptrdiff_t line_size)

{

    int i;

    vec_u8 perm = vec_lvsl(0, pixels);

    const vec_u8 zero = (const vec_u8)vec_splat_u8(0);

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

        /* Read potentially unaligned pixels.

         * We're reading 16 pixels, and actually only want 8,

         * but we simply ignore the extras. */

        vec_u8 pixl = vec_ld(0, pixels);

        vec_u8 pixr = vec_ld(7, pixels);

        vec_u8 bytes = vec_perm(pixl, pixr, perm);

        // Convert the bytes into shorts.

        vec_s16 shorts = (vec_s16)vec_mergeh(zero, bytes);

        // Save the data to the block, we assume the block is 16-byte aligned.

        vec_st(shorts, i * 16, (vec_s16 *)block);

        pixels += line_size;

    }

}


static int spapr_phb_init(SysBusDevice *s)

{

    sPAPRPHBState *sphb = SPAPR_PCI_HOST_BRIDGE(s);

    PCIHostState *phb = PCI_HOST_BRIDGE(s);

    char *namebuf;

    int i;

    PCIBus *bus;

    sphb->dtbusname = g_strdup_printf("pci@%" PRIx64, sphb->buid);

    namebuf = alloca(strlen(sphb->dtbusname) + 32);

    /* Initialize memory regions */

    sprintf(namebuf, "%s.mmio", sphb->dtbusname);

    memory_region_init(&sphb->memspace, namebuf, INT64_MAX);

    sprintf(namebuf, "%s.mmio-alias", sphb->dtbusname);

    memory_region_init_alias(&sphb->memwindow, namebuf, &sphb->memspace,

                             SPAPR_PCI_MEM_WIN_BUS_OFFSET, sphb->mem_win_size);

    memory_region_add_subregion(get_system_memory(), sphb->mem_win_addr,

                                &sphb->memwindow);

    /* On ppc, we only have MMIO no specific IO space from the CPU

     * perspective.  In theory we ought to be able to embed the PCI IO

     * memory region direction in the system memory space.  However,

     * if any of the IO BAR subregions use the old_portio mechanism,

     * that won't be processed properly unless accessed from the

     * system io address space.  This hack to bounce things via

     * system_io works around the problem until all the users of

     * old_portion are updated */

    sprintf(namebuf, "%s.io", sphb->dtbusname);

    memory_region_init(&sphb->iospace, namebuf, SPAPR_PCI_IO_WIN_SIZE);

    /* FIXME: fix to support multiple PHBs */

    memory_region_add_subregion(get_system_io(), 0, &sphb->iospace);

    sprintf(namebuf, "%s.io-alias", sphb->dtbusname);

    memory_region_init_io(&sphb->iowindow, &spapr_io_ops, sphb,

                          namebuf, SPAPR_PCI_IO_WIN_SIZE);

    memory_region_add_subregion(get_system_memory(), sphb->io_win_addr,

                                &sphb->iowindow);

    /* As MSI/MSIX interrupts trigger by writing at MSI/MSIX vectors,

     * we need to allocate some memory to catch those writes coming

     * from msi_notify()/msix_notify() */

    if (msi_supported) {

        sprintf(namebuf, "%s.msi", sphb->dtbusname);

        memory_region_init_io(&sphb->msiwindow, &spapr_msi_ops, sphb,

                              namebuf, SPAPR_MSIX_MAX_DEVS * 0x10000);

        memory_region_add_subregion(get_system_memory(), sphb->msi_win_addr,

                                    &sphb->msiwindow);

    }

    bus = pci_register_bus(DEVICE(s),

                           sphb->busname ? sphb->busname : sphb->dtbusname,

                           pci_spapr_set_irq, pci_spapr_map_irq, sphb,

                           &sphb->memspace, &sphb->iospace,

                           PCI_DEVFN(0, 0), PCI_NUM_PINS);

    phb->bus = bus;

    sphb->dma_liobn = SPAPR_PCI_BASE_LIOBN | (pci_find_domain(bus) << 16);

    sphb->dma_window_start = 0;

    sphb->dma_window_size = 0x40000000;

    sphb->dma = spapr_tce_new_dma_context(sphb->dma_liobn, sphb->dma_window_size);

    pci_setup_iommu(bus, spapr_pci_dma_context_fn, sphb);

    QLIST_INSERT_HEAD(&spapr->phbs, sphb, list);

    /* Initialize the LSI table */

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

        uint32_t irq;

        irq = spapr_allocate_lsi(0);

        if (!irq) {

            return -1;

        }

        sphb->lsi_table[i].irq = irq;

    }

    return 0;

}


static int xen_pt_msgctrl_reg_write(XenPCIPassthroughState *s,

                                    XenPTReg *cfg_entry, uint16_t *val,

                                    uint16_t dev_value, uint16_t valid_mask)

{

    XenPTRegInfo *reg = cfg_entry->reg;

    XenPTMSI *msi = s->msi;

    uint16_t writable_mask = 0;

    uint16_t throughable_mask = 0;

    uint16_t raw_val;

    /* Currently no support for multi-vector */

    if (*val & PCI_MSI_FLAGS_QSIZE) {

        XEN_PT_WARN(&s->dev, "Tries to set more than 1 vector ctrl %x\n", *val);

    }

    /* modify emulate register */

    writable_mask = reg->emu_mask & ~reg->ro_mask & valid_mask;

    cfg_entry->data = XEN_PT_MERGE_VALUE(*val, cfg_entry->data, writable_mask);

    msi->flags |= cfg_entry->data & ~PCI_MSI_FLAGS_ENABLE;

    /* create value for writing to I/O device register */

    raw_val = *val;

    throughable_mask = ~reg->emu_mask & valid_mask;

    *val = XEN_PT_MERGE_VALUE(*val, dev_value, throughable_mask);

    /* update MSI */

    if (raw_val & PCI_MSI_FLAGS_ENABLE) {

        /* setup MSI pirq for the first time */

        if (!msi->initialized) {

            /* Init physical one */

            XEN_PT_LOG(&s->dev, "setup MSI\n");

            if (xen_pt_msi_setup(s)) {

                /* We do not broadcast the error to the framework code, so

                 * that MSI errors are contained in MSI emulation code and

                 * QEMU can go on running.

                 * Guest MSI would be actually not working.

                 */

                *val &= ~PCI_MSI_FLAGS_ENABLE;

                XEN_PT_WARN(&s->dev, "Can not map MSI.\n");

                return 0;

            }

            if (xen_pt_msi_update(s)) {

                *val &= ~PCI_MSI_FLAGS_ENABLE;

                XEN_PT_WARN(&s->dev, "Can not bind MSI\n");

                return 0;

            }

            msi->initialized = true;

            msi->mapped = true;

        }

        msi->flags |= PCI_MSI_FLAGS_ENABLE;

    } else {

        msi->flags &= ~PCI_MSI_FLAGS_ENABLE;

    }

    /* pass through MSI_ENABLE bit */

    *val &= ~PCI_MSI_FLAGS_ENABLE;

    *val |= raw_val & PCI_MSI_FLAGS_ENABLE;

    return 0;

}


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

{

#ifdef DEBUG_UNASSIGNED

    printf("Unassigned mem write " TARGET_FMT_plx " = 0x%x\n", addr, val);

#endif

#if defined(TARGET_ALPHA) || defined(TARGET_SPARC) || defined(TARGET_MICROBLAZE)

    do_unassigned_access(addr, 1, 0, 0, 2);

#endif

}


static int i386_tr_init_disas_context(DisasContextBase *dcbase, CPUState *cpu,

                                      int max_insns)

{

    DisasContext *dc = container_of(dcbase, DisasContext, base);

    CPUX86State *env = cpu->env_ptr;

    uint32_t flags = dc->base.tb->flags;

    target_ulong cs_base = dc->base.tb->cs_base;

    dc->pe = (flags >> HF_PE_SHIFT) & 1;

    dc->code32 = (flags >> HF_CS32_SHIFT) & 1;

    dc->ss32 = (flags >> HF_SS32_SHIFT) & 1;

    dc->addseg = (flags >> HF_ADDSEG_SHIFT) & 1;

    dc->f_st = 0;

    dc->vm86 = (flags >> VM_SHIFT) & 1;

    dc->cpl = (flags >> HF_CPL_SHIFT) & 3;

    dc->iopl = (flags >> IOPL_SHIFT) & 3;

    dc->tf = (flags >> TF_SHIFT) & 1;

    dc->cc_op = CC_OP_DYNAMIC;

    dc->cc_op_dirty = false;

    dc->cs_base = cs_base;

    dc->popl_esp_hack = 0;

    /* select memory access functions */

    dc->mem_index = 0;

#ifdef CONFIG_SOFTMMU

    dc->mem_index = cpu_mmu_index(env, false);

#endif

    dc->cpuid_features = env->features[FEAT_1_EDX];

    dc->cpuid_ext_features = env->features[FEAT_1_ECX];

    dc->cpuid_ext2_features = env->features[FEAT_8000_0001_EDX];

    dc->cpuid_ext3_features = env->features[FEAT_8000_0001_ECX];

    dc->cpuid_7_0_ebx_features = env->features[FEAT_7_0_EBX];

    dc->cpuid_xsave_features = env->features[FEAT_XSAVE];

#ifdef TARGET_X86_64

    dc->lma = (flags >> HF_LMA_SHIFT) & 1;

    dc->code64 = (flags >> HF_CS64_SHIFT) & 1;

#endif

    dc->flags = flags;

    dc->jmp_opt = !(dc->tf || dc->base.singlestep_enabled ||

                    (flags & HF_INHIBIT_IRQ_MASK));

    /* Do not optimize repz jumps at all in icount mode, because

       rep movsS instructions are execured with different paths

       in !repz_opt and repz_opt modes. The first one was used

       always except single step mode. And this setting

       disables jumps optimization and control paths become

       equivalent in run and single step modes.

       Now there will be no jump optimization for repz in

       record/replay modes and there will always be an

       additional step for ecx=0 when icount is enabled.

     */

    dc->repz_opt = !dc->jmp_opt && !(dc->base.tb->cflags & CF_USE_ICOUNT);

#if 0

    /* check addseg logic */

    if (!dc->addseg && (dc->vm86 || !dc->pe || !dc->code32))

        printf("ERROR addseg\n");

#endif

    cpu_T0 = tcg_temp_new();

    cpu_T1 = tcg_temp_new();

    cpu_A0 = tcg_temp_new();

    cpu_tmp0 = tcg_temp_new();

    cpu_tmp1_i64 = tcg_temp_new_i64();

    cpu_tmp2_i32 = tcg_temp_new_i32();

    cpu_tmp3_i32 = tcg_temp_new_i32();

    cpu_tmp4 = tcg_temp_new();

    cpu_ptr0 = tcg_temp_new_ptr();

    cpu_ptr1 = tcg_temp_new_ptr();

    cpu_cc_srcT = tcg_temp_local_new();

    return max_insns;

}


void RENAME(interleaveBytes)(uint8_t *src1, uint8_t *src2, uint8_t *dest,

			    unsigned width, unsigned height, int src1Stride,

			    int src2Stride, int dstStride){

	unsigned h;

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

	{

		unsigned w;

#ifdef HAVE_MMX

#ifdef HAVE_SSE2

		asm(

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

			"1:				\n\t"

			PREFETCH" 64(%1, %%"REG_a")	\n\t"

			PREFETCH" 64(%2, %%"REG_a")	\n\t"

			"movdqa (%1, %%"REG_a"), %%xmm0	\n\t"

			"movdqa (%1, %%"REG_a"), %%xmm1	\n\t"

			"movdqa (%2, %%"REG_a"), %%xmm2	\n\t"

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

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

			"movntdq %%xmm0, (%0, %%"REG_a", 2)\n\t"

			"movntdq %%xmm1, 16(%0, %%"REG_a", 2)\n\t"

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

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

			" jb 1b				\n\t"

			::"r"(dest), "r"(src1), "r"(src2), "r" ((long)width-15)

			: "memory", "%"REG_a""

		);

#else

		asm(

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

			"1:				\n\t"

			PREFETCH" 64(%1, %%"REG_a")	\n\t"

			PREFETCH" 64(%2, %%"REG_a")	\n\t"

			"movq (%1, %%"REG_a"), %%mm0	\n\t"

			"movq 8(%1, %%"REG_a"), %%mm2	\n\t"

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

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

			"movq (%2, %%"REG_a"), %%mm4	\n\t"

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

			"punpcklbw %%mm4, %%mm0		\n\t"

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

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

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

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

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

			MOVNTQ" %%mm2, 16(%0, %%"REG_a", 2)\n\t"

			MOVNTQ" %%mm3, 24(%0, %%"REG_a", 2)\n\t"

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

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

			" jb 1b				\n\t"

			::"r"(dest), "r"(src1), "r"(src2), "r" ((long)width-15)

			: "memory", "%"REG_a

		);

#endif

		for(w= (width&(~15)); w < width; w++)

		{

			dest[2*w+0] = src1[w];

			dest[2*w+1] = src2[w];

		}

#else

		for(w=0; w < width; w++)

		{

			dest[2*w+0] = src1[w];

			dest[2*w+1] = src2[w];

		}

#endif

		dest += dstStride;

                src1 += src1Stride;

                src2 += src2Stride;

	}

#ifdef HAVE_MMX

	asm(

		EMMS" \n\t"

		SFENCE" \n\t"

		::: "memory"

		);

#endif

}


void OPPROTO op_check_subfo (void)

{

    if (likely(!(((uint32_t)(~T2) ^ (uint32_t)T1 ^ UINT32_MAX) &

                 ((uint32_t)(~T2) ^ (uint32_t)T0) & (1UL << 31)))) {

        xer_ov = 0;

    } else {

        xer_ov = 1;

        xer_so = 1;

    }

    RETURN();

}


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

{

    ASFContext *asf = s->priv_data;

    ASFStream *stream;

    int64_t duration;

    AVCodecContext *codec;

    int64_t packet_st, pts;

    int start_sec, i;

    int flags = pkt->flags;

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

    stream = &asf->streams[pkt->stream_index];

    if (codec->codec_type == AVMEDIA_TYPE_AUDIO)

        flags &= ~AV_PKT_FLAG_KEY;

    pts = (pkt->pts != AV_NOPTS_VALUE) ? pkt->pts : pkt->dts;

    if (pts < 0) {

        av_log(s, AV_LOG_ERROR,

               "Negative dts not supported stream %d, dts %"PRId64"\n",

               pkt->stream_index, pts);

        return AVERROR(ENOSYS);

    }

    assert(pts != AV_NOPTS_VALUE);

    duration      = pts * 10000;

    asf->duration = FFMAX(asf->duration, duration + pkt->duration * 10000);

    packet_st = asf->nb_packets;

    put_frame(s, stream, s->streams[pkt->stream_index],

              pkt->dts, pkt->data, pkt->size, flags);

    /* check index */

    if ((!asf->is_streamed) && (flags & AV_PKT_FLAG_KEY)) {

        start_sec = (int)(duration / INT64_C(10000000));

        if (start_sec != (int)(asf->last_indexed_pts / INT64_C(10000000))) {

            for (i = asf->nb_index_count; i < start_sec; i++) {

                if (i >= asf->nb_index_memory_alloc) {

                    asf->nb_index_memory_alloc += ASF_INDEX_BLOCK;

                    asf->index_ptr              = (ASFIndex *)av_realloc(asf->index_ptr,

                                                                         sizeof(ASFIndex) *

                                                                         asf->nb_index_memory_alloc);

                }

                // store

                asf->index_ptr[i].packet_number = (uint32_t)packet_st;

                asf->index_ptr[i].packet_count  = (uint16_t)(asf->nb_packets - packet_st);

                asf->maximum_packet             = FFMAX(asf->maximum_packet,

                                                        (uint16_t)(asf->nb_packets - packet_st));

            }

            asf->nb_index_count   = start_sec;

            asf->last_indexed_pts = duration;

        }

    }

    return 0;

}


int avpriv_snprintf(char *restrict s, size_t n, const char *restrict fmt, ...)

{

    va_list ap;

    int ret;

    va_start(ap, fmt);

    ret = avpriv_vsnprintf(s, n, fmt, ap);

    va_end(ap);

    return ret;

}


static void virtio_pci_device_plugged(DeviceState *d, Error **errp)

{

    VirtIOPCIProxy *proxy = VIRTIO_PCI(d);

    VirtioBusState *bus = &proxy->bus;

    bool legacy = virtio_pci_legacy(proxy);

    bool modern;

    bool modern_pio = proxy->flags & VIRTIO_PCI_FLAG_MODERN_PIO_NOTIFY;

    uint8_t *config;

    uint32_t size;

    VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);

    /*

     * Virtio capabilities present without

     * VIRTIO_F_VERSION_1 confuses guests

     */

    if (!proxy->ignore_backend_features &&

            !virtio_has_feature(vdev->host_features, VIRTIO_F_VERSION_1)) {

        virtio_pci_disable_modern(proxy);

        if (!legacy) {

            error_setg(errp, "Device doesn't support modern mode, and legacy"

                             " mode is disabled");

            error_append_hint(errp, "Set disable-legacy to off\n");

            return;

        }

    }

    modern = virtio_pci_modern(proxy);

    config = proxy->pci_dev.config;

    if (proxy->class_code) {

        pci_config_set_class(config, proxy->class_code);

    }

    if (legacy) {

        if (virtio_host_has_feature(vdev, VIRTIO_F_IOMMU_PLATFORM)) {

            error_setg(errp, "VIRTIO_F_IOMMU_PLATFORM was supported by"

                       "neither legacy nor transitional device.");

            return ;

        }

        /* legacy and transitional */

        pci_set_word(config + PCI_SUBSYSTEM_VENDOR_ID,

                     pci_get_word(config + PCI_VENDOR_ID));

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

    } else {

        /* pure virtio-1.0 */

        pci_set_word(config + PCI_VENDOR_ID,

                     PCI_VENDOR_ID_REDHAT_QUMRANET);

        pci_set_word(config + PCI_DEVICE_ID,

                     0x1040 + virtio_bus_get_vdev_id(bus));

        pci_config_set_revision(config, 1);

    }

    config[PCI_INTERRUPT_PIN] = 1;

    if (modern) {

        struct virtio_pci_cap cap = {

            .cap_len = sizeof cap,

        };

        struct virtio_pci_notify_cap notify = {

            .cap.cap_len = sizeof notify,

            .notify_off_multiplier =

                cpu_to_le32(virtio_pci_queue_mem_mult(proxy)),

        };

        struct virtio_pci_cfg_cap cfg = {

            .cap.cap_len = sizeof cfg,

            .cap.cfg_type = VIRTIO_PCI_CAP_PCI_CFG,

        };

        struct virtio_pci_notify_cap notify_pio = {

            .cap.cap_len = sizeof notify,

            .notify_off_multiplier = cpu_to_le32(0x0),

        };

        struct virtio_pci_cfg_cap *cfg_mask;

        virtio_pci_modern_regions_init(proxy);

        virtio_pci_modern_mem_region_map(proxy, &proxy->common, &cap);

        virtio_pci_modern_mem_region_map(proxy, &proxy->isr, &cap);

        virtio_pci_modern_mem_region_map(proxy, &proxy->device, &cap);

        virtio_pci_modern_mem_region_map(proxy, &proxy->notify, &notify.cap);

        if (modern_pio) {

            memory_region_init(&proxy->io_bar, OBJECT(proxy),

                               "virtio-pci-io", 0x4);

            pci_register_bar(&proxy->pci_dev, proxy->modern_io_bar_idx,

                             PCI_BASE_ADDRESS_SPACE_IO, &proxy->io_bar);

            virtio_pci_modern_io_region_map(proxy, &proxy->notify_pio,

                                            &notify_pio.cap);

        }

        pci_register_bar(&proxy->pci_dev, proxy->modern_mem_bar_idx,

                         PCI_BASE_ADDRESS_SPACE_MEMORY |

                         PCI_BASE_ADDRESS_MEM_PREFETCH |

                         PCI_BASE_ADDRESS_MEM_TYPE_64,

                         &proxy->modern_bar);

        proxy->config_cap = virtio_pci_add_mem_cap(proxy, &cfg.cap);

        cfg_mask = (void *)(proxy->pci_dev.wmask + proxy->config_cap);

        pci_set_byte(&cfg_mask->cap.bar, ~0x0);

        pci_set_long((uint8_t *)&cfg_mask->cap.offset, ~0x0);

        pci_set_long((uint8_t *)&cfg_mask->cap.length, ~0x0);

        pci_set_long(cfg_mask->pci_cfg_data, ~0x0);

    }

    if (proxy->nvectors) {

        int err = msix_init_exclusive_bar(&proxy->pci_dev, proxy->nvectors,

                                          proxy->msix_bar_idx, NULL);

        if (err) {

            /* Notice when a system that supports MSIx can't initialize it */

            if (err != -ENOTSUP) {

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

                             proxy->nvectors);

            }

            proxy->nvectors = 0;

        }

    }

    proxy->pci_dev.config_write = virtio_write_config;

    proxy->pci_dev.config_read = virtio_read_config;

    if (legacy) {

        size = VIRTIO_PCI_REGION_SIZE(&proxy->pci_dev)

            + virtio_bus_get_vdev_config_len(bus);

        size = pow2ceil(size);

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

                              &virtio_pci_config_ops,

                              proxy, "virtio-pci", size);

        pci_register_bar(&proxy->pci_dev, proxy->legacy_io_bar_idx,

                         PCI_BASE_ADDRESS_SPACE_IO, &proxy->bar);

    }

}


static void phys_page_compact_all(AddressSpaceDispatch *d, int nodes_nb)

{

    DECLARE_BITMAP(compacted, nodes_nb);

    if (d->phys_map.skip) {

        phys_page_compact(&d->phys_map, d->nodes, compacted);

    }

}


int avpriv_adx_decode_header(AVCodecContext *avctx, const uint8_t *buf,

                             int bufsize, int *header_size, int *coeff)

{

    int offset, cutoff;

    if (bufsize < 24)

        return AVERROR_INVALIDDATA;

    if (AV_RB16(buf) != 0x8000)

        return AVERROR_INVALIDDATA;

    offset = AV_RB16(buf + 2) + 4;

    /* if copyright string is within the provided data, validate it */

    if (bufsize >= offset && memcmp(buf + offset - 6, "(c)CRI", 6))

        return AVERROR_INVALIDDATA;

    /* check for encoding=3 block_size=18, sample_size=4 */

    if (buf[4] != 3 || buf[5] != 18 || buf[6] != 4) {

        avpriv_request_sample(avctx, "Support for this ADX format");

        return AVERROR_PATCHWELCOME;

    }

    /* channels */

    avctx->channels = buf[7];

    if (avctx->channels <= 0 || avctx->channels > 2)

        return AVERROR_INVALIDDATA;

    /* sample rate */

    avctx->sample_rate = AV_RB32(buf + 8);

    if (avctx->sample_rate < 1 ||

        avctx->sample_rate > INT_MAX / (avctx->channels * BLOCK_SIZE * 8))

        return AVERROR_INVALIDDATA;

    /* bit rate */

    avctx->bit_rate = avctx->sample_rate * avctx->channels * BLOCK_SIZE * 8 / BLOCK_SAMPLES;

    /* LPC coefficients */

    if (coeff) {

        cutoff = AV_RB16(buf + 16);

        ff_adx_calculate_coeffs(cutoff, avctx->sample_rate, COEFF_BITS, coeff);

    }

    *header_size = offset;

    return 0;

}


int walk_memory_regions(void *priv, walk_memory_regions_fn fn)

{

    struct walk_memory_regions_data data;

    uintptr_t i;

    data.fn = fn;

    data.priv = priv;

    data.start = -1ul;

    data.prot = 0;

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

        int rc = walk_memory_regions_1(&data, (abi_ulong)i << V_L1_SHIFT,

                                       V_L1_SHIFT / L2_BITS - 1, l1_map + i);

        if (rc != 0) {

            return rc;

        }

    }

    return walk_memory_regions_end(&data, 0, 0);

}


static int es1370_initfn (PCIDevice *dev)

{

    ES1370State *s = DO_UPCAST (ES1370State, dev, dev);

    uint8_t *c = s->dev.config;

    pci_config_set_vendor_id (c, PCI_VENDOR_ID_ENSONIQ);

    pci_config_set_device_id (c, PCI_DEVICE_ID_ENSONIQ_ES1370);

    c[PCI_STATUS + 1] = PCI_STATUS_DEVSEL_SLOW >> 8;

    pci_config_set_class (c, PCI_CLASS_MULTIMEDIA_AUDIO);

#if 1

    c[PCI_SUBSYSTEM_VENDOR_ID] = 0x42;

    c[PCI_SUBSYSTEM_VENDOR_ID + 1] = 0x49;

    c[PCI_SUBSYSTEM_ID] = 0x4c;

    c[PCI_SUBSYSTEM_ID + 1] = 0x4c;

#else

    c[PCI_SUBSYSTEM_VENDOR_ID] = 0x74;

    c[PCI_SUBSYSTEM_VENDOR_ID + 1] = 0x12;

    c[PCI_SUBSYSTEM_ID] = 0x71;

    c[PCI_SUBSYSTEM_ID + 1] = 0x13;

    c[PCI_CAPABILITY_LIST] = 0xdc;

    c[PCI_INTERRUPT_LINE] = 10;

    c[0xdc] = 0x00;

#endif

    /* TODO: RST# value should be 0. */

    c[PCI_INTERRUPT_PIN] = 1;

    c[PCI_MIN_GNT] = 0x0c;

    c[PCI_MAX_LAT] = 0x80;

    pci_register_bar (&s->dev, 0, 256, PCI_BASE_ADDRESS_SPACE_IO, es1370_map);

    qemu_register_reset (es1370_on_reset, s);

    AUD_register_card ("es1370", &s->card);

    es1370_reset (s);

    return 0;

}


int qemu_can_send_packet(VLANClientState *sender)

{

    VLANState *vlan = sender->vlan;

    VLANClientState *vc;

    for (vc = vlan->first_client; vc != NULL; vc = vc->next) {

        if (vc == sender) {

            continue;

        }

        /* no can_receive() handler, they can always receive */

        if (!vc->can_receive || vc->can_receive(vc->opaque)) {

            return 1;

        }

    }

    return 0;

}


static uint32_t apic_mem_readw(void *opaque, target_phys_addr_t addr)

{

    return 0;

}


static int ppc_hash64_pp_check(int key, int pp, bool nx)

{

    int access;

    /* Compute access rights */

    /* When pp is 4, 5 or 7, the result is undefined. Set it to noaccess */

    access = 0;

    if (key == 0) {

        switch (pp) {

        case 0x0:

        case 0x1:

        case 0x2:

            access |= PAGE_WRITE;

            /* No break here */

        case 0x3:

        case 0x6:

            access |= PAGE_READ;

            break;

        }

    } else {

        switch (pp) {

        case 0x0:

        case 0x6:

            access = 0;

            break;

        case 0x1:

        case 0x3:

            access = PAGE_READ;

            break;

        case 0x2:

            access = PAGE_READ | PAGE_WRITE;

            break;

        }

    }

    if (!nx) {

        access |= PAGE_EXEC;

    }

    return access;

}


long do_rt_sigreturn(CPUAlphaState *env)

{

    abi_ulong frame_addr = env->ir[IR_A0];

    struct target_rt_sigframe *frame;

    sigset_t set;

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

        goto badframe;

    }

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

    sigprocmask(SIG_SETMASK, &set, NULL);

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

        goto badframe;

    }

    if (do_sigaltstack(frame_addr + offsetof(struct target_rt_sigframe,

                                             uc.tuc_stack),

                       0, env->ir[IR_SP]) == -EFAULT) {

        goto badframe;

    }

    unlock_user_struct(frame, frame_addr, 0);

    return env->ir[IR_V0];

 badframe:

    unlock_user_struct(frame, frame_addr, 0);

    force_sig(TARGET_SIGSEGV);

}


static int tcx_init1(SysBusDevice *dev)

{

    TCXState *s = FROM_SYSBUS(TCXState, dev);

    ram_addr_t vram_offset = 0;

    int size;

    uint8_t *vram_base;

    memory_region_init_ram(&s->vram_mem, "tcx.vram",

                           s->vram_size * (1 + 4 + 4));

    vmstate_register_ram_global(&s->vram_mem);

    vram_base = memory_region_get_ram_ptr(&s->vram_mem);

    /* 8-bit plane */

    s->vram = vram_base;

    size = s->vram_size;

    memory_region_init_alias(&s->vram_8bit, "tcx.vram.8bit",

                             &s->vram_mem, vram_offset, size);

    sysbus_init_mmio(dev, &s->vram_8bit);

    vram_offset += size;

    vram_base += size;

    /* DAC */

    memory_region_init_io(&s->dac, &tcx_dac_ops, s, "tcx.dac", TCX_DAC_NREGS);

    sysbus_init_mmio(dev, &s->dac);

    /* TEC (dummy) */

    memory_region_init_io(&s->tec, &dummy_ops, s, "tcx.tec", TCX_TEC_NREGS);

    sysbus_init_mmio(dev, &s->tec);

    /* THC: NetBSD writes here even with 8-bit display: dummy */

    memory_region_init_io(&s->thc24, &dummy_ops, s, "tcx.thc24",

                          TCX_THC_NREGS_24);

    sysbus_init_mmio(dev, &s->thc24);

    if (s->depth == 24) {

        /* 24-bit plane */

        size = s->vram_size * 4;

        s->vram24 = (uint32_t *)vram_base;

        s->vram24_offset = vram_offset;

        memory_region_init_alias(&s->vram_24bit, "tcx.vram.24bit",

                                 &s->vram_mem, vram_offset, size);

        sysbus_init_mmio(dev, &s->vram_24bit);

        vram_offset += size;

        vram_base += size;

        /* Control plane */

        size = s->vram_size * 4;

        s->cplane = (uint32_t *)vram_base;

        s->cplane_offset = vram_offset;

        memory_region_init_alias(&s->vram_cplane, "tcx.vram.cplane",

                                 &s->vram_mem, vram_offset, size);

        sysbus_init_mmio(dev, &s->vram_cplane);

        s->con = graphic_console_init(tcx24_update_display,

                                      tcx24_invalidate_display,

                                      tcx24_screen_dump, NULL, s);

    } else {

        /* THC 8 bit (dummy) */

        memory_region_init_io(&s->thc8, &dummy_ops, s, "tcx.thc8",

                              TCX_THC_NREGS_8);

        sysbus_init_mmio(dev, &s->thc8);

        s->con = graphic_console_init(tcx_update_display,

                                      tcx_invalidate_display,

                                      tcx_screen_dump, NULL, s);

    }

    qemu_console_resize(s->con, s->width, s->height);

    return 0;

}


static QObject *qmp_input_get_object(QmpInputVisitor *qiv,

                                     const char *name,

                                     bool consume)

{

    StackObject *tos;

    QObject *qobj;

    QObject *ret;

    if (!qiv->nb_stack) {

        /* Starting at root, name is ignored. */

        return qiv->root;

    }

    /* We are in a container; find the next element. */

    tos = &qiv->stack[qiv->nb_stack - 1];

    qobj = tos->obj;

    assert(qobj);

    if (qobject_type(qobj) == QTYPE_QDICT) {

        assert(name);

        ret = qdict_get(qobject_to_qdict(qobj), name);

        if (tos->h && consume && ret) {

            bool removed = g_hash_table_remove(tos->h, name);

            assert(removed);

        }

    } else {

        assert(qobject_type(qobj) == QTYPE_QLIST);

        assert(!name);

        ret = qlist_entry_obj(tos->entry);

        if (consume) {

            tos->entry = qlist_next(tos->entry);

        }

    }

    return ret;

}


int qemu_add_polling_cb(PollingFunc *func, void *opaque)

{

    PollingEntry **ppe, *pe;

    pe = g_malloc0(sizeof(PollingEntry));

    pe->func = func;

    pe->opaque = opaque;

    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);

    *ppe = pe;

    return 0;

}


static void xtensa_ml605_init(MachineState *machine)

{

    static const LxBoardDesc ml605_board = {

        .flash_base = 0xf8000000,

        .flash_size = 0x01000000,

        .flash_sector_size = 0x20000,

        .sram_size = 0x2000000,

    };

    lx_init(&ml605_board, machine);

}


START_TEST(qstring_from_str_test)

{

    QString *qstring;

    const char *str = "QEMU";

    qstring = qstring_from_str(str);

    fail_unless(qstring != NULL);

    fail_unless(qstring->base.refcnt == 1);

    fail_unless(strcmp(str, qstring->string) == 0);

    fail_unless(qobject_type(QOBJECT(qstring)) == QTYPE_QSTRING);

    // destroy doesn't exit yet

    g_free(qstring->string);

    g_free(qstring);

}


static void virtio_vga_realize(VirtIOPCIProxy *vpci_dev, Error **errp)

{

    VirtIOVGA *vvga = VIRTIO_VGA(vpci_dev);

    VirtIOGPU *g = &vvga->vdev;

    VGACommonState *vga = &vvga->vga;

    Error *err = NULL;

    uint32_t offset;

    int i;

    /* init vga compat bits */

    vga->vram_size_mb = 8;

    vga_common_init(vga, OBJECT(vpci_dev), false);

    vga_init(vga, OBJECT(vpci_dev), pci_address_space(&vpci_dev->pci_dev),

             pci_address_space_io(&vpci_dev->pci_dev), true);

    pci_register_bar(&vpci_dev->pci_dev, 0,

                     PCI_BASE_ADDRESS_MEM_PREFETCH, &vga->vram);

    /*

     * Configure virtio bar and regions

     *

     * We use bar #2 for the mmio regions, to be compatible with stdvga.

     * virtio regions are moved to the end of bar #2, to make room for

     * the stdvga mmio registers at the start of bar #2.

     */

    vpci_dev->modern_mem_bar = 2;

    vpci_dev->msix_bar = 4;

    offset = memory_region_size(&vpci_dev->modern_bar);

    offset -= vpci_dev->notify.size;

    vpci_dev->notify.offset = offset;

    offset -= vpci_dev->device.size;

    vpci_dev->device.offset = offset;

    offset -= vpci_dev->isr.size;

    vpci_dev->isr.offset = offset;

    offset -= vpci_dev->common.size;

    vpci_dev->common.offset = offset;

    /* init virtio bits */

    qdev_set_parent_bus(DEVICE(g), BUS(&vpci_dev->bus));

    /* force virtio-1.0 */

    vpci_dev->flags &= ~VIRTIO_PCI_FLAG_DISABLE_MODERN;

    vpci_dev->flags |= VIRTIO_PCI_FLAG_DISABLE_LEGACY;

    object_property_set_bool(OBJECT(g), true, "realized", &err);

    if (err) {

        error_propagate(errp, err);

        return;

    }

    /* add stdvga mmio regions */

    pci_std_vga_mmio_region_init(vga, &vpci_dev->modern_bar,

                                 vvga->vga_mrs, true);

    vga->con = g->scanout[0].con;

    graphic_console_set_hwops(vga->con, &virtio_vga_ops, vvga);

    for (i = 0; i < g->conf.max_outputs; i++) {

        object_property_set_link(OBJECT(g->scanout[i].con),

                                 OBJECT(vpci_dev),

                                 "device", errp);

    }

}


static int virtio_read_many(ulong sector, void *load_addr, int sec_num)

{

    struct virtio_blk_outhdr out_hdr;

    u8 status;

    /* Tell the host we want to read */

    out_hdr.type = VIRTIO_BLK_T_IN;

    out_hdr.ioprio = 99;

    out_hdr.sector = sector;

    vring_send_buf(&block, &out_hdr, sizeof(out_hdr), VRING_DESC_F_NEXT);

    /* This is where we want to receive data */

    vring_send_buf(&block, load_addr, SECTOR_SIZE * sec_num,

                   VRING_DESC_F_WRITE | VRING_HIDDEN_IS_CHAIN |

                   VRING_DESC_F_NEXT);

    /* status field */

    vring_send_buf(&block, &status, sizeof(u8), VRING_DESC_F_WRITE |

                   VRING_HIDDEN_IS_CHAIN);

    /* Now we can tell the host to read */

    vring_wait_reply(&block, 0);

    drain_irqs(block.schid);

    return status;

}


static int filter_frame(AVFilterLink *link, AVFrame *in)

{

    AVFilterContext *ctx = link->dst;

    AVFilterLink *outlink = ctx->outputs[0];

    ColorSpaceContext *s = ctx->priv;

    // FIXME if yuv2yuv_passthrough, don't get a new buffer but use the

    // input one if it is writable *OR* the actual literal values of in_*

    // and out_* are identical (not just their respective properties)

    AVFrame *out = ff_get_video_buffer(outlink, outlink->w, outlink->h);

    int res;

    ptrdiff_t rgb_stride = FFALIGN(in->width * sizeof(int16_t), 32);

    unsigned rgb_sz = rgb_stride * in->height;

    struct ThreadData td;

    if (!out) {

        av_frame_free(&in);

        return AVERROR(ENOMEM);

    }

    av_frame_copy_props(out, in);

    out->color_primaries = s->user_prm == AVCOL_PRI_UNSPECIFIED ?

                           default_prm[FFMIN(s->user_all, CS_NB)] : s->user_prm;

    if (s->user_trc == AVCOL_TRC_UNSPECIFIED) {

        const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(out->format);

        out->color_trc   = default_trc[FFMIN(s->user_all, CS_NB)];

        if (out->color_trc == AVCOL_TRC_BT2020_10 && desc && desc->comp[0].depth >= 12)

            out->color_trc = AVCOL_TRC_BT2020_12;

    } else {

        out->color_trc   = s->user_trc;

    }

    out->colorspace      = s->user_csp == AVCOL_SPC_UNSPECIFIED ?

                           default_csp[FFMIN(s->user_all, CS_NB)] : s->user_csp;

    out->color_range     = s->user_rng == AVCOL_RANGE_UNSPECIFIED ?

                           in->color_range : s->user_rng;

    if (rgb_sz != s->rgb_sz) {

        const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(out->format);

        int uvw = in->width >> desc->log2_chroma_w;

        av_freep(&s->rgb[0]);

        av_freep(&s->rgb[1]);

        av_freep(&s->rgb[2]);

        s->rgb_sz = 0;

        av_freep(&s->dither_scratch_base[0][0]);

        av_freep(&s->dither_scratch_base[0][1]);

        av_freep(&s->dither_scratch_base[1][0]);

        av_freep(&s->dither_scratch_base[1][1]);

        av_freep(&s->dither_scratch_base[2][0]);

        av_freep(&s->dither_scratch_base[2][1]);

        s->rgb[0] = av_malloc(rgb_sz);

        s->rgb[1] = av_malloc(rgb_sz);

        s->rgb[2] = av_malloc(rgb_sz);

        s->dither_scratch_base[0][0] =

            av_malloc(sizeof(*s->dither_scratch_base[0][0]) * (in->width + 4));

        s->dither_scratch_base[0][1] =

            av_malloc(sizeof(*s->dither_scratch_base[0][1]) * (in->width + 4));

        s->dither_scratch_base[1][0] =

            av_malloc(sizeof(*s->dither_scratch_base[1][0]) * (uvw + 4));

        s->dither_scratch_base[1][1] =

            av_malloc(sizeof(*s->dither_scratch_base[1][1]) * (uvw + 4));

        s->dither_scratch_base[2][0] =

            av_malloc(sizeof(*s->dither_scratch_base[2][0]) * (uvw + 4));

        s->dither_scratch_base[2][1] =

            av_malloc(sizeof(*s->dither_scratch_base[2][1]) * (uvw + 4));

        s->dither_scratch[0][0] = &s->dither_scratch_base[0][0][1];

        s->dither_scratch[0][1] = &s->dither_scratch_base[0][1][1];

        s->dither_scratch[1][0] = &s->dither_scratch_base[1][0][1];

        s->dither_scratch[1][1] = &s->dither_scratch_base[1][1][1];

        s->dither_scratch[2][0] = &s->dither_scratch_base[2][0][1];

        s->dither_scratch[2][1] = &s->dither_scratch_base[2][1][1];

        if (!s->rgb[0] || !s->rgb[1] || !s->rgb[2] ||

            !s->dither_scratch_base[0][0] || !s->dither_scratch_base[0][1] ||

            !s->dither_scratch_base[1][0] || !s->dither_scratch_base[1][1] ||

            !s->dither_scratch_base[2][0] || !s->dither_scratch_base[2][1]) {

            uninit(ctx);

            return AVERROR(ENOMEM);

        }

        s->rgb_sz = rgb_sz;

    }

    res = create_filtergraph(ctx, in, out);

    if (res < 0)

        return res;

    s->rgb_stride = rgb_stride / sizeof(int16_t);

    td.in = in;

    td.out = out;

    td.in_linesize[0] = in->linesize[0];

    td.in_linesize[1] = in->linesize[1];

    td.in_linesize[2] = in->linesize[2];

    td.out_linesize[0] = out->linesize[0];

    td.out_linesize[1] = out->linesize[1];

    td.out_linesize[2] = out->linesize[2];

    td.in_ss_h = av_pix_fmt_desc_get(in->format)->log2_chroma_h;

    td.out_ss_h = av_pix_fmt_desc_get(out->format)->log2_chroma_h;

    if (s->yuv2yuv_passthrough) {

        res = av_frame_copy(out, in);

        if (res < 0)

            return res;

    } else {

        ctx->internal->execute(ctx, convert, &td, NULL,

                               FFMIN((in->height + 1) >> 1, ctx->graph->nb_threads));

    }

    av_frame_free(&in);

    return ff_filter_frame(outlink, out);

}


static void do_subtitle_out(AVFormatContext *s,

                            OutputStream *ost,

                            InputStream *ist,

                            AVSubtitle *sub,

                            int64_t pts)

{

    static uint8_t *subtitle_out = NULL;

    int subtitle_out_max_size = 1024 * 1024;

    int subtitle_out_size, nb, i;

    AVCodecContext *enc;

    AVPacket pkt;

    if (pts == AV_NOPTS_VALUE) {

        av_log(NULL, AV_LOG_ERROR, "Subtitle packets must have a pts\n");

        if (exit_on_error)

            exit_program(1);

        return;

    }

    enc = ost->enc_ctx;

    if (!subtitle_out) {

        subtitle_out = av_malloc(subtitle_out_max_size);

    }

    /* Note: DVB subtitle need one packet to draw them and one other

       packet to clear them */

    /* XXX: signal it in the codec context ? */

    if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE)

        nb = 2;

    else

        nb = 1;

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

        ost->sync_opts = av_rescale_q(pts, ist->st->time_base, enc->time_base);

        if (!check_recording_time(ost))

            return;

        sub->pts = av_rescale_q(pts, ist->st->time_base, AV_TIME_BASE_Q);

        // start_display_time is required to be 0

        sub->pts               += av_rescale_q(sub->start_display_time, (AVRational){ 1, 1000 }, AV_TIME_BASE_Q);

        sub->end_display_time  -= sub->start_display_time;

        sub->start_display_time = 0;

        ost->frames_encoded++;

        subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,

                                                    subtitle_out_max_size, sub);

        if (subtitle_out_size < 0) {

            av_log(NULL, AV_LOG_FATAL, "Subtitle encoding failed\n");

            exit_program(1);

        }

        av_init_packet(&pkt);

        pkt.data = subtitle_out;

        pkt.size = subtitle_out_size;

        pkt.pts  = av_rescale_q(sub->pts, AV_TIME_BASE_Q, ost->st->time_base);

        if (enc->codec_id == AV_CODEC_ID_DVB_SUBTITLE) {

            /* XXX: the pts correction is handled here. Maybe handling

               it in the codec would be better */

            if (i == 0)

                pkt.pts += 90 * sub->start_display_time;

            else

                pkt.pts += 90 * sub->end_display_time;

        }

        output_packet(s, &pkt, ost);

    }

}


static inline void RENAME(yuy2toyv12)(const uint8_t *src, uint8_t *ydst, uint8_t *udst, uint8_t *vdst,

	long width, long height,

	long lumStride, long chromStride, long srcStride)

{

	long y;

	const long chromWidth= width>>1;

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

	{

#ifdef HAVE_MMX

		asm volatile(

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

			"pcmpeqw %%mm7, %%mm7		\n\t"

			"psrlw $8, %%mm7		\n\t" // FF,00,FF,00...

			ASMALIGN(4)

			"1:				\n\t"

			PREFETCH" 64(%0, %%"REG_a", 4)	\n\t"

			"movq (%0, %%"REG_a", 4), %%mm0	\n\t" // YUYV YUYV(0)

			"movq 8(%0, %%"REG_a", 4), %%mm1\n\t" // YUYV YUYV(4)

			"movq %%mm0, %%mm2		\n\t" // YUYV YUYV(0)

			"movq %%mm1, %%mm3		\n\t" // YUYV YUYV(4)

			"psrlw $8, %%mm0		\n\t" // U0V0 U0V0(0)

			"psrlw $8, %%mm1		\n\t" // U0V0 U0V0(4)

			"pand %%mm7, %%mm2		\n\t" // Y0Y0 Y0Y0(0)

			"pand %%mm7, %%mm3		\n\t" // Y0Y0 Y0Y0(4)

			"packuswb %%mm1, %%mm0		\n\t" // UVUV UVUV(0)

			"packuswb %%mm3, %%mm2		\n\t" // YYYY YYYY(0)

			MOVNTQ" %%mm2, (%1, %%"REG_a", 2)\n\t"

			"movq 16(%0, %%"REG_a", 4), %%mm1\n\t" // YUYV YUYV(8)

			"movq 24(%0, %%"REG_a", 4), %%mm2\n\t" // YUYV YUYV(12)

			"movq %%mm1, %%mm3		\n\t" // YUYV YUYV(8)

			"movq %%mm2, %%mm4		\n\t" // YUYV YUYV(12)

			"psrlw $8, %%mm1		\n\t" // U0V0 U0V0(8)

			"psrlw $8, %%mm2		\n\t" // U0V0 U0V0(12)

			"pand %%mm7, %%mm3		\n\t" // Y0Y0 Y0Y0(8)

			"pand %%mm7, %%mm4		\n\t" // Y0Y0 Y0Y0(12)

			"packuswb %%mm2, %%mm1		\n\t" // UVUV UVUV(8)

			"packuswb %%mm4, %%mm3		\n\t" // YYYY YYYY(8)

			MOVNTQ" %%mm3, 8(%1, %%"REG_a", 2)\n\t"

			"movq %%mm0, %%mm2		\n\t" // UVUV UVUV(0)

			"movq %%mm1, %%mm3		\n\t" // UVUV UVUV(8)

			"psrlw $8, %%mm0		\n\t" // V0V0 V0V0(0)

			"psrlw $8, %%mm1		\n\t" // V0V0 V0V0(8)

			"pand %%mm7, %%mm2		\n\t" // U0U0 U0U0(0)

			"pand %%mm7, %%mm3		\n\t" // U0U0 U0U0(8)

			"packuswb %%mm1, %%mm0		\n\t" // VVVV VVVV(0)

			"packuswb %%mm3, %%mm2		\n\t" // UUUU UUUU(0)

			MOVNTQ" %%mm0, (%3, %%"REG_a")	\n\t"

			MOVNTQ" %%mm2, (%2, %%"REG_a")	\n\t"

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

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

			" jb 1b				\n\t"

			::"r"(src), "r"(ydst), "r"(udst), "r"(vdst), "g" (chromWidth)

			: "memory", "%"REG_a

		);

		ydst += lumStride;

		src  += srcStride;

		asm volatile(

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

			ASMALIGN(4)

			"1:				\n\t"

			PREFETCH" 64(%0, %%"REG_a", 4)	\n\t"

			"movq (%0, %%"REG_a", 4), %%mm0	\n\t" // YUYV YUYV(0)

			"movq 8(%0, %%"REG_a", 4), %%mm1\n\t" // YUYV YUYV(4)

			"movq 16(%0, %%"REG_a", 4), %%mm2\n\t" // YUYV YUYV(8)

			"movq 24(%0, %%"REG_a", 4), %%mm3\n\t" // YUYV YUYV(12)

			"pand %%mm7, %%mm0		\n\t" // Y0Y0 Y0Y0(0)

			"pand %%mm7, %%mm1		\n\t" // Y0Y0 Y0Y0(4)

			"pand %%mm7, %%mm2		\n\t" // Y0Y0 Y0Y0(8)

			"pand %%mm7, %%mm3		\n\t" // Y0Y0 Y0Y0(12)

			"packuswb %%mm1, %%mm0		\n\t" // YYYY YYYY(0)

			"packuswb %%mm3, %%mm2		\n\t" // YYYY YYYY(8)

			MOVNTQ" %%mm0, (%1, %%"REG_a", 2)\n\t"

			MOVNTQ" %%mm2, 8(%1, %%"REG_a", 2)\n\t"

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

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

			" jb 1b				\n\t"

			::"r"(src), "r"(ydst), "r"(udst), "r"(vdst), "g" (chromWidth)

			: "memory", "%"REG_a

		);

#else

		long i;

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

		{

			ydst[2*i+0] 	= src[4*i+0];

			udst[i] 	= src[4*i+1];

			ydst[2*i+1] 	= src[4*i+2];

			vdst[i] 	= src[4*i+3];

		}

		ydst += lumStride;

		src  += srcStride;

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

		{

			ydst[2*i+0] 	= src[4*i+0];

			ydst[2*i+1] 	= src[4*i+2];

		}

#endif

		udst += chromStride;

		vdst += chromStride;

		ydst += lumStride;

		src  += srcStride;

	}

#ifdef HAVE_MMX

asm volatile(   EMMS" \n\t"

        	SFENCE" \n\t"

        	:::"memory");

#endif

}


static void tcx_update_display(void *opaque)

{

    TCXState *ts = opaque;

    ram_addr_t page, page_min, page_max;

    int y, y_start, dd, ds;

    uint8_t *d, *s;

    void (*f)(TCXState *s1, uint8_t *dst, const uint8_t *src, int width);

    if (ts->ds->depth == 0)

        return;

    page = ts->vram_offset;

    y_start = -1;

    page_min = 0xffffffff;

    page_max = 0;

    d = ts->ds->data;

    s = ts->vram;

    dd = ts->ds->linesize;

    ds = 1024;

    switch (ts->ds->depth) {

    case 32:

        f = tcx_draw_line32;

        break;

    case 15:

    case 16:

        f = tcx_draw_line16;

        break;

    default:

    case 8:

        f = tcx_draw_line8;

        break;

    case 0:

        return;

    }

    for(y = 0; y < ts->height; y += 4, page += TARGET_PAGE_SIZE) {

        if (cpu_physical_memory_get_dirty(page, VGA_DIRTY_FLAG)) {

            if (y_start < 0)

                y_start = y;

            if (page < page_min)

                page_min = page;

            if (page > page_max)

                page_max = page;

            f(ts, d, s, ts->width);

            d += dd;

            s += ds;

            f(ts, d, s, ts->width);

            d += dd;

            s += ds;

            f(ts, d, s, ts->width);

            d += dd;

            s += ds;

            f(ts, d, s, ts->width);

            d += dd;

            s += ds;

        } else {

            if (y_start >= 0) {

                /* flush to display */

                dpy_update(ts->ds, 0, y_start,

                           ts->width, y - y_start);

                y_start = -1;

            }

            d += dd * 4;

            s += ds * 4;

        }

    }

    if (y_start >= 0) {

        /* flush to display */

        dpy_update(ts->ds, 0, y_start,

                   ts->width, y - y_start);

    }

    /* reset modified pages */

    if (page_min <= page_max) {

        cpu_physical_memory_reset_dirty(page_min, page_max + TARGET_PAGE_SIZE,

                                        VGA_DIRTY_FLAG);

    }

}


static int bamboo_load_device_tree(hwaddr addr,

                                     uint32_t ramsize,

                                     hwaddr initrd_base,

                                     hwaddr initrd_size,

                                     const char *kernel_cmdline)

{

    int ret = -1;

    uint32_t mem_reg_property[] = { 0, 0, cpu_to_be32(ramsize) };

    char *filename;

    int fdt_size;

    void *fdt;

    uint32_t tb_freq = 400000000;

    uint32_t clock_freq = 400000000;

    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, BINARY_DEVICE_TREE_FILE);

    if (!filename) {

        goto out;

    }

    fdt = load_device_tree(filename, &fdt_size);

    g_free(filename);

    if (fdt == NULL) {

        goto out;

    }

    /* Manipulate device tree in memory. */

    ret = qemu_devtree_setprop(fdt, "/memory", "reg", mem_reg_property,

                               sizeof(mem_reg_property));

    if (ret < 0)

        fprintf(stderr, "couldn't set /memory/reg\n");

    ret = qemu_devtree_setprop_cell(fdt, "/chosen", "linux,initrd-start",

                                    initrd_base);

    if (ret < 0)

        fprintf(stderr, "couldn't set /chosen/linux,initrd-start\n");

    ret = qemu_devtree_setprop_cell(fdt, "/chosen", "linux,initrd-end",

                                    (initrd_base + initrd_size));

    if (ret < 0)

        fprintf(stderr, "couldn't set /chosen/linux,initrd-end\n");

    ret = qemu_devtree_setprop_string(fdt, "/chosen", "bootargs",

                                      kernel_cmdline);

    if (ret < 0)

        fprintf(stderr, "couldn't set /chosen/bootargs\n");

    /* Copy data from the host device tree into the guest. Since the guest can

     * directly access the timebase without host involvement, we must expose

     * the correct frequencies. */

    if (kvm_enabled()) {

        tb_freq = kvmppc_get_tbfreq();

        clock_freq = kvmppc_get_clockfreq();

    }

    qemu_devtree_setprop_cell(fdt, "/cpus/cpu@0", "clock-frequency",

                              clock_freq);

    qemu_devtree_setprop_cell(fdt, "/cpus/cpu@0", "timebase-frequency",

                              tb_freq);

    ret = rom_add_blob_fixed(BINARY_DEVICE_TREE_FILE, fdt, fdt_size, addr);

    g_free(fdt);

out:

    return ret;

}


static int vp7_decode_frame_header(VP8Context *s, const uint8_t *buf, int buf_size)
{
    VP56RangeCoder *c = &s->c;
    int part1_size, hscale, vscale, i, j, ret;
    int width  = s->avctx->width;
    int height = s->avctx->height;
    s->profile   =  (buf[0]>>1) & 7;
    if (s->profile > 1) {
        avpriv_request_sample(s->avctx, "Unknown profile %d", s->profile);
    s->keyframe  = !(buf[0] & 1);
    s->invisible = 0;
    part1_size   = AV_RL24(buf) >> 4;
    buf      += 4 - s->profile;
    buf_size -= 4 - s->profile;
    memcpy(s->put_pixels_tab, s->vp8dsp.put_vp8_epel_pixels_tab, sizeof(s->put_pixels_tab));
    ff_vp56_init_range_decoder(c, buf, part1_size);
    buf      += part1_size;
    buf_size -= part1_size;
    /* A. Dimension information (keyframes only) */
    if (s->keyframe) {
        width  = vp8_rac_get_uint(c, 12);
        height = vp8_rac_get_uint(c, 12);
        hscale = vp8_rac_get_uint(c, 2);
        vscale = vp8_rac_get_uint(c, 2);
        if (hscale || vscale)
            avpriv_request_sample(s->avctx, "Upscaling");
        s->update_golden = s->update_altref = VP56_FRAME_CURRENT;
        vp78_reset_probability_tables(s);
        memcpy(s->prob->pred16x16, vp8_pred16x16_prob_inter, sizeof(s->prob->pred16x16));
        memcpy(s->prob->pred8x8c , vp8_pred8x8c_prob_inter , sizeof(s->prob->pred8x8c));
        for (i = 0; i < 2; i++)
            memcpy(s->prob->mvc[i], vp7_mv_default_prob[i], sizeof(vp7_mv_default_prob[i]));
        memset(&s->segmentation, 0, sizeof(s->segmentation));
        memset(&s->lf_delta, 0, sizeof(s->lf_delta));
        memcpy(s->prob[0].scan, zigzag_scan, sizeof(s->prob[0].scan));
    if (s->keyframe || s->profile > 0)
        memset(s->inter_dc_pred, 0 , sizeof(s->inter_dc_pred));
    /* B. Decoding information for all four macroblock-level features */
    for (i = 0; i < 4; i++) {
        s->feature_enabled[i] = vp8_rac_get(c);
        if (s->feature_enabled[i]) {
             s->feature_present_prob[i] = vp8_rac_get_uint(c, 8);
             for (j = 0; j < 3; j++)
                 s->feature_index_prob[i][j] = vp8_rac_get(c) ? vp8_rac_get_uint(c, 8) : 255;
             if (vp7_feature_value_size[i])
                 for (j = 0; j < 4; j++)
                     s->feature_value[i][j] = vp8_rac_get(c) ? vp8_rac_get_uint(c, vp7_feature_value_size[s->profile][i]) : 0;
    s->segmentation.enabled = 0;
    s->segmentation.update_map = 0;
    s->lf_delta.enabled = 0;
    s->num_coeff_partitions = 1;
    ff_vp56_init_range_decoder(&s->coeff_partition[0], buf, buf_size);
    if (!s->macroblocks_base || /* first frame */
        width != s->avctx->width || height != s->avctx->height || (width+15)/16 != s->mb_width || (height+15)/16 != s->mb_height) {
        if ((ret = update_dimensions(s, width, height)) < 0)
            return ret;
    /* C. Dequantization indices */
    vp7_get_quants(s);
    /* D. Golden frame update flag (a Flag) for interframes only */
    if (!s->keyframe) {
        s->update_golden = vp8_rac_get(c) ? VP56_FRAME_CURRENT : VP56_FRAME_NONE;
        s->sign_bias[VP56_FRAME_GOLDEN] = 0;
    s->update_last = 1;
    s->update_probabilities = 1;
    s->fade_present         = 1;
    if (s->profile > 0) {
        s->update_probabilities = vp8_rac_get(c);
        if (!s->update_probabilities)
            s->prob[1] = s->prob[0];
        if (!s->keyframe)
            s->fade_present = vp8_rac_get(c);
    /* E. Fading information for previous frame */
    if (s->fade_present && vp8_rac_get(c)) {
        int alpha = (int8_t)vp8_rac_get_uint(c, 8);
        int beta  = (int8_t)vp8_rac_get_uint(c, 8);
        if (!s->keyframe && (alpha || beta)) {
            /* preserve the golden frame */
            if (s->framep[VP56_FRAME_GOLDEN] == s->framep[VP56_FRAME_PREVIOUS]) {
                AVFrame *gold = s->framep[VP56_FRAME_GOLDEN]->tf.f;
                AVFrame *prev;
                int i, j;
                s->framep[VP56_FRAME_PREVIOUS] = vp8_find_free_buffer(s);
                if ((ret = vp8_alloc_frame(s, s->framep[VP56_FRAME_PREVIOUS], 1)) < 0)
                   return ret;
                prev = s->framep[VP56_FRAME_PREVIOUS]->tf.f;
                fade(prev->data[0], prev->linesize[0], gold->data[0], gold->linesize[0], s->mb_width * 16, s->mb_height * 16, alpha, beta);
                for (j = 1; j < 3; j++)
                    for (i = 0; i < s->mb_height * 8; i++)
                        memcpy(prev->data[j] + i * prev->linesize[j], gold->data[j] + i * gold->linesize[j], s->mb_width * 8);
            } else {
                AVFrame *prev = s->framep[VP56_FRAME_PREVIOUS]->tf.f;
                fade(prev->data[0], prev->linesize[0], prev->data[0], prev->linesize[0], s->mb_width * 16, s->mb_height * 16, alpha, beta);
    /* F. Loop filter type */
    if (!s->profile)
        s->filter.simple = vp8_rac_get(c);
    /* G. DCT coefficient ordering specification */
    if (vp8_rac_get(c))
        for (i = 1; i < 16; i++)
            s->prob[0].scan[i] = zigzag_scan[vp8_rac_get_uint(c, 4)];
    /* H. Loop filter levels  */
    if (s->profile > 0)
        s->filter.simple = vp8_rac_get(c);
    s->filter.level     = vp8_rac_get_uint(c, 6);
    s->filter.sharpness = vp8_rac_get_uint(c, 3);
    /* I. DCT coefficient probability update; 13.3 Token Probability Updates */
    vp78_update_probability_tables(s);
    s->mbskip_enabled = 0;
    /* J. The remaining frame header data occurs ONLY FOR INTERFRAMES */
    if (!s->keyframe) {
        s->prob->intra  = vp8_rac_get_uint(c, 8);
        s->prob->last   = vp8_rac_get_uint(c, 8);
        vp78_update_pred16x16_pred8x8_mvc_probabilities(s);
    return 0;


static void virtio_write_config(PCIDevice *pci_dev, uint32_t address,

                                uint32_t val, int len)

{

    pci_default_write_config(pci_dev, address, val, len);

    msix_write_config(pci_dev, address, val, len);

}


static av_cold int theora_decode_init(AVCodecContext *avctx)

{

    Vp3DecodeContext *s = avctx->priv_data;

    GetBitContext gb;

    int ptype;

    const uint8_t *header_start[3];

    int header_len[3];

    int i;

    avctx->pix_fmt = AV_PIX_FMT_YUV420P;

    s->theora = 1;

    if (!avctx->extradata_size) {

        av_log(avctx, AV_LOG_ERROR, "Missing extradata!\n");

        return -1;

    }

    if (avpriv_split_xiph_headers(avctx->extradata, avctx->extradata_size,

                                  42, header_start, header_len) < 0) {

        av_log(avctx, AV_LOG_ERROR, "Corrupt extradata\n");

        return -1;

    }

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

        if (header_len[i] <= 0)

            continue;

        init_get_bits8(&gb, header_start[i], header_len[i]);

        ptype = get_bits(&gb, 8);

        if (!(ptype & 0x80)) {

            av_log(avctx, AV_LOG_ERROR, "Invalid extradata!\n");

//          return -1;

        }

        // FIXME: Check for this as well.

        skip_bits_long(&gb, 6 * 8); /* "theora" */

        switch (ptype) {

        case 0x80:

            if (theora_decode_header(avctx, &gb) < 0)

                return -1;

            break;

        case 0x81:

// FIXME: is this needed? it breaks sometimes

//            theora_decode_comments(avctx, gb);

            break;

        case 0x82:

            if (theora_decode_tables(avctx, &gb))

                return -1;

            break;

        default:

            av_log(avctx, AV_LOG_ERROR,

                   "Unknown Theora config packet: %d\n", ptype & ~0x80);

            break;

        }

        if (ptype != 0x81 && 8 * header_len[i] != get_bits_count(&gb))

            av_log(avctx, AV_LOG_WARNING,

                   "%d bits left in packet %X\n",

                   8 * header_len[i] - get_bits_count(&gb), ptype);

        if (s->theora < 0x030200)

            break;

    }

    return vp3_decode_init(avctx);

}