static int encode_dvb_subtitles(DVBSubtitleContext *s,

                                uint8_t *outbuf, const AVSubtitle *h)

{

    uint8_t *q, *pseg_len;

    int page_id, region_id, clut_id, object_id, i, bpp_index, page_state;

    q = outbuf;

    page_id = 1;

    if (h->num_rects == 0 || h->rects == NULL)

        return -1;

    *q++ = 0x00; /* subtitle_stream_id */

    /* page composition segment */

    *q++ = 0x0f; /* sync_byte */

    *q++ = 0x10; /* segment_type */

    bytestream_put_be16(&q, page_id);

    pseg_len = q;

    q += 2; /* segment length */

    *q++ = 30; /* page_timeout (seconds) */

    if (s->hide_state)

        page_state = 0; /* normal case */

    else

        page_state = 2; /* mode change */

    /* page_version = 0 + page_state */

    *q++ = (s->object_version << 4) | (page_state << 2) | 3;

    for (region_id = 0; region_id < h->num_rects; region_id++) {

        *q++ = region_id;

        *q++ = 0xff; /* reserved */

        bytestream_put_be16(&q, h->rects[region_id]->x); /* left pos */

        bytestream_put_be16(&q, h->rects[region_id]->y); /* top pos */

    }

    bytestream_put_be16(&pseg_len, q - pseg_len - 2);

    if (!s->hide_state) {

        for (clut_id = 0; clut_id < h->num_rects; clut_id++) {

            /* CLUT segment */

            if (h->rects[clut_id]->nb_colors <= 4) {

                /* 2 bpp, some decoders do not support it correctly */

                bpp_index = 0;

            } else if (h->rects[clut_id]->nb_colors <= 16) {

                /* 4 bpp, standard encoding */

                bpp_index = 1;

            } else {

                return -1;

            }

            *q++ = 0x0f; /* sync byte */

            *q++ = 0x12; /* CLUT definition segment */

            bytestream_put_be16(&q, page_id);

            pseg_len = q;

            q += 2; /* segment length */

            *q++ = clut_id;

            *q++ = (0 << 4) | 0xf; /* version = 0 */

            for(i = 0; i < h->rects[clut_id]->nb_colors; i++) {

                *q++ = i; /* clut_entry_id */

                *q++ = (1 << (7 - bpp_index)) | (0xf << 1) | 1; /* 2 bits/pixel full range */

                {

                    int a, r, g, b;

                    uint32_t x= ((uint32_t*)h->rects[clut_id]->pict.data[1])[i];

                    a = (x >> 24) & 0xff;

                    r = (x >> 16) & 0xff;

                    g = (x >>  8) & 0xff;

                    b = (x >>  0) & 0xff;

                    *q++ = RGB_TO_Y_CCIR(r, g, b);

                    *q++ = RGB_TO_V_CCIR(r, g, b, 0);

                    *q++ = RGB_TO_U_CCIR(r, g, b, 0);

                    *q++ = 255 - a;

                }

            }

            bytestream_put_be16(&pseg_len, q - pseg_len - 2);

        }

    }

    for (region_id = 0; region_id < h->num_rects; region_id++) {

        /* region composition segment */

        if (h->rects[region_id]->nb_colors <= 4) {

            /* 2 bpp, some decoders do not support it correctly */

            bpp_index = 0;

        } else if (h->rects[region_id]->nb_colors <= 16) {

            /* 4 bpp, standard encoding */

            bpp_index = 1;

        } else {

            return -1;

        }

        *q++ = 0x0f; /* sync_byte */

        *q++ = 0x11; /* segment_type */

        bytestream_put_be16(&q, page_id);

        pseg_len = q;

        q += 2; /* segment length */

        *q++ = region_id;

        *q++ = (s->object_version << 4) | (0 << 3) | 0x07; /* version , no fill */

        bytestream_put_be16(&q, h->rects[region_id]->w); /* region width */

        bytestream_put_be16(&q, h->rects[region_id]->h); /* region height */

        *q++ = ((1 + bpp_index) << 5) | ((1 + bpp_index) << 2) | 0x03;

        *q++ = region_id; /* clut_id == region_id */

        *q++ = 0; /* 8 bit fill colors */

        *q++ = 0x03; /* 4 bit and 2 bit fill colors */

        if (!s->hide_state) {

            bytestream_put_be16(&q, region_id); /* object_id == region_id */

            *q++ = (0 << 6) | (0 << 4);

            *q++ = 0;

            *q++ = 0xf0;

            *q++ = 0;

        }

        bytestream_put_be16(&pseg_len, q - pseg_len - 2);

    }

    if (!s->hide_state) {

        for (object_id = 0; object_id < h->num_rects; object_id++) {

            /* Object Data segment */

            if (h->rects[object_id]->nb_colors <= 4) {

                /* 2 bpp, some decoders do not support it correctly */

                bpp_index = 0;

            } else if (h->rects[object_id]->nb_colors <= 16) {

                /* 4 bpp, standard encoding */

                bpp_index = 1;

            } else {

                return -1;

            }

            *q++ = 0x0f; /* sync byte */

            *q++ = 0x13;

            bytestream_put_be16(&q, page_id);

            pseg_len = q;

            q += 2; /* segment length */

            bytestream_put_be16(&q, object_id);

            *q++ = (s->object_version << 4) | (0 << 2) | (0 << 1) | 1; /* version = 0,

                                                                       onject_coding_method,

                                                                       non_modifying_color_flag */

            {

                uint8_t *ptop_field_len, *pbottom_field_len, *top_ptr, *bottom_ptr;

                void (*dvb_encode_rle)(uint8_t **pq,

                                        const uint8_t *bitmap, int linesize,

                                        int w, int h);

                ptop_field_len = q;

                q += 2;

                pbottom_field_len = q;

                q += 2;

                if (bpp_index == 0)

                    dvb_encode_rle = dvb_encode_rle2;

                else

                    dvb_encode_rle = dvb_encode_rle4;

                top_ptr = q;

                dvb_encode_rle(&q, h->rects[object_id]->pict.data[0], h->rects[object_id]->w * 2,

                                    h->rects[object_id]->w, h->rects[object_id]->h >> 1);

                bottom_ptr = q;

                dvb_encode_rle(&q, h->rects[object_id]->pict.data[0] + h->rects[object_id]->w,

                                    h->rects[object_id]->w * 2, h->rects[object_id]->w,

                                    h->rects[object_id]->h >> 1);

                bytestream_put_be16(&ptop_field_len, bottom_ptr - top_ptr);

                bytestream_put_be16(&pbottom_field_len, q - bottom_ptr);

            }

            bytestream_put_be16(&pseg_len, q - pseg_len - 2);

        }

    }

    /* end of display set segment */

    *q++ = 0x0f; /* sync_byte */

    *q++ = 0x80; /* segment_type */

    bytestream_put_be16(&q, page_id);

    pseg_len = q;

    q += 2; /* segment length */

    bytestream_put_be16(&pseg_len, q - pseg_len - 2);

    *q++ = 0xff; /* end of PES data */

    s->object_version = (s->object_version + 1) & 0xf;

    s->hide_state = !s->hide_state;

    return q - outbuf;

}


int ff_rtsp_open_transport_ctx(AVFormatContext *s, RTSPStream *rtsp_st)

{

    RTSPState *rt = s->priv_data;

    AVStream *st = NULL;

    int reordering_queue_size = rt->reordering_queue_size;

    if (reordering_queue_size < 0) {

        if (rt->lower_transport == RTSP_LOWER_TRANSPORT_TCP || !s->max_delay)

            reordering_queue_size = 0;

        else

            reordering_queue_size = RTP_REORDER_QUEUE_DEFAULT_SIZE;

    }

    /* open the RTP context */

    if (rtsp_st->stream_index >= 0)

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

    if (!st)

        s->ctx_flags |= AVFMTCTX_NOHEADER;

    if (CONFIG_RTSP_MUXER && s->oformat) {

        int ret = ff_rtp_chain_mux_open((AVFormatContext **)&rtsp_st->transport_priv,

                                        s, st, rtsp_st->rtp_handle,

                                        RTSP_TCP_MAX_PACKET_SIZE,

                                        rtsp_st->stream_index);

        /* Ownership of rtp_handle is passed to the rtp mux context */

        rtsp_st->rtp_handle = NULL;

        if (ret < 0)

            return ret;

        st->time_base = ((AVFormatContext*)rtsp_st->transport_priv)->streams[0]->time_base;

    } else if (rt->transport == RTSP_TRANSPORT_RAW) {

        return 0; // Don't need to open any parser here

    } else if (CONFIG_RTPDEC && rt->transport == RTSP_TRANSPORT_RDT)

        rtsp_st->transport_priv = ff_rdt_parse_open(s, st->index,

                                            rtsp_st->dynamic_protocol_context,

                                            rtsp_st->dynamic_handler);

    else if (CONFIG_RTPDEC)

        rtsp_st->transport_priv = ff_rtp_parse_open(s, st,

                                         rtsp_st->sdp_payload_type,

                                         reordering_queue_size);

    if (!rtsp_st->transport_priv) {

         return AVERROR(ENOMEM);

    } else if (CONFIG_RTPDEC && rt->transport == RTSP_TRANSPORT_RTP) {

        if (rtsp_st->dynamic_handler) {

            ff_rtp_parse_set_dynamic_protocol(rtsp_st->transport_priv,

                                              rtsp_st->dynamic_protocol_context,

                                              rtsp_st->dynamic_handler);

        }

        if (rtsp_st->crypto_suite[0])

            ff_rtp_parse_set_crypto(rtsp_st->transport_priv,

                                    rtsp_st->crypto_suite,

                                    rtsp_st->crypto_params);

    }

    return 0;

}


int ff_h264_set_parameter_from_sps(H264Context *h)

{

    if (h->flags & CODEC_FLAG_LOW_DELAY ||

        (h->sps.bitstream_restriction_flag &&

         !h->sps.num_reorder_frames)) {

        if (h->avctx->has_b_frames > 1 || h->delayed_pic[0])

            av_log(h->avctx, AV_LOG_WARNING, "Delayed frames seen. "

                   "Reenabling low delay requires a codec flush.\n");

        else

            h->low_delay = 1;

    }

    if (h->avctx->has_b_frames < 2)

        h->avctx->has_b_frames = !h->low_delay;

    if (h->avctx->bits_per_raw_sample != h->sps.bit_depth_luma ||

        h->cur_chroma_format_idc      != h->sps.chroma_format_idc) {

        if (h->sps.bit_depth_luma >= 8 && h->sps.bit_depth_luma <= 10) {

            h->avctx->bits_per_raw_sample = h->sps.bit_depth_luma;

            h->cur_chroma_format_idc      = h->sps.chroma_format_idc;

            h->pixel_shift                = h->sps.bit_depth_luma > 8;

            ff_h264dsp_init(&h->h264dsp, h->sps.bit_depth_luma,

                            h->sps.chroma_format_idc);

            ff_h264chroma_init(&h->h264chroma, h->sps.bit_depth_chroma);

            ff_h264qpel_init(&h->h264qpel, h->sps.bit_depth_luma);

            ff_h264_pred_init(&h->hpc, h->avctx->codec_id, h->sps.bit_depth_luma,

                              h->sps.chroma_format_idc);

            if (CONFIG_ERROR_RESILIENCE)

                ff_me_cmp_init(&h->mecc, h->avctx);

            ff_videodsp_init(&h->vdsp, h->sps.bit_depth_luma);

        } else {

            av_log(h->avctx, AV_LOG_ERROR, "Unsupported bit depth %d\n",

                   h->sps.bit_depth_luma);

            return AVERROR_INVALIDDATA;

        }

    }

    return 0;

}


void ff_weight_h264_pixels4_8_msa(uint8_t *src, int stride,

                                  int height, int log2_denom,

                                  int weight_src, int offset)

{

    avc_wgt_4width_msa(src, stride,

                       height, log2_denom, weight_src, offset);

}


static av_cold int vaapi_encode_h265_init_constant_bitrate(AVCodecContext *avctx)

{

    VAAPIEncodeContext      *ctx = avctx->priv_data;

    VAAPIEncodeH265Context *priv = ctx->priv_data;

    int hrd_buffer_size;

    int hrd_initial_buffer_fullness;

    if (avctx->bit_rate > INT32_MAX) {

        av_log(avctx, AV_LOG_ERROR, "Target bitrate of 2^31 bps or "

               "higher is not supported.\n");

        return AVERROR(EINVAL);

    }

    if (avctx->rc_buffer_size)

        hrd_buffer_size = avctx->rc_buffer_size;

    else

        hrd_buffer_size = avctx->bit_rate;

    if (avctx->rc_initial_buffer_occupancy)

        hrd_initial_buffer_fullness = avctx->rc_initial_buffer_occupancy;

    else

        hrd_initial_buffer_fullness = hrd_buffer_size * 3 / 4;

    priv->rc_params.misc.type = VAEncMiscParameterTypeRateControl;

    priv->rc_params.rc = (VAEncMiscParameterRateControl) {

        .bits_per_second   = avctx->bit_rate,

        .target_percentage = 66,

        .window_size       = 1000,

        .initial_qp        = (avctx->qmax >= 0 ? avctx->qmax : 40),

        .min_qp            = (avctx->qmin >= 0 ? avctx->qmin : 20),

        .basic_unit_size   = 0,

    };

    ctx->global_params[ctx->nb_global_params] =

        &priv->rc_params.misc;

    ctx->global_params_size[ctx->nb_global_params++] =

        sizeof(priv->rc_params);

    priv->hrd_params.misc.type = VAEncMiscParameterTypeHRD;

    priv->hrd_params.hrd = (VAEncMiscParameterHRD) {

        .initial_buffer_fullness = hrd_initial_buffer_fullness,

        .buffer_size             = hrd_buffer_size,

    };

    ctx->global_params[ctx->nb_global_params] =

        &priv->hrd_params.misc;

    ctx->global_params_size[ctx->nb_global_params++] =

        sizeof(priv->hrd_params);

    // These still need to be  set for pic_init_qp/slice_qp_delta.

    priv->fixed_qp_idr = 30;

    priv->fixed_qp_p   = 30;

    priv->fixed_qp_b   = 30;

    av_log(avctx, AV_LOG_DEBUG, "Using constant-bitrate = %"PRId64" bps.\n",

           avctx->bit_rate);

    return 0;

}


static int filter_query_formats(AVFilterContext *ctx)

{

    int ret, i;

    AVFilterFormats *formats;

    AVFilterChannelLayouts *chlayouts;

    AVFilterFormats *samplerates;

    enum AVMediaType type = ctx->inputs  && ctx->inputs [0] ? ctx->inputs [0]->type :

                            ctx->outputs && ctx->outputs[0] ? ctx->outputs[0]->type :

                            AVMEDIA_TYPE_VIDEO;

    if ((ret = ctx->filter->query_formats(ctx)) < 0) {

        av_log(ctx, AV_LOG_ERROR, "Query format failed for '%s': %s\n",

               ctx->name, av_err2str(ret));

        return ret;

    }

    for (i = 0; i < ctx->nb_inputs; i++)

        sanitize_channel_layouts(ctx, ctx->inputs[i]->out_channel_layouts);

    for (i = 0; i < ctx->nb_outputs; i++)

        sanitize_channel_layouts(ctx, ctx->outputs[i]->in_channel_layouts);

    formats = ff_all_formats(type);

    if (!formats)

        return AVERROR(ENOMEM);

    ff_set_common_formats(ctx, formats);

    if (type == AVMEDIA_TYPE_AUDIO) {

        samplerates = ff_all_samplerates();

        if (!samplerates)

            return AVERROR(ENOMEM);

        ff_set_common_samplerates(ctx, samplerates);

        chlayouts = ff_all_channel_layouts();

        if (!chlayouts)

            return AVERROR(ENOMEM);

        ff_set_common_channel_layouts(ctx, chlayouts);

    }

    return 0;

}


static int coroutine_fn sd_co_rw_vector(void *p)

{

    SheepdogAIOCB *acb = p;

    int ret = 0;

    unsigned long len, done = 0, total = acb->nb_sectors * BDRV_SECTOR_SIZE;

    unsigned long idx = acb->sector_num * BDRV_SECTOR_SIZE / SD_DATA_OBJ_SIZE;

    uint64_t oid;

    uint64_t offset = (acb->sector_num * BDRV_SECTOR_SIZE) % SD_DATA_OBJ_SIZE;

    BDRVSheepdogState *s = acb->common.bs->opaque;

    SheepdogInode *inode = &s->inode;

    AIOReq *aio_req;

    if (acb->aiocb_type == AIOCB_WRITE_UDATA && s->is_snapshot) {

        /*

         * In the case we open the snapshot VDI, Sheepdog creates the

         * writable VDI when we do a write operation first.

         */

        ret = sd_create_branch(s);

        if (ret) {

            acb->ret = -EIO;

            goto out;

        }

    }

    /*

     * Make sure we don't free the aiocb before we are done with all requests.

     * This additional reference is dropped at the end of this function.

     */

    acb->nr_pending++;

    while (done != total) {

        uint8_t flags = 0;

        uint64_t old_oid = 0;

        bool create = false;

        oid = vid_to_data_oid(inode->data_vdi_id[idx], idx);

        len = MIN(total - done, SD_DATA_OBJ_SIZE - offset);

        switch (acb->aiocb_type) {

        case AIOCB_READ_UDATA:

            if (!inode->data_vdi_id[idx]) {

                qemu_iovec_memset(acb->qiov, done, 0, len);

                goto done;

            }

            break;

        case AIOCB_WRITE_UDATA:

            if (!inode->data_vdi_id[idx]) {

                create = true;

            } else if (!is_data_obj_writable(inode, idx)) {

                /* Copy-On-Write */

                create = true;

                old_oid = oid;

                flags = SD_FLAG_CMD_COW;

            }

            break;

        case AIOCB_DISCARD_OBJ:

            /*

             * We discard the object only when the whole object is

             * 1) allocated 2) trimmed. Otherwise, simply skip it.

             */

            if (len != SD_DATA_OBJ_SIZE || inode->data_vdi_id[idx] == 0) {

                goto done;

            }

            break;

        default:

            break;

        }

        if (create) {

            DPRINTF("update ino (%" PRIu32 ") %" PRIu64 " %" PRIu64 " %ld\n",

                    inode->vdi_id, oid,

                    vid_to_data_oid(inode->data_vdi_id[idx], idx), idx);

            oid = vid_to_data_oid(inode->vdi_id, idx);

            DPRINTF("new oid %" PRIx64 "\n", oid);

        }

        aio_req = alloc_aio_req(s, acb, oid, len, offset, flags, old_oid, done);

        if (create) {

            AIOReq *areq;

            QLIST_FOREACH(areq, &s->inflight_aio_head, aio_siblings) {

                if (areq->oid == oid) {

                    /*

                     * Sheepdog cannot handle simultaneous create

                     * requests to the same object.  So we cannot send

                     * the request until the previous request

                     * finishes.

                     */

                    aio_req->flags = 0;

                    aio_req->base_oid = 0;

                    QLIST_INSERT_HEAD(&s->pending_aio_head, aio_req,

                                      aio_siblings);

                    goto done;

                }

            }

        }

        QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);

        add_aio_request(s, aio_req, acb->qiov->iov, acb->qiov->niov, create,

                        acb->aiocb_type);

    done:

        offset = 0;

        idx++;

        done += len;

    }

out:

    if (!--acb->nr_pending) {

        return acb->ret;

    }

    return 1;

}


static qemu_irq *ppce500_init_mpic(MachineState *machine, PPCE500Params *params,

                                   MemoryRegion *ccsr, qemu_irq **irqs)

{

    qemu_irq *mpic;

    DeviceState *dev = NULL;

    SysBusDevice *s;

    int i;

    mpic = g_new0(qemu_irq, 256);

    if (kvm_enabled()) {

        Error *err = NULL;

        if (machine_kernel_irqchip_allowed(machine)) {

            dev = ppce500_init_mpic_kvm(params, irqs, &err);

        }

        if (machine_kernel_irqchip_required(machine) && !dev) {

            error_reportf_err(err,

                              "kernel_irqchip requested but unavailable: ");

            exit(1);

        }

    }

    if (!dev) {

        dev = ppce500_init_mpic_qemu(params, irqs);

    }

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

        mpic[i] = qdev_get_gpio_in(dev, i);

    }

    s = SYS_BUS_DEVICE(dev);

    memory_region_add_subregion(ccsr, MPC8544_MPIC_REGS_OFFSET,

                                s->mmio[0].memory);

    return mpic;

}


static ExitStatus trans_fop_ded(DisasContext *ctx, uint32_t insn,

                                const DisasInsn *di)

{

    unsigned rt = extract32(insn, 0, 5);

    unsigned ra = extract32(insn, 21, 5);

    return do_fop_ded(ctx, rt, ra, di->f_ded);

}


static void xhci_xfer_report(XHCITransfer *xfer)

{

    uint32_t edtla = 0;

    unsigned int left;

    bool reported = 0;

    bool shortpkt = 0;

    XHCIEvent event = {ER_TRANSFER, CC_SUCCESS};

    XHCIState *xhci = xfer->xhci;

    int i;

    left = xfer->packet.actual_length;

    for (i = 0; i < xfer->trb_count; i++) {

        XHCITRB *trb = &xfer->trbs[i];

        unsigned int chunk = 0;

        switch (TRB_TYPE(*trb)) {

        case TR_DATA:

        case TR_NORMAL:

        case TR_ISOCH:

            chunk = trb->status & 0x1ffff;

            if (chunk > left) {

                chunk = left;

                if (xfer->status == CC_SUCCESS) {

                    shortpkt = 1;

                }

            }

            left -= chunk;

            edtla += chunk;

            break;

        case TR_STATUS:

            reported = 0;

            shortpkt = 0;

            break;

        }

        if (!reported && ((trb->control & TRB_TR_IOC) ||

                          (shortpkt && (trb->control & TRB_TR_ISP)) ||

                          (xfer->status != CC_SUCCESS && left == 0))) {

            event.slotid = xfer->slotid;

            event.epid = xfer->epid;

            event.length = (trb->status & 0x1ffff) - chunk;

            event.flags = 0;

            event.ptr = trb->addr;

            if (xfer->status == CC_SUCCESS) {

                event.ccode = shortpkt ? CC_SHORT_PACKET : CC_SUCCESS;

            } else {

                event.ccode = xfer->status;

            }

            if (TRB_TYPE(*trb) == TR_EVDATA) {

                event.ptr = trb->parameter;

                event.flags |= TRB_EV_ED;

                event.length = edtla & 0xffffff;

                DPRINTF("xhci_xfer_data: EDTLA=%d\n", event.length);

                edtla = 0;

            }

            xhci_event(xhci, &event, TRB_INTR(*trb));

            reported = 1;

            if (xfer->status != CC_SUCCESS) {

                return;

            }

        }

    }

}


static void usb_hid_handle_destroy(USBDevice *dev)

{

    USBHIDState *s = (USBHIDState *)dev;

    if (s->kind != USB_KEYBOARD)

        qemu_remove_mouse_event_handler(s->ptr.eh_entry);

    /* TODO: else */

}


static void do_subtitle_out(AVFormatContext *s,

                            OutputStream *ost,

                            InputStream *ist,

                            AVSubtitle *sub,

                            int64_t pts)

{

    int subtitle_out_max_size = 1024 * 1024;

    int subtitle_out_size, nb, i;

    AVCodecContext *enc;

    AVPacket pkt;

    if (pts == AV_NOPTS_VALUE) {

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

        if (exit_on_error)

            exit_program(1);

        return;

    }

    enc = ost->st->codec;

    if (!subtitle_out) {

        subtitle_out = av_malloc(subtitle_out_max_size);

    }

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

       packet to clear them */

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

    if (enc->codec_id == CODEC_ID_DVB_SUBTITLE)

        nb = 2;

    else

        nb = 1;

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

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

        if (!check_recording_time(ost))

            return;

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

        // start_display_time is required to be 0

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

        sub->end_display_time  -= sub->start_display_time;

        sub->start_display_time = 0;

        subtitle_out_size = avcodec_encode_subtitle(enc, subtitle_out,

                                                    subtitle_out_max_size, sub);

        if (subtitle_out_size < 0) {

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

            exit_program(1);

        }

        av_init_packet(&pkt);

        pkt.data = subtitle_out;

        pkt.size = subtitle_out_size;

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

        pkt.duration = av_rescale_q(sub->end_display_time, (AVRational){ 1, 1000 }, ost->st->time_base);

        if (enc->codec_id == CODEC_ID_DVB_SUBTITLE) {

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

               it in the codec would be better */

            if (i == 0)

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

            else

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

        }

        write_frame(s, &pkt, ost);

        subtitle_size += pkt.size;

    }

}


static CharDriverState *qmp_chardev_open_file(ChardevFile *file, Error **errp)

{

    int flags, in = -1, out = -1;

    flags = O_WRONLY | O_TRUNC | O_CREAT | O_BINARY;

    out = qmp_chardev_open_file_source(file->out, flags, errp);

    if (error_is_set(errp)) {

        return NULL;

    }

    if (file->has_in) {

        flags = O_RDONLY;

        in = qmp_chardev_open_file_source(file->in, flags, errp);

        if (error_is_set(errp)) {

            qemu_close(out);

            return NULL;

        }

    }

    return qemu_chr_open_fd(in, out);

}


static void gen_advance_ccount_cond(DisasContext *dc)

{

    if (dc->ccount_delta > 0) {

        TCGv_i32 tmp = tcg_const_i32(dc->ccount_delta);

        gen_helper_advance_ccount(cpu_env, tmp);

        tcg_temp_free(tmp);

    }

}


static inline void RENAME(hcscale_fast)(SwsContext *c, int16_t *dst1, int16_t *dst2,

                                        long dstWidth, const uint8_t *src1,

                                        const uint8_t *src2, int srcW, int xInc)

{

    int32_t *filterPos = c->hChrFilterPos;

    int16_t *filter    = c->hChrFilter;

    int     canMMX2BeUsed  = c->canMMX2BeUsed;

    void    *mmx2FilterCode= c->chrMmx2FilterCode;

    int i;

#if defined(PIC)

    DECLARE_ALIGNED(8, uint64_t, ebxsave);

#endif

    __asm__ volatile(

#if defined(PIC)

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

#endif

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

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

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

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

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

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

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

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

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

        CALL_MMX2_FILTER_CODE

        CALL_MMX2_FILTER_CODE

        CALL_MMX2_FILTER_CODE

        CALL_MMX2_FILTER_CODE

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

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

        "mov                 %6, %%"REG_D"  \n\t" // buf2

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

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

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

        CALL_MMX2_FILTER_CODE

        CALL_MMX2_FILTER_CODE

        CALL_MMX2_FILTER_CODE

        CALL_MMX2_FILTER_CODE

#if defined(PIC)

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

#endif

        :: "m" (src1), "m" (dst1), "m" (filter), "m" (filterPos),

           "m" (mmx2FilterCode), "m" (src2), "m"(dst2)

#if defined(PIC)

          ,"m" (ebxsave)

#endif

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

#if !defined(PIC)

         ,"%"REG_b

#endif

    );

    for (i=dstWidth-1; (i*xInc)>>16 >=srcW-1; i--) {

        dst1[i] = src1[srcW-1]*128;

        dst2[i] = src2[srcW-1]*128;

    }

}


static av_cold int fbdev_read_header(AVFormatContext *avctx)

{

    FBDevContext *fbdev = avctx->priv_data;

    AVStream *st = NULL;

    enum AVPixelFormat pix_fmt;

    int ret, flags = O_RDONLY;

    if (!(st = avformat_new_stream(avctx, NULL)))

        return AVERROR(ENOMEM);

    avpriv_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in microseconds */

    /* NONBLOCK is ignored by the fbdev driver, only set for consistency */

    if (avctx->flags & AVFMT_FLAG_NONBLOCK)

        flags |= O_NONBLOCK;

    if ((fbdev->fd = avpriv_open(avctx->filename, flags)) == -1) {

        ret = AVERROR(errno);

        av_log(avctx, AV_LOG_ERROR,

               "Could not open framebuffer device '%s': %s\n",

               avctx->filename, strerror(ret));

        return ret;

    }

    if (ioctl(fbdev->fd, FBIOGET_VSCREENINFO, &fbdev->varinfo) < 0) {

        ret = AVERROR(errno);

        av_log(avctx, AV_LOG_ERROR,

               "FBIOGET_VSCREENINFO: %s\n", strerror(errno));

        goto fail;

    }

    if (ioctl(fbdev->fd, FBIOGET_FSCREENINFO, &fbdev->fixinfo) < 0) {

        ret = AVERROR(errno);

        av_log(avctx, AV_LOG_ERROR,

               "FBIOGET_FSCREENINFO: %s\n", strerror(errno));

        goto fail;

    }

    pix_fmt = get_pixfmt_from_fb_varinfo(&fbdev->varinfo);

    if (pix_fmt == AV_PIX_FMT_NONE) {

        ret = AVERROR(EINVAL);

        av_log(avctx, AV_LOG_ERROR,

               "Framebuffer pixel format not supported.\n");

        goto fail;

    }

    fbdev->width           = fbdev->varinfo.xres;

    fbdev->height          = fbdev->varinfo.yres;

    fbdev->bytes_per_pixel = (fbdev->varinfo.bits_per_pixel + 7) >> 3;

    fbdev->frame_linesize  = fbdev->width * fbdev->bytes_per_pixel;

    fbdev->frame_size      = fbdev->frame_linesize * fbdev->height;

    fbdev->time_frame      = AV_NOPTS_VALUE;

    fbdev->data = mmap(NULL, fbdev->fixinfo.smem_len, PROT_READ, MAP_SHARED, fbdev->fd, 0);

    if (fbdev->data == MAP_FAILED) {

        ret = AVERROR(errno);

        av_log(avctx, AV_LOG_ERROR, "Error in mmap(): %s\n", strerror(errno));

        goto fail;

    }

    st->codec->codec_type = AVMEDIA_TYPE_VIDEO;

    st->codec->codec_id   = AV_CODEC_ID_RAWVIDEO;

    st->codec->width      = fbdev->width;

    st->codec->height     = fbdev->height;

    st->codec->pix_fmt    = pix_fmt;

    st->codec->time_base  = av_inv_q(fbdev->framerate_q);

    st->codec->bit_rate   =

        fbdev->width * fbdev->height * fbdev->bytes_per_pixel * av_q2d(fbdev->framerate_q) * 8;

    av_log(avctx, AV_LOG_INFO,

           "w:%d h:%d bpp:%d pixfmt:%s fps:%d/%d bit_rate:%d\n",

           fbdev->width, fbdev->height, fbdev->varinfo.bits_per_pixel,

           av_get_pix_fmt_name(pix_fmt),

           fbdev->framerate_q.num, fbdev->framerate_q.den,

           st->codec->bit_rate);

    return 0;

fail:

    close(fbdev->fd);

    return ret;

}


void ff_build_rac_states(RangeCoder *c, int factor, int max_p){

    const int64_t one= 1LL<<32;

    int64_t p;

    int last_p8, p8, i;

    memset(c->zero_state, 0, sizeof(c->zero_state));

    memset(c-> one_state, 0, sizeof(c-> one_state));

#if 0

    for(i=1; i<256; i++){

        if(c->one_state[i])

            continue;

        p= (i*one + 128) >> 8;

        last_p8= i;

        for(;;){

            p+= ((one-p)*factor + one/2) >> 32;

            p8= (256*p + one/2) >> 32; //FIXME try without the one

            if(p8 <= last_p8) p8= last_p8+1;

            if(p8 > max_p) p8= max_p;

            if(p8 < last_p8)

                break;

            c->one_state[last_p8]=     p8;

            if(p8 == last_p8)

                break;

            last_p8= p8;

        }

    }

#endif

#if 1

    last_p8= 0;

    p= one/2;

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

        p8= (256*p + one/2) >> 32; //FIXME try without the one

        if(p8 <= last_p8) p8= last_p8+1;

        if(last_p8 && last_p8<256 && p8<=max_p)

            c->one_state[last_p8]= p8;

        p+= ((one-p)*factor + one/2) >> 32;

        last_p8= p8;

    }

#endif

    for(i=256-max_p; i<=max_p; i++){

        if(c->one_state[i])

            continue;

        p= (i*one + 128) >> 8;

        p+= ((one-p)*factor + one/2) >> 32;

        p8= (256*p + one/2) >> 32; //FIXME try without the one

        if(p8 <= i) p8= i+1;

        if(p8 > max_p) p8= max_p;

        c->one_state[    i]=     p8;

    }

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

        c->zero_state[i]= 256-c->one_state[256-i];

#if 0

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

        av_log(NULL, AV_LOG_DEBUG, "%3d %3d\n", i, c->one_state[i]);

#endif

}


static void test_notify(void)

{

    g_assert(!aio_poll(ctx, false));

    aio_notify(ctx);

    g_assert(!aio_poll(ctx, true));

    g_assert(!aio_poll(ctx, false));

}


static int scsi_qdev_init(DeviceState *qdev)

{

    SCSIDevice *dev = SCSI_DEVICE(qdev);

    SCSIBus *bus = DO_UPCAST(SCSIBus, qbus, dev->qdev.parent_bus);

    SCSIDevice *d;

    int rc = -1;

    if (dev->channel > bus->info->max_channel) {

        error_report("bad scsi channel id: %d", dev->channel);

        goto err;

    }

    if (dev->id != -1 && dev->id > bus->info->max_target) {

        error_report("bad scsi device id: %d", dev->id);

        goto err;

    }

    if (dev->id == -1) {

        int id = -1;

        if (dev->lun == -1) {

            dev->lun = 0;

        }

        do {

            d = scsi_device_find(bus, dev->channel, ++id, dev->lun);

        } while (d && d->lun == dev->lun && id <= bus->info->max_target);

        if (id > bus->info->max_target) {

            error_report("no free target");

            goto err;

        }

        dev->id = id;

    } else if (dev->lun == -1) {

        int lun = -1;

        do {

            d = scsi_device_find(bus, dev->channel, dev->id, ++lun);

        } while (d && d->lun == lun && lun < bus->info->max_lun);

        if (lun > bus->info->max_lun) {

            error_report("no free lun");

            goto err;

        }

        dev->lun = lun;

    } else {

        d = scsi_device_find(bus, dev->channel, dev->id, dev->lun);

        if (dev->lun == d->lun && dev != d) {

            qdev_free(&d->qdev);

        }

    }

    QTAILQ_INIT(&dev->requests);

    rc = scsi_device_init(dev);

    if (rc == 0) {

        dev->vmsentry = qemu_add_vm_change_state_handler(scsi_dma_restart_cb,

                                                         dev);

    }

err:

    return rc;

}


static const char *addr2str(target_phys_addr_t addr)

{

    return nr2str(ehci_mmio_names, ARRAY_SIZE(ehci_mmio_names), addr);

}


static int dca_convert_bitstream(uint8_t * src, int src_size, uint8_t * dst,
                          int max_size)
{
    uint32_t mrk;
    int i, tmp;
    uint16_t *ssrc = (uint16_t *) src, *sdst = (uint16_t *) dst;
    PutBitContext pb;
    mrk = AV_RB32(src);
    switch (mrk) {
    case DCA_MARKER_RAW_BE:
        memcpy(dst, src, FFMIN(src_size, max_size));
        return FFMIN(src_size, max_size);
    case DCA_MARKER_RAW_LE:
        for (i = 0; i < (FFMIN(src_size, max_size) + 1) >> 1; i++)
            *sdst++ = bswap_16(*ssrc++);
        return FFMIN(src_size, max_size);
    case DCA_MARKER_14B_BE:
    case DCA_MARKER_14B_LE:
        init_put_bits(&pb, dst, max_size);
        for (i = 0; i < (src_size + 1) >> 1; i++, src += 2) {
            tmp = ((mrk == DCA_MARKER_14B_BE) ? AV_RB16(src) : AV_RL16(src)) & 0x3FFF;
            put_bits(&pb, 14, tmp);
        }
        flush_put_bits(&pb);
        return (put_bits_count(&pb) + 7) >> 3;
    default:
    }
}


static void *spapr_create_fdt_skel(hwaddr initrd_base,
                                   hwaddr initrd_size,
                                   hwaddr kernel_size,
                                   bool little_endian,
                                   const char *boot_device,
                                   const char *kernel_cmdline,
                                   uint32_t epow_irq)
{
    void *fdt;
    CPUState *cs;
    uint32_t start_prop = cpu_to_be32(initrd_base);
    uint32_t end_prop = cpu_to_be32(initrd_base + initrd_size);
    GString *hypertas = g_string_sized_new(256);
    GString *qemu_hypertas = g_string_sized_new(256);
    uint32_t refpoints[] = {cpu_to_be32(0x4), cpu_to_be32(0x4)};
    uint32_t interrupt_server_ranges_prop[] = {0, cpu_to_be32(smp_cpus)};
    int smt = kvmppc_smt_threads();
    unsigned char vec5[] = {0x0, 0x0, 0x0, 0x0, 0x0, 0x80};
    QemuOpts *opts = qemu_opts_find(qemu_find_opts("smp-opts"), NULL);
    unsigned sockets = opts ? qemu_opt_get_number(opts, "sockets", 0) : 0;
    uint32_t cpus_per_socket = sockets ? (smp_cpus / sockets) : 1;
    add_str(hypertas, "hcall-pft");
    add_str(hypertas, "hcall-term");
    add_str(hypertas, "hcall-dabr");
    add_str(hypertas, "hcall-interrupt");
    add_str(hypertas, "hcall-tce");
    add_str(hypertas, "hcall-vio");
    add_str(hypertas, "hcall-splpar");
    add_str(hypertas, "hcall-bulk");
    add_str(hypertas, "hcall-set-mode");
    add_str(qemu_hypertas, "hcall-memop1");
    fdt = g_malloc0(FDT_MAX_SIZE);
    _FDT((fdt_create(fdt, FDT_MAX_SIZE)));
    if (kernel_size) {
        _FDT((fdt_add_reservemap_entry(fdt, KERNEL_LOAD_ADDR, kernel_size)));
    }
    if (initrd_size) {
        _FDT((fdt_add_reservemap_entry(fdt, initrd_base, initrd_size)));
    }
    _FDT((fdt_finish_reservemap(fdt)));
    /* Root node */
    _FDT((fdt_begin_node(fdt, "")));
    _FDT((fdt_property_string(fdt, "device_type", "chrp")));
    _FDT((fdt_property_string(fdt, "model", "IBM pSeries (emulated by qemu)")));
    _FDT((fdt_property_string(fdt, "compatible", "qemu,pseries")));
    _FDT((fdt_property_cell(fdt, "#address-cells", 0x2)));
    _FDT((fdt_property_cell(fdt, "#size-cells", 0x2)));
    /* /chosen */
    _FDT((fdt_begin_node(fdt, "chosen")));
    /* Set Form1_affinity */
    _FDT((fdt_property(fdt, "ibm,architecture-vec-5", vec5, sizeof(vec5))));
    _FDT((fdt_property_string(fdt, "bootargs", kernel_cmdline)));
    _FDT((fdt_property(fdt, "linux,initrd-start",
                       &start_prop, sizeof(start_prop))));
    _FDT((fdt_property(fdt, "linux,initrd-end",
                       &end_prop, sizeof(end_prop))));
    if (kernel_size) {
        uint64_t kprop[2] = { cpu_to_be64(KERNEL_LOAD_ADDR),
                              cpu_to_be64(kernel_size) };
        _FDT((fdt_property(fdt, "qemu,boot-kernel", &kprop, sizeof(kprop))));
        if (little_endian) {
            _FDT((fdt_property(fdt, "qemu,boot-kernel-le", NULL, 0)));
        }
    }
    if (boot_device) {
        _FDT((fdt_property_string(fdt, "qemu,boot-device", boot_device)));
    }
    if (boot_menu) {
        _FDT((fdt_property_cell(fdt, "qemu,boot-menu", boot_menu)));
    }
    _FDT((fdt_property_cell(fdt, "qemu,graphic-width", graphic_width)));
    _FDT((fdt_property_cell(fdt, "qemu,graphic-height", graphic_height)));
    _FDT((fdt_property_cell(fdt, "qemu,graphic-depth", graphic_depth)));
    _FDT((fdt_end_node(fdt)));
    /* cpus */
    _FDT((fdt_begin_node(fdt, "cpus")));
    _FDT((fdt_property_cell(fdt, "#address-cells", 0x1)));
    _FDT((fdt_property_cell(fdt, "#size-cells", 0x0)));
    CPU_FOREACH(cs) {
        PowerPCCPU *cpu = POWERPC_CPU(cs);
        CPUPPCState *env = &cpu->env;
        DeviceClass *dc = DEVICE_GET_CLASS(cs);
        PowerPCCPUClass *pcc = POWERPC_CPU_GET_CLASS(cs);
        int index = ppc_get_vcpu_dt_id(cpu);
        char *nodename;
        uint32_t segs[] = {cpu_to_be32(28), cpu_to_be32(40),
                           0xffffffff, 0xffffffff};
        uint32_t tbfreq = kvm_enabled() ? kvmppc_get_tbfreq() : TIMEBASE_FREQ;
        uint32_t cpufreq = kvm_enabled() ? kvmppc_get_clockfreq() : 1000000000;
        uint32_t page_sizes_prop[64];
        size_t page_sizes_prop_size;
        if ((index % smt) != 0) {
            continue;
        }
        nodename = g_strdup_printf("%s@%x", dc->fw_name, index);
        _FDT((fdt_begin_node(fdt, nodename)));
        g_free(nodename);
        _FDT((fdt_property_cell(fdt, "reg", index)));
        _FDT((fdt_property_string(fdt, "device_type", "cpu")));
        _FDT((fdt_property_cell(fdt, "cpu-version", env->spr[SPR_PVR])));
        _FDT((fdt_property_cell(fdt, "d-cache-block-size",
                                env->dcache_line_size)));
        _FDT((fdt_property_cell(fdt, "d-cache-line-size",
                                env->dcache_line_size)));
        _FDT((fdt_property_cell(fdt, "i-cache-block-size",
                                env->icache_line_size)));
        _FDT((fdt_property_cell(fdt, "i-cache-line-size",
                                env->icache_line_size)));
        if (pcc->l1_dcache_size) {
            _FDT((fdt_property_cell(fdt, "d-cache-size", pcc->l1_dcache_size)));
        } else {
            fprintf(stderr, "Warning: Unknown L1 dcache size for cpu\n");
        }
        if (pcc->l1_icache_size) {
            _FDT((fdt_property_cell(fdt, "i-cache-size", pcc->l1_icache_size)));
        } else {
            fprintf(stderr, "Warning: Unknown L1 icache size for cpu\n");
        }
        _FDT((fdt_property_cell(fdt, "timebase-frequency", tbfreq)));
        _FDT((fdt_property_cell(fdt, "clock-frequency", cpufreq)));
        _FDT((fdt_property_cell(fdt, "ibm,slb-size", env->slb_nr)));
        _FDT((fdt_property_string(fdt, "status", "okay")));
        _FDT((fdt_property(fdt, "64-bit", NULL, 0)));
        if (env->spr_cb[SPR_PURR].oea_read) {
            _FDT((fdt_property(fdt, "ibm,purr", NULL, 0)));
        }
        if (env->mmu_model & POWERPC_MMU_1TSEG) {
            _FDT((fdt_property(fdt, "ibm,processor-segment-sizes",
                               segs, sizeof(segs))));
        }
        /* Advertise VMX/VSX (vector extensions) if available
         *   0 / no property == no vector extensions
         *   1               == VMX / Altivec available
         *   2               == VSX available */
        if (env->insns_flags & PPC_ALTIVEC) {
            uint32_t vmx = (env->insns_flags2 & PPC2_VSX) ? 2 : 1;
            _FDT((fdt_property_cell(fdt, "ibm,vmx", vmx)));
        }
        /* Advertise DFP (Decimal Floating Point) if available
         *   0 / no property == no DFP
         *   1               == DFP available */
        if (env->insns_flags2 & PPC2_DFP) {
            _FDT((fdt_property_cell(fdt, "ibm,dfp", 1)));
        }
        page_sizes_prop_size = create_page_sizes_prop(env, page_sizes_prop,
                                                      sizeof(page_sizes_prop));
        if (page_sizes_prop_size) {
            _FDT((fdt_property(fdt, "ibm,segment-page-sizes",
                               page_sizes_prop, page_sizes_prop_size)));
        }
        _FDT((fdt_property_cell(fdt, "ibm,chip-id",
                                cs->cpu_index / cpus_per_socket)));
        _FDT((fdt_end_node(fdt)));
    }
    _FDT((fdt_end_node(fdt)));
    /* RTAS */
    _FDT((fdt_begin_node(fdt, "rtas")));
    if (!kvm_enabled() || kvmppc_spapr_use_multitce()) {
        add_str(hypertas, "hcall-multi-tce");
    }
    _FDT((fdt_property(fdt, "ibm,hypertas-functions", hypertas->str,
                       hypertas->len)));
    g_string_free(hypertas, TRUE);
    _FDT((fdt_property(fdt, "qemu,hypertas-functions", qemu_hypertas->str,
                       qemu_hypertas->len)));
    g_string_free(qemu_hypertas, TRUE);
    _FDT((fdt_property(fdt, "ibm,associativity-reference-points",
        refpoints, sizeof(refpoints))));
    _FDT((fdt_property_cell(fdt, "rtas-error-log-max", RTAS_ERROR_LOG_MAX)));
    _FDT((fdt_end_node(fdt)));
    /* interrupt controller */
    _FDT((fdt_begin_node(fdt, "interrupt-controller")));
    _FDT((fdt_property_string(fdt, "device_type",
                              "PowerPC-External-Interrupt-Presentation")));
    _FDT((fdt_property_string(fdt, "compatible", "IBM,ppc-xicp")));
    _FDT((fdt_property(fdt, "interrupt-controller", NULL, 0)));
    _FDT((fdt_property(fdt, "ibm,interrupt-server-ranges",
                       interrupt_server_ranges_prop,
                       sizeof(interrupt_server_ranges_prop))));
    _FDT((fdt_property_cell(fdt, "#interrupt-cells", 2)));
    _FDT((fdt_property_cell(fdt, "linux,phandle", PHANDLE_XICP)));
    _FDT((fdt_property_cell(fdt, "phandle", PHANDLE_XICP)));
    _FDT((fdt_end_node(fdt)));
    /* vdevice */
    _FDT((fdt_begin_node(fdt, "vdevice")));
    _FDT((fdt_property_string(fdt, "device_type", "vdevice")));
    _FDT((fdt_property_string(fdt, "compatible", "IBM,vdevice")));
    _FDT((fdt_property_cell(fdt, "#address-cells", 0x1)));
    _FDT((fdt_property_cell(fdt, "#size-cells", 0x0)));
    _FDT((fdt_property_cell(fdt, "#interrupt-cells", 0x2)));
    _FDT((fdt_property(fdt, "interrupt-controller", NULL, 0)));
    _FDT((fdt_end_node(fdt)));
    /* event-sources */
    spapr_events_fdt_skel(fdt, epow_irq);
    /* /hypervisor node */
    if (kvm_enabled()) {
        uint8_t hypercall[16];
        /* indicate KVM hypercall interface */
        _FDT((fdt_begin_node(fdt, "hypervisor")));
        _FDT((fdt_property_string(fdt, "compatible", "linux,kvm")));
        if (kvmppc_has_cap_fixup_hcalls()) {
             * Older KVM versions with older guest kernels were broken with the
             * magic page, don't allow the guest to map it.
            kvmppc_get_hypercall(first_cpu->env_ptr, hypercall,
                                 sizeof(hypercall));
            _FDT((fdt_property(fdt, "hcall-instructions", hypercall,
                              sizeof(hypercall))));
        }
        _FDT((fdt_end_node(fdt)));
    }
    _FDT((fdt_end_node(fdt))); /* close root node */
    _FDT((fdt_finish(fdt)));
    return fdt;
}


static void vga_screen_dump(void *opaque, const char *filename)

{

    VGAState *s = (VGAState *)opaque;

    if (!(s->ar_index & 0x20))

        vga_screen_dump_blank(s, filename);

    else if (s->gr[6] & 1)

        vga_screen_dump_graphic(s, filename);

    else

        vga_screen_dump_text(s, filename);

}


static void bamboo_init(ram_addr_t ram_size,

                        const char *boot_device,

                        const char *kernel_filename,

                        const char *kernel_cmdline,

                        const char *initrd_filename,

                        const char *cpu_model)

{

    unsigned int pci_irq_nrs[4] = { 28, 27, 26, 25 };

    PCIBus *pcibus;

    CPUState *env;

    uint64_t elf_entry;

    uint64_t elf_lowaddr;

    target_phys_addr_t entry = 0;

    target_phys_addr_t loadaddr = 0;

    target_long initrd_size = 0;

    int success;

    int i;

    /* Setup CPU. */

    env = ppc440ep_init(&ram_size, &pcibus, pci_irq_nrs, 1, cpu_model);

    if (pcibus) {

        /* Register network interfaces. */

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

            /* There are no PCI NICs on the Bamboo board, but there are

             * PCI slots, so we can pick whatever default model we want. */

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

        }

    }

    /* Load kernel. */

    if (kernel_filename) {

        success = load_uimage(kernel_filename, &entry, &loadaddr, NULL);

        if (success < 0) {

            success = load_elf(kernel_filename, NULL, NULL, &elf_entry,

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

            entry = elf_entry;

            loadaddr = elf_lowaddr;

        }

        /* XXX try again as binary */

        if (success < 0) {

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

                    kernel_filename);

            exit(1);

        }

    }

    /* Load initrd. */

    if (initrd_filename) {

        initrd_size = load_image_targphys(initrd_filename, RAMDISK_ADDR,

                                          ram_size - RAMDISK_ADDR);

        if (initrd_size < 0) {

            fprintf(stderr, "qemu: could not load ram disk '%s' at %x\n",

                    initrd_filename, RAMDISK_ADDR);

            exit(1);

        }

    }

    /* If we're loading a kernel directly, we must load the device tree too. */

    if (kernel_filename) {

        if (bamboo_load_device_tree(FDT_ADDR, ram_size, RAMDISK_ADDR,

                                    initrd_size, kernel_cmdline) < 0) {

            fprintf(stderr, "couldn't load device tree\n");

            exit(1);

        }

        cpu_synchronize_state(env);

        /* Set initial guest state. */

        env->gpr[1] = (16<<20) - 8;

        env->gpr[3] = FDT_ADDR;

        env->nip = entry;

        /* XXX we currently depend on KVM to create some initial TLB entries. */

    }

    if (kvm_enabled())

        kvmppc_init();

}


static int show_hwaccels(void *optctx, const char *opt, const char *arg)

{

    int i;

    printf("Hardware acceleration methods:\n");

    for (i = 0; hwaccels[i].name; i++) {

        printf("%s\n", hwaccels[i].name);

    }

    printf("\n");

    return 0;

}


static int Faac_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,

                             const AVFrame *frame, int *got_packet_ptr)

{

    FaacAudioContext *s = avctx->priv_data;

    int bytes_written, ret;

    int num_samples  = frame ? frame->nb_samples : 0;

    void *samples    = frame ? frame->data[0]    : NULL;

    if ((ret = ff_alloc_packet2(avctx, avpkt, (7 + 768) * avctx->channels))) {

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

        return ret;

    }

    bytes_written = faacEncEncode(s->faac_handle, samples,

                                  num_samples * avctx->channels,

                                  avpkt->data, avpkt->size);

    if (bytes_written < 0) {

        av_log(avctx, AV_LOG_ERROR, "faacEncEncode() error\n");

        return bytes_written;

    }

    /* add current frame to the queue */

    if (frame) {

        if ((ret = ff_af_queue_add(&s->afq, frame)) < 0)

            return ret;

    }

    if (!bytes_written)

        return 0;

    /* Get the next frame pts/duration */

    ff_af_queue_remove(&s->afq, avctx->frame_size, &avpkt->pts,

                       &avpkt->duration);

    avpkt->size = bytes_written;

    *got_packet_ptr = 1;

    return 0;

}


static int check_mv(H264Context *h, long b_idx, long bn_idx, int mvy_limit){

    int v;

    v = h->ref_cache[0][b_idx] != h->ref_cache[0][bn_idx] |

        h->mv_cache[0][b_idx][0] - h->mv_cache[0][bn_idx][0] + 3 >= 7U |

        FFABS( h->mv_cache[0][b_idx][1] - h->mv_cache[0][bn_idx][1] ) >= mvy_limit;

    if(h->list_count==2){

        if(!v)

            v = h->ref_cache[1][b_idx] != h->ref_cache[1][bn_idx] |

                h->mv_cache[1][b_idx][0] - h->mv_cache[1][bn_idx][0] + 3 >= 7U |

                FFABS( h->mv_cache[1][b_idx][1] - h->mv_cache[1][bn_idx][1] ) >= mvy_limit;

        if(v){

            if(h->ref_cache[0][b_idx] != h->ref_cache[1][bn_idx] |

               h->ref_cache[1][b_idx] != h->ref_cache[0][bn_idx])

                return 1;

            return

                h->mv_cache[0][b_idx][0] - h->mv_cache[1][bn_idx][0] + 3 >= 7U |

                FFABS( h->mv_cache[0][b_idx][1] - h->mv_cache[1][bn_idx][1] ) >= mvy_limit |

                h->mv_cache[1][b_idx][0] - h->mv_cache[0][bn_idx][0] + 3 >= 7U |

                FFABS( h->mv_cache[1][b_idx][1] - h->mv_cache[0][bn_idx][1] ) >= mvy_limit;

        }

    }

    return v;

}


static int decode_band_types(AACContext *ac, enum BandType band_type[120],

                             int band_type_run_end[120], GetBitContext *gb,

                             IndividualChannelStream *ics)

{

    int g, idx = 0;

    const int bits = (ics->window_sequence[0] == EIGHT_SHORT_SEQUENCE) ? 3 : 5;

    for (g = 0; g < ics->num_window_groups; g++) {

        int k = 0;

        while (k < ics->max_sfb) {

            uint8_t sect_end = k;

            int sect_len_incr;

            int sect_band_type = get_bits(gb, 4);

            if (sect_band_type == 12) {

                av_log(ac->avctx, AV_LOG_ERROR, "invalid band type\n");

                return -1;

            }

            while ((sect_len_incr = get_bits(gb, bits)) == (1 << bits) - 1)

                sect_end += sect_len_incr;

            sect_end += sect_len_incr;

            if (get_bits_left(gb) < 0) {

                av_log(ac->avctx, AV_LOG_ERROR, overread_err);

                return -1;

            }

            if (sect_end > ics->max_sfb) {

                av_log(ac->avctx, AV_LOG_ERROR,

                       "Number of bands (%d) exceeds limit (%d).\n",

                       sect_end, ics->max_sfb);

                return -1;

            }

            for (; k < sect_end; k++) {

                band_type        [idx]   = sect_band_type;

                band_type_run_end[idx++] = sect_end;

            }

        }

    }

    return 0;

}


static void unassign_storage(SCCB *sccb)

{

    MemoryRegion *mr = NULL;

    AssignStorage *assign_info = (AssignStorage *) sccb;

    sclpMemoryHotplugDev *mhd = get_sclp_memory_hotplug_dev();

    assert(mhd);

    ram_addr_t unassign_addr = (assign_info->rn - 1) * mhd->rzm;

    MemoryRegion *sysmem = get_system_memory();

    /* if the addr is a multiple of 256 MB */

    if ((unassign_addr % MEM_SECTION_SIZE == 0) &&

        (unassign_addr >= mhd->padded_ram_size)) {

        mhd->standby_state_map[(unassign_addr -

                           mhd->padded_ram_size) / MEM_SECTION_SIZE] = 0;

        /* find the specified memory region and destroy it */

        mr = memory_region_find(sysmem, unassign_addr, 1).mr;

        if (mr) {

            int i;

            int is_removable = 1;

            ram_addr_t map_offset = (unassign_addr - mhd->padded_ram_size -

                                     (unassign_addr - mhd->padded_ram_size)

                                     % mhd->standby_subregion_size);

            /* Mark all affected subregions as 'standby' once again */

            for (i = 0;

                 i < (mhd->standby_subregion_size / MEM_SECTION_SIZE);

                 i++) {

                if (mhd->standby_state_map[i + map_offset / MEM_SECTION_SIZE]) {

                    is_removable = 0;

                    break;

                }

            }

            if (is_removable) {

                memory_region_del_subregion(sysmem, mr);

                object_unparent(OBJECT(mr));

                g_free(mr);

            }

        }

    }

    sccb->h.response_code = cpu_to_be16(SCLP_RC_NORMAL_COMPLETION);

}


static int vpc_read(BlockDriverState *bs, int64_t sector_num,

                    uint8_t *buf, int nb_sectors)

{

    BDRVVPCState *s = bs->opaque;

    int ret;

    int64_t offset;

    int64_t sectors, sectors_per_block;

    VHDFooter *footer = (VHDFooter *) s->footer_buf;

    if (cpu_to_be32(footer->type) == VHD_FIXED) {

        return bdrv_read(bs->file, sector_num, buf, nb_sectors);

    }

    while (nb_sectors > 0) {

        offset = get_sector_offset(bs, sector_num, 0);

        sectors_per_block = s->block_size >> BDRV_SECTOR_BITS;

        sectors = sectors_per_block - (sector_num % sectors_per_block);

        if (sectors > nb_sectors) {

            sectors = nb_sectors;

        }

        if (offset == -1) {

            memset(buf, 0, sectors * BDRV_SECTOR_SIZE);

        } else {

            ret = bdrv_pread(bs->file, offset, buf,

                sectors * BDRV_SECTOR_SIZE);

            if (ret != sectors * BDRV_SECTOR_SIZE) {

                return -1;

            }

        }

        nb_sectors -= sectors;

        sector_num += sectors;

        buf += sectors * BDRV_SECTOR_SIZE;

    }

    return 0;

}


BlockDriverAIOCB *dma_bdrv_io(

    BlockDriverState *bs, QEMUSGList *sg, uint64_t sector_num,

    DMAIOFunc *io_func, BlockDriverCompletionFunc *cb,

    void *opaque, bool to_dev)

{

    DMAAIOCB *dbs = qemu_aio_get(&dma_aio_pool, bs, cb, opaque);

    dbs->acb = NULL;

    dbs->bs = bs;

    dbs->sg = sg;

    dbs->sector_num = sector_num;

    dbs->sg_cur_index = 0;

    dbs->sg_cur_byte = 0;

    dbs->to_dev = to_dev;

    dbs->io_func = io_func;

    dbs->bh = NULL;

    qemu_iovec_init(&dbs->iov, sg->nsg);

    dma_bdrv_cb(dbs, 0);

    if (!dbs->acb) {

        qemu_aio_release(dbs);

        return NULL;

    }

    return &dbs->common;

}


static int avr_probe(AVProbeData *p)

{

    if (AV_RL32(p->buf) == MKTAG('2', 'B', 'I', 'T'))

        return AVPROBE_SCORE_EXTENSION;

    return 0;

}


QList *qobject_to_qlist(const QObject *obj)

{

    if (qobject_type(obj) != QTYPE_QLIST) {

        return NULL;

    }

    return container_of(obj, QList, base);

}


static void *spapr_create_fdt_skel(const char *cpu_model,
                                   target_phys_addr_t rma_size,
                                   target_phys_addr_t initrd_base,
                                   target_phys_addr_t initrd_size,
                                   target_phys_addr_t kernel_size,
                                   const char *boot_device,
                                   const char *kernel_cmdline,
                                   long hash_shift)
{
    void *fdt;
    CPUPPCState *env;
    uint64_t mem_reg_property[2];
    uint32_t start_prop = cpu_to_be32(initrd_base);
    uint32_t end_prop = cpu_to_be32(initrd_base + initrd_size);
    uint32_t pft_size_prop[] = {0, cpu_to_be32(hash_shift)};
    char hypertas_prop[] = "hcall-pft\0hcall-term\0hcall-dabr\0hcall-interrupt"
        "\0hcall-tce\0hcall-vio\0hcall-splpar\0hcall-bulk";
    uint32_t interrupt_server_ranges_prop[] = {0, cpu_to_be32(smp_cpus)};
    int i;
    char *modelname;
    int smt = kvmppc_smt_threads();
    unsigned char vec5[] = {0x0, 0x0, 0x0, 0x0, 0x0, 0x80};
    uint32_t refpoints[] = {cpu_to_be32(0x4), cpu_to_be32(0x4)};
    uint32_t associativity[] = {cpu_to_be32(0x4), cpu_to_be32(0x0),
                                cpu_to_be32(0x0), cpu_to_be32(0x0),
                                cpu_to_be32(0x0)};
    char mem_name[32];
    target_phys_addr_t node0_size, mem_start;
#define _FDT(exp) \
    do { \
        int ret = (exp);                                           \
        if (ret < 0) {                                             \
            fprintf(stderr, "qemu: error creating device tree: %s: %s\n", \
                    #exp, fdt_strerror(ret));                      \
            exit(1);                                               \
        }                                                          \
    } while (0)
    fdt = g_malloc0(FDT_MAX_SIZE);
    _FDT((fdt_create(fdt, FDT_MAX_SIZE)));
    if (kernel_size) {
        _FDT((fdt_add_reservemap_entry(fdt, KERNEL_LOAD_ADDR, kernel_size)));
    if (initrd_size) {
        _FDT((fdt_add_reservemap_entry(fdt, initrd_base, initrd_size)));
    _FDT((fdt_finish_reservemap(fdt)));
    /* Root node */
    _FDT((fdt_begin_node(fdt, "")));
    _FDT((fdt_property_string(fdt, "device_type", "chrp")));
    _FDT((fdt_property_string(fdt, "model", "IBM pSeries (emulated by qemu)")));
    _FDT((fdt_property_cell(fdt, "#address-cells", 0x2)));
    _FDT((fdt_property_cell(fdt, "#size-cells", 0x2)));
    /* /chosen */
    _FDT((fdt_begin_node(fdt, "chosen")));
    /* Set Form1_affinity */
    _FDT((fdt_property(fdt, "ibm,architecture-vec-5", vec5, sizeof(vec5))));
    _FDT((fdt_property_string(fdt, "bootargs", kernel_cmdline)));
    _FDT((fdt_property(fdt, "linux,initrd-start",
                       &start_prop, sizeof(start_prop))));
    _FDT((fdt_property(fdt, "linux,initrd-end",
                       &end_prop, sizeof(end_prop))));
    if (kernel_size) {
        uint64_t kprop[2] = { cpu_to_be64(KERNEL_LOAD_ADDR),
                              cpu_to_be64(kernel_size) };
        _FDT((fdt_property(fdt, "qemu,boot-kernel", &kprop, sizeof(kprop))));
    _FDT((fdt_property_string(fdt, "qemu,boot-device", boot_device)));
    _FDT((fdt_end_node(fdt)));
    /* memory node(s) */
    node0_size = (nb_numa_nodes > 1) ? node_mem[0] : ram_size;
    if (rma_size > node0_size) {
        rma_size = node0_size;
    /* RMA */
    mem_reg_property[0] = 0;
    mem_reg_property[1] = cpu_to_be64(rma_size);
    _FDT((fdt_begin_node(fdt, "memory@0")));
    _FDT((fdt_property_string(fdt, "device_type", "memory")));
    _FDT((fdt_property(fdt, "reg", mem_reg_property,
        sizeof(mem_reg_property))));
    _FDT((fdt_property(fdt, "ibm,associativity", associativity,
        sizeof(associativity))));
    _FDT((fdt_end_node(fdt)));
    /* RAM: Node 0 */
    if (node0_size > rma_size) {
        mem_reg_property[0] = cpu_to_be64(rma_size);
        mem_reg_property[1] = cpu_to_be64(node0_size - rma_size);
        sprintf(mem_name, "memory@" TARGET_FMT_lx, rma_size);
        _FDT((fdt_begin_node(fdt, mem_name)));
        _FDT((fdt_property_string(fdt, "device_type", "memory")));
        _FDT((fdt_property(fdt, "reg", mem_reg_property,
                           sizeof(mem_reg_property))));
        _FDT((fdt_property(fdt, "ibm,associativity", associativity,
                           sizeof(associativity))));
        _FDT((fdt_end_node(fdt)));
    /* RAM: Node 1 and beyond */
    mem_start = node0_size;
    for (i = 1; i < nb_numa_nodes; i++) {
        mem_reg_property[0] = cpu_to_be64(mem_start);
        mem_reg_property[1] = cpu_to_be64(node_mem[i]);
        associativity[3] = associativity[4] = cpu_to_be32(i);
        sprintf(mem_name, "memory@" TARGET_FMT_lx, mem_start);
        _FDT((fdt_begin_node(fdt, mem_name)));
        _FDT((fdt_property_string(fdt, "device_type", "memory")));
        _FDT((fdt_property(fdt, "reg", mem_reg_property,
            sizeof(mem_reg_property))));
        _FDT((fdt_property(fdt, "ibm,associativity", associativity,
            sizeof(associativity))));
        _FDT((fdt_end_node(fdt)));
        mem_start += node_mem[i];
    /* cpus */
    _FDT((fdt_begin_node(fdt, "cpus")));
    _FDT((fdt_property_cell(fdt, "#address-cells", 0x1)));
    _FDT((fdt_property_cell(fdt, "#size-cells", 0x0)));
    modelname = g_strdup(cpu_model);
    for (i = 0; i < strlen(modelname); i++) {
        modelname[i] = toupper(modelname[i]);
    /* This is needed during FDT finalization */
    spapr->cpu_model = g_strdup(modelname);
    for (env = first_cpu; env != NULL; env = env->next_cpu) {
        int index = env->cpu_index;
        uint32_t servers_prop[smp_threads];
        uint32_t gservers_prop[smp_threads * 2];
        char *nodename;
        uint32_t segs[] = {cpu_to_be32(28), cpu_to_be32(40),
                           0xffffffff, 0xffffffff};
        uint32_t tbfreq = kvm_enabled() ? kvmppc_get_tbfreq() : TIMEBASE_FREQ;
        uint32_t cpufreq = kvm_enabled() ? kvmppc_get_clockfreq() : 1000000000;
        uint32_t page_sizes_prop[64];
        size_t page_sizes_prop_size;
        if ((index % smt) != 0) {
            continue;
        if (asprintf(&nodename, "%s@%x", modelname, index) < 0) {
            fprintf(stderr, "Allocation failure\n");
            exit(1);
        _FDT((fdt_begin_node(fdt, nodename)));
        free(nodename);
        _FDT((fdt_property_cell(fdt, "reg", index)));
        _FDT((fdt_property_string(fdt, "device_type", "cpu")));
        _FDT((fdt_property_cell(fdt, "cpu-version", env->spr[SPR_PVR])));
        _FDT((fdt_property_cell(fdt, "dcache-block-size",
                                env->dcache_line_size)));
        _FDT((fdt_property_cell(fdt, "icache-block-size",
                                env->icache_line_size)));
        _FDT((fdt_property_cell(fdt, "timebase-frequency", tbfreq)));
        _FDT((fdt_property_cell(fdt, "clock-frequency", cpufreq)));
        _FDT((fdt_property_cell(fdt, "ibm,slb-size", env->slb_nr)));
        _FDT((fdt_property(fdt, "ibm,pft-size",
                           pft_size_prop, sizeof(pft_size_prop))));
        _FDT((fdt_property_string(fdt, "status", "okay")));
        _FDT((fdt_property(fdt, "64-bit", NULL, 0)));
        /* Build interrupt servers and gservers properties */
        for (i = 0; i < smp_threads; i++) {
            servers_prop[i] = cpu_to_be32(index + i);
            /* Hack, direct the group queues back to cpu 0 */
            gservers_prop[i*2] = cpu_to_be32(index + i);
            gservers_prop[i*2 + 1] = 0;
        _FDT((fdt_property(fdt, "ibm,ppc-interrupt-server#s",
                           servers_prop, sizeof(servers_prop))));
        _FDT((fdt_property(fdt, "ibm,ppc-interrupt-gserver#s",
                           gservers_prop, sizeof(gservers_prop))));
        if (env->mmu_model & POWERPC_MMU_1TSEG) {
            _FDT((fdt_property(fdt, "ibm,processor-segment-sizes",
                               segs, sizeof(segs))));
        /* Advertise VMX/VSX (vector extensions) if available
         *   0 / no property == no vector extensions
         *   1               == VMX / Altivec available
         *   2               == VSX available */
        if (env->insns_flags & PPC_ALTIVEC) {
            uint32_t vmx = (env->insns_flags2 & PPC2_VSX) ? 2 : 1;
            _FDT((fdt_property_cell(fdt, "ibm,vmx", vmx)));
        /* Advertise DFP (Decimal Floating Point) if available
         *   0 / no property == no DFP
         *   1               == DFP available */
        if (env->insns_flags2 & PPC2_DFP) {
            _FDT((fdt_property_cell(fdt, "ibm,dfp", 1)));
        _FDT((fdt_end_node(fdt)));
    g_free(modelname);
    _FDT((fdt_end_node(fdt)));
    /* RTAS */
    _FDT((fdt_begin_node(fdt, "rtas")));
    _FDT((fdt_property(fdt, "ibm,hypertas-functions", hypertas_prop,
                       sizeof(hypertas_prop))));
    _FDT((fdt_property(fdt, "ibm,associativity-reference-points",
        refpoints, sizeof(refpoints))));
    _FDT((fdt_end_node(fdt)));
    /* interrupt controller */
    _FDT((fdt_begin_node(fdt, "interrupt-controller")));
    _FDT((fdt_property_string(fdt, "device_type",
                              "PowerPC-External-Interrupt-Presentation")));
    _FDT((fdt_property_string(fdt, "compatible", "IBM,ppc-xicp")));
    _FDT((fdt_property(fdt, "interrupt-controller", NULL, 0)));
    _FDT((fdt_property(fdt, "ibm,interrupt-server-ranges",
                       interrupt_server_ranges_prop,
                       sizeof(interrupt_server_ranges_prop))));
    _FDT((fdt_property_cell(fdt, "#interrupt-cells", 2)));
    _FDT((fdt_property_cell(fdt, "linux,phandle", PHANDLE_XICP)));
    _FDT((fdt_property_cell(fdt, "phandle", PHANDLE_XICP)));
    _FDT((fdt_end_node(fdt)));
    /* vdevice */
    _FDT((fdt_begin_node(fdt, "vdevice")));
    _FDT((fdt_property_string(fdt, "device_type", "vdevice")));
    _FDT((fdt_property_string(fdt, "compatible", "IBM,vdevice")));
    _FDT((fdt_property_cell(fdt, "#address-cells", 0x1)));
    _FDT((fdt_property_cell(fdt, "#size-cells", 0x0)));
    _FDT((fdt_property_cell(fdt, "#interrupt-cells", 0x2)));
    _FDT((fdt_property(fdt, "interrupt-controller", NULL, 0)));
    _FDT((fdt_end_node(fdt)));
    _FDT((fdt_end_node(fdt))); /* close root node */
    _FDT((fdt_finish(fdt)));
    return fdt;


void checkasm_check_jpeg2000dsp(void)

{

    LOCAL_ALIGNED_32(uint8_t, ref, [BUF_SIZE*3]);

    LOCAL_ALIGNED_32(uint8_t, new, [BUF_SIZE*3]);

    Jpeg2000DSPContext h;

    ff_jpeg2000dsp_init(&h);

    if (check_func(h.mct_decode[FF_DWT53], "jpeg2000_rct_int"))

        check_mct(&ref[BUF_SIZE*0], &ref[BUF_SIZE*1], &ref[BUF_SIZE*2],

                  &new[BUF_SIZE*0], &new[BUF_SIZE*1], &new[BUF_SIZE*2]);

    report("mct_decode");

}


static int skip_check(MpegEncContext *s, Picture *p, Picture *ref){

    int x, y, plane;

    int score=0;

    int64_t score64=0;

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

        const int stride= p->linesize[plane];

        const int bw= plane ? 1 : 2;

        for(y=0; y<s->mb_height*bw; y++){

            for(x=0; x<s->mb_width*bw; x++){

                int v= s->dsp.frame_skip_cmp[1](s, p->data[plane] + 8*(x + y*stride), ref->data[plane] + 8*(x + y*stride), stride, 8);

                switch(s->avctx->frame_skip_exp){

                    case 0: score= FFMAX(score, v); break;

                    case 1: score+= ABS(v);break;

                    case 2: score+= v*v;break;

                    case 3: score64+= ABS(v*v*(int64_t)v);break;

                    case 4: score64+= v*v*(int64_t)(v*v);break;

                }

            }

        }

    }

    if(score) score64= score;

    if(score64 < s->avctx->frame_skip_threshold)

        return 1;

    if(score64 < ((s->avctx->frame_skip_factor * (int64_t)s->lambda)>>8))

        return 1;

    return 0;

}


static inline int get_segment(CPUState *env, mmu_ctx_t *ctx,

                              target_ulong eaddr, int rw, int type)

{

    target_phys_addr_t hash;

    target_ulong vsid;

    int ds, pr, target_page_bits;

    int ret, ret2;

    pr = msr_pr;

    ctx->eaddr = eaddr;

#if defined(TARGET_PPC64)

    if (env->mmu_model & POWERPC_MMU_64) {

        ppc_slb_t *slb;

        target_ulong pageaddr;

        int segment_bits;

        LOG_MMU("Check SLBs\n");

        slb = slb_lookup(env, eaddr);

        if (!slb) {

            return -5;

        }

        if (slb->vsid & SLB_VSID_B) {

            vsid = (slb->vsid & SLB_VSID_VSID) >> SLB_VSID_SHIFT_1T;

            segment_bits = 40;

        } else {

            vsid = (slb->vsid & SLB_VSID_VSID) >> SLB_VSID_SHIFT;

            segment_bits = 28;

        }

        target_page_bits = (slb->vsid & SLB_VSID_L)

            ? TARGET_PAGE_BITS_16M : TARGET_PAGE_BITS;

        ctx->key = !!(pr ? (slb->vsid & SLB_VSID_KP)

                      : (slb->vsid & SLB_VSID_KS));

        ds = 0;

        ctx->nx = !!(slb->vsid & SLB_VSID_N);

        pageaddr = eaddr & ((1ULL << segment_bits)

                            - (1ULL << target_page_bits));

        if (slb->vsid & SLB_VSID_B) {

            hash = vsid ^ (vsid << 25) ^ (pageaddr >> target_page_bits);

        } else {

            hash = vsid ^ (pageaddr >> target_page_bits);

        }

        /* Only 5 bits of the page index are used in the AVPN */

        ctx->ptem = (slb->vsid & SLB_VSID_PTEM) |

            ((pageaddr >> 16) & ((1ULL << segment_bits) - 0x80));

    } else

#endif /* defined(TARGET_PPC64) */

    {

        target_ulong sr, pgidx;

        sr = env->sr[eaddr >> 28];

        ctx->key = (((sr & 0x20000000) && (pr != 0)) ||

                    ((sr & 0x40000000) && (pr == 0))) ? 1 : 0;

        ds = sr & 0x80000000 ? 1 : 0;

        ctx->nx = sr & 0x10000000 ? 1 : 0;

        vsid = sr & 0x00FFFFFF;

        target_page_bits = TARGET_PAGE_BITS;

        LOG_MMU("Check segment v=" TARGET_FMT_lx " %d " TARGET_FMT_lx " nip="

                TARGET_FMT_lx " lr=" TARGET_FMT_lx

                " ir=%d dr=%d pr=%d %d t=%d\n",

                eaddr, (int)(eaddr >> 28), sr, env->nip, env->lr, (int)msr_ir,

                (int)msr_dr, pr != 0 ? 1 : 0, rw, type);

        pgidx = (eaddr & ~SEGMENT_MASK_256M) >> target_page_bits;

        hash = vsid ^ pgidx;

        ctx->ptem = (vsid << 7) | (pgidx >> 10);

    }

    LOG_MMU("pte segment: key=%d ds %d nx %d vsid " TARGET_FMT_lx "\n",

            ctx->key, ds, ctx->nx, vsid);

    ret = -1;

    if (!ds) {

        /* Check if instruction fetch is allowed, if needed */

        if (type != ACCESS_CODE || ctx->nx == 0) {

            /* Page address translation */

            LOG_MMU("htab_base " TARGET_FMT_plx " htab_mask " TARGET_FMT_plx

                    " hash " TARGET_FMT_plx "\n",

                    env->htab_base, env->htab_mask, hash);

            ctx->hash[0] = hash;

            ctx->hash[1] = ~hash;

            /* Initialize real address with an invalid value */

            ctx->raddr = (target_phys_addr_t)-1ULL;

            if (unlikely(env->mmu_model == POWERPC_MMU_SOFT_6xx ||

                         env->mmu_model == POWERPC_MMU_SOFT_74xx)) {

                /* Software TLB search */

                ret = ppc6xx_tlb_check(env, ctx, eaddr, rw, type);

            } else {

                LOG_MMU("0 htab=" TARGET_FMT_plx "/" TARGET_FMT_plx

                        " vsid=" TARGET_FMT_lx " ptem=" TARGET_FMT_lx

                        " hash=" TARGET_FMT_plx "\n",

                        env->htab_base, env->htab_mask, vsid, ctx->ptem,

                        ctx->hash[0]);

                /* Primary table lookup */

                ret = find_pte(env, ctx, 0, rw, type, target_page_bits);

                if (ret < 0) {

                    /* Secondary table lookup */

                    if (eaddr != 0xEFFFFFFF)

                        LOG_MMU("1 htab=" TARGET_FMT_plx "/" TARGET_FMT_plx

                                " vsid=" TARGET_FMT_lx " api=" TARGET_FMT_lx

                                " hash=" TARGET_FMT_plx " pg_addr="

                                TARGET_FMT_plx "\n", env->htab_base,

                                env->htab_mask, vsid, ctx->ptem, ctx->hash[1]);

                    ret2 = find_pte(env, ctx, 1, rw, type,

                                    target_page_bits);

                    if (ret2 != -1)

                        ret = ret2;

                }

            }

#if defined (DUMP_PAGE_TABLES)

            if (qemu_log_enabled()) {

                target_phys_addr_t curaddr;

                uint32_t a0, a1, a2, a3;

                qemu_log("Page table: " TARGET_FMT_plx " len " TARGET_FMT_plx

                         "\n", sdr, mask + 0x80);

                for (curaddr = sdr; curaddr < (sdr + mask + 0x80);

                     curaddr += 16) {

                    a0 = ldl_phys(curaddr);

                    a1 = ldl_phys(curaddr + 4);

                    a2 = ldl_phys(curaddr + 8);

                    a3 = ldl_phys(curaddr + 12);

                    if (a0 != 0 || a1 != 0 || a2 != 0 || a3 != 0) {

                        qemu_log(TARGET_FMT_plx ": %08x %08x %08x %08x\n",

                                 curaddr, a0, a1, a2, a3);

                    }

                }

            }

#endif

        } else {

            LOG_MMU("No access allowed\n");

            ret = -3;

        }

    } else {

        LOG_MMU("direct store...\n");

        /* Direct-store segment : absolutely *BUGGY* for now */

        switch (type) {

        case ACCESS_INT:

            /* Integer load/store : only access allowed */

            break;

        case ACCESS_CODE:

            /* No code fetch is allowed in direct-store areas */

            return -4;

        case ACCESS_FLOAT:

            /* Floating point load/store */

            return -4;

        case ACCESS_RES:

            /* lwarx, ldarx or srwcx. */

            return -4;

        case ACCESS_CACHE:

            /* dcba, dcbt, dcbtst, dcbf, dcbi, dcbst, dcbz, or icbi */

            /* Should make the instruction do no-op.

             * As it already do no-op, it's quite easy :-)

             */

            ctx->raddr = eaddr;

            return 0;

        case ACCESS_EXT:

            /* eciwx or ecowx */

            return -4;

        default:

            qemu_log("ERROR: instruction should not need "

                        "address translation\n");

            return -4;

        }

        if ((rw == 1 || ctx->key != 1) && (rw == 0 || ctx->key != 0)) {

            ctx->raddr = eaddr;

            ret = 2;

        } else {

            ret = -2;

        }

    }

    return ret;

}


static always_inline void gen_op_subfco (void)

{

    gen_op_move_T2_T0();

    gen_op_subf();

    gen_op_check_subfc();

    gen_op_check_subfo();

}


static void ivshmem_read(void *opaque, const uint8_t *buf, int size)

{

    IVShmemState *s = opaque;

    int incoming_fd, tmp_fd;

    int guest_max_eventfd;

    long incoming_posn;

    if (fifo8_is_empty(&s->incoming_fifo) && size == sizeof(incoming_posn)) {

        memcpy(&incoming_posn, buf, size);

    } else {

        const uint8_t *p;

        uint32_t num;

        IVSHMEM_DPRINTF("short read of %d bytes\n", size);

        num = MAX(size, sizeof(long) - fifo8_num_used(&s->incoming_fifo));

        fifo8_push_all(&s->incoming_fifo, buf, num);

        if (fifo8_num_used(&s->incoming_fifo) < sizeof(incoming_posn)) {

            return;

        }

        size -= num;

        buf += num;

        p = fifo8_pop_buf(&s->incoming_fifo, sizeof(incoming_posn), &num);

        g_assert(num == sizeof(incoming_posn));

        memcpy(&incoming_posn, p, sizeof(incoming_posn));

        if (size > 0) {

            fifo8_push_all(&s->incoming_fifo, buf, size);

        }

    }

    if (incoming_posn < -1) {

        IVSHMEM_DPRINTF("invalid incoming_posn %ld\n", incoming_posn);

        return;

    }

    /* pick off s->server_chr->msgfd and store it, posn should accompany msg */

    tmp_fd = qemu_chr_fe_get_msgfd(s->server_chr);

    IVSHMEM_DPRINTF("posn is %ld, fd is %d\n", incoming_posn, tmp_fd);

    /* make sure we have enough space for this guest */

    if (incoming_posn >= s->nb_peers) {

        if (increase_dynamic_storage(s, incoming_posn) < 0) {

            error_report("increase_dynamic_storage() failed");

            if (tmp_fd != -1) {

            }

            return;

        }

    }

    if (tmp_fd == -1) {

        /* if posn is positive and unseen before then this is our posn*/

        if ((incoming_posn >= 0) &&

                            (s->peers[incoming_posn].eventfds == NULL)) {

            /* receive our posn */

            s->vm_id = incoming_posn;

            return;

        } else {

            /* otherwise an fd == -1 means an existing guest has gone away */

            IVSHMEM_DPRINTF("posn %ld has gone away\n", incoming_posn);

            close_guest_eventfds(s, incoming_posn);

            return;

        }

    }

    /* because of the implementation of get_msgfd, we need a dup */

    incoming_fd = dup(tmp_fd);

    if (incoming_fd == -1) {

        fprintf(stderr, "could not allocate file descriptor %s\n",

                                                            strerror(errno));

        return;

    }

    /* if the position is -1, then it's shared memory region fd */

    if (incoming_posn == -1) {

        void * map_ptr;

        s->max_peer = 0;

        if (check_shm_size(s, incoming_fd) == -1) {

            exit(-1);

        }

        /* mmap the region and map into the BAR2 */

        map_ptr = mmap(0, s->ivshmem_size, PROT_READ|PROT_WRITE, MAP_SHARED,

                                                            incoming_fd, 0);

        memory_region_init_ram_ptr(&s->ivshmem, OBJECT(s),

                                   "ivshmem.bar2", s->ivshmem_size, map_ptr);

        vmstate_register_ram(&s->ivshmem, DEVICE(s));

        IVSHMEM_DPRINTF("guest h/w addr = %p, size = %" PRIu64 "\n",

                         map_ptr, s->ivshmem_size);

        memory_region_add_subregion(&s->bar, 0, &s->ivshmem);

        /* only store the fd if it is successfully mapped */

        s->shm_fd = incoming_fd;

        return;

    }

    /* each guest has an array of eventfds, and we keep track of how many

     * guests for each VM */

    guest_max_eventfd = s->peers[incoming_posn].nb_eventfds;

    if (guest_max_eventfd == 0) {

        /* one eventfd per MSI vector */

        s->peers[incoming_posn].eventfds = g_new(EventNotifier, s->vectors);

    }

    /* this is an eventfd for a particular guest VM */

    IVSHMEM_DPRINTF("eventfds[%ld][%d] = %d\n", incoming_posn,

                                            guest_max_eventfd, incoming_fd);

    event_notifier_init_fd(&s->peers[incoming_posn].eventfds[guest_max_eventfd],

                           incoming_fd);

    /* increment count for particular guest */

    s->peers[incoming_posn].nb_eventfds++;

    /* keep track of the maximum VM ID */

    if (incoming_posn > s->max_peer) {

        s->max_peer = incoming_posn;

    }

    if (incoming_posn == s->vm_id) {

        s->eventfd_chr[guest_max_eventfd] = create_eventfd_chr_device(s,

                   &s->peers[s->vm_id].eventfds[guest_max_eventfd],

                   guest_max_eventfd);

    }

    if (ivshmem_has_feature(s, IVSHMEM_IOEVENTFD)) {

        ivshmem_add_eventfd(s, incoming_posn, guest_max_eventfd);

    }

}


static void kvm_s390_flic_class_init(ObjectClass *oc, void *data)

{

    DeviceClass *dc = DEVICE_CLASS(oc);

    S390FLICStateClass *fsc = S390_FLIC_COMMON_CLASS(oc);

    dc->realize = kvm_s390_flic_realize;

    dc->vmsd = &kvm_s390_flic_vmstate;

    dc->reset = kvm_s390_flic_reset;

    fsc->register_io_adapter = kvm_s390_register_io_adapter;

    fsc->io_adapter_map = kvm_s390_io_adapter_map;

    fsc->add_adapter_routes = kvm_s390_add_adapter_routes;

    fsc->release_adapter_routes = kvm_s390_release_adapter_routes;

    fsc->clear_io_irq = kvm_s390_clear_io_flic;

}


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

{

    MachineState *ms = MACHINE(obj);

    return ms->kernel_irqchip;

}


void bdrv_init_with_whitelist(void)

{

    use_bdrv_whitelist = 1;

    bdrv_init();

}


static void gen_cas_asi(DisasContext *dc, TCGv addr, TCGv val2,

                        int insn, int rd)

{

    TCGv val1 = gen_load_gpr(dc, rd);

    TCGv dst = gen_dest_gpr(dc, rd);

    TCGv_i32 r_asi = gen_get_asi(dc, insn);

    gen_helper_cas_asi(dst, cpu_env, addr, val1, val2, r_asi);

    tcg_temp_free_i32(r_asi);

    gen_store_gpr(dc, rd, dst);

}


static void rng_random_finalize(Object *obj)

{

    RndRandom *s = RNG_RANDOM(obj);

    qemu_set_fd_handler(s->fd, NULL, NULL, NULL);

    if (s->fd != -1) {

        qemu_close(s->fd);

    }

    g_free(s->filename);

}


static void blend_image_rgb(AVFilterContext *ctx, AVFrame *dst, const AVFrame *src, int x, int y)

{

    blend_image_packed_rgb(ctx, dst, src, 0, x, y, 0);

}


static int update_frame_pool(AVCodecContext *avctx, AVFrame *frame)

{

    FramePool *pool = avctx->internal->pool;

    int i, ret;

    switch (avctx->codec_type) {

    case AVMEDIA_TYPE_VIDEO: {

        uint8_t *data[4];

        int linesize[4];

        int size[4] = { 0 };

        int w = frame->width;

        int h = frame->height;

        int tmpsize, unaligned;

        if (pool->format == frame->format &&

            pool->width == frame->width && pool->height == frame->height)

            return 0;

        avcodec_align_dimensions2(avctx, &w, &h, pool->stride_align);

        do {

            // NOTE: do not align linesizes individually, this breaks e.g. assumptions

            // that linesize[0] == 2*linesize[1] in the MPEG-encoder for 4:2:2

            av_image_fill_linesizes(linesize, avctx->pix_fmt, w);

            // increase alignment of w for next try (rhs gives the lowest bit set in w)

            w += w & ~(w - 1);

            unaligned = 0;

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

                unaligned |= linesize[i] % pool->stride_align[i];

        } while (unaligned);

        tmpsize = av_image_fill_pointers(data, avctx->pix_fmt, h,

                                         NULL, linesize);

        if (tmpsize < 0)

            return -1;

        for (i = 0; i < 3 && data[i + 1]; i++)

            size[i] = data[i + 1] - data[i];

        size[i] = tmpsize - (data[i] - data[0]);

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

            av_buffer_pool_uninit(&pool->pools[i]);

            pool->linesize[i] = linesize[i];

            if (size[i]) {

                pool->pools[i] = av_buffer_pool_init(size[i] + 16 + STRIDE_ALIGN - 1,

                                                     CONFIG_MEMORY_POISONING ?

                                                        NULL :

                                                        av_buffer_allocz);

                if (!pool->pools[i]) {

                    ret = AVERROR(ENOMEM);

                    goto fail;

                }

            }

        }

        pool->format = frame->format;

        pool->width  = frame->width;

        pool->height = frame->height;

        break;

        }

    case AVMEDIA_TYPE_AUDIO: {

        int ch     = av_frame_get_channels(frame); //av_get_channel_layout_nb_channels(frame->channel_layout);

        int planar = av_sample_fmt_is_planar(frame->format);

        int planes = planar ? ch : 1;

        if (pool->format == frame->format && pool->planes == planes &&

            pool->channels == ch && frame->nb_samples == pool->samples)

            return 0;

        av_buffer_pool_uninit(&pool->pools[0]);

        ret = av_samples_get_buffer_size(&pool->linesize[0], ch,

                                         frame->nb_samples, frame->format, 0);

        if (ret < 0)

            goto fail;

        pool->pools[0] = av_buffer_pool_init(pool->linesize[0], NULL);

        if (!pool->pools[0]) {

            ret = AVERROR(ENOMEM);

            goto fail;

        }

        pool->format     = frame->format;

        pool->planes     = planes;

        pool->channels   = ch;

        pool->samples = frame->nb_samples;

        break;

        }

    default: av_assert0(0);

    }

    return 0;

fail:

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

        av_buffer_pool_uninit(&pool->pools[i]);

    pool->format = -1;

    pool->planes = pool->channels = pool->samples = 0;

    pool->width  = pool->height = 0;

    return ret;

}


int vring_pop(VirtIODevice *vdev, Vring *vring,

              VirtQueueElement *elem)

{

    struct vring_desc desc;

    unsigned int i, head, found = 0, num = vring->vr.num;

    uint16_t avail_idx, last_avail_idx;

    int ret;

    /* Initialize elem so it can be safely unmapped */

    elem->in_num = elem->out_num = 0;

    /* If there was a fatal error then refuse operation */

    if (vring->broken) {

        ret = -EFAULT;

        goto out;

    }

    /* Check it isn't doing very strange things with descriptor numbers. */

    last_avail_idx = vring->last_avail_idx;

    avail_idx = vring_get_avail_idx(vdev, vring);

    barrier(); /* load indices now and not again later */

    if (unlikely((uint16_t)(avail_idx - last_avail_idx) > num)) {

        error_report("Guest moved used index from %u to %u",

                     last_avail_idx, avail_idx);

        ret = -EFAULT;

        goto out;

    }

    /* If there's nothing new since last we looked. */

    if (avail_idx == last_avail_idx) {

        ret = -EAGAIN;

        goto out;

    }

    /* Only get avail ring entries after they have been exposed by guest. */

    smp_rmb();

    /* Grab the next descriptor number they're advertising, and increment

     * the index we've seen. */

    head = vring_get_avail_ring(vdev, vring, last_avail_idx % num);

    elem->index = head;

    /* If their number is silly, that's an error. */

    if (unlikely(head >= num)) {

        error_report("Guest says index %u > %u is available", head, num);

        ret = -EFAULT;

        goto out;

    }

    i = head;

    do {

        if (unlikely(i >= num)) {

            error_report("Desc index is %u > %u, head = %u", i, num, head);

            ret = -EFAULT;

            goto out;

        }

        if (unlikely(++found > num)) {

            error_report("Loop detected: last one at %u vq size %u head %u",

                         i, num, head);

            ret = -EFAULT;

            goto out;

        }

        copy_in_vring_desc(vdev, &vring->vr.desc[i], &desc);

        /* Ensure descriptor is loaded before accessing fields */

        barrier();

        if (desc.flags & VRING_DESC_F_INDIRECT) {

            ret = get_indirect(vdev, vring, elem, &desc);

            if (ret < 0) {

                goto out;

            }

            continue;

        }

        ret = get_desc(vring, elem, &desc);

        if (ret < 0) {

            goto out;

        }

        i = desc.next;

    } while (desc.flags & VRING_DESC_F_NEXT);

    /* On success, increment avail index. */

    vring->last_avail_idx++;

    if (virtio_has_feature(vdev, VIRTIO_RING_F_EVENT_IDX)) {

        vring_avail_event(&vring->vr) =

            virtio_tswap16(vdev, vring->last_avail_idx);

    }

    return head;

out:

    assert(ret < 0);

    if (ret == -EFAULT) {

        vring->broken = true;

    }

    vring_unmap_element(elem);

    return ret;

}


static void cpu_ppc_hdecr_cb(void *opaque)

{

    PowerPCCPU *cpu = opaque;

    _cpu_ppc_store_hdecr(cpu, 0x00000000, 0xFFFFFFFF, 1);

}


void qemu_system_killed(int signal, pid_t pid)

{

    shutdown_signal = signal;

    shutdown_pid = pid;

    no_shutdown = 0;

    qemu_system_shutdown_request();

}


static void gen_spr_405 (CPUPPCState *env)

{

    spr_register(env, SPR_4xx_CCR0, "CCR0",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00700000);

    /* Debug */

    /* XXX : not implemented */

    spr_register(env, SPR_405_DBCR1, "DBCR1",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_405_DVC1, "DVC1",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_405_DVC2, "DVC2",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_405_IAC3, "IAC3",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_405_IAC4, "IAC4",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* Storage control */

    spr_register(env, SPR_405_SLER, "SLER",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_40x_sler,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_405_SU0R, "SU0R",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* SPRG */

    spr_register(env, SPR_USPRG0, "USPRG0",

                 &spr_read_ureg, SPR_NOACCESS,

                 &spr_read_ureg, SPR_NOACCESS,

                 0x00000000);

    spr_register(env, SPR_SPRG4, "SPRG4",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    spr_register(env, SPR_USPRG4, "USPRG4",

                 &spr_read_ureg, SPR_NOACCESS,

                 &spr_read_ureg, SPR_NOACCESS,

                 0x00000000);

    spr_register(env, SPR_SPRG5, "SPRG5",

                 SPR_NOACCESS, SPR_NOACCESS,

                 spr_read_generic, &spr_write_generic,

                 0x00000000);

    spr_register(env, SPR_USPRG5, "USPRG5",

                 &spr_read_ureg, SPR_NOACCESS,

                 &spr_read_ureg, SPR_NOACCESS,

                 0x00000000);

    spr_register(env, SPR_SPRG6, "SPRG6",

                 SPR_NOACCESS, SPR_NOACCESS,

                 spr_read_generic, &spr_write_generic,

                 0x00000000);

    spr_register(env, SPR_USPRG6, "USPRG6",

                 &spr_read_ureg, SPR_NOACCESS,

                 &spr_read_ureg, SPR_NOACCESS,

                 0x00000000);

    spr_register(env, SPR_SPRG7, "SPRG7",

                 SPR_NOACCESS, SPR_NOACCESS,

                 spr_read_generic, &spr_write_generic,

                 0x00000000);

    spr_register(env, SPR_USPRG7, "USPRG7",

                 &spr_read_ureg, SPR_NOACCESS,

                 &spr_read_ureg, SPR_NOACCESS,

                 0x00000000);

}


static void realtime_init(void)

{

    if (enable_mlock) {

        if (os_mlock() < 0) {

            fprintf(stderr, "qemu: locking memory failed\n");

            exit(1);

        }

    }

}


int net_init_hubport(const NetClientOptions *opts, const char *name,

                     NetClientState *peer, Error **errp)

{

    const NetdevHubPortOptions *hubport;

    assert(opts->type == NET_CLIENT_OPTIONS_KIND_HUBPORT);

    assert(!peer);

    hubport = opts->u.hubport;

    net_hub_add_port(hubport->hubid, name);

    return 0;

}


static void switch_v7m_sp(CPUARMState *env, bool new_spsel)

{

    uint32_t tmp;

    bool old_spsel = env->v7m.control & R_V7M_CONTROL_SPSEL_MASK;

    if (old_spsel != new_spsel) {

        tmp = env->v7m.other_sp;

        env->v7m.other_sp = env->regs[13];

        env->regs[13] = tmp;

        env->v7m.control = deposit32(env->v7m.control,

                                     R_V7M_CONTROL_SPSEL_SHIFT,

                                     R_V7M_CONTROL_SPSEL_LENGTH, new_spsel);

    }

}


void qxl_log_cmd_cursor(PCIQXLDevice *qxl, QXLCursorCmd *cmd, int group_id)

{

    QXLCursor *cursor;

    fprintf(stderr, ": %s",

            qxl_name(qxl_cursor_cmd, cmd->type));

    switch (cmd->type) {

    case QXL_CURSOR_SET:

        fprintf(stderr, " +%d+%d visible %s, shape @ 0x%" PRIx64,

                cmd->u.set.position.x,

                cmd->u.set.position.y,

                cmd->u.set.visible ? "yes" : "no",

                cmd->u.set.shape);

        cursor = qxl_phys2virt(qxl, cmd->u.set.shape, group_id);

        fprintf(stderr, " type %s size %dx%d hot-spot +%d+%d"

                " unique 0x%" PRIx64 " data-size %d",

                qxl_name(spice_cursor_type, cursor->header.type),

                cursor->header.width, cursor->header.height,

                cursor->header.hot_spot_x, cursor->header.hot_spot_y,

                cursor->header.unique, cursor->data_size);

        break;

    case QXL_CURSOR_MOVE:

        fprintf(stderr, " +%d+%d", cmd->u.position.x, cmd->u.position.y);

        break;

    }

}


static void filter_mb(VP8Context *s, uint8_t *dst[3], VP8Macroblock *mb, int mb_x, int mb_y)

{

    int filter_level, inner_limit, hev_thresh, mbedge_lim, bedge_lim;

    filter_level_for_mb(s, mb, &filter_level, &inner_limit, &hev_thresh);

    if (!filter_level)

        return;

    mbedge_lim = 2*(filter_level+2) + inner_limit;

     bedge_lim = 2* filter_level    + inner_limit;

    if (mb_x) {

        s->vp8dsp.vp8_h_loop_filter16(dst[0], s->linesize,   mbedge_lim, inner_limit, hev_thresh);

        s->vp8dsp.vp8_h_loop_filter8 (dst[1], s->uvlinesize, mbedge_lim, inner_limit, hev_thresh);

        s->vp8dsp.vp8_h_loop_filter8 (dst[2], s->uvlinesize, mbedge_lim, inner_limit, hev_thresh);

    }

    if (!mb->skip || mb->mode == MODE_I4x4 || mb->mode == VP8_MVMODE_SPLIT) {

        s->vp8dsp.vp8_h_loop_filter16_inner(dst[0]+ 4, s->linesize,   bedge_lim, inner_limit, hev_thresh);

        s->vp8dsp.vp8_h_loop_filter16_inner(dst[0]+ 8, s->linesize,   bedge_lim, inner_limit, hev_thresh);

        s->vp8dsp.vp8_h_loop_filter16_inner(dst[0]+12, s->linesize,   bedge_lim, inner_limit, hev_thresh);

        s->vp8dsp.vp8_h_loop_filter8_inner (dst[1]+ 4, s->uvlinesize, bedge_lim, inner_limit, hev_thresh);

        s->vp8dsp.vp8_h_loop_filter8_inner (dst[2]+ 4, s->uvlinesize, bedge_lim, inner_limit, hev_thresh);

    }

    if (mb_y) {

        s->vp8dsp.vp8_v_loop_filter16(dst[0], s->linesize,   mbedge_lim, inner_limit, hev_thresh);

        s->vp8dsp.vp8_v_loop_filter8 (dst[1], s->uvlinesize, mbedge_lim, inner_limit, hev_thresh);

        s->vp8dsp.vp8_v_loop_filter8 (dst[2], s->uvlinesize, mbedge_lim, inner_limit, hev_thresh);

    }

    if (!mb->skip || mb->mode == MODE_I4x4 || mb->mode == VP8_MVMODE_SPLIT) {

        s->vp8dsp.vp8_v_loop_filter16_inner(dst[0]+ 4*s->linesize,   s->linesize,   bedge_lim, inner_limit, hev_thresh);

        s->vp8dsp.vp8_v_loop_filter16_inner(dst[0]+ 8*s->linesize,   s->linesize,   bedge_lim, inner_limit, hev_thresh);

        s->vp8dsp.vp8_v_loop_filter16_inner(dst[0]+12*s->linesize,   s->linesize,   bedge_lim, inner_limit, hev_thresh);

        s->vp8dsp.vp8_v_loop_filter8_inner (dst[1]+ 4*s->uvlinesize, s->uvlinesize, bedge_lim, inner_limit, hev_thresh);

        s->vp8dsp.vp8_v_loop_filter8_inner (dst[2]+ 4*s->uvlinesize, s->uvlinesize, bedge_lim, inner_limit, hev_thresh);

    }

}


static uint64_t memcard_read(void *opaque, target_phys_addr_t addr,

                             unsigned size)

{

    MilkymistMemcardState *s = opaque;

    uint32_t r = 0;

    addr >>= 2;

    switch (addr) {

    case R_CMD:

        if (!s->enabled) {

            r = 0xff;

        } else {

            r = s->response[s->response_read_ptr++];

            if (s->response_read_ptr > s->response_len) {

                error_report("milkymist_memcard: "

                        "read more cmd bytes than available. Clipping.");

                s->response_read_ptr = 0;

            }

        }

        break;

    case R_DAT:

        if (!s->enabled) {

            r = 0xffffffff;

        } else {

            r = 0;

            r |= sd_read_data(s->card) << 24;

            r |= sd_read_data(s->card) << 16;

            r |= sd_read_data(s->card) << 8;

            r |= sd_read_data(s->card);

        }

        break;

    case R_CLK2XDIV:

    case R_ENABLE:

    case R_PENDING:

    case R_START:

        r = s->regs[addr];

        break;

    default:

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

                TARGET_FMT_plx, addr << 2);

        break;

    }

    trace_milkymist_memcard_memory_read(addr << 2, r);

    return r;

}


START_TEST(qstring_get_str_test)

{

    QString *qstring;

    const char *ret_str;

    const char *str = "QEMU/KVM";

    qstring = qstring_from_str(str);

    ret_str = qstring_get_str(qstring);

    fail_unless(strcmp(ret_str, str) == 0);

    QDECREF(qstring);

}


static inline void set_bit(uint32_t *field, int bit)

{

    field[bit >> 5] |= 1 << (bit & 0x1F);

}


static int vdi_co_read(BlockDriverState *bs,

        int64_t sector_num, uint8_t *buf, int nb_sectors)

{

    BDRVVdiState *s = bs->opaque;

    uint32_t bmap_entry;

    uint32_t block_index;

    uint32_t sector_in_block;

    uint32_t n_sectors;

    int ret;

    logout("\n");

restart:

    block_index = sector_num / s->block_sectors;

    sector_in_block = sector_num % s->block_sectors;

    n_sectors = s->block_sectors - sector_in_block;

    if (n_sectors > nb_sectors) {

        n_sectors = nb_sectors;

    }

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

           n_sectors, sector_num);

    /* prepare next AIO request */

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

    if (!VDI_IS_ALLOCATED(bmap_entry)) {

        /* Block not allocated, return zeros, no need to wait. */

        memset(buf, 0, n_sectors * SECTOR_SIZE);

        ret = 0;

    } else {

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

                          (uint64_t)bmap_entry * s->block_sectors +

                          sector_in_block;

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

    }

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

    nb_sectors -= n_sectors;

    sector_num += n_sectors;

    buf += n_sectors * SECTOR_SIZE;

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

        goto restart;

    }

    return ret;

}


static void hmp_cont_cb(void *opaque, int err)

{

    Monitor *mon = opaque;

    if (!err) {

        hmp_cont(mon, NULL);

    }

}


static int64_t buffered_get_rate_limit(void *opaque)

{

    QEMUFileBuffered *s = opaque;

    return s->xfer_limit;

}