static void filter_mb_fast( H264Context *h, int mb_x, int mb_y, uint8_t *img_y, uint8_t *img_cb, uint8_t *img_cr, unsigned int linesize, unsigned int uvlinesize) {

    MpegEncContext * const s = &h->s;

    int mb_y_firstrow = s->picture_structure == PICT_BOTTOM_FIELD;

    int mb_xy, mb_type;

    int qp, qp0, qp1, qpc, qpc0, qpc1, qp_thresh;

    mb_xy = h->mb_xy;

    if(mb_x==0 || mb_y==mb_y_firstrow || !s->dsp.h264_loop_filter_strength || h->pps.chroma_qp_diff ||

        !(s->flags2 & CODEC_FLAG2_FAST) || //FIXME filter_mb_fast is broken, thus hasto be, but should not under CODEC_FLAG2_FAST

       (h->deblocking_filter == 2 && (h->slice_table[mb_xy] != h->slice_table[h->top_mb_xy] ||

                                      h->slice_table[mb_xy] != h->slice_table[mb_xy - 1]))) {

        filter_mb(h, mb_x, mb_y, img_y, img_cb, img_cr, linesize, uvlinesize);

        return;

    }

    assert(!FRAME_MBAFF);

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

    qp = s->current_picture.qscale_table[mb_xy];

    qp0 = s->current_picture.qscale_table[mb_xy-1];

    qp1 = s->current_picture.qscale_table[h->top_mb_xy];

    qpc = get_chroma_qp( h, 0, qp );

    qpc0 = get_chroma_qp( h, 0, qp0 );

    qpc1 = get_chroma_qp( h, 0, qp1 );

    qp0 = (qp + qp0 + 1) >> 1;

    qp1 = (qp + qp1 + 1) >> 1;

    qpc0 = (qpc + qpc0 + 1) >> 1;

    qpc1 = (qpc + qpc1 + 1) >> 1;

    qp_thresh = 15 - h->slice_alpha_c0_offset;

    if(qp <= qp_thresh && qp0 <= qp_thresh && qp1 <= qp_thresh &&

       qpc <= qp_thresh && qpc0 <= qp_thresh && qpc1 <= qp_thresh)

        return;

    if( IS_INTRA(mb_type) ) {

        int16_t bS4[4] = {4,4,4,4};

        int16_t bS3[4] = {3,3,3,3};

        int16_t *bSH = FIELD_PICTURE ? bS3 : bS4;

        if( IS_8x8DCT(mb_type) ) {

            filter_mb_edgev( h, &img_y[4*0], linesize, bS4, qp0 );

            filter_mb_edgev( h, &img_y[4*2], linesize, bS3, qp );

            filter_mb_edgeh( h, &img_y[4*0*linesize], linesize, bSH, qp1 );

            filter_mb_edgeh( h, &img_y[4*2*linesize], linesize, bS3, qp );

        } else {

            filter_mb_edgev( h, &img_y[4*0], linesize, bS4, qp0 );

            filter_mb_edgev( h, &img_y[4*1], linesize, bS3, qp );

            filter_mb_edgev( h, &img_y[4*2], linesize, bS3, qp );

            filter_mb_edgev( h, &img_y[4*3], linesize, bS3, qp );

            filter_mb_edgeh( h, &img_y[4*0*linesize], linesize, bSH, qp1 );

            filter_mb_edgeh( h, &img_y[4*1*linesize], linesize, bS3, qp );

            filter_mb_edgeh( h, &img_y[4*2*linesize], linesize, bS3, qp );

            filter_mb_edgeh( h, &img_y[4*3*linesize], linesize, bS3, qp );

        }

        filter_mb_edgecv( h, &img_cb[2*0], uvlinesize, bS4, qpc0 );

        filter_mb_edgecv( h, &img_cb[2*2], uvlinesize, bS3, qpc );

        filter_mb_edgecv( h, &img_cr[2*0], uvlinesize, bS4, qpc0 );

        filter_mb_edgecv( h, &img_cr[2*2], uvlinesize, bS3, qpc );

        filter_mb_edgech( h, &img_cb[2*0*uvlinesize], uvlinesize, bSH, qpc1 );

        filter_mb_edgech( h, &img_cb[2*2*uvlinesize], uvlinesize, bS3, qpc );

        filter_mb_edgech( h, &img_cr[2*0*uvlinesize], uvlinesize, bSH, qpc1 );

        filter_mb_edgech( h, &img_cr[2*2*uvlinesize], uvlinesize, bS3, qpc );

        return;

    } else {

        DECLARE_ALIGNED_8(int16_t, bS[2][4][4]);

        uint64_t (*bSv)[4] = (uint64_t(*)[4])bS;

        int edges;

        if( IS_8x8DCT(mb_type) && (h->cbp&7) == 7 ) {

            edges = 4;

            bSv[0][0] = bSv[0][2] = bSv[1][0] = bSv[1][2] = 0x0002000200020002ULL;

        } else {

            int mask_edge1 = (mb_type & (MB_TYPE_16x16 | MB_TYPE_8x16)) ? 3 :

                             (mb_type & MB_TYPE_16x8) ? 1 : 0;

            int mask_edge0 = (mb_type & (MB_TYPE_16x16 | MB_TYPE_8x16))

                             && (s->current_picture.mb_type[mb_xy-1] & (MB_TYPE_16x16 | MB_TYPE_8x16))

                             ? 3 : 0;

            int step = IS_8x8DCT(mb_type) ? 2 : 1;

            edges = (mb_type & MB_TYPE_16x16) && !(h->cbp & 15) ? 1 : 4;

            s->dsp.h264_loop_filter_strength( bS, h->non_zero_count_cache, h->ref_cache, h->mv_cache,

                                              (h->slice_type_nos == FF_B_TYPE), edges, step, mask_edge0, mask_edge1, FIELD_PICTURE);

        }

        if( IS_INTRA(s->current_picture.mb_type[mb_xy-1]) )

            bSv[0][0] = 0x0004000400040004ULL;

        if( IS_INTRA(s->current_picture.mb_type[h->top_mb_xy]) )

            bSv[1][0] = FIELD_PICTURE ? 0x0003000300030003ULL : 0x0004000400040004ULL;

#define FILTER(hv,dir,edge)\

        if(bSv[dir][edge]) {\

            filter_mb_edge##hv( h, &img_y[4*edge*(dir?linesize:1)], linesize, bS[dir][edge], edge ? qp : qp##dir );\

            if(!(edge&1)) {\

                filter_mb_edgec##hv( h, &img_cb[2*edge*(dir?uvlinesize:1)], uvlinesize, bS[dir][edge], edge ? qpc : qpc##dir );\

                filter_mb_edgec##hv( h, &img_cr[2*edge*(dir?uvlinesize:1)], uvlinesize, bS[dir][edge], edge ? qpc : qpc##dir );\

            }\

        }

        if( edges == 1 ) {

            FILTER(v,0,0);

            FILTER(h,1,0);

        } else if( IS_8x8DCT(mb_type) ) {

            FILTER(v,0,0);

            FILTER(v,0,2);

            FILTER(h,1,0);

            FILTER(h,1,2);

        } else {

            FILTER(v,0,0);

            FILTER(v,0,1);

            FILTER(v,0,2);

            FILTER(v,0,3);

            FILTER(h,1,0);

            FILTER(h,1,1);

            FILTER(h,1,2);

            FILTER(h,1,3);

        }

#undef FILTER

    }

}


static int read_ffserver_streams(OptionsContext *o, AVFormatContext *s, const char *filename)

{

    int i, err;

    AVFormatContext *ic = avformat_alloc_context();

    ic->interrupt_callback = int_cb;

    err = avformat_open_input(&ic, filename, NULL, NULL);

    if (err < 0)

        return err;

    /* copy stream format */

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

        AVStream *st;

        OutputStream *ost;

        AVCodec *codec;

        const char *enc_config;

        codec = avcodec_find_encoder(ic->streams[i]->codecpar->codec_id);

        if (!codec) {

            av_log(s, AV_LOG_ERROR, "no encoder found for codec id %i\n", ic->streams[i]->codecpar->codec_id);

            return AVERROR(EINVAL);

        }

        if (codec->type == AVMEDIA_TYPE_AUDIO)

            opt_audio_codec(o, "c:a", codec->name);

        else if (codec->type == AVMEDIA_TYPE_VIDEO)

            opt_video_codec(o, "c:v", codec->name);

        ost   = new_output_stream(o, s, codec->type, -1);

        st    = ost->st;

        avcodec_get_context_defaults3(st->codec, codec);

        enc_config = av_stream_get_recommended_encoder_configuration(ic->streams[i]);

        if (enc_config) {

            AVDictionary *opts = NULL;

            av_dict_parse_string(&opts, enc_config, "=", ",", 0);

            av_opt_set_dict2(st->codec, &opts, AV_OPT_SEARCH_CHILDREN);

            av_dict_free(&opts);

        }

        if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && !ost->stream_copy)

            choose_sample_fmt(st, codec);

        else if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && !ost->stream_copy)

            choose_pixel_fmt(st, st->codec, codec, st->codecpar->format);

        avcodec_copy_context(ost->enc_ctx, st->codec);

        if (enc_config)

            av_dict_parse_string(&ost->encoder_opts, enc_config, "=", ",", 0);

    }

    avformat_close_input(&ic);

    return err;

}


VirtIODevice *virtio_balloon_init(DeviceState *dev)

{

    VirtIOBalloon *s;

    s = (VirtIOBalloon *)virtio_common_init("virtio-balloon",

                                            VIRTIO_ID_BALLOON,

                                            8, sizeof(VirtIOBalloon));

    s->vdev.get_config = virtio_balloon_get_config;

    s->vdev.set_config = virtio_balloon_set_config;

    s->vdev.get_features = virtio_balloon_get_features;

    s->ivq = virtio_add_queue(&s->vdev, 128, virtio_balloon_handle_output);

    s->dvq = virtio_add_queue(&s->vdev, 128, virtio_balloon_handle_output);

    s->svq = virtio_add_queue(&s->vdev, 128, virtio_balloon_receive_stats);

    reset_stats(s);

    qemu_add_balloon_handler(virtio_balloon_to_target, s);

    register_savevm(dev, "virtio-balloon", -1, 1,

                    virtio_balloon_save, virtio_balloon_load, s);

    return &s->vdev;

}


static int decode_audio(InputStream *ist, AVPacket *pkt, int *got_output)

{

    AVFrame *decoded_frame, *f;

    AVCodecContext *avctx = ist->dec_ctx;

    int i, ret, err = 0;

    if (!ist->decoded_frame && !(ist->decoded_frame = av_frame_alloc()))

        return AVERROR(ENOMEM);

    if (!ist->filter_frame && !(ist->filter_frame = av_frame_alloc()))

        return AVERROR(ENOMEM);

    decoded_frame = ist->decoded_frame;

    ret = decode(avctx, decoded_frame, got_output, pkt);

    if (!*got_output || ret < 0)

        return ret;

    ist->samples_decoded += decoded_frame->nb_samples;

    ist->frames_decoded++;

    /* if the decoder provides a pts, use it instead of the last packet pts.

       the decoder could be delaying output by a packet or more. */

    if (decoded_frame->pts != AV_NOPTS_VALUE)

        ist->next_dts = decoded_frame->pts;

    else if (pkt && pkt->pts != AV_NOPTS_VALUE) {

        decoded_frame->pts = pkt->pts;

    }

    if (decoded_frame->pts != AV_NOPTS_VALUE)

        decoded_frame->pts = av_rescale_q(decoded_frame->pts,

                                          ist->st->time_base,

                                          (AVRational){1, avctx->sample_rate});

    ist->nb_samples = decoded_frame->nb_samples;

    for (i = 0; i < ist->nb_filters; i++) {

        if (i < ist->nb_filters - 1) {

            f = ist->filter_frame;

            err = av_frame_ref(f, decoded_frame);

            if (err < 0)

                break;

        } else

            f = decoded_frame;

        err = ifilter_send_frame(ist->filters[i], f);

        if (err < 0)

            break;

    }

    av_frame_unref(ist->filter_frame);

    av_frame_unref(decoded_frame);

    return err < 0 ? err : ret;

}


static void test_port(int port)

{

    struct qhc uhci;

    g_assert(port > 0);

    qusb_pci_init_one(qs->pcibus, &uhci, QPCI_DEVFN(0x1d, 0), 4);

    uhci_port_test(&uhci, port - 1, UHCI_PORT_CCS);

}


rgb16_32ToUV_c_template(uint8_t *dstU, uint8_t *dstV,

                        const uint8_t *src, int width,

                        enum PixelFormat origin,

                        int shr,   int shg,   int shb, int shp,

                        int maskr, int maskg, int maskb,

                        int rsh,   int gsh,   int bsh, int S)

{

    const int ru = RU << rsh, gu = GU << gsh, bu = BU << bsh,

              rv = RV << rsh, gv = GV << gsh, bv = BV << bsh,

              rnd = 257 << (S - 1);

    int i;

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

        int px = input_pixel(i) >> shp;

        int b = (px & maskb) >> shb;

        int g = (px & maskg) >> shg;

        int r = (px & maskr) >> shr;

        dstU[i] = (ru * r + gu * g + bu * b + rnd) >> S;

        dstV[i] = (rv * r + gv * g + bv * b + rnd) >> S;

    }

}


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

{

    Error *err = NULL;

    qmp_block_set_io_throttle(qdict_get_str(qdict, "device"),

                              qdict_get_int(qdict, "bps"),

                              qdict_get_int(qdict, "bps_rd"),

                              qdict_get_int(qdict, "bps_wr"),

                              qdict_get_int(qdict, "iops"),

                              qdict_get_int(qdict, "iops_rd"),

                              qdict_get_int(qdict, "iops_wr"), &err);

    hmp_handle_error(mon, &err);

}


void qemu_system_shutdown_request(void)

{

    trace_qemu_system_shutdown_request();

    replay_shutdown_request();

    shutdown_requested = 1;

    qemu_notify_event();

}


size_t mptsas_config_ioc_0(MPTSASState *s, uint8_t **data, int address)

{

    PCIDeviceClass *pcic = PCI_DEVICE_GET_CLASS(s);

    return MPTSAS_CONFIG_PACK(0, MPI_CONFIG_PAGETYPE_IOC, 0x01,

                              "*l*lwwb*b*b*blww",

                              pcic->vendor_id, pcic->device_id, pcic->revision,

                              pcic->subsystem_vendor_id,

                              pcic->subsystem_id);

}


static uint32_t sh_serial_ioport_read(void *opaque, uint32_t offs)

{

    sh_serial_state *s = opaque;

    uint32_t ret = ~0;

#if 0

    switch(offs) {

    case 0x00:

        ret = s->smr;

        break;

    case 0x04:

        ret = s->brr;

	break;

    case 0x08:

        ret = s->scr;

        break;

    case 0x14:

        ret = 0;

        break;

    }

#endif

    if (s->feat & SH_SERIAL_FEAT_SCIF) {

        switch(offs) {

        case 0x00: /* SMR */

            ret = s->smr;

            break;

        case 0x08: /* SCR */

            ret = s->scr;

            break;

        case 0x10: /* FSR */

            ret = 0;

            if (s->flags & SH_SERIAL_FLAG_TEND)

                ret |= (1 << 6);

            if (s->flags & SH_SERIAL_FLAG_TDE)

                ret |= (1 << 5);

            if (s->flags & SH_SERIAL_FLAG_BRK)

                ret |= (1 << 4);

            if (s->flags & SH_SERIAL_FLAG_RDF)

                ret |= (1 << 1);

            if (s->flags & SH_SERIAL_FLAG_DR)

                ret |= (1 << 0);

            if (s->scr & (1 << 5))

                s->flags |= SH_SERIAL_FLAG_TDE | SH_SERIAL_FLAG_TEND;

            break;

        case 0x14:

            if (s->rx_cnt > 0) {

                ret = s->rx_fifo[s->rx_tail++];

                s->rx_cnt--;

                if (s->rx_tail == SH_RX_FIFO_LENGTH)

                    s->rx_tail = 0;

                if (s->rx_cnt < s->rtrg)

                    s->flags &= ~SH_SERIAL_FLAG_RDF;

            }

            break;

#if 0

        case 0x18:

            ret = s->fcr;

            break;

#endif

        case 0x1c:

            ret = s->rx_cnt;

            break;

        case 0x20:

            ret = s->sptr;

            break;

        case 0x24:

            ret = 0;

            break;

        }

    }

    else {

#if 0

        switch(offs) {

        case 0x0c:

            ret = s->dr;

            break;

        case 0x10:

            ret = 0;

            break;

        case 0x14:

            ret = s->rx_fifo[0];

            break;

        case 0x1c:

            ret = s->sptr;

            break;

        }

#endif

    }

#ifdef DEBUG_SERIAL

    printf("sh_serial: read offs=0x%02x val=0x%x\n",

	   offs, ret);

#endif

    if (ret & ~((1 << 16) - 1)) {

        fprintf(stderr, "sh_serial: unsupported read from 0x%02x\n", offs);

	assert(0);

    }

    return ret;

}


void ide_dma_cb(void *opaque, int ret)

{

    IDEState *s = opaque;

    int n;

    int64_t sector_num;

    bool stay_active = false;

    if (ret < 0) {

        int op = BM_STATUS_DMA_RETRY;

        if (s->dma_cmd == IDE_DMA_READ)

            op |= BM_STATUS_RETRY_READ;

        else if (s->dma_cmd == IDE_DMA_TRIM)

            op |= BM_STATUS_RETRY_TRIM;

        if (ide_handle_rw_error(s, -ret, op)) {

            return;

    n = s->io_buffer_size >> 9;

    if (n > s->nsector) {

        /* The PRDs were longer than needed for this request. Shorten them so

         * we don't get a negative remainder. The Active bit must remain set

         * after the request completes. */

        n = s->nsector;

        stay_active = true;

    sector_num = ide_get_sector(s);

    if (n > 0) {

        dma_buf_commit(s);

        sector_num += n;

        ide_set_sector(s, sector_num);

        s->nsector -= n;

    /* end of transfer ? */

    if (s->nsector == 0) {

        s->status = READY_STAT | SEEK_STAT;

        ide_set_irq(s->bus);

        goto eot;

    /* launch next transfer */

    n = s->nsector;

    s->io_buffer_index = 0;

    s->io_buffer_size = n * 512;

    if (s->bus->dma->ops->prepare_buf(s->bus->dma, ide_cmd_is_read(s)) == 0) {

        /* The PRDs were too short. Reset the Active bit, but don't raise an

         * interrupt. */

        goto eot;

#ifdef DEBUG_AIO

    printf("ide_dma_cb: sector_num=%" PRId64 " n=%d, cmd_cmd=%d\n",

           sector_num, n, s->dma_cmd);

#endif

    switch (s->dma_cmd) {

    case IDE_DMA_READ:

        s->bus->dma->aiocb = dma_bdrv_read(s->bs, &s->sg, sector_num,

                                           ide_dma_cb, s);

        break;

    case IDE_DMA_WRITE:

        s->bus->dma->aiocb = dma_bdrv_write(s->bs, &s->sg, sector_num,

                                            ide_dma_cb, s);

        break;

    case IDE_DMA_TRIM:

        s->bus->dma->aiocb = dma_bdrv_io(s->bs, &s->sg, sector_num,

                                         ide_issue_trim, ide_dma_cb, s,

                                         DMA_DIRECTION_TO_DEVICE);

        break;

    return;

eot:

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

        bdrv_acct_done(s->bs, &s->acct);

    ide_set_inactive(s);


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

{

    ICPState *icp = ICP(dev);

    ICPStateClass *icpc = ICP_GET_CLASS(dev);

    PowerPCCPU *cpu;

    CPUPPCState *env;

    Object *obj;

    Error *err = NULL;

    obj = object_property_get_link(OBJECT(dev), ICP_PROP_XICS, &err);

    if (!obj) {

        error_setg(errp, "%s: required link '" ICP_PROP_XICS "' not found: %s",

                   __func__, error_get_pretty(err));

        return;

    }

    icp->xics = XICS_FABRIC(obj);

    obj = object_property_get_link(OBJECT(dev), ICP_PROP_CPU, &err);

    if (!obj) {

        error_setg(errp, "%s: required link '" ICP_PROP_CPU "' not found: %s",

                   __func__, error_get_pretty(err));

        return;

    }

    cpu = POWERPC_CPU(obj);

    cpu->intc = OBJECT(icp);

    icp->cs = CPU(obj);

    env = &cpu->env;

    switch (PPC_INPUT(env)) {

    case PPC_FLAGS_INPUT_POWER7:

        icp->output = env->irq_inputs[POWER7_INPUT_INT];

        break;

    case PPC_FLAGS_INPUT_970:

        icp->output = env->irq_inputs[PPC970_INPUT_INT];

        break;

    default:

        error_setg(errp, "XICS interrupt controller does not support this CPU bus model");

        return;

    }

    if (icpc->realize) {

        icpc->realize(icp, errp);

    }

    qemu_register_reset(icp_reset, dev);

    vmstate_register(NULL, icp->cs->cpu_index, &vmstate_icp_server, icp);

}


static inline void gen_st8(TCGv val, TCGv addr, int index)

{

    tcg_gen_qemu_st8(val, addr, index);

    dead_tmp(val);

}


static int show_stream(WriterContext *w, AVFormatContext *fmt_ctx, int stream_idx, InputStream *ist, int in_program)

{

    AVStream *stream = ist->st;

    AVCodecParameters *par;

    AVCodecContext *dec_ctx;

    char val_str[128];

    const char *s;

    AVRational sar, dar;

    AVBPrint pbuf;

    const AVCodecDescriptor *cd;

    int ret = 0;

    const char *profile = NULL;

    av_bprint_init(&pbuf, 1, AV_BPRINT_SIZE_UNLIMITED);

    writer_print_section_header(w, in_program ? SECTION_ID_PROGRAM_STREAM : SECTION_ID_STREAM);

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

    par     = stream->codecpar;

    dec_ctx = ist->dec_ctx;

    if (cd = avcodec_descriptor_get(par->codec_id)) {

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

        if (!do_bitexact) {

            print_str("codec_long_name",

                      cd->long_name ? cd->long_name : "unknown");

        }

    } else {

        print_str_opt("codec_name", "unknown");

        if (!do_bitexact) {

            print_str_opt("codec_long_name", "unknown");

        }

    }

    if (!do_bitexact && (profile = avcodec_profile_name(par->codec_id, par->profile)))

        print_str("profile", profile);

    else {

        if (par->profile != FF_PROFILE_UNKNOWN) {

            char profile_num[12];

            snprintf(profile_num, sizeof(profile_num), "%d", par->profile);

            print_str("profile", profile_num);

        } else

            print_str_opt("profile", "unknown");

    }

    s = av_get_media_type_string(par->codec_type);

    if (s) print_str    ("codec_type", s);

    else   print_str_opt("codec_type", "unknown");

#if FF_API_LAVF_AVCTX

    print_q("codec_time_base", dec_ctx->time_base, '/');

#endif

    /* print AVI/FourCC tag */

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

    print_str("codec_tag_string",    val_str);

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

    switch (par->codec_type) {

    case AVMEDIA_TYPE_VIDEO:

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

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

        if (dec_ctx) {

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

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

        }

        print_int("has_b_frames", par->video_delay);

        sar = av_guess_sample_aspect_ratio(fmt_ctx, stream, NULL);

        if (sar.den) {

            print_q("sample_aspect_ratio", sar, ':');

            av_reduce(&dar.num, &dar.den,

                      par->width  * sar.num,

                      par->height * sar.den,

                      1024*1024);

            print_q("display_aspect_ratio", dar, ':');

        } else {

            print_str_opt("sample_aspect_ratio", "N/A");

            print_str_opt("display_aspect_ratio", "N/A");

        }

        s = av_get_pix_fmt_name(par->format);

        if (s) print_str    ("pix_fmt", s);

        else   print_str_opt("pix_fmt", "unknown");

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

        if (par->color_range != AVCOL_RANGE_UNSPECIFIED)

            print_str    ("color_range", av_color_range_name(par->color_range));

        else

            print_str_opt("color_range", "N/A");

        s = av_get_colorspace_name(par->color_space);

        if (s) print_str    ("color_space", s);

        else   print_str_opt("color_space", "unknown");

        if (par->color_trc != AVCOL_TRC_UNSPECIFIED)

            print_str("color_transfer", av_color_transfer_name(par->color_trc));

        else

            print_str_opt("color_transfer", av_color_transfer_name(par->color_trc));

        if (par->color_primaries != AVCOL_PRI_UNSPECIFIED)

            print_str("color_primaries", av_color_primaries_name(par->color_primaries));

        else

            print_str_opt("color_primaries", av_color_primaries_name(par->color_primaries));

        if (par->chroma_location != AVCHROMA_LOC_UNSPECIFIED)

            print_str("chroma_location", av_chroma_location_name(par->chroma_location));

        else

            print_str_opt("chroma_location", av_chroma_location_name(par->chroma_location));

#if FF_API_PRIVATE_OPT

        if (dec_ctx && dec_ctx->timecode_frame_start >= 0) {

            char tcbuf[AV_TIMECODE_STR_SIZE];

            av_timecode_make_mpeg_tc_string(tcbuf, dec_ctx->timecode_frame_start);

            print_str("timecode", tcbuf);

        } else {

            print_str_opt("timecode", "N/A");

        }

#endif

        if (dec_ctx)

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

        break;

    case AVMEDIA_TYPE_AUDIO:

        s = av_get_sample_fmt_name(par->format);

        if (s) print_str    ("sample_fmt", s);

        else   print_str_opt("sample_fmt", "unknown");

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

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

        if (par->channel_layout) {

            av_bprint_clear(&pbuf);

            av_bprint_channel_layout(&pbuf, par->channels, par->channel_layout);

            print_str    ("channel_layout", pbuf.str);

        } else {

            print_str_opt("channel_layout", "unknown");

        }

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

        break;

    case AVMEDIA_TYPE_SUBTITLE:

        if (par->width)

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

        else

            print_str_opt("width",   "N/A");

        if (par->height)

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

        else

            print_str_opt("height",  "N/A");

        break;

    }

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

        const AVOption *opt = NULL;

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

            uint8_t *str;

            if (opt->flags) continue;

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

                print_str(opt->name, str);

                av_free(str);

            }

        }

    }

    if (fmt_ctx->iformat->flags & AVFMT_SHOW_IDS) print_fmt    ("id", "0x%x", stream->id);

    else                                          print_str_opt("id", "N/A");

    print_q("r_frame_rate",   stream->r_frame_rate,   '/');

    print_q("avg_frame_rate", stream->avg_frame_rate, '/');

    print_q("time_base",      stream->time_base,      '/');

    print_ts  ("start_pts",   stream->start_time);

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

    print_ts  ("duration_ts", stream->duration);

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

    if (par->bit_rate > 0)     print_val    ("bit_rate", par->bit_rate, unit_bit_per_second_str);

    else                       print_str_opt("bit_rate", "N/A");

#if FF_API_LAVF_AVCTX

    if (stream->codec->rc_max_rate > 0) print_val ("max_bit_rate", stream->codec->rc_max_rate, unit_bit_per_second_str);

    else                                print_str_opt("max_bit_rate", "N/A");

#endif

    if (dec_ctx && dec_ctx->bits_per_raw_sample > 0) print_fmt("bits_per_raw_sample", "%d", dec_ctx->bits_per_raw_sample);

    else                                             print_str_opt("bits_per_raw_sample", "N/A");

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

    else                   print_str_opt("nb_frames", "N/A");

    if (nb_streams_frames[stream_idx])  print_fmt    ("nb_read_frames", "%"PRIu64, nb_streams_frames[stream_idx]);

    else                                print_str_opt("nb_read_frames", "N/A");

    if (nb_streams_packets[stream_idx]) print_fmt    ("nb_read_packets", "%"PRIu64, nb_streams_packets[stream_idx]);

    else                                print_str_opt("nb_read_packets", "N/A");

    if (do_show_data)

        writer_print_data(w, "extradata", par->extradata,

                                          par->extradata_size);

    writer_print_data_hash(w, "extradata_hash", par->extradata,

                                                par->extradata_size);

    /* Print disposition information */

#define PRINT_DISPOSITION(flagname, name) do {                                \

        print_int(name, !!(stream->disposition & AV_DISPOSITION_##flagname)); \

    } while (0)

    if (do_show_stream_disposition) {

    writer_print_section_header(w, in_program ? SECTION_ID_PROGRAM_STREAM_DISPOSITION : SECTION_ID_STREAM_DISPOSITION);

    PRINT_DISPOSITION(DEFAULT,          "default");

    PRINT_DISPOSITION(DUB,              "dub");

    PRINT_DISPOSITION(ORIGINAL,         "original");

    PRINT_DISPOSITION(COMMENT,          "comment");

    PRINT_DISPOSITION(LYRICS,           "lyrics");

    PRINT_DISPOSITION(KARAOKE,          "karaoke");

    PRINT_DISPOSITION(FORCED,           "forced");

    PRINT_DISPOSITION(HEARING_IMPAIRED, "hearing_impaired");

    PRINT_DISPOSITION(VISUAL_IMPAIRED,  "visual_impaired");

    PRINT_DISPOSITION(CLEAN_EFFECTS,    "clean_effects");

    PRINT_DISPOSITION(ATTACHED_PIC,     "attached_pic");

    writer_print_section_footer(w);

    }

    if (do_show_stream_tags)

        ret = show_tags(w, stream->metadata, in_program ? SECTION_ID_PROGRAM_STREAM_TAGS : SECTION_ID_STREAM_TAGS);

    if (stream->nb_side_data) {

        int i;

        writer_print_section_header(w, SECTION_ID_STREAM_SIDE_DATA_LIST);

        for (i = 0; i < stream->nb_side_data; i++) {

            AVPacketSideData *sd = &stream->side_data[i];

            const char *name = av_packet_side_data_name(sd->type);

            writer_print_section_header(w, SECTION_ID_STREAM_SIDE_DATA);

            print_str("side_data_type", name ? name : "unknown");

            print_int("side_data_size", sd->size);

            if (sd->type == AV_PKT_DATA_DISPLAYMATRIX && sd->size >= 9*4) {

                writer_print_integers(w, "displaymatrix", sd->data, 9, " %11d", 3, 4, 1);

                print_int("rotation", av_display_rotation_get((int32_t *)sd->data));

            }

            writer_print_section_footer(w);

        }

        writer_print_section_footer(w);

    }

    writer_print_section_footer(w);

    av_bprint_finalize(&pbuf, NULL);

    fflush(stdout);

    return ret;

}


static int build_filter(ResampleContext *c, void *filter, double factor, int tap_count, int alloc, int phase_count, int scale,

                        int filter_type, int kaiser_beta){

    int ph, i;

    double x, y, w;

    double *tab = av_malloc_array(tap_count+1,  sizeof(*tab));

    const int center= (tap_count-1)/2;

    if (!tab)

        return AVERROR(ENOMEM);

    /* if upsampling, only need to interpolate, no filter */

    if (factor > 1.0)

        factor = 1.0;

    av_assert0(phase_count == 1 || phase_count % 2 == 0);

    for(ph = 0; ph <= phase_count / 2; ph++) {

        double norm = 0;

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

            x = M_PI * ((double)(i - center) - (double)ph / phase_count) * factor;

            if (x == 0) y = 1.0;

            else        y = sin(x) / x;

            switch(filter_type){

            case SWR_FILTER_TYPE_CUBIC:{

                const float d= -0.5; //first order derivative = -0.5

                x = fabs(((double)(i - center) - (double)ph / phase_count) * factor);

                if(x<1.0) y= 1 - 3*x*x + 2*x*x*x + d*(            -x*x + x*x*x);

                else      y=                       d*(-4 + 8*x - 5*x*x + x*x*x);

                break;}

            case SWR_FILTER_TYPE_BLACKMAN_NUTTALL:

                w = 2.0*x / (factor*tap_count) + M_PI;

                y *= 0.3635819 - 0.4891775 * cos(w) + 0.1365995 * cos(2*w) - 0.0106411 * cos(3*w);

                break;

            case SWR_FILTER_TYPE_KAISER:

                w = 2.0*x / (factor*tap_count*M_PI);

                y *= bessel(kaiser_beta*sqrt(FFMAX(1-w*w, 0)));

                break;

            default:

                av_assert0(0);

            }

            tab[i] = y;

            if (i < tap_count)

                norm += y;

        }

        /* normalize so that an uniform color remains the same */

        switch(c->format){

        case AV_SAMPLE_FMT_S16P:

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

                ((int16_t*)filter)[ph * alloc + i] = av_clip(lrintf(tab[i] * scale / norm), INT16_MIN, INT16_MAX);

            if (tap_count % 2 == 0) {

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

                    ((int16_t*)filter)[(phase_count-ph) * alloc + tap_count-1-i] = ((int16_t*)filter)[ph * alloc + i];

            }

            else {

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

                    ((int16_t*)filter)[(phase_count-ph) * alloc + tap_count-i] =

                        av_clip(lrintf(tab[i] * scale / (norm - tab[0] + tab[tap_count])), INT16_MIN, INT16_MAX);

            }

            break;

        case AV_SAMPLE_FMT_S32P:

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

                ((int32_t*)filter)[ph * alloc + i] = av_clipl_int32(llrint(tab[i] * scale / norm));

            if (tap_count % 2 == 0) {

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

                    ((int32_t*)filter)[(phase_count-ph) * alloc + tap_count-1-i] = ((int32_t*)filter)[ph * alloc + i];

            }

            else {

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

                    ((int32_t*)filter)[(phase_count-ph) * alloc + tap_count-i] =

                        av_clipl_int32(llrint(tab[i] * scale / (norm - tab[0] + tab[tap_count])));

            }

            break;

        case AV_SAMPLE_FMT_FLTP:

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

                ((float*)filter)[ph * alloc + i] = tab[i] * scale / norm;

            if (tap_count % 2 == 0) {

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

                    ((float*)filter)[(phase_count-ph) * alloc + tap_count-1-i] = ((float*)filter)[ph * alloc + i];

            }

            else {

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

                    ((float*)filter)[(phase_count-ph) * alloc + tap_count-i] = tab[i] * scale / (norm - tab[0] + tab[tap_count]);

            }

            break;

        case AV_SAMPLE_FMT_DBLP:

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

                ((double*)filter)[ph * alloc + i] = tab[i] * scale / norm;

            if (tap_count % 2 == 0) {

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

                    ((double*)filter)[(phase_count-ph) * alloc + tap_count-1-i] = ((double*)filter)[ph * alloc + i];

            }

            else {

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

                    ((double*)filter)[(phase_count-ph) * alloc + tap_count-i] = tab[i] * scale / (norm - tab[0] + tab[tap_count]);

            }

            break;

        }

    }

#if 0

    {

#define LEN 1024

        int j,k;

        double sine[LEN + tap_count];

        double filtered[LEN];

        double maxff=-2, minff=2, maxsf=-2, minsf=2;

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

            double ss=0, sf=0, ff=0;

            for(j=0; j<LEN+tap_count; j++)

                sine[j]= cos(i*j*M_PI/LEN);

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

                double sum=0;

                ph=0;

                for(k=0; k<tap_count; k++)

                    sum += filter[ph * tap_count + k] * sine[k+j];

                filtered[j]= sum / (1<<FILTER_SHIFT);

                ss+= sine[j + center] * sine[j + center];

                ff+= filtered[j] * filtered[j];

                sf+= sine[j + center] * filtered[j];

            }

            ss= sqrt(2*ss/LEN);

            ff= sqrt(2*ff/LEN);

            sf= 2*sf/LEN;

            maxff= FFMAX(maxff, ff);

            minff= FFMIN(minff, ff);

            maxsf= FFMAX(maxsf, sf);

            minsf= FFMIN(minsf, sf);

            if(i%11==0){

                av_log(NULL, AV_LOG_ERROR, "i:%4d ss:%f ff:%13.6e-%13.6e sf:%13.6e-%13.6e\n", i, ss, maxff, minff, maxsf, minsf);

                minff=minsf= 2;

                maxff=maxsf= -2;

            }

        }

    }

#endif

    av_free(tab);

    return 0;

}


e1000e_write_ps_rx_descr(E1000ECore *core, uint8_t *desc,

                         struct NetRxPkt *pkt,

                         const E1000E_RSSInfo *rss_info,

                         size_t ps_hdr_len,

                         uint16_t(*written)[MAX_PS_BUFFERS])

{

    int i;

    union e1000_rx_desc_packet_split *d =

        (union e1000_rx_desc_packet_split *) desc;

    memset(d, 0, sizeof(*d));

    d->wb.middle.length0 = cpu_to_le16((*written)[0]);

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

        d->wb.upper.length[i] = cpu_to_le16((*written)[i + 1]);

    }

    e1000e_build_rx_metadata(core, pkt, pkt != NULL,

                             rss_info,

                             &d->wb.lower.hi_dword.rss,

                             &d->wb.lower.mrq,

                             &d->wb.middle.status_error,

                             &d->wb.lower.hi_dword.csum_ip.ip_id,

                             &d->wb.middle.vlan);

    d->wb.upper.header_status =

        cpu_to_le16(ps_hdr_len | (ps_hdr_len ? E1000_RXDPS_HDRSTAT_HDRSP : 0));

    trace_e1000e_rx_desc_ps_write((*written)[0], (*written)[1],

                                  (*written)[2], (*written)[3]);

}


static void print_track_chunks(FILE *out, struct Tracks *tracks, int main,

                               const char *type)

{

    int i, j;

    struct Track *track = tracks->tracks[main];

    for (i = 0; i < track->chunks; i++) {

        for (j = main + 1; j < tracks->nb_tracks; j++) {

            if (tracks->tracks[j]->is_audio == track->is_audio &&

                track->offsets[i].duration != tracks->tracks[j]->offsets[i].duration)

                fprintf(stderr, "Mismatched duration of %s chunk %d in %s and %s\n",

                        type, i, track->name, tracks->tracks[j]->name);

        }

        fprintf(out, "\t\t<c n=\"%d\" d=\"%d\" />\n",

                i, track->offsets[i].duration);

    }

}


void vncws_handshake_read(void *opaque)

{

    VncState *vs = opaque;

    uint8_t *handshake_end;

    long ret;

    buffer_reserve(&vs->ws_input, 4096);

    ret = vnc_client_read_buf(vs, buffer_end(&vs->ws_input), 4096);

    if (!ret) {

        if (vs->csock == -1) {

            vnc_disconnect_finish(vs);

        }

        return;

    }

    vs->ws_input.offset += ret;

    handshake_end = (uint8_t *)g_strstr_len((char *)vs->ws_input.buffer,

            vs->ws_input.offset, WS_HANDSHAKE_END);

    if (handshake_end) {

        qemu_set_fd_handler2(vs->csock, NULL, vnc_client_read, NULL, vs);

        vncws_process_handshake(vs, vs->ws_input.buffer, vs->ws_input.offset);

        buffer_advance(&vs->ws_input, handshake_end - vs->ws_input.buffer +

                strlen(WS_HANDSHAKE_END));

    }

}


void helper_rfmci(CPUPPCState *env)

{

    do_rfi(env, env->spr[SPR_BOOKE_MCSRR0], SPR_BOOKE_MCSRR1,

           ~((target_ulong)0x3FFF0000), 0);

}


static int get_phys_addr_lpae(CPUARMState *env, target_ulong address,

                              int access_type, int is_user,

                              hwaddr *phys_ptr, int *prot,

                              target_ulong *page_size_ptr)

{

    CPUState *cs = CPU(arm_env_get_cpu(env));

    /* Read an LPAE long-descriptor translation table. */

    MMUFaultType fault_type = translation_fault;

    uint32_t level = 1;

    uint32_t epd;

    int32_t tsz;

    uint32_t tg;

    uint64_t ttbr;

    int ttbr_select;

    hwaddr descaddr, descmask;

    uint32_t tableattrs;

    target_ulong page_size;

    uint32_t attrs;

    int32_t granule_sz = 9;

    int32_t va_size = 32;

    int32_t tbi = 0;

    if (arm_el_is_aa64(env, 1)) {

        va_size = 64;

        if (extract64(address, 55, 1))

            tbi = extract64(env->cp15.c2_control, 38, 1);

        else

            tbi = extract64(env->cp15.c2_control, 37, 1);

        tbi *= 8;

    }

    /* Determine whether this address is in the region controlled by

     * TTBR0 or TTBR1 (or if it is in neither region and should fault).

     * This is a Non-secure PL0/1 stage 1 translation, so controlled by

     * TTBCR/TTBR0/TTBR1 in accordance with ARM ARM DDI0406C table B-32:

     */

    uint32_t t0sz = extract32(env->cp15.c2_control, 0, 6);

    if (arm_el_is_aa64(env, 1)) {

        t0sz = MIN(t0sz, 39);

        t0sz = MAX(t0sz, 16);

    }

    uint32_t t1sz = extract32(env->cp15.c2_control, 16, 6);

    if (arm_el_is_aa64(env, 1)) {

        t1sz = MIN(t1sz, 39);

        t1sz = MAX(t1sz, 16);

    }

    if (t0sz && !extract64(address, va_size - t0sz, t0sz - tbi)) {

        /* there is a ttbr0 region and we are in it (high bits all zero) */

        ttbr_select = 0;

    } else if (t1sz && !extract64(~address, va_size - t1sz, t1sz - tbi)) {

        /* there is a ttbr1 region and we are in it (high bits all one) */

        ttbr_select = 1;

    } else if (!t0sz) {

        /* ttbr0 region is "everything not in the ttbr1 region" */

        ttbr_select = 0;

    } else if (!t1sz) {

        /* ttbr1 region is "everything not in the ttbr0 region" */

        ttbr_select = 1;

    } else {

        /* in the gap between the two regions, this is a Translation fault */

        fault_type = translation_fault;

        goto do_fault;

    }

    /* Note that QEMU ignores shareability and cacheability attributes,

     * so we don't need to do anything with the SH, ORGN, IRGN fields

     * in the TTBCR.  Similarly, TTBCR:A1 selects whether we get the

     * ASID from TTBR0 or TTBR1, but QEMU's TLB doesn't currently

     * implement any ASID-like capability so we can ignore it (instead

     * we will always flush the TLB any time the ASID is changed).

     */

    if (ttbr_select == 0) {

        ttbr = env->cp15.ttbr0_el1;

        epd = extract32(env->cp15.c2_control, 7, 1);

        tsz = t0sz;

        tg = extract32(env->cp15.c2_control, 14, 2);

        if (tg == 1) { /* 64KB pages */

            granule_sz = 13;

        }

        if (tg == 2) { /* 16KB pages */

            granule_sz = 11;

        }

    } else {

        ttbr = env->cp15.ttbr1_el1;

        epd = extract32(env->cp15.c2_control, 23, 1);

        tsz = t1sz;

        tg = extract32(env->cp15.c2_control, 30, 2);

        if (tg == 3)  { /* 64KB pages */

            granule_sz = 13;

        }

        if (tg == 1) { /* 16KB pages */

            granule_sz = 11;

        }

    }

    if (epd) {

        /* Translation table walk disabled => Translation fault on TLB miss */

        goto do_fault;

    }

    /* The starting level depends on the virtual address size which can be

     * up to 48-bits and the translation granule size.

     */

    if ((va_size - tsz) > (granule_sz * 4 + 3)) {

        level = 0;

    } else if ((va_size - tsz) > (granule_sz * 3 + 3)) {

        level = 1;

    } else {

        level = 2;

    }

    /* Clear the vaddr bits which aren't part of the within-region address,

     * so that we don't have to special case things when calculating the

     * first descriptor address.

     */

    if (tsz) {

        address &= (1ULL << (va_size - tsz)) - 1;

    }

    descmask = (1ULL << (granule_sz + 3)) - 1;

    /* Now we can extract the actual base address from the TTBR */

    descaddr = extract64(ttbr, 0, 48);

    descaddr &= ~((1ULL << (va_size - tsz - (granule_sz * (4 - level)))) - 1);

    tableattrs = 0;

    for (;;) {

        uint64_t descriptor;

        descaddr |= (address >> (granule_sz * (4 - level))) & descmask;

        descaddr &= ~7ULL;

        descriptor = ldq_phys(cs->as, descaddr);

        if (!(descriptor & 1) ||

            (!(descriptor & 2) && (level == 3))) {

            /* Invalid, or the Reserved level 3 encoding */

            goto do_fault;

        }

        descaddr = descriptor & 0xfffffff000ULL;

        if ((descriptor & 2) && (level < 3)) {

            /* Table entry. The top five bits are attributes which  may

             * propagate down through lower levels of the table (and

             * which are all arranged so that 0 means "no effect", so

             * we can gather them up by ORing in the bits at each level).

             */

            tableattrs |= extract64(descriptor, 59, 5);

            level++;

            continue;

        }

        /* Block entry at level 1 or 2, or page entry at level 3.

         * These are basically the same thing, although the number

         * of bits we pull in from the vaddr varies.

         */

        page_size = (1 << ((granule_sz * (4 - level)) + 3));

        descaddr |= (address & (page_size - 1));

        /* Extract attributes from the descriptor and merge with table attrs */

        if (arm_feature(env, ARM_FEATURE_V8)) {

            attrs = extract64(descriptor, 2, 10)

                | (extract64(descriptor, 53, 11) << 10);

        } else {

            attrs = extract64(descriptor, 2, 10)

                | (extract64(descriptor, 52, 12) << 10);

        }

        attrs |= extract32(tableattrs, 0, 2) << 11; /* XN, PXN */

        attrs |= extract32(tableattrs, 3, 1) << 5; /* APTable[1] => AP[2] */

        /* The sense of AP[1] vs APTable[0] is reversed, as APTable[0] == 1

         * means "force PL1 access only", which means forcing AP[1] to 0.

         */

        if (extract32(tableattrs, 2, 1)) {

            attrs &= ~(1 << 4);

        }

        /* Since we're always in the Non-secure state, NSTable is ignored. */

        break;

    }

    /* Here descaddr is the final physical address, and attributes

     * are all in attrs.

     */

    fault_type = access_fault;

    if ((attrs & (1 << 8)) == 0) {

        /* Access flag */

        goto do_fault;

    }

    fault_type = permission_fault;

    if (is_user && !(attrs & (1 << 4))) {

        /* Unprivileged access not enabled */

        goto do_fault;

    }

    *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;

    if (attrs & (1 << 12) || (!is_user && (attrs & (1 << 11)))) {

        /* XN or PXN */

        if (access_type == 2) {

            goto do_fault;

        }

        *prot &= ~PAGE_EXEC;

    }

    if (attrs & (1 << 5)) {

        /* Write access forbidden */

        if (access_type == 1) {

            goto do_fault;

        }

        *prot &= ~PAGE_WRITE;

    }

    *phys_ptr = descaddr;

    *page_size_ptr = page_size;

    return 0;

do_fault:

    /* Long-descriptor format IFSR/DFSR value */

    return (1 << 9) | (fault_type << 2) | level;

}


av_cold void ff_diracdsp_init(DiracDSPContext *c)

{

    c->dirac_hpel_filter = dirac_hpel_filter;

    c->add_rect_clamped = add_rect_clamped_c;

    c->put_signed_rect_clamped[0] = put_signed_rect_clamped_8bit_c;

    c->put_signed_rect_clamped[1] = put_signed_rect_clamped_10bit_c;

    c->add_dirac_obmc[0] = add_obmc8_c;

    c->add_dirac_obmc[1] = add_obmc16_c;

    c->add_dirac_obmc[2] = add_obmc32_c;

    c->weight_dirac_pixels_tab[0] = weight_dirac_pixels8_c;

    c->weight_dirac_pixels_tab[1] = weight_dirac_pixels16_c;

    c->weight_dirac_pixels_tab[2] = weight_dirac_pixels32_c;

    c->biweight_dirac_pixels_tab[0] = biweight_dirac_pixels8_c;

    c->biweight_dirac_pixels_tab[1] = biweight_dirac_pixels16_c;

    c->biweight_dirac_pixels_tab[2] = biweight_dirac_pixels32_c;

    PIXFUNC(put, 8);

    PIXFUNC(put, 16);

    PIXFUNC(put, 32);

    PIXFUNC(avg, 8);

    PIXFUNC(avg, 16);

    PIXFUNC(avg, 32);

    if (HAVE_MMX && HAVE_YASM) ff_diracdsp_init_mmx(c);

}


static int encode_block(SVQ1Context *s, uint8_t *src, uint8_t *ref, uint8_t *decoded, int stride, int level, int threshold, int lambda, int intra){

    int count, y, x, i, j, split, best_mean, best_score, best_count;

    int best_vector[6];

    int block_sum[7]= {0, 0, 0, 0, 0, 0};

    int w= 2<<((level+2)>>1);

    int h= 2<<((level+1)>>1);

    int size=w*h;

    int16_t block[7][256];

    const int8_t *codebook_sum, *codebook;

    const uint16_t (*mean_vlc)[2];

    const uint8_t (*multistage_vlc)[2];

    best_score=0;

    //FIXME optimize, this doenst need to be done multiple times

    if(intra){

        codebook_sum= svq1_intra_codebook_sum[level];

        codebook= ff_svq1_intra_codebooks[level];

        mean_vlc= ff_svq1_intra_mean_vlc;

        multistage_vlc= ff_svq1_intra_multistage_vlc[level];

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

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

                int v= src[x + y*stride];

                block[0][x + w*y]= v;

                best_score += v*v;

                block_sum[0] += v;

            }

        }

    }else{

        codebook_sum= svq1_inter_codebook_sum[level];

        codebook= ff_svq1_inter_codebooks[level];

        mean_vlc= ff_svq1_inter_mean_vlc + 256;

        multistage_vlc= ff_svq1_inter_multistage_vlc[level];

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

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

                int v= src[x + y*stride] - ref[x + y*stride];

                block[0][x + w*y]= v;

                best_score += v*v;

                block_sum[0] += v;

            }

        }

    }

    best_count=0;

    best_score -= ((block_sum[0]*block_sum[0])>>(level+3));

    best_mean= (block_sum[0] + (size>>1)) >> (level+3);

    if(level<4){

        for(count=1; count<7; count++){

            int best_vector_score= INT_MAX;

            int best_vector_sum=-999, best_vector_mean=-999;

            const int stage= count-1;

            const int8_t *vector;

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

                int sum= codebook_sum[stage*16 + i];

                int sqr, diff, score;

                vector = codebook + stage*size*16 + i*size;

                sqr = s->dsp.ssd_int8_vs_int16(vector, block[stage], size);

                diff= block_sum[stage] - sum;

                score= sqr - ((diff*(int64_t)diff)>>(level+3)); //FIXME 64bit slooow

                if(score < best_vector_score){

                    int mean= (diff + (size>>1)) >> (level+3);

                    assert(mean >-300 && mean<300);

                    mean= av_clip(mean, intra?0:-256, 255);

                    best_vector_score= score;

                    best_vector[stage]= i;

                    best_vector_sum= sum;

                    best_vector_mean= mean;

                }

            }

            assert(best_vector_mean != -999);

            vector= codebook + stage*size*16 + best_vector[stage]*size;

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

                block[stage+1][j] = block[stage][j] - vector[j];

            }

            block_sum[stage+1]= block_sum[stage] - best_vector_sum;

            best_vector_score +=

                lambda*(+ 1 + 4*count

                        + multistage_vlc[1+count][1]

                        + mean_vlc[best_vector_mean][1]);

            if(best_vector_score < best_score){

                best_score= best_vector_score;

                best_count= count;

                best_mean= best_vector_mean;

            }

        }

    }

    split=0;

    if(best_score > threshold && level){

        int score=0;

        int offset= (level&1) ? stride*h/2 : w/2;

        PutBitContext backup[6];

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

            backup[i]= s->reorder_pb[i];

        }

        score += encode_block(s, src         , ref         , decoded         , stride, level-1, threshold>>1, lambda, intra);

        score += encode_block(s, src + offset, ref + offset, decoded + offset, stride, level-1, threshold>>1, lambda, intra);

        score += lambda;

        if(score < best_score){

            best_score= score;

            split=1;

        }else{

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

                s->reorder_pb[i]= backup[i];

            }

        }

    }

    if (level > 0)

        put_bits(&s->reorder_pb[level], 1, split);

    if(!split){

        assert((best_mean >= 0 && best_mean<256) || !intra);

        assert(best_mean >= -256 && best_mean<256);

        assert(best_count >=0 && best_count<7);

        assert(level<4 || best_count==0);

        /* output the encoding */

        put_bits(&s->reorder_pb[level],

            multistage_vlc[1 + best_count][1],

            multistage_vlc[1 + best_count][0]);

        put_bits(&s->reorder_pb[level], mean_vlc[best_mean][1],

            mean_vlc[best_mean][0]);

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

            assert(best_vector[i]>=0 && best_vector[i]<16);

            put_bits(&s->reorder_pb[level], 4, best_vector[i]);

        }

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

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

                decoded[x + y*stride]= src[x + y*stride] - block[best_count][x + w*y] + best_mean;

            }

        }

    }

    return best_score;

}


void object_property_set_link(Object *obj, Object *value,

                              const char *name, Error **errp)

{

    object_property_set_str(obj, object_get_canonical_path(value),

                            name, errp);

}


static int qcow2_cache_entry_flush(BlockDriverState *bs, Qcow2Cache *c, int i)

{

    BDRVQcowState *s = bs->opaque;

    int ret = 0;

    if (!c->entries[i].dirty || !c->entries[i].offset) {

        return 0;

    }

    trace_qcow2_cache_entry_flush(qemu_coroutine_self(),

                                  c == s->l2_table_cache, i);

    if (c->depends) {

        ret = qcow2_cache_flush_dependency(bs, c);

    } else if (c->depends_on_flush) {

        ret = bdrv_flush(bs->file);

        if (ret >= 0) {

            c->depends_on_flush = false;

        }

    }

    if (ret < 0) {

        return ret;

    }

    if (c == s->refcount_block_cache) {

        ret = qcow2_pre_write_overlap_check(bs,

                QCOW2_OL_DEFAULT & ~QCOW2_OL_REFCOUNT_BLOCK,

                c->entries[i].offset, s->cluster_size);

    } else if (c == s->l2_table_cache) {

        ret = qcow2_pre_write_overlap_check(bs,

                QCOW2_OL_DEFAULT & ~QCOW2_OL_ACTIVE_L2,

                c->entries[i].offset, s->cluster_size);

    } else {

        ret = qcow2_pre_write_overlap_check(bs, QCOW2_OL_DEFAULT,

                c->entries[i].offset, s->cluster_size);

    }

    if (ret < 0) {

        return ret;

    }

    if (c == s->refcount_block_cache) {

        BLKDBG_EVENT(bs->file, BLKDBG_REFBLOCK_UPDATE_PART);

    } else if (c == s->l2_table_cache) {

        BLKDBG_EVENT(bs->file, BLKDBG_L2_UPDATE);

    }

    ret = bdrv_pwrite(bs->file, c->entries[i].offset, c->entries[i].table,

        s->cluster_size);

    if (ret < 0) {

        return ret;

    }

    c->entries[i].dirty = false;

    return 0;

}


USBBus *usb_bus_new(DeviceState *host)

{

    USBBus *bus;

    bus = FROM_QBUS(USBBus, qbus_create(&usb_bus_info, host, NULL));

    bus->busnr = next_usb_bus++;

    TAILQ_INIT(&bus->free);

    TAILQ_INIT(&bus->used);

    TAILQ_INSERT_TAIL(&busses, bus, next);

    return bus;

}


sPAPRTCETable *spapr_tce_new_table(DeviceState *owner, uint32_t liobn)

{

    sPAPRTCETable *tcet;

    char tmp[32];

    if (spapr_tce_find_by_liobn(liobn)) {

        error_report("Attempted to create TCE table with duplicate"

                " LIOBN 0x%x", liobn);

        return NULL;

    }

    tcet = SPAPR_TCE_TABLE(object_new(TYPE_SPAPR_TCE_TABLE));

    tcet->liobn = liobn;

    snprintf(tmp, sizeof(tmp), "tce-table-%x", liobn);

    object_property_add_child(OBJECT(owner), tmp, OBJECT(tcet), NULL);

    object_property_set_bool(OBJECT(tcet), true, "realized", NULL);

    return tcet;

}


bool arm_regime_using_lpae_format(CPUARMState *env, ARMMMUIdx mmu_idx)

{

    return regime_using_lpae_format(env, mmu_idx);

}


static int usb_hub_initfn(USBDevice *dev)

{

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

    USBHubPort *port;

    int i;

    s->dev.speed = USB_SPEED_FULL;

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

        port = &s->ports[i];

        usb_register_port(usb_bus_from_device(dev),

                          &port->port, s, i, &s->dev, usb_hub_attach);

        port->wPortStatus = PORT_STAT_POWER;

        port->wPortChange = 0;

    }

    return 0;

}


static void horizontal_filter(unsigned char *first_pixel, int stride,

    int *bounding_values)

{

    unsigned char *end;

    int filter_value;

    for (end= first_pixel + 8*stride; first_pixel < end; first_pixel += stride) {

        filter_value =

            (first_pixel[-2] - first_pixel[ 1])

         +3*(first_pixel[ 0] - first_pixel[-1]);

        filter_value = bounding_values[(filter_value + 4) >> 3];

        first_pixel[-1] = clip_uint8(first_pixel[-1] + filter_value);

        first_pixel[ 0] = clip_uint8(first_pixel[ 0] - filter_value);

    }

}


build_dmar_q35(GArray *table_data, BIOSLinker *linker)

{

    int dmar_start = table_data->len;

    AcpiTableDmar *dmar;

    AcpiDmarHardwareUnit *drhd;

    AcpiDmarRootPortATS *atsr;

    uint8_t dmar_flags = 0;

    X86IOMMUState *iommu = x86_iommu_get_default();

    AcpiDmarDeviceScope *scope = NULL;

    /* Root complex IOAPIC use one path[0] only */

    size_t ioapic_scope_size = sizeof(*scope) + sizeof(scope->path[0]);

    assert(iommu);

    if (iommu->intr_supported) {

        dmar_flags |= 0x1;      /* Flags: 0x1: INT_REMAP */

    }

    dmar = acpi_data_push(table_data, sizeof(*dmar));

    dmar->host_address_width = VTD_HOST_ADDRESS_WIDTH - 1;

    dmar->flags = dmar_flags;

    /* DMAR Remapping Hardware Unit Definition structure */

    drhd = acpi_data_push(table_data, sizeof(*drhd) + ioapic_scope_size);

    drhd->type = cpu_to_le16(ACPI_DMAR_TYPE_HARDWARE_UNIT);

    drhd->length = cpu_to_le16(sizeof(*drhd) + ioapic_scope_size);

    drhd->flags = ACPI_DMAR_INCLUDE_PCI_ALL;

    drhd->pci_segment = cpu_to_le16(0);

    drhd->address = cpu_to_le64(Q35_HOST_BRIDGE_IOMMU_ADDR);

    /* Scope definition for the root-complex IOAPIC. See VT-d spec

     * 8.3.1 (version Oct. 2014 or later). */

    scope = &drhd->scope[0];

    scope->entry_type = 0x03;   /* Type: 0x03 for IOAPIC */

    scope->length = ioapic_scope_size;

    scope->enumeration_id = ACPI_BUILD_IOAPIC_ID;

    scope->bus = Q35_PSEUDO_BUS_PLATFORM;

    scope->path[0].device = PCI_SLOT(Q35_PSEUDO_DEVFN_IOAPIC);

    scope->path[0].function = PCI_FUNC(Q35_PSEUDO_DEVFN_IOAPIC);

    if (iommu->dt_supported) {

        atsr = acpi_data_push(table_data, sizeof(*atsr));

        atsr->type = cpu_to_le16(ACPI_DMAR_TYPE_ATSR);

        atsr->length = cpu_to_le16(sizeof(*atsr));

        atsr->flags = ACPI_DMAR_ATSR_ALL_PORTS;

        atsr->pci_segment = cpu_to_le16(0);

    }

    build_header(linker, table_data, (void *)(table_data->data + dmar_start),

                 "DMAR", table_data->len - dmar_start, 1, NULL, NULL);

}


static void spapr_dr_connector_class_init(ObjectClass *k, void *data)

{

    DeviceClass *dk = DEVICE_CLASS(k);

    sPAPRDRConnectorClass *drck = SPAPR_DR_CONNECTOR_CLASS(k);

    dk->reset = reset;

    dk->realize = realize;

    dk->unrealize = unrealize;

    drck->set_isolation_state = set_isolation_state;

    drck->set_allocation_state = set_allocation_state;

    drck->release_pending = release_pending;

    drck->set_signalled = set_signalled;

    /*

     * Reason: it crashes FIXME find and document the real reason

     */

    dk->user_creatable = false;

}


static void smbios_validate_table(void)

{

    if (smbios_type4_count && smbios_type4_count != smp_cpus) {

         fprintf(stderr,

                 "Number of SMBIOS Type 4 tables must match cpu count.\n");

        exit(1);

    }

}


static int xen_pt_bar_reg_write(XenPCIPassthroughState *s, XenPTReg *cfg_entry,

                                uint32_t *val, uint32_t dev_value,

                                uint32_t valid_mask)

{

    XenPTRegInfo *reg = cfg_entry->reg;

    XenPTRegion *base = NULL;

    PCIDevice *d = &s->dev;

    const PCIIORegion *r;

    uint32_t writable_mask = 0;

    uint32_t bar_emu_mask = 0;

    uint32_t bar_ro_mask = 0;

    uint32_t r_size = 0;

    int index = 0;

    index = xen_pt_bar_offset_to_index(reg->offset);

    if (index < 0 || index >= PCI_NUM_REGIONS) {

        XEN_PT_ERR(d, "Internal error: Invalid BAR index [%d].\n", index);

        return -1;

    }

    r = &d->io_regions[index];

    base = &s->bases[index];

    r_size = xen_pt_get_emul_size(base->bar_flag, r->size);

    /* set emulate mask and read-only mask values depend on the BAR flag */

    switch (s->bases[index].bar_flag) {

    case XEN_PT_BAR_FLAG_MEM:

        bar_emu_mask = XEN_PT_BAR_MEM_EMU_MASK;

        if (!r_size) {

            /* low 32 bits mask for 64 bit bars */

            bar_ro_mask = XEN_PT_BAR_ALLF;

        } else {

            bar_ro_mask = XEN_PT_BAR_MEM_RO_MASK | (r_size - 1);

        }

        break;

    case XEN_PT_BAR_FLAG_IO:

        bar_emu_mask = XEN_PT_BAR_IO_EMU_MASK;

        bar_ro_mask = XEN_PT_BAR_IO_RO_MASK | (r_size - 1);

        break;

    case XEN_PT_BAR_FLAG_UPPER:

        bar_emu_mask = XEN_PT_BAR_ALLF;

        bar_ro_mask = r_size ? r_size - 1 : 0;

        break;

    default:

        break;

    }

    /* modify emulate register */

    writable_mask = bar_emu_mask & ~bar_ro_mask & valid_mask;

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

    /* check whether we need to update the virtual region address or not */

    switch (s->bases[index].bar_flag) {

    case XEN_PT_BAR_FLAG_UPPER:

    case XEN_PT_BAR_FLAG_MEM:

        /* nothing to do */

        break;

    case XEN_PT_BAR_FLAG_IO:

        /* nothing to do */

        break;

    default:

        break;

    }

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

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

    return 0;

}


static void v9fs_write(void *opaque)

{

    ssize_t err;

    int32_t fid;

    uint64_t off;

    uint32_t count;

    int32_t len = 0;

    int32_t total = 0;

    size_t offset = 7;

    V9fsFidState *fidp;

    V9fsPDU *pdu = opaque;

    V9fsState *s = pdu->s;

    QEMUIOVector qiov_full;

    QEMUIOVector qiov;

    offset += pdu_unmarshal(pdu, offset, "dqd", &fid, &off, &count);

    v9fs_init_qiov_from_pdu(&qiov_full, pdu, offset, count, true);

    trace_v9fs_write(pdu->tag, pdu->id, fid, off, count, qiov_full.niov);

    fidp = get_fid(pdu, fid);

    if (fidp == NULL) {

        err = -EINVAL;

        goto out_nofid;

    }

    if (fidp->fid_type == P9_FID_FILE) {

        if (fidp->fs.fd == -1) {

            err = -EINVAL;

            goto out;

        }

    } else if (fidp->fid_type == P9_FID_XATTR) {

        /*

         * setxattr operation

         */

        err = v9fs_xattr_write(s, pdu, fidp, off, count,

                               qiov_full.iov, qiov_full.niov);

        goto out;

    } else {

        err = -EINVAL;

        goto out;

    }

    qemu_iovec_init(&qiov, qiov_full.niov);

    do {

        qemu_iovec_reset(&qiov);

        qemu_iovec_copy(&qiov, &qiov_full, total, qiov_full.size - total);

        if (0) {

            print_sg(qiov.iov, qiov.niov);

        }

        /* Loop in case of EINTR */

        do {

            len = v9fs_co_pwritev(pdu, fidp, qiov.iov, qiov.niov, off);

            if (len >= 0) {

                off   += len;

                total += len;

            }

        } while (len == -EINTR && !pdu->cancelled);

        if (len < 0) {

            /* IO error return the error */

            err = len;

            goto out_qiov;

        }

    } while (total < count && len > 0);

    offset = 7;

    offset += pdu_marshal(pdu, offset, "d", total);

    err = offset;

    trace_v9fs_write_return(pdu->tag, pdu->id, total, err);

out_qiov:

    qemu_iovec_destroy(&qiov);

out:

    put_fid(pdu, fidp);

out_nofid:

    qemu_iovec_destroy(&qiov_full);

    complete_pdu(s, pdu, err);

}


void machine_register_compat_props(MachineState *machine)

{

    MachineClass *mc = MACHINE_GET_CLASS(machine);

    int i;

    GlobalProperty *p;

    if (!mc->compat_props) {

        return;

    }

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

        p = g_array_index(mc->compat_props, GlobalProperty *, i);

        /* Machine compat_props must never cause errors: */

        p->errp = &error_abort;

        qdev_prop_register_global(p);

    }

}


static int win_chr_pipe_init(CharDriverState *chr, const char *filename,

                             Error **errp)

{

    WinCharState *s = chr->opaque;

    OVERLAPPED ov;

    int ret;

    DWORD size;

    char openname[CHR_MAX_FILENAME_SIZE];

    s->fpipe = TRUE;

    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);

    if (!s->hsend) {

        error_setg(errp, "Failed CreateEvent");

        goto fail;

    }

    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);

    if (!s->hrecv) {

        error_setg(errp, "Failed CreateEvent");

        goto fail;

    }

    snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);

    s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,

                              PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |

                              PIPE_WAIT,

                              MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);

    if (s->hcom == INVALID_HANDLE_VALUE) {

        error_setg(errp, "Failed CreateNamedPipe (%lu)", GetLastError());

        s->hcom = NULL;

        goto fail;

    }

    ZeroMemory(&ov, sizeof(ov));

    ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

    ret = ConnectNamedPipe(s->hcom, &ov);

    if (ret) {

        error_setg(errp, "Failed ConnectNamedPipe");

        goto fail;

    }

    ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);

    if (!ret) {

        error_setg(errp, "Failed GetOverlappedResult");

        if (ov.hEvent) {

            CloseHandle(ov.hEvent);

            ov.hEvent = NULL;

        }

        goto fail;

    }

    if (ov.hEvent) {

        CloseHandle(ov.hEvent);

        ov.hEvent = NULL;

    }

    qemu_add_polling_cb(win_chr_pipe_poll, chr);

    return 0;

 fail:

    win_chr_close(chr);

    return -1;

}


static PCIDevice *do_pci_register_device(PCIDevice *pci_dev, PCIBus *bus,

                                         const char *name, int devfn,

                                         Error **errp)

{

    PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);

    PCIConfigReadFunc *config_read = pc->config_read;

    PCIConfigWriteFunc *config_write = pc->config_write;

    Error *local_err = NULL;

    DeviceState *dev = DEVICE(pci_dev);

    pci_dev->bus = bus;

    /* Only pci bridges can be attached to extra PCI root buses */

    if (pci_bus_is_root(bus) && bus->parent_dev && !pc->is_bridge) {

        error_setg(errp,

                   "PCI: Only PCI/PCIe bridges can be plugged into %s",

                    bus->parent_dev->name);

        return NULL;

    }

    if (devfn < 0) {

        for(devfn = bus->devfn_min ; devfn < ARRAY_SIZE(bus->devices);

            devfn += PCI_FUNC_MAX) {

            if (!bus->devices[devfn])

                goto found;

        }

        error_setg(errp, "PCI: no slot/function available for %s, all in use",

                   name);

        return NULL;

    found: ;

    } else if (bus->devices[devfn]) {

        error_setg(errp, "PCI: slot %d function %d not available for %s,"

                   " in use by %s",

                   PCI_SLOT(devfn), PCI_FUNC(devfn), name,

                   bus->devices[devfn]->name);

        return NULL;

    } else if (dev->hotplugged &&

               pci_get_function_0(pci_dev)) {

        error_setg(errp, "PCI: slot %d function 0 already ocuppied by %s,"

                   " new func %s cannot be exposed to guest.",

                   PCI_SLOT(pci_get_function_0(pci_dev)->devfn),

                   pci_get_function_0(pci_dev)->name,

                   name);

       return NULL;

    }

    pci_dev->devfn = devfn;

    pci_dev->requester_id_cache = pci_req_id_cache_get(pci_dev);

    memory_region_init(&pci_dev->bus_master_container_region, OBJECT(pci_dev),

                       "bus master container", UINT64_MAX);

    address_space_init(&pci_dev->bus_master_as,

                       &pci_dev->bus_master_container_region, pci_dev->name);

    if (qdev_hotplug) {

        pci_init_bus_master(pci_dev);

    }

    pstrcpy(pci_dev->name, sizeof(pci_dev->name), name);

    pci_dev->irq_state = 0;

    pci_config_alloc(pci_dev);

    pci_config_set_vendor_id(pci_dev->config, pc->vendor_id);

    pci_config_set_device_id(pci_dev->config, pc->device_id);

    pci_config_set_revision(pci_dev->config, pc->revision);

    pci_config_set_class(pci_dev->config, pc->class_id);

    if (!pc->is_bridge) {

        if (pc->subsystem_vendor_id || pc->subsystem_id) {

            pci_set_word(pci_dev->config + PCI_SUBSYSTEM_VENDOR_ID,

                         pc->subsystem_vendor_id);

            pci_set_word(pci_dev->config + PCI_SUBSYSTEM_ID,

                         pc->subsystem_id);

        } else {

            pci_set_default_subsystem_id(pci_dev);

        }

    } else {

        /* subsystem_vendor_id/subsystem_id are only for header type 0 */

        assert(!pc->subsystem_vendor_id);

        assert(!pc->subsystem_id);

    }

    pci_init_cmask(pci_dev);

    pci_init_wmask(pci_dev);

    pci_init_w1cmask(pci_dev);

    if (pc->is_bridge) {

        pci_init_mask_bridge(pci_dev);

    }

    pci_init_multifunction(bus, pci_dev, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        do_pci_unregister_device(pci_dev);

        return NULL;

    }

    if (!config_read)

        config_read = pci_default_read_config;

    if (!config_write)

        config_write = pci_default_write_config;

    pci_dev->config_read = config_read;

    pci_dev->config_write = config_write;

    bus->devices[devfn] = pci_dev;

    pci_dev->version_id = 2; /* Current pci device vmstate version */

    return pci_dev;

}


int floatx80_lt(floatx80 a, floatx80 b, float_status *status)

{

    flag aSign, bSign;

    if (    (    ( extractFloatx80Exp( a ) == 0x7FFF )

              && (uint64_t) ( extractFloatx80Frac( a )<<1 ) )

         || (    ( extractFloatx80Exp( b ) == 0x7FFF )

              && (uint64_t) ( extractFloatx80Frac( b )<<1 ) )

       ) {

        float_raise(float_flag_invalid, status);

        return 0;

    }

    aSign = extractFloatx80Sign( a );

    bSign = extractFloatx80Sign( b );

    if ( aSign != bSign ) {

        return

               aSign

            && (    ( ( (uint16_t) ( ( a.high | b.high )<<1 ) ) | a.low | b.low )

                 != 0 );

    }

    return

          aSign ? lt128( b.high, b.low, a.high, a.low )

        : lt128( a.high, a.low, b.high, b.low );

}


int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,

                          const char *tag)

{

    while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {

        bs = bs->file;

    }

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

        return bs->drv->bdrv_debug_breakpoint(bs, event, tag);

    }

    return -ENOTSUP;

}


static target_ulong h_add_logical_lan_buffer(PowerPCCPU *cpu,

                                             sPAPRMachineState *spapr,

                                             target_ulong opcode,

                                             target_ulong *args)

{

    target_ulong reg = args[0];

    target_ulong buf = args[1];

    VIOsPAPRDevice *sdev = spapr_vio_find_by_reg(spapr->vio_bus, reg);

    VIOsPAPRVLANDevice *dev = VIO_SPAPR_VLAN_DEVICE(sdev);

    target_long ret;

    DPRINTF("H_ADD_LOGICAL_LAN_BUFFER(0x" TARGET_FMT_lx

            ", 0x" TARGET_FMT_lx ")\n", reg, buf);

    if (!sdev) {

        hcall_dprintf("Bad device\n");

        return H_PARAMETER;

    }

    if ((check_bd(dev, buf, 4) < 0)

        || (VLAN_BD_LEN(buf) < 16)) {

        hcall_dprintf("Bad buffer enqueued\n");

        return H_PARAMETER;

    }

    if (!dev->isopen) {

        return H_RESOURCE;

    }

    ret = spapr_vlan_add_rxbuf_to_page(dev, buf);

    if (ret) {

        return ret;

    }

    dev->rx_bufs++;

    qemu_flush_queued_packets(qemu_get_queue(dev->nic));

    return H_SUCCESS;

}


static void openrisc_pic_cpu_handler(void *opaque, int irq, int level)

{

    OpenRISCCPU *cpu = (OpenRISCCPU *)opaque;

    CPUState *cs = CPU(cpu);

    int i;

    uint32_t irq_bit = 1 << irq;

    if (irq > 31 || irq < 0) {

        return;

    }

    if (level) {

        cpu->env.picsr |= irq_bit;

    } else {

        cpu->env.picsr &= ~irq_bit;

    }

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

        if ((cpu->env.picsr && (1 << i)) && (cpu->env.picmr && (1 << i))) {

            cpu_interrupt(cs, CPU_INTERRUPT_HARD);

        } else {

            cpu_reset_interrupt(cs, CPU_INTERRUPT_HARD);

            cpu->env.picsr &= ~(1 << i);

        }

    }

}


static void virtio_net_tx_bh(void *opaque)

{

    VirtIONetQueue *q = opaque;

    VirtIONet *n = q->n;

    VirtIODevice *vdev = VIRTIO_DEVICE(n);

    int32_t ret;

    assert(vdev->vm_running);

    q->tx_waiting = 0;

    /* Just in case the driver is not ready on more */

    if (unlikely(!(vdev->status & VIRTIO_CONFIG_S_DRIVER_OK))) {

        return;

    }

    ret = virtio_net_flush_tx(q);

    if (ret == -EBUSY) {

        return; /* Notification re-enable handled by tx_complete */

    }

    /* If we flush a full burst of packets, assume there are

     * more coming and immediately reschedule */

    if (ret >= n->tx_burst) {

        qemu_bh_schedule(q->tx_bh);

        q->tx_waiting = 1;

        return;

    }

    /* If less than a full burst, re-enable notification and flush

     * anything that may have come in while we weren't looking.  If

     * we find something, assume the guest is still active and reschedule */

    virtio_queue_set_notification(q->tx_vq, 1);

    if (virtio_net_flush_tx(q) > 0) {

        virtio_queue_set_notification(q->tx_vq, 0);

        qemu_bh_schedule(q->tx_bh);

        q->tx_waiting = 1;

    }

}


static int sclp_parse(const char *devname)

{

    QemuOptsList *device = qemu_find_opts("device");

    static int index = 0;

    char label[32];

    QemuOpts *dev_opts;

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

        return 0;

    }

    if (index == MAX_SCLP_CONSOLES) {

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

        exit(1);

    }

    assert(arch_type == QEMU_ARCH_S390X);

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

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

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

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

    if (!sclp_hds[index]) {

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

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

        return -1;

    }

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

    index++;

    return 0;

}


void arm_gen_test_cc(int cc, int label)

{

    TCGv_i32 tmp;

    int inv;

    switch (cc) {

    case 0: /* eq: Z */

        tcg_gen_brcondi_i32(TCG_COND_EQ, cpu_ZF, 0, label);

        break;

    case 1: /* ne: !Z */

        tcg_gen_brcondi_i32(TCG_COND_NE, cpu_ZF, 0, label);

        break;

    case 2: /* cs: C */

        tcg_gen_brcondi_i32(TCG_COND_NE, cpu_CF, 0, label);

        break;

    case 3: /* cc: !C */

        tcg_gen_brcondi_i32(TCG_COND_EQ, cpu_CF, 0, label);

        break;

    case 4: /* mi: N */

        tcg_gen_brcondi_i32(TCG_COND_LT, cpu_NF, 0, label);

        break;

    case 5: /* pl: !N */

        tcg_gen_brcondi_i32(TCG_COND_GE, cpu_NF, 0, label);

        break;

    case 6: /* vs: V */

        tcg_gen_brcondi_i32(TCG_COND_LT, cpu_VF, 0, label);

        break;

    case 7: /* vc: !V */

        tcg_gen_brcondi_i32(TCG_COND_GE, cpu_VF, 0, label);

        break;

    case 8: /* hi: C && !Z */

        inv = gen_new_label();

        tcg_gen_brcondi_i32(TCG_COND_EQ, cpu_CF, 0, inv);

        tcg_gen_brcondi_i32(TCG_COND_NE, cpu_ZF, 0, label);

        gen_set_label(inv);

        break;

    case 9: /* ls: !C || Z */

        tcg_gen_brcondi_i32(TCG_COND_EQ, cpu_CF, 0, label);

        tcg_gen_brcondi_i32(TCG_COND_EQ, cpu_ZF, 0, label);

        break;

    case 10: /* ge: N == V -> N ^ V == 0 */

        tmp = tcg_temp_new_i32();

        tcg_gen_xor_i32(tmp, cpu_VF, cpu_NF);

        tcg_gen_brcondi_i32(TCG_COND_GE, tmp, 0, label);

        tcg_temp_free_i32(tmp);

        break;

    case 11: /* lt: N != V -> N ^ V != 0 */

        tmp = tcg_temp_new_i32();

        tcg_gen_xor_i32(tmp, cpu_VF, cpu_NF);

        tcg_gen_brcondi_i32(TCG_COND_LT, tmp, 0, label);

        tcg_temp_free_i32(tmp);

        break;

    case 12: /* gt: !Z && N == V */

        inv = gen_new_label();

        tcg_gen_brcondi_i32(TCG_COND_EQ, cpu_ZF, 0, inv);

        tmp = tcg_temp_new_i32();

        tcg_gen_xor_i32(tmp, cpu_VF, cpu_NF);

        tcg_gen_brcondi_i32(TCG_COND_GE, tmp, 0, label);

        tcg_temp_free_i32(tmp);

        gen_set_label(inv);

        break;

    case 13: /* le: Z || N != V */

        tcg_gen_brcondi_i32(TCG_COND_EQ, cpu_ZF, 0, label);

        tmp = tcg_temp_new_i32();

        tcg_gen_xor_i32(tmp, cpu_VF, cpu_NF);

        tcg_gen_brcondi_i32(TCG_COND_LT, tmp, 0, label);

        tcg_temp_free_i32(tmp);

        break;

    default:

        fprintf(stderr, "Bad condition code 0x%x\n", cc);

        abort();

    }

}


void ide_init_drive(IDEState *s, DriveInfo *dinfo, const char *version)

{

    int cylinders, heads, secs;

    uint64_t nb_sectors;

    if (dinfo && dinfo->bdrv) {

        s->bs = dinfo->bdrv;

        bdrv_get_geometry(s->bs, &nb_sectors);

        bdrv_guess_geometry(s->bs, &cylinders, &heads, &secs);

        s->cylinders = cylinders;

        s->heads = heads;

        s->sectors = secs;

        s->nb_sectors = nb_sectors;

        /* The SMART values should be preserved across power cycles

           but they aren't.  */

        s->smart_enabled = 1;

        s->smart_autosave = 1;

        s->smart_errors = 0;

        s->smart_selftest_count = 0;

        if (bdrv_get_type_hint(s->bs) == BDRV_TYPE_CDROM) {

            s->is_cdrom = 1;

            bdrv_set_change_cb(s->bs, cdrom_change_cb, s);

        }

        strncpy(s->drive_serial_str, drive_get_serial(s->bs),

                sizeof(s->drive_serial_str));

    }

    if (strlen(s->drive_serial_str) == 0)

        snprintf(s->drive_serial_str, sizeof(s->drive_serial_str),

                 "QM%05d", s->drive_serial);

    if (version) {

        pstrcpy(s->version, sizeof(s->version), version);

    } else {

        pstrcpy(s->version, sizeof(s->version), QEMU_VERSION);

    }

    ide_reset(s);

}


static void ppc_heathrow_init(QEMUMachineInitArgs *args)

{

    ram_addr_t ram_size = args->ram_size;

    const char *cpu_model = args->cpu_model;

    const char *kernel_filename = args->kernel_filename;

    const char *kernel_cmdline = args->kernel_cmdline;

    const char *initrd_filename = args->initrd_filename;

    const char *boot_device = args->boot_device;

    MemoryRegion *sysmem = get_system_memory();

    PowerPCCPU *cpu = NULL;

    CPUPPCState *env = NULL;

    char *filename;

    qemu_irq *pic, **heathrow_irqs;

    int linux_boot, i;

    MemoryRegion *ram = g_new(MemoryRegion, 1);

    MemoryRegion *bios = g_new(MemoryRegion, 1);

    MemoryRegion *isa = g_new(MemoryRegion, 1);

    uint32_t kernel_base, initrd_base, cmdline_base = 0;

    int32_t kernel_size, initrd_size;

    PCIBus *pci_bus;

    PCIDevice *macio;

    MACIOIDEState *macio_ide;

    DeviceState *dev;

    BusState *adb_bus;

    int bios_size;

    MemoryRegion *pic_mem;

    MemoryRegion *escc_mem, *escc_bar = g_new(MemoryRegion, 1);

    uint16_t ppc_boot_device;

    DriveInfo *hd[MAX_IDE_BUS * MAX_IDE_DEVS];

    void *fw_cfg;

    linux_boot = (kernel_filename != NULL);

    /* init CPUs */

    if (cpu_model == NULL)

        cpu_model = "G3";

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

        cpu = cpu_ppc_init(cpu_model);

        if (cpu == NULL) {

            fprintf(stderr, "Unable to find PowerPC CPU definition\n");

            exit(1);

        }

        env = &cpu->env;

        /* Set time-base frequency to 16.6 Mhz */

        cpu_ppc_tb_init(env,  TBFREQ);

        qemu_register_reset(ppc_heathrow_reset, cpu);

    }

    /* allocate RAM */

    if (ram_size > (2047 << 20)) {

        fprintf(stderr,

                "qemu: Too much memory for this machine: %d MB, maximum 2047 MB\n",

                ((unsigned int)ram_size / (1 << 20)));

        exit(1);

    }

    memory_region_init_ram(ram, NULL, "ppc_heathrow.ram", ram_size);

    vmstate_register_ram_global(ram);

    memory_region_add_subregion(sysmem, 0, ram);

    /* allocate and load BIOS */

    memory_region_init_ram(bios, NULL, "ppc_heathrow.bios", BIOS_SIZE);

    vmstate_register_ram_global(bios);

    if (bios_name == NULL)

        bios_name = PROM_FILENAME;

    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);

    memory_region_set_readonly(bios, true);

    memory_region_add_subregion(sysmem, PROM_ADDR, bios);

    /* Load OpenBIOS (ELF) */

    if (filename) {

        bios_size = load_elf(filename, 0, NULL, NULL, NULL, NULL,

                             1, ELF_MACHINE, 0);

        g_free(filename);

    } else {

        bios_size = -1;

    }

    if (bios_size < 0 || bios_size > BIOS_SIZE) {

        hw_error("qemu: could not load PowerPC bios '%s'\n", bios_name);

        exit(1);

    }

    if (linux_boot) {

        uint64_t lowaddr = 0;

        int bswap_needed;

#ifdef BSWAP_NEEDED

        bswap_needed = 1;

#else

        bswap_needed = 0;

#endif

        kernel_base = KERNEL_LOAD_ADDR;

        kernel_size = load_elf(kernel_filename, translate_kernel_address, NULL,

                               NULL, &lowaddr, NULL, 1, ELF_MACHINE, 0);

        if (kernel_size < 0)

            kernel_size = load_aout(kernel_filename, kernel_base,

                                    ram_size - kernel_base, bswap_needed,

                                    TARGET_PAGE_SIZE);

        if (kernel_size < 0)

            kernel_size = load_image_targphys(kernel_filename,

                                              kernel_base,

                                              ram_size - kernel_base);

        if (kernel_size < 0) {

            hw_error("qemu: could not load kernel '%s'\n",

                      kernel_filename);

            exit(1);

        }

        /* load initrd */

        if (initrd_filename) {

            initrd_base = round_page(kernel_base + kernel_size + KERNEL_GAP);

            initrd_size = load_image_targphys(initrd_filename, initrd_base,

                                              ram_size - initrd_base);

            if (initrd_size < 0) {

                hw_error("qemu: could not load initial ram disk '%s'\n",

                         initrd_filename);

                exit(1);

            }

            cmdline_base = round_page(initrd_base + initrd_size);

        } else {

            initrd_base = 0;

            initrd_size = 0;

            cmdline_base = round_page(kernel_base + kernel_size + KERNEL_GAP);

        }

        ppc_boot_device = 'm';

    } else {

        kernel_base = 0;

        kernel_size = 0;

        initrd_base = 0;

        initrd_size = 0;

        ppc_boot_device = '\0';

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

            /* TOFIX: for now, the second IDE channel is not properly

             *        used by OHW. The Mac floppy disk are not emulated.

             *        For now, OHW cannot boot from the network.

             */

#if 0

            if (boot_device[i] >= 'a' && boot_device[i] <= 'f') {

                ppc_boot_device = boot_device[i];

                break;

            }

#else

            if (boot_device[i] >= 'c' && boot_device[i] <= 'd') {

                ppc_boot_device = boot_device[i];

                break;

            }

#endif

        }

        if (ppc_boot_device == '\0') {

            fprintf(stderr, "No valid boot device for G3 Beige machine\n");

            exit(1);

        }

    }

    /* Register 2 MB of ISA IO space */

    memory_region_init_alias(isa, NULL, "isa_mmio",

                             get_system_io(), 0, 0x00200000);

    memory_region_add_subregion(sysmem, 0xfe000000, isa);

    /* XXX: we register only 1 output pin for heathrow PIC */

    heathrow_irqs = g_malloc0(smp_cpus * sizeof(qemu_irq *));

    heathrow_irqs[0] =

        g_malloc0(smp_cpus * sizeof(qemu_irq) * 1);

    /* Connect the heathrow PIC outputs to the 6xx bus */

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

        switch (PPC_INPUT(env)) {

        case PPC_FLAGS_INPUT_6xx:

            heathrow_irqs[i] = heathrow_irqs[0] + (i * 1);

            heathrow_irqs[i][0] =

                ((qemu_irq *)env->irq_inputs)[PPC6xx_INPUT_INT];

            break;

        default:

            hw_error("Bus model not supported on OldWorld Mac machine\n");

        }

    }

    /* init basic PC hardware */

    if (PPC_INPUT(env) != PPC_FLAGS_INPUT_6xx) {

        hw_error("Only 6xx bus is supported on heathrow machine\n");

    }

    pic = heathrow_pic_init(&pic_mem, 1, heathrow_irqs);

    pci_bus = pci_grackle_init(0xfec00000, pic,

                               get_system_memory(),

                               get_system_io());

    pci_vga_init(pci_bus);

    escc_mem = escc_init(0, pic[0x0f], pic[0x10], serial_hds[0],

                               serial_hds[1], ESCC_CLOCK, 4);

    memory_region_init_alias(escc_bar, NULL, "escc-bar",

                             escc_mem, 0, memory_region_size(escc_mem));

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

        pci_nic_init_nofail(&nd_table[i], pci_bus, "ne2k_pci", NULL);

    ide_drive_get(hd, MAX_IDE_BUS);

    macio = pci_create(pci_bus, -1, TYPE_OLDWORLD_MACIO);

    dev = DEVICE(macio);

    qdev_connect_gpio_out(dev, 0, pic[0x12]); /* CUDA */

    qdev_connect_gpio_out(dev, 1, pic[0x0D]); /* IDE-0 */

    qdev_connect_gpio_out(dev, 2, pic[0x02]); /* IDE-0 DMA */

    qdev_connect_gpio_out(dev, 3, pic[0x0E]); /* IDE-1 */

    qdev_connect_gpio_out(dev, 4, pic[0x03]); /* IDE-1 DMA */

    macio_init(macio, pic_mem, escc_bar);

    macio_ide = MACIO_IDE(object_resolve_path_component(OBJECT(macio),

                                                        "ide[0]"));

    macio_ide_init_drives(macio_ide, hd);

    macio_ide = MACIO_IDE(object_resolve_path_component(OBJECT(macio),

                                                        "ide[1]"));

    macio_ide_init_drives(macio_ide, &hd[MAX_IDE_DEVS]);

    dev = DEVICE(object_resolve_path_component(OBJECT(macio), "cuda"));

    adb_bus = qdev_get_child_bus(dev, "adb.0");

    dev = qdev_create(adb_bus, TYPE_ADB_KEYBOARD);

    qdev_init_nofail(dev);

    dev = qdev_create(adb_bus, TYPE_ADB_MOUSE);

    qdev_init_nofail(dev);

    if (usb_enabled(false)) {

        pci_create_simple(pci_bus, -1, "pci-ohci");

    }

    if (graphic_depth != 15 && graphic_depth != 32 && graphic_depth != 8)

        graphic_depth = 15;

    /* No PCI init: the BIOS will do it */

    fw_cfg = fw_cfg_init(0, 0, CFG_ADDR, CFG_ADDR + 2);

    fw_cfg_add_i16(fw_cfg, FW_CFG_MAX_CPUS, (uint16_t)max_cpus);

    fw_cfg_add_i32(fw_cfg, FW_CFG_ID, 1);

    fw_cfg_add_i64(fw_cfg, FW_CFG_RAM_SIZE, (uint64_t)ram_size);

    fw_cfg_add_i16(fw_cfg, FW_CFG_MACHINE_ID, ARCH_HEATHROW);

    fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_ADDR, kernel_base);

    fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_SIZE, kernel_size);

    if (kernel_cmdline) {

        fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_CMDLINE, cmdline_base);

        pstrcpy_targphys("cmdline", cmdline_base, TARGET_PAGE_SIZE, kernel_cmdline);

    } else {

        fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_CMDLINE, 0);

    }

    fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_ADDR, initrd_base);

    fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_SIZE, initrd_size);

    fw_cfg_add_i16(fw_cfg, FW_CFG_BOOT_DEVICE, ppc_boot_device);

    fw_cfg_add_i16(fw_cfg, FW_CFG_PPC_WIDTH, graphic_width);

    fw_cfg_add_i16(fw_cfg, FW_CFG_PPC_HEIGHT, graphic_height);

    fw_cfg_add_i16(fw_cfg, FW_CFG_PPC_DEPTH, graphic_depth);

    fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_IS_KVM, kvm_enabled());

    if (kvm_enabled()) {

#ifdef CONFIG_KVM

        uint8_t *hypercall;

        fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_TBFREQ, kvmppc_get_tbfreq());

        hypercall = g_malloc(16);

        kvmppc_get_hypercall(env, hypercall, 16);

        fw_cfg_add_bytes(fw_cfg, FW_CFG_PPC_KVM_HC, hypercall, 16);

        fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_KVM_PID, getpid());

#endif

    } else {

        fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_TBFREQ, TBFREQ);

    }

    /* Mac OS X requires a "known good" clock-frequency value; pass it one. */

    fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_CLOCKFREQ, 266000000);

    qemu_register_boot_set(fw_cfg_boot_set, fw_cfg);

}


static void synthfilt_build_sb_samples(QDM2Context *q, GetBitContext *gb,

                                       int length, int sb_min, int sb_max)

{

    int sb, j, k, n, ch, run, channels;

    int joined_stereo, zero_encoding, chs;

    int type34_first;

    float type34_div = 0;

    float type34_predictor;

    float samples[10], sign_bits[16];

    if (length == 0) {

        // If no data use noise

        for (sb=sb_min; sb < sb_max; sb++)

            build_sb_samples_from_noise (q, sb);

        return;

    }

    for (sb = sb_min; sb < sb_max; sb++) {

        FIX_NOISE_IDX(q->noise_idx);

        channels = q->nb_channels;

        if (q->nb_channels <= 1 || sb < 12)

            joined_stereo = 0;

        else if (sb >= 24)

            joined_stereo = 1;

        else

            joined_stereo = (get_bits_left(gb) >= 1) ? get_bits1 (gb) : 0;

        if (joined_stereo) {

            if (get_bits_left(gb) >= 16)

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

                    sign_bits[j] = get_bits1 (gb);

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

                if (q->coding_method[1][sb][j] > q->coding_method[0][sb][j])

                    q->coding_method[0][sb][j] = q->coding_method[1][sb][j];

            fix_coding_method_array(sb, q->nb_channels, q->coding_method);

            channels = 1;

        }

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

            zero_encoding = (get_bits_left(gb) >= 1) ? get_bits1(gb) : 0;

            type34_predictor = 0.0;

            type34_first = 1;

            for (j = 0; j < 128; ) {

                switch (q->coding_method[ch][sb][j / 2]) {

                    case 8:

                        if (get_bits_left(gb) >= 10) {

                            if (zero_encoding) {

                                for (k = 0; k < 5; k++) {

                                    if ((j + 2 * k) >= 128)

                                        break;

                                    samples[2 * k] = get_bits1(gb) ? dequant_1bit[joined_stereo][2 * get_bits1(gb)] : 0;

                                }

                            } else {

                                n = get_bits(gb, 8);

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

                                    samples[2 * k] = dequant_1bit[joined_stereo][random_dequant_index[n][k]];

                            }

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

                                samples[2 * k + 1] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        } else {

                            for (k = 0; k < 10; k++)

                                samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        }

                        run = 10;

                        break;

                    case 10:

                        if (get_bits_left(gb) >= 1) {

                            float f = 0.81;

                            if (get_bits1(gb))

                                f = -f;

                            f -= noise_samples[((sb + 1) * (j +5 * ch + 1)) & 127] * 9.0 / 40.0;

                            samples[0] = f;

                        } else {

                            samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        }

                        run = 1;

                        break;

                    case 16:

                        if (get_bits_left(gb) >= 10) {

                            if (zero_encoding) {

                                for (k = 0; k < 5; k++) {

                                    if ((j + k) >= 128)

                                        break;

                                    samples[k] = (get_bits1(gb) == 0) ? 0 : dequant_1bit[joined_stereo][2 * get_bits1(gb)];

                                }

                            } else {

                                n = get_bits (gb, 8);

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

                                    samples[k] = dequant_1bit[joined_stereo][random_dequant_index[n][k]];

                            }

                        } else {

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

                                samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        }

                        run = 5;

                        break;

                    case 24:

                        if (get_bits_left(gb) >= 7) {

                            n = get_bits(gb, 7);

                            for (k = 0; k < 3; k++)

                                samples[k] = (random_dequant_type24[n][k] - 2.0) * 0.5;

                        } else {

                            for (k = 0; k < 3; k++)

                                samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        }

                        run = 3;

                        break;

                    case 30:

                        if (get_bits_left(gb) >= 4) {

                            unsigned index = qdm2_get_vlc(gb, &vlc_tab_type30, 0, 1);

                            if (index < FF_ARRAY_ELEMS(type30_dequant)) {

                                samples[0] = type30_dequant[index];

                            } else

                                samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        } else

                            samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        run = 1;

                        break;

                    case 34:

                        if (get_bits_left(gb) >= 7) {

                            if (type34_first) {

                                type34_div = (float)(1 << get_bits(gb, 2));

                                samples[0] = ((float)get_bits(gb, 5) - 16.0) / 15.0;

                                type34_predictor = samples[0];

                                type34_first = 0;

                            } else {

                                unsigned index = qdm2_get_vlc(gb, &vlc_tab_type34, 0, 1);

                                if (index < FF_ARRAY_ELEMS(type34_delta)) {

                                    samples[0] = type34_delta[index] / type34_div + type34_predictor;

                                    type34_predictor = samples[0];

                                } else

                                    samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);

                            }

                        } else {

                            samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        }

                        run = 1;

                        break;

                    default:

                        samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        run = 1;

                        break;

                }

                if (joined_stereo) {

                    float tmp[10][MPA_MAX_CHANNELS];

                    for (k = 0; k < run; k++) {

                        tmp[k][0] = samples[k];

                        tmp[k][1] = (sign_bits[(j + k) / 8]) ? -samples[k] : samples[k];

                    }

                    for (chs = 0; chs < q->nb_channels; chs++)

                        for (k = 0; k < run; k++)

                            if ((j + k) < 128)

                                q->sb_samples[chs][j + k][sb] = q->tone_level[chs][sb][((j + k)/2)] * tmp[k][chs];

                } else {

                    for (k = 0; k < run; k++)

                        if ((j + k) < 128)

                            q->sb_samples[ch][j + k][sb] = q->tone_level[ch][sb][(j + k)/2] * samples[k];

                }

                j += run;

            } // j loop

        } // channel loop

    } // subband loop

}


void usb_desc_create_serial(USBDevice *dev)

{

    DeviceState *hcd = dev->qdev.parent_bus->parent;

    const USBDesc *desc = usb_device_get_usb_desc(dev);

    int index = desc->id.iSerialNumber;

    char serial[64];

    char *path;

    int dst;

    if (dev->serial) {

        /* 'serial' usb bus property has priority if present */

        usb_desc_set_string(dev, index, dev->serial);

        return;

    }

    assert(index != 0 && desc->str[index] != NULL);

    dst = snprintf(serial, sizeof(serial), "%s", desc->str[index]);

    path = qdev_get_dev_path(hcd);

    if (path) {

        dst += snprintf(serial+dst, sizeof(serial)-dst, "-%s", path);

    }

    dst += snprintf(serial+dst, sizeof(serial)-dst, "-%s", dev->port->path);

    usb_desc_set_string(dev, index, serial);

    g_free(path);

}


static void xics_kvm_cpu_setup(XICSState *xics, PowerPCCPU *cpu)

{

    CPUState *cs;

    ICPState *ss;

    KVMXICSState *xicskvm = XICS_SPAPR_KVM(xics);

    cs = CPU(cpu);

    ss = &xics->ss[cs->cpu_index];

    assert(cs->cpu_index < xics->nr_servers);

    if (xicskvm->kernel_xics_fd == -1) {

        abort();

    }

    /*

     * If we are reusing a parked vCPU fd corresponding to the CPU

     * which was hot-removed earlier we don't have to renable

     * KVM_CAP_IRQ_XICS capability again.

     */

    if (ss->cap_irq_xics_enabled) {

        return;

    }

    if (xicskvm->kernel_xics_fd != -1) {

        int ret;

        ret = kvm_vcpu_enable_cap(cs, KVM_CAP_IRQ_XICS, 0,

                                  xicskvm->kernel_xics_fd,

                                  kvm_arch_vcpu_id(cs));

        if (ret < 0) {

            error_report("Unable to connect CPU%ld to kernel XICS: %s",

                    kvm_arch_vcpu_id(cs), strerror(errno));

            exit(1);

        }

        ss->cap_irq_xics_enabled = true;

    }

}


static inline void tcg_out_ldst(TCGContext *s, int ret, int addr,

                                int offset, int op)

{

    if (check_fit_tl(offset, 13)) {

        tcg_out32(s, op | INSN_RD(ret) | INSN_RS1(addr) |

                  INSN_IMM13(offset));

    } else {

        tcg_out_movi(s, TCG_TYPE_PTR, TCG_REG_T1, offset);

        tcg_out_ldst_rr(s, ret, addr, TCG_REG_T1, op);

    }

}