static int txd_decode_frame(AVCodecContext *avctx, void *data, int *data_size,

                            AVPacket *avpkt) {

    const uint8_t *buf = avpkt->data;

    TXDContext * const s = avctx->priv_data;

    AVFrame *picture = data;

    AVFrame * const p = &s->picture;

    unsigned int version, w, h, d3d_format, depth, stride, mipmap_count, flags;

    unsigned int y, v;

    uint8_t *ptr;

    const uint8_t *cur = buf;

    const uint32_t *palette = (const uint32_t *)(cur + 88);

    uint32_t *pal;

    version         = AV_RL32(cur);

    d3d_format      = AV_RL32(cur+76);

    w               = AV_RL16(cur+80);

    h               = AV_RL16(cur+82);

    depth           = AV_RL8 (cur+84);

    mipmap_count    = AV_RL8 (cur+85);

    flags           = AV_RL8 (cur+87);

    cur            += 92;

    if (version < 8 || version > 9) {

        av_log(avctx, AV_LOG_ERROR, "texture data version %i is unsupported\n",

                                                                    version);

        return -1;

    }

    if (depth == 8) {

        avctx->pix_fmt = PIX_FMT_PAL8;

        cur += 1024;

    } else if (depth == 16 || depth == 32)

        avctx->pix_fmt = PIX_FMT_RGB32;

    else {

        av_log(avctx, AV_LOG_ERROR, "depth of %i is unsupported\n", depth);

        return -1;

    }

    if (p->data[0])

        avctx->release_buffer(avctx, p);

    if (av_image_check_size(w, h, 0, avctx))

        return -1;

    if (w != avctx->width || h != avctx->height)

        avcodec_set_dimensions(avctx, w, h);

    if (avctx->get_buffer(avctx, p) < 0) {

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

        return -1;

    }

    p->pict_type = AV_PICTURE_TYPE_I;

    ptr    = p->data[0];

    stride = p->linesize[0];

    if (depth == 8) {

        pal = (uint32_t *) p->data[1];

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

            v = AV_RB32(palette+y);

            pal[y] = (v>>8) + (v<<24);

        }

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

            memcpy(ptr, cur, w);

            ptr += stride;

            cur += w;

        }

    } else if (depth == 16) {

        switch (d3d_format) {

        case 0:

            if (!(flags & 1))

                goto unsupported;

        case FF_S3TC_DXT1:

            ff_decode_dxt1(cur, ptr, w, h, stride);

            break;

        case FF_S3TC_DXT3:

            ff_decode_dxt3(cur, ptr, w, h, stride);

            break;

        default:

            goto unsupported;

        }

    } else if (depth == 32) {

        switch (d3d_format) {

        case 0x15:

        case 0x16:

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

                memcpy(ptr, cur, w*4);

                ptr += stride;

                cur += w*4;

            }

            break;

        default:

            goto unsupported;

        }

    }

    for (; mipmap_count > 1; mipmap_count--)

        cur += AV_RL32(cur) + 4;

    *picture   = s->picture;

    *data_size = sizeof(AVPicture);

    return cur - buf;

unsupported:

    av_log(avctx, AV_LOG_ERROR, "unsupported d3d format (%08x)\n", d3d_format);

    return -1;

}


void virtio_scsi_dataplane_start(VirtIOSCSI *s)

{

    int i;

    int rc;

    BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(s)));

    VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);

    VirtIOSCSICommon *vs = VIRTIO_SCSI_COMMON(s);

    if (s->dataplane_started ||

        s->dataplane_starting ||

        s->dataplane_fenced ||

        s->ctx != iothread_get_aio_context(vs->conf.iothread)) {

        return;

    }

    s->dataplane_starting = true;

    /* Set up guest notifier (irq) */

    rc = k->set_guest_notifiers(qbus->parent, vs->conf.num_queues + 2, true);

    if (rc != 0) {

        fprintf(stderr, "virtio-scsi: Failed to set guest notifiers (%d), "

                "ensure -enable-kvm is set\n", rc);

        goto fail_guest_notifiers;

    }

    aio_context_acquire(s->ctx);

    rc = virtio_scsi_vring_init(s, vs->ctrl_vq, 0);

    if (rc) {

        goto fail_vrings;

    }

    rc = virtio_scsi_vring_init(s, vs->event_vq, 1);

    if (rc) {

        goto fail_vrings;

    }

    for (i = 0; i < vs->conf.num_queues; i++) {

        rc = virtio_scsi_vring_init(s, vs->cmd_vqs[i], i + 2);

        if (rc) {

            goto fail_vrings;

        }

    }

    s->dataplane_starting = false;

    s->dataplane_started = true;

    aio_context_release(s->ctx);

    return;

fail_vrings:

    virtio_scsi_clear_aio(s);

    aio_context_release(s->ctx);

    for (i = 0; i < vs->conf.num_queues + 2; i++) {

        k->set_host_notifier(qbus->parent, i, false);

    }

    k->set_guest_notifiers(qbus->parent, vs->conf.num_queues + 2, false);

fail_guest_notifiers:

    s->dataplane_fenced = true;

    s->dataplane_starting = false;

    s->dataplane_started = true;

}


int bdrv_open(BlockDriverState *bs, const char *filename, int flags,

              BlockDriver *drv)

{

    int ret;

    char tmp_filename[PATH_MAX];

    if (flags & BDRV_O_SNAPSHOT) {

        BlockDriverState *bs1;

        int64_t total_size;

        int is_protocol = 0;

        BlockDriver *bdrv_qcow2;

        QEMUOptionParameter *options;

        char backing_filename[PATH_MAX];

        /* if snapshot, we create a temporary backing file and open it

           instead of opening 'filename' directly */

        /* if there is a backing file, use it */

        bs1 = bdrv_new("");

        ret = bdrv_open(bs1, filename, 0, drv);

        if (ret < 0) {

            bdrv_delete(bs1);

            return ret;

        }

        total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;

        if (bs1->drv && bs1->drv->protocol_name)

            is_protocol = 1;

        bdrv_delete(bs1);

        get_tmp_filename(tmp_filename, sizeof(tmp_filename));

        /* Real path is meaningless for protocols */

        if (is_protocol)

            snprintf(backing_filename, sizeof(backing_filename),

                     "%s", filename);

        else if (!realpath(filename, backing_filename))

            return -errno;

        bdrv_qcow2 = bdrv_find_format("qcow2");

        options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);

        set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size);

        set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);

        if (drv) {

            set_option_parameter(options, BLOCK_OPT_BACKING_FMT,

                drv->format_name);

        }

        ret = bdrv_create(bdrv_qcow2, tmp_filename, options);

        free_option_parameters(options);

        if (ret < 0) {

            return ret;

        }

        filename = tmp_filename;

        drv = bdrv_qcow2;

        bs->is_temporary = 1;

    }

    /* Find the right image format driver */

    if (!drv) {

        ret = find_image_format(filename, &drv);

    }

    if (!drv) {

        goto unlink_and_fail;

    }

    /* Open the image */

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

    if (ret < 0) {

        goto unlink_and_fail;

    }

    /* If there is a backing file, use it */

    if ((flags & BDRV_O_NO_BACKING) == 0 && bs->backing_file[0] != '\0') {

        char backing_filename[PATH_MAX];

        int back_flags;

        BlockDriver *back_drv = NULL;

        bs->backing_hd = bdrv_new("");

        bdrv_get_full_backing_filename(bs, backing_filename,

                                       sizeof(backing_filename));

        if (bs->backing_format[0] != '\0') {

            back_drv = bdrv_find_format(bs->backing_format);

        }

        /* backing files always opened read-only */

        back_flags =

            flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);

        ret = bdrv_open(bs->backing_hd, backing_filename, back_flags, back_drv);

        if (ret < 0) {

            bdrv_close(bs);

            return ret;

        }

        if (bs->is_temporary) {

            bs->backing_hd->keep_read_only = !(flags & BDRV_O_RDWR);

        } else {

            /* base image inherits from "parent" */

            bs->backing_hd->keep_read_only = bs->keep_read_only;

        }

    }

    if (!bdrv_key_required(bs)) {

        bdrv_dev_change_media_cb(bs, true);

    }

    /* throttling disk I/O limits */

    if (bs->io_limits_enabled) {

        bdrv_io_limits_enable(bs);

    }

    return 0;

unlink_and_fail:

    if (bs->is_temporary) {

        unlink(filename);

    }

    return ret;

}


void helper_booke206_tlbwe(void)
{
    uint32_t tlbncfg, tlbn;
    ppcmas_tlb_t *tlb;
    uint32_t size_tlb, size_ps;
    switch (env->spr[SPR_BOOKE_MAS0] & MAS0_WQ_MASK) {
    case MAS0_WQ_ALWAYS:
        /* good to go, write that entry */
        break;
    case MAS0_WQ_COND:
        /* XXX check if reserved */
        if (0) {
            return;
        break;
    case MAS0_WQ_CLR_RSRV:
        /* XXX clear entry */
        return;
    default:
        /* no idea what to do */
        return;
    if (((env->spr[SPR_BOOKE_MAS0] & MAS0_ATSEL) == MAS0_ATSEL_LRAT) &&
         !msr_gs) {
        /* XXX we don't support direct LRAT setting yet */
        fprintf(stderr, "cpu: don't support LRAT setting yet\n");
        return;
    tlbn = (env->spr[SPR_BOOKE_MAS0] & MAS0_TLBSEL_MASK) >> MAS0_TLBSEL_SHIFT;
    tlbncfg = env->spr[SPR_BOOKE_TLB0CFG + tlbn];
    tlb = booke206_cur_tlb(env);
    if (msr_gs) {
        cpu_abort(env, "missing HV implementation\n");
    tlb->mas7_3 = ((uint64_t)env->spr[SPR_BOOKE_MAS7] << 32) |
                  env->spr[SPR_BOOKE_MAS3];
    tlb->mas1 = env->spr[SPR_BOOKE_MAS1];
    /* XXX needs to change when supporting 64-bit e500 */
    tlb->mas2 = env->spr[SPR_BOOKE_MAS2] & 0xffffffff;
    if (!(tlbncfg & TLBnCFG_IPROT)) {
        /* no IPROT supported by TLB */
        tlb->mas1 &= ~MAS1_IPROT;
    if (booke206_tlb_to_page_size(env, tlb) == TARGET_PAGE_SIZE) {
        tlb_flush_page(env, tlb->mas2 & MAS2_EPN_MASK);
    } else {
        tlb_flush(env, 1);


static void s390_qemu_cpu_model_initfn(Object *obj)
{
}


static int start_frame(AVFilterLink *inlink, AVFilterBufferRef *picref)

{

    AVFilterContext *ctx  = inlink->dst;

    TileContext *tile    = ctx->priv;

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

    if (tile->current)

        return 0;

    outlink->out_buf = ff_get_video_buffer(outlink, AV_PERM_WRITE,

                                                 outlink->w, outlink->h);

    avfilter_copy_buffer_ref_props(outlink->out_buf, picref);

    outlink->out_buf->video->w = outlink->w;

    outlink->out_buf->video->h = outlink->h;

    /* fill surface once for margin/padding */

    if (tile->margin || tile->padding)

        ff_fill_rectangle(&tile->draw, &tile->blank,

                          outlink->out_buf->data, outlink->out_buf->linesize,

                          0, 0, outlink->w, outlink->h);

    return 0;

}


static int v4l2_read_header(AVFormatContext *ctx)

{

    struct video_data *s = ctx->priv_data;

    AVStream *st;

    int res = 0;

    uint32_t desired_format;

    enum AVCodecID codec_id = AV_CODEC_ID_NONE;

    enum AVPixelFormat pix_fmt = AV_PIX_FMT_NONE;

    struct v4l2_input input = { 0 };

    st = avformat_new_stream(ctx, NULL);

    if (!st)

        return AVERROR(ENOMEM);

#if CONFIG_LIBV4L2

    /* silence libv4l2 logging. if fopen() fails v4l2_log_file will be NULL

       and errors will get sent to stderr */

    if (s->use_libv4l2)

        v4l2_log_file = fopen("/dev/null", "w");

#endif

    s->fd = device_open(ctx);

    if (s->fd < 0)

        return s->fd;

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

        /* set video input */

        av_log(ctx, AV_LOG_DEBUG, "Selecting input_channel: %d\n", s->channel);

        if (v4l2_ioctl(s->fd, VIDIOC_S_INPUT, &s->channel) < 0) {

            res = AVERROR(errno);

            av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_S_INPUT): %s\n", av_err2str(res));

            goto fail;

        }

    } else {

        /* get current video input */

        if (v4l2_ioctl(s->fd, VIDIOC_G_INPUT, &s->channel) < 0) {

            res = AVERROR(errno);

            av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_G_INPUT): %s\n", av_err2str(res));

            goto fail;

        }

    }

    /* enum input */

    input.index = s->channel;

    if (v4l2_ioctl(s->fd, VIDIOC_ENUMINPUT, &input) < 0) {

        res = AVERROR(errno);

        av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_ENUMINPUT): %s\n", av_err2str(res));

        goto fail;

    }

    s->std_id = input.std;

    av_log(ctx, AV_LOG_DEBUG, "Current input_channel: %d, input_name: %s, input_std: %"PRIx64"\n",

           s->channel, input.name, (uint64_t)input.std);

    if (s->list_format) {

        list_formats(ctx, s->list_format);

        res = AVERROR_EXIT;

        goto fail;

    }

    if (s->list_standard) {

        list_standards(ctx);

        res = AVERROR_EXIT;

        goto fail;

    }

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

    if ((res = v4l2_set_parameters(ctx)) < 0)

        goto fail;

    if (s->pixel_format) {

        AVCodec *codec = avcodec_find_decoder_by_name(s->pixel_format);

        if (codec)

            ctx->video_codec_id = codec->id;

        pix_fmt = av_get_pix_fmt(s->pixel_format);

        if (pix_fmt == AV_PIX_FMT_NONE && !codec) {

            av_log(ctx, AV_LOG_ERROR, "No such input format: %s.\n",

                   s->pixel_format);

            res = AVERROR(EINVAL);

            goto fail;

        }

    }

    if (!s->width && !s->height) {

        struct v4l2_format fmt = { .type = V4L2_BUF_TYPE_VIDEO_CAPTURE };

        av_log(ctx, AV_LOG_VERBOSE,

               "Querying the device for the current frame size\n");

        if (v4l2_ioctl(s->fd, VIDIOC_G_FMT, &fmt) < 0) {

            res = AVERROR(errno);

            av_log(ctx, AV_LOG_ERROR, "ioctl(VIDIOC_G_FMT): %s\n", av_err2str(res));

            goto fail;

        }

        s->width  = fmt.fmt.pix.width;

        s->height = fmt.fmt.pix.height;

        av_log(ctx, AV_LOG_VERBOSE,

               "Setting frame size to %dx%d\n", s->width, s->height);

    }

    res = device_try_init(ctx, pix_fmt, &s->width, &s->height, &desired_format, &codec_id);

    if (res < 0)

        goto fail;

    /* If no pixel_format was specified, the codec_id was not known up

     * until now. Set video_codec_id in the context, as codec_id will

     * not be available outside this function

     */

    if (codec_id != AV_CODEC_ID_NONE && ctx->video_codec_id == AV_CODEC_ID_NONE)

        ctx->video_codec_id = codec_id;

    if ((res = av_image_check_size(s->width, s->height, 0, ctx)) < 0)

        goto fail;

    s->frame_format = desired_format;

    st->codec->pix_fmt = avpriv_fmt_v4l2ff(desired_format, codec_id);

    s->frame_size =

        avpicture_get_size(st->codec->pix_fmt, s->width, s->height);

    if ((res = mmap_init(ctx)) ||

        (res = mmap_start(ctx)) < 0)

            goto fail;

    s->top_field_first = first_field(s);

    st->codec->codec_type = AVMEDIA_TYPE_VIDEO;

    st->codec->codec_id = codec_id;

    if (codec_id == AV_CODEC_ID_RAWVIDEO)

        st->codec->codec_tag =

            avcodec_pix_fmt_to_codec_tag(st->codec->pix_fmt);

    else if (codec_id == AV_CODEC_ID_H264) {

        st->need_parsing = AVSTREAM_PARSE_HEADERS;

    }

    if (desired_format == V4L2_PIX_FMT_YVU420)

        st->codec->codec_tag = MKTAG('Y', 'V', '1', '2');

    else if (desired_format == V4L2_PIX_FMT_YVU410)

        st->codec->codec_tag = MKTAG('Y', 'V', 'U', '9');

    st->codec->width = s->width;

    st->codec->height = s->height;

    if (st->avg_frame_rate.den)

        st->codec->bit_rate = s->frame_size * av_q2d(st->avg_frame_rate) * 8;

    return 0;

fail:

    v4l2_close(s->fd);

    return res;

}


static int output_frame(H264Context *h, AVFrame *dst, Picture *srcp)

{

    AVFrame *src = &srcp->f;

    int i;

    int ret = av_frame_ref(dst, src);

    if (ret < 0)

        return ret;

    av_dict_set(&dst->metadata, "stereo_mode", ff_h264_sei_stereo_mode(h), 0);

    if (!srcp->crop)

        return 0;

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

        int hshift = (i > 0) ? h->chroma_x_shift : 0;

        int vshift = (i > 0) ? h->chroma_y_shift : 0;

        int off    = ((srcp->crop_left >> hshift) << h->pixel_shift) +

                      (srcp->crop_top  >> vshift) * dst->linesize[i];

        dst->data[i] += off;

    }

    return 0;

}


static int flac_write_header(struct AVFormatContext *s)

{

    int ret;

    AVCodecContext *codec = s->streams[0]->codec;

    FlacMuxerContext *c   = s->priv_data;

    if (!c->write_header)

        return 0;

    ret = ff_flac_write_header(s->pb, codec, 0);

    if (ret)

        return ret;

    ret = flac_write_block_comment(s->pb, &s->metadata, 0,

                                   codec->flags & CODEC_FLAG_BITEXACT);

    if (ret)

        return ret;

    /* The command line flac encoder defaults to placing a seekpoint

     * every 10s.  So one might add padding to allow that later

     * but there seems to be no simple way to get the duration here.

     * So let's try the flac default of 8192 bytes */

    flac_write_block_padding(s->pb, 8192, 1);

    return ret;

}


int ff_qsv_enc_init(AVCodecContext *avctx, QSVEncContext *q)

{

    int opaque_alloc = 0;

    int ret;

    q->param.IOPattern  = MFX_IOPATTERN_IN_SYSTEM_MEMORY;

    q->param.AsyncDepth = q->async_depth;

    q->async_fifo = av_fifo_alloc((1 + q->async_depth) *

                                  (sizeof(AVPacket) + sizeof(mfxSyncPoint) + sizeof(mfxBitstream*)));

    if (!q->async_fifo)

        return AVERROR(ENOMEM);

    if (avctx->hwaccel_context) {

        AVQSVContext *qsv = avctx->hwaccel_context;

        q->session         = qsv->session;

        q->param.IOPattern = qsv->iopattern;

        opaque_alloc = qsv->opaque_alloc;

    }

    if (!q->session) {

        ret = ff_qsv_init_internal_session(avctx, &q->internal_session,

                                           q->load_plugins);

        if (ret < 0)

            return ret;

        q->session = q->internal_session;

    }

    ret = init_video_param(avctx, q);

    if (ret < 0)

        return ret;

    ret = MFXVideoENCODE_QueryIOSurf(q->session, &q->param, &q->req);

    if (ret < 0) {

        av_log(avctx, AV_LOG_ERROR, "Error querying the encoding parameters\n");

        return ff_qsv_error(ret);

    }

    if (opaque_alloc) {

        ret = qsv_init_opaque_alloc(avctx, q);

        if (ret < 0)

            return ret;

    }

    if (avctx->hwaccel_context) {

        AVQSVContext *qsv = avctx->hwaccel_context;

        int i, j;

        q->extparam = av_mallocz_array(qsv->nb_ext_buffers + q->nb_extparam_internal,

                                       sizeof(*q->extparam));

        if (!q->extparam)

            return AVERROR(ENOMEM);

        q->param.ExtParam = q->extparam;

        for (i = 0; i < qsv->nb_ext_buffers; i++)

            q->param.ExtParam[i] = qsv->ext_buffers[i];

        q->param.NumExtParam = qsv->nb_ext_buffers;

        for (i = 0; i < q->nb_extparam_internal; i++) {

            for (j = 0; j < qsv->nb_ext_buffers; j++) {

                if (qsv->ext_buffers[j]->BufferId == q->extparam_internal[i]->BufferId)

                    break;

            }

            if (j < qsv->nb_ext_buffers)

                continue;

            q->param.ExtParam[q->param.NumExtParam++] = q->extparam_internal[i];

        }

    } else {

        q->param.ExtParam    = q->extparam_internal;

        q->param.NumExtParam = q->nb_extparam_internal;

    }

    ret = MFXVideoENCODE_Init(q->session, &q->param);

    if (ret < 0) {

        av_log(avctx, AV_LOG_ERROR, "Error initializing the encoder\n");

        return ff_qsv_error(ret);

    }

    ret = qsv_retrieve_enc_params(avctx, q);

    if (ret < 0) {

        av_log(avctx, AV_LOG_ERROR, "Error retrieving encoding parameters.\n");

        return ret;

    }

    q->avctx = avctx;

    return 0;

}


void st_print_trace(FILE *stream, int (*stream_printf)(FILE *stream, const char *fmt, ...))

{

    unsigned int i;

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

        TraceRecord record;

        if (!get_trace_record(i, &record)) {

            continue;

        }

        stream_printf(stream, "Event %" PRIu64 " : %" PRIx64 " %" PRIx64

                      " %" PRIx64 " %" PRIx64 " %" PRIx64 " %" PRIx64 "\n",

                      record.event, record.x1, record.x2,

                      record.x3, record.x4, record.x5,

                      record.x6);

    }

}


static int vorbis_parse_setup_hdr_floors(vorbis_context *vc) {

    GetBitContext *gb=&vc->gb;

    uint_fast16_t i,j,k;

    vc->floor_count=get_bits(gb, 6)+1;

    vc->floors=av_mallocz(vc->floor_count * sizeof(vorbis_floor));

    for (i=0;i<vc->floor_count;++i) {

        vorbis_floor *floor_setup=&vc->floors[i];

        floor_setup->floor_type=get_bits(gb, 16);

        AV_DEBUG(" %d. floor type %d \n", i, floor_setup->floor_type);

        if (floor_setup->floor_type==1) {

            uint_fast8_t maximum_class=0;

            uint_fast8_t rangebits;

            uint_fast16_t floor1_values=2;

            floor_setup->decode=vorbis_floor1_decode;

            floor_setup->data.t1.partitions=get_bits(gb, 5);

            AV_DEBUG(" %d.floor: %d partitions \n", i, floor_setup->data.t1.partitions);

            for(j=0;j<floor_setup->data.t1.partitions;++j) {

                floor_setup->data.t1.partition_class[j]=get_bits(gb, 4);

                if (floor_setup->data.t1.partition_class[j]>maximum_class) maximum_class=floor_setup->data.t1.partition_class[j];

                AV_DEBUG(" %d. floor %d partition class %d \n", i, j, floor_setup->data.t1.partition_class[j]);

            }

            AV_DEBUG(" maximum class %d \n", maximum_class);

            floor_setup->data.t1.maximum_class=maximum_class;

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

                floor_setup->data.t1.class_dimensions[j]=get_bits(gb, 3)+1;

                floor_setup->data.t1.class_subclasses[j]=get_bits(gb, 2);

                AV_DEBUG(" %d floor %d class dim: %d subclasses %d \n", i, j, floor_setup->data.t1.class_dimensions[j], floor_setup->data.t1.class_subclasses[j]);

                if (floor_setup->data.t1.class_subclasses[j]) {

                    floor_setup->data.t1.class_masterbook[j]=get_bits(gb, 8);

                    AV_DEBUG("   masterbook: %d \n", floor_setup->data.t1.class_masterbook[j]);

                }

                for(k=0;k<(1<<floor_setup->data.t1.class_subclasses[j]);++k) {

                    floor_setup->data.t1.subclass_books[j][k]=(int16_t)get_bits(gb, 8)-1;

                    AV_DEBUG("    book %d. : %d \n", k, floor_setup->data.t1.subclass_books[j][k]);

                }

            }

            floor_setup->data.t1.multiplier=get_bits(gb, 2)+1;

            floor_setup->data.t1.x_list_dim=2;

            for(j=0;j<floor_setup->data.t1.partitions;++j) {

                floor_setup->data.t1.x_list_dim+=floor_setup->data.t1.class_dimensions[floor_setup->data.t1.partition_class[j]];

            }

            floor_setup->data.t1.list=av_mallocz(floor_setup->data.t1.x_list_dim * sizeof(vorbis_floor1_entry));

            rangebits=get_bits(gb, 4);

            floor_setup->data.t1.list[0].x = 0;

            floor_setup->data.t1.list[1].x = (1<<rangebits);

            for(j=0;j<floor_setup->data.t1.partitions;++j) {

                for(k=0;k<floor_setup->data.t1.class_dimensions[floor_setup->data.t1.partition_class[j]];++k,++floor1_values) {

                    floor_setup->data.t1.list[floor1_values].x=get_bits(gb, rangebits);

                    AV_DEBUG(" %d. floor1 Y coord. %d \n", floor1_values, floor_setup->data.t1.list[floor1_values].x);

                }

            }

// Precalculate order of x coordinates - needed for decode

            ff_vorbis_ready_floor1_list(floor_setup->data.t1.list, floor_setup->data.t1.x_list_dim);

        }

        else if(floor_setup->floor_type==0) {

            uint_fast8_t max_codebook_dim=0;

            floor_setup->decode=vorbis_floor0_decode;

            floor_setup->data.t0.order=get_bits(gb, 8);

            floor_setup->data.t0.rate=get_bits(gb, 16);

            floor_setup->data.t0.bark_map_size=get_bits(gb, 16);

            floor_setup->data.t0.amplitude_bits=get_bits(gb, 6);

            /* zero would result in a div by zero later *

             * 2^0 - 1 == 0                             */

            if (floor_setup->data.t0.amplitude_bits == 0) {

              av_log(vc->avccontext, AV_LOG_ERROR,

                     "Floor 0 amplitude bits is 0.\n");

              return 1;

            }

            floor_setup->data.t0.amplitude_offset=get_bits(gb, 8);

            floor_setup->data.t0.num_books=get_bits(gb, 4)+1;

            /* allocate mem for booklist */

            floor_setup->data.t0.book_list=

                av_malloc(floor_setup->data.t0.num_books);

            if(!floor_setup->data.t0.book_list) { return 1; }

            /* read book indexes */

            {

                int idx;

                uint_fast8_t book_idx;

                for (idx=0;idx<floor_setup->data.t0.num_books;++idx) {

                    book_idx=get_bits(gb, 8);

                    if (book_idx>=vc->codebook_count)

                        return 1;

                    floor_setup->data.t0.book_list[idx]=book_idx;

                    if (vc->codebooks[book_idx].dimensions > max_codebook_dim)

                        max_codebook_dim=vc->codebooks[book_idx].dimensions;

                }

            }

            create_map( vc, i );

            /* allocate mem for lsp coefficients */

            {

                /* codebook dim is for padding if codebook dim doesn't *

                 * divide order+1 then we need to read more data       */

                floor_setup->data.t0.lsp=

                    av_malloc((floor_setup->data.t0.order+1 + max_codebook_dim)

                              * sizeof(float));

                if(!floor_setup->data.t0.lsp) { return 1; }

            }

#ifdef V_DEBUG /* debug output parsed headers */

            AV_DEBUG("floor0 order: %u\n", floor_setup->data.t0.order);

            AV_DEBUG("floor0 rate: %u\n", floor_setup->data.t0.rate);

            AV_DEBUG("floor0 bark map size: %u\n",

              floor_setup->data.t0.bark_map_size);

            AV_DEBUG("floor0 amplitude bits: %u\n",

              floor_setup->data.t0.amplitude_bits);

            AV_DEBUG("floor0 amplitude offset: %u\n",

              floor_setup->data.t0.amplitude_offset);

            AV_DEBUG("floor0 number of books: %u\n",

              floor_setup->data.t0.num_books);

            AV_DEBUG("floor0 book list pointer: %p\n",

              floor_setup->data.t0.book_list);

            {

              int idx;

              for (idx=0;idx<floor_setup->data.t0.num_books;++idx) {

                AV_DEBUG( "  Book %d: %u\n",

                  idx+1,

                  floor_setup->data.t0.book_list[idx] );

              }

            }

#endif

        }

        else {

            av_log(vc->avccontext, AV_LOG_ERROR, "Invalid floor type!\n");

            return 1;

        }

    }

    return 0;

}


void qemu_anon_ram_free(void *ptr, size_t size)

{

    trace_qemu_anon_ram_free(ptr, size);

    if (ptr) {

        munmap(ptr, size);

    }

}


void qemu_run_all_timers(void)

{

    /* rearm timer, if not periodic */

    if (alarm_timer->expired) {

        alarm_timer->expired = 0;

        qemu_rearm_alarm_timer(alarm_timer);

    }

    alarm_timer->pending = 0;

    /* vm time timers */

    if (vm_running) {

        qemu_run_timers(vm_clock);

    }

    qemu_run_timers(rt_clock);

    qemu_run_timers(host_clock);

}


static void mips_jazz_init(MemoryRegion *address_space,

                           MemoryRegion *address_space_io,

                           ram_addr_t ram_size,

                           const char *cpu_model,

                           enum jazz_model_e jazz_model)

{

    char *filename;

    int bios_size, n;

    MIPSCPU *cpu;

    CPUMIPSState *env;

    qemu_irq *rc4030, *i8259;

    rc4030_dma *dmas;

    void* rc4030_opaque;

    MemoryRegion *rtc = g_new(MemoryRegion, 1);

    MemoryRegion *i8042 = g_new(MemoryRegion, 1);

    MemoryRegion *dma_dummy = g_new(MemoryRegion, 1);

    NICInfo *nd;

    DeviceState *dev;

    SysBusDevice *sysbus;

    ISABus *isa_bus;

    ISADevice *pit;

    DriveInfo *fds[MAX_FD];

    qemu_irq esp_reset, dma_enable;

    qemu_irq *cpu_exit_irq;

    MemoryRegion *ram = g_new(MemoryRegion, 1);

    MemoryRegion *bios = g_new(MemoryRegion, 1);

    MemoryRegion *bios2 = g_new(MemoryRegion, 1);

    /* init CPUs */

    if (cpu_model == NULL) {

#ifdef TARGET_MIPS64

        cpu_model = "R4000";

#else

        /* FIXME: All wrong, this maybe should be R3000 for the older JAZZs. */

        cpu_model = "24Kf";

#endif

    }

    cpu = cpu_mips_init(cpu_model);

    if (cpu == NULL) {

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

        exit(1);

    }

    env = &cpu->env;

    qemu_register_reset(main_cpu_reset, cpu);

    /* allocate RAM */

    memory_region_init_ram(ram, "mips_jazz.ram", ram_size);

    vmstate_register_ram_global(ram);

    memory_region_add_subregion(address_space, 0, ram);

    memory_region_init_ram(bios, "mips_jazz.bios", MAGNUM_BIOS_SIZE);

    vmstate_register_ram_global(bios);

    memory_region_set_readonly(bios, true);

    memory_region_init_alias(bios2, "mips_jazz.bios", bios,

                             0, MAGNUM_BIOS_SIZE);

    memory_region_add_subregion(address_space, 0x1fc00000LL, bios);

    memory_region_add_subregion(address_space, 0xfff00000LL, bios2);

    /* load the BIOS image. */

    if (bios_name == NULL)

        bios_name = BIOS_FILENAME;

    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);

    if (filename) {

        bios_size = load_image_targphys(filename, 0xfff00000LL,

                                        MAGNUM_BIOS_SIZE);

        g_free(filename);

    } else {

        bios_size = -1;

    }

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

        fprintf(stderr, "qemu: Could not load MIPS bios '%s'\n",

                bios_name);

        exit(1);

    }

    /* Init CPU internal devices */

    cpu_mips_irq_init_cpu(env);

    cpu_mips_clock_init(env);

    /* Chipset */

    rc4030_opaque = rc4030_init(env->irq[6], env->irq[3], &rc4030, &dmas,

                                address_space);

    memory_region_init_io(dma_dummy, &dma_dummy_ops, NULL, "dummy_dma", 0x1000);

    memory_region_add_subregion(address_space, 0x8000d000, dma_dummy);

    /* ISA devices */

    isa_bus = isa_bus_new(NULL, address_space_io);

    i8259 = i8259_init(isa_bus, env->irq[4]);

    isa_bus_irqs(isa_bus, i8259);

    cpu_exit_irq = qemu_allocate_irqs(cpu_request_exit, NULL, 1);

    DMA_init(0, cpu_exit_irq);

    pit = pit_init(isa_bus, 0x40, 0, NULL);

    pcspk_init(isa_bus, pit);

    /* ISA IO space at 0x90000000 */

    isa_mmio_init(0x90000000, 0x01000000);

    isa_mem_base = 0x11000000;

    /* Video card */

    switch (jazz_model) {

    case JAZZ_MAGNUM:

        dev = qdev_create(NULL, "sysbus-g364");

        qdev_init_nofail(dev);

        sysbus = sysbus_from_qdev(dev);

        sysbus_mmio_map(sysbus, 0, 0x60080000);

        sysbus_mmio_map(sysbus, 1, 0x40000000);

        sysbus_connect_irq(sysbus, 0, rc4030[3]);

        {

            /* Simple ROM, so user doesn't have to provide one */

            MemoryRegion *rom_mr = g_new(MemoryRegion, 1);

            memory_region_init_ram(rom_mr, "g364fb.rom", 0x80000);

            vmstate_register_ram_global(rom_mr);

            memory_region_set_readonly(rom_mr, true);

            uint8_t *rom = memory_region_get_ram_ptr(rom_mr);

            memory_region_add_subregion(address_space, 0x60000000, rom_mr);

            rom[0] = 0x10; /* Mips G364 */

        }

        break;

    case JAZZ_PICA61:

        isa_vga_mm_init(0x40000000, 0x60000000, 0, get_system_memory());

        break;

    default:

        break;

    }

    /* Network controller */

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

        nd = &nd_table[n];

        if (!nd->model)

            nd->model = g_strdup("dp83932");

        if (strcmp(nd->model, "dp83932") == 0) {

            dp83932_init(nd, 0x80001000, 2, get_system_memory(), rc4030[4],

                         rc4030_opaque, rc4030_dma_memory_rw);

            break;

        } else if (strcmp(nd->model, "?") == 0) {

            fprintf(stderr, "qemu: Supported NICs: dp83932\n");

            exit(1);

        } else {

            fprintf(stderr, "qemu: Unsupported NIC: %s\n", nd->model);

            exit(1);

        }

    }

    /* SCSI adapter */

    esp_init(0x80002000, 0,

             rc4030_dma_read, rc4030_dma_write, dmas[0],

             rc4030[5], &esp_reset, &dma_enable);

    /* Floppy */

    if (drive_get_max_bus(IF_FLOPPY) >= MAX_FD) {

        fprintf(stderr, "qemu: too many floppy drives\n");

        exit(1);

    }

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

        fds[n] = drive_get(IF_FLOPPY, 0, n);

    }

    fdctrl_init_sysbus(rc4030[1], 0, 0x80003000, fds);

    /* Real time clock */

    rtc_init(isa_bus, 1980, NULL);

    memory_region_init_io(rtc, &rtc_ops, NULL, "rtc", 0x1000);

    memory_region_add_subregion(address_space, 0x80004000, rtc);

    /* Keyboard (i8042) */

    i8042_mm_init(rc4030[6], rc4030[7], i8042, 0x1000, 0x1);

    memory_region_add_subregion(address_space, 0x80005000, i8042);

    /* Serial ports */

    if (serial_hds[0]) {

        serial_mm_init(address_space, 0x80006000, 0, rc4030[8], 8000000/16,

                       serial_hds[0], DEVICE_NATIVE_ENDIAN);

    }

    if (serial_hds[1]) {

        serial_mm_init(address_space, 0x80007000, 0, rc4030[9], 8000000/16,

                       serial_hds[1], DEVICE_NATIVE_ENDIAN);

    }

    /* Parallel port */

    if (parallel_hds[0])

        parallel_mm_init(address_space, 0x80008000, 0, rc4030[0],

                         parallel_hds[0]);

    /* Sound card */

    /* FIXME: missing Jazz sound at 0x8000c000, rc4030[2] */

    audio_init(isa_bus, NULL);

    /* NVRAM */

    dev = qdev_create(NULL, "ds1225y");

    qdev_init_nofail(dev);

    sysbus = sysbus_from_qdev(dev);

    sysbus_mmio_map(sysbus, 0, 0x80009000);

    /* LED indicator */

    sysbus_create_simple("jazz-led", 0x8000f000, NULL);

}


static int qemu_rdma_close(void *opaque)

{

    DPRINTF("Shutting down connection.\n");

    QEMUFileRDMA *r = opaque;

    if (r->rdma) {

        qemu_rdma_cleanup(r->rdma);

        g_free(r->rdma);

    }

    g_free(r);

    return 0;

}


static int encode_block(WMACodecContext *s, float (*src_coefs)[BLOCK_MAX_SIZE], int total_gain){

    int v, bsize, ch, coef_nb_bits, parse_exponents;

    float mdct_norm;

    int nb_coefs[MAX_CHANNELS];

    static const int fixed_exp[25]={20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20};

    //FIXME remove duplication relative to decoder

    if (s->use_variable_block_len) {

        assert(0); //FIXME not implemented

    }else{

        /* fixed block len */

        s->next_block_len_bits = s->frame_len_bits;

        s->prev_block_len_bits = s->frame_len_bits;

        s->block_len_bits = s->frame_len_bits;

    }

    s->block_len = 1 << s->block_len_bits;

//     assert((s->block_pos + s->block_len) <= s->frame_len);

    bsize = s->frame_len_bits - s->block_len_bits;

    //FIXME factor

    v = s->coefs_end[bsize] - s->coefs_start;

    for(ch = 0; ch < s->nb_channels; ch++)

        nb_coefs[ch] = v;

    {

        int n4 = s->block_len / 2;

        mdct_norm = 1.0 / (float)n4;

        if (s->version == 1) {

            mdct_norm *= sqrt(n4);

        }

    }

    if (s->nb_channels == 2) {

        put_bits(&s->pb, 1, !!s->ms_stereo);

    }

    for(ch = 0; ch < s->nb_channels; ch++) {

        s->channel_coded[ch] = 1; //FIXME only set channel_coded when needed, instead of always

        if (s->channel_coded[ch]) {

            init_exp(s, ch, fixed_exp);

        }

    }

    for(ch = 0; ch < s->nb_channels; ch++) {

        if (s->channel_coded[ch]) {

            WMACoef *coefs1;

            float *coefs, *exponents, mult;

            int i, n;

            coefs1 = s->coefs1[ch];

            exponents = s->exponents[ch];

            mult = pow(10, total_gain * 0.05) / s->max_exponent[ch];

            mult *= mdct_norm;

            coefs = src_coefs[ch];

            if (s->use_noise_coding && 0) {

                assert(0); //FIXME not implemented

            } else {

                coefs += s->coefs_start;

                n = nb_coefs[ch];

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

                    double t= *coefs++ / (exponents[i] * mult);

                    if(t<-32768 || t>32767)

                        return -1;

                    coefs1[i] = lrint(t);

                }

            }

        }

    }

    v = 0;

    for(ch = 0; ch < s->nb_channels; ch++) {

        int a = s->channel_coded[ch];

        put_bits(&s->pb, 1, a);

        v |= a;

    }

    if (!v)

        return 1;

    for(v= total_gain-1; v>=127; v-= 127)

        put_bits(&s->pb, 7, 127);

    put_bits(&s->pb, 7, v);

    coef_nb_bits= ff_wma_total_gain_to_bits(total_gain);

    if (s->use_noise_coding) {

        for(ch = 0; ch < s->nb_channels; ch++) {

            if (s->channel_coded[ch]) {

                int i, n;

                n = s->exponent_high_sizes[bsize];

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

                    put_bits(&s->pb, 1, s->high_band_coded[ch][i]= 0);

                    if (0)

                        nb_coefs[ch] -= s->exponent_high_bands[bsize][i];

                }

            }

        }

    }

    parse_exponents = 1;

    if (s->block_len_bits != s->frame_len_bits) {

        put_bits(&s->pb, 1, parse_exponents);

    }

    if (parse_exponents) {

        for(ch = 0; ch < s->nb_channels; ch++) {

            if (s->channel_coded[ch]) {

                if (s->use_exp_vlc) {

                    encode_exp_vlc(s, ch, fixed_exp);

                } else {

                    assert(0); //FIXME not implemented

//                    encode_exp_lsp(s, ch);

                }

            }

        }

    } else {

        assert(0); //FIXME not implemented

    }

    for(ch = 0; ch < s->nb_channels; ch++) {

        if (s->channel_coded[ch]) {

            int run, tindex;

            WMACoef *ptr, *eptr;

            tindex = (ch == 1 && s->ms_stereo);

            ptr = &s->coefs1[ch][0];

            eptr = ptr + nb_coefs[ch];

            run=0;

            for(;ptr < eptr; ptr++){

                if(*ptr){

                    int level= *ptr;

                    int abs_level= FFABS(level);

                    int code= 0;

                    if(abs_level <= s->coef_vlcs[tindex]->max_level){

                        if(run < s->coef_vlcs[tindex]->levels[abs_level-1])

                            code= run + s->int_table[tindex][abs_level-1];

                    }

                    assert(code < s->coef_vlcs[tindex]->n);

                    put_bits(&s->pb, s->coef_vlcs[tindex]->huffbits[code], s->coef_vlcs[tindex]->huffcodes[code]);

                    if(code == 0){

                        if(1<<coef_nb_bits <= abs_level)

                            return -1;

                        //Workaround minor rounding differences for the regression tests, FIXME we should find and replace the problematic float by fixpoint for reg tests

                        if(abs_level == 0x71B && (s->avctx->flags & CODEC_FLAG_BITEXACT)) abs_level=0x71A;

                        put_bits(&s->pb, coef_nb_bits, abs_level);

                        put_bits(&s->pb, s->frame_len_bits, run);

                    }

                    put_bits(&s->pb, 1, level < 0); //FIXME the sign is fliped somewhere

                    run=0;

                }else{

                    run++;

                }

            }

            if(run)

                put_bits(&s->pb, s->coef_vlcs[tindex]->huffbits[1], s->coef_vlcs[tindex]->huffcodes[1]);

        }

        if (s->version == 1 && s->nb_channels >= 2) {

            avpriv_align_put_bits(&s->pb);

        }

    }

    return 0;

}


static void check(int a, int b, bool expected)

{

    struct qht_stats stats;

    int i;

    for (i = a; i < b; i++) {

        void *p;

        uint32_t hash;

        int32_t val;

        val = i;

        hash = i;

        p = qht_lookup(&ht, is_equal, &val, hash);

        g_assert_true(!!p == expected);

    }

    rcu_read_unlock();

    qht_statistics_init(&ht, &stats);

    if (stats.used_head_buckets) {

        g_assert_cmpfloat(qdist_avg(&stats.chain), >=, 1.0);

    }

    g_assert_cmpuint(stats.head_buckets, >, 0);

    qht_statistics_destroy(&stats);

}


int net_init_netmap(const NetClientOptions *opts,

                    const char *name, NetClientState *peer, Error **errp)

{

    const NetdevNetmapOptions *netmap_opts = opts->u.netmap;

    struct nm_desc *nmd;

    NetClientState *nc;

    Error *err = NULL;

    NetmapState *s;

    nmd = netmap_open(netmap_opts, &err);

    if (err) {

        error_propagate(errp, err);

        return -1;

    }

    /* Create the object. */

    nc = qemu_new_net_client(&net_netmap_info, peer, "netmap", name);

    s = DO_UPCAST(NetmapState, nc, nc);

    s->nmd = nmd;

    s->tx = NETMAP_TXRING(nmd->nifp, 0);

    s->rx = NETMAP_RXRING(nmd->nifp, 0);

    s->vnet_hdr_len = 0;

    pstrcpy(s->ifname, sizeof(s->ifname), netmap_opts->ifname);

    netmap_read_poll(s, true); /* Initially only poll for reads. */

    return 0;

}


static void pc_init1(MachineState *machine,

                     const char *host_type, const char *pci_type)

{

    PCMachineState *pcms = PC_MACHINE(machine);

    PCMachineClass *pcmc = PC_MACHINE_GET_CLASS(pcms);

    MemoryRegion *system_memory = get_system_memory();

    MemoryRegion *system_io = get_system_io();

    int i;

    PCIBus *pci_bus;

    ISABus *isa_bus;

    PCII440FXState *i440fx_state;

    int piix3_devfn = -1;

    qemu_irq *i8259;

    qemu_irq smi_irq;

    GSIState *gsi_state;

    DriveInfo *hd[MAX_IDE_BUS * MAX_IDE_DEVS];

    BusState *idebus[MAX_IDE_BUS];

    ISADevice *rtc_state;

    MemoryRegion *ram_memory;

    MemoryRegion *pci_memory;

    MemoryRegion *rom_memory;

    ram_addr_t lowmem;

    /*

     * Calculate ram split, for memory below and above 4G.  It's a bit

     * complicated for backward compatibility reasons ...

     *

     *  - Traditional split is 3.5G (lowmem = 0xe0000000).  This is the

     *    default value for max_ram_below_4g now.

     *

     *  - Then, to gigabyte align the memory, we move the split to 3G

     *    (lowmem = 0xc0000000).  But only in case we have to split in

     *    the first place, i.e. ram_size is larger than (traditional)

     *    lowmem.  And for new machine types (gigabyte_align = true)

     *    only, for live migration compatibility reasons.

     *

     *  - Next the max-ram-below-4g option was added, which allowed to

     *    reduce lowmem to a smaller value, to allow a larger PCI I/O

     *    window below 4G.  qemu doesn't enforce gigabyte alignment here,

     *    but prints a warning.

     *

     *  - Finally max-ram-below-4g got updated to also allow raising lowmem,

     *    so legacy non-PAE guests can get as much memory as possible in

     *    the 32bit address space below 4G.

     *

     *  - Note that Xen has its own ram setp code in xen_ram_init(),

     *    called via xen_hvm_init().

     *

     * Examples:

     *    qemu -M pc-1.7 -m 4G    (old default)    -> 3584M low,  512M high

     *    qemu -M pc -m 4G        (new default)    -> 3072M low, 1024M high

     *    qemu -M pc,max-ram-below-4g=2G -m 4G     -> 2048M low, 2048M high

     *    qemu -M pc,max-ram-below-4g=4G -m 3968M  -> 3968M low (=4G-128M)

     */

    if (xen_enabled()) {

        xen_hvm_init(pcms, &ram_memory);

    } else {

        if (!pcms->max_ram_below_4g) {

            pcms->max_ram_below_4g = 0xe0000000; /* default: 3.5G */

        }

        lowmem = pcms->max_ram_below_4g;

        if (machine->ram_size >= pcms->max_ram_below_4g) {

            if (pcmc->gigabyte_align) {

                if (lowmem > 0xc0000000) {

                    lowmem = 0xc0000000;

                }

                if (lowmem & ((1ULL << 30) - 1)) {

                    error_report("Warning: Large machine and max_ram_below_4g "

                                 "(%" PRIu64 ") not a multiple of 1G; "

                                 "possible bad performance.",

                                 pcms->max_ram_below_4g);

                }

            }

        }

        if (machine->ram_size >= lowmem) {

            pcms->above_4g_mem_size = machine->ram_size - lowmem;

            pcms->below_4g_mem_size = lowmem;

        } else {

            pcms->above_4g_mem_size = 0;

            pcms->below_4g_mem_size = machine->ram_size;

        }

    }

    pc_cpus_init(pcms);

    if (kvm_enabled() && pcmc->kvmclock_enabled) {

        kvmclock_create();

    }

    if (pcmc->pci_enabled) {

        pci_memory = g_new(MemoryRegion, 1);

        memory_region_init(pci_memory, NULL, "pci", UINT64_MAX);

        rom_memory = pci_memory;

    } else {

        pci_memory = NULL;

        rom_memory = system_memory;

    }

    pc_guest_info_init(pcms);

    if (pcmc->smbios_defaults) {

        MachineClass *mc = MACHINE_GET_CLASS(machine);

        /* These values are guest ABI, do not change */

        smbios_set_defaults("QEMU", "Standard PC (i440FX + PIIX, 1996)",

                            mc->name, pcmc->smbios_legacy_mode,

                            pcmc->smbios_uuid_encoded,

                            SMBIOS_ENTRY_POINT_21);

    }

    /* allocate ram and load rom/bios */

    if (!xen_enabled()) {

        pc_memory_init(pcms, system_memory,

                       rom_memory, &ram_memory);

    } else if (machine->kernel_filename != NULL) {

        /* For xen HVM direct kernel boot, load linux here */

        xen_load_linux(pcms);

    }

    gsi_state = g_malloc0(sizeof(*gsi_state));

    if (kvm_ioapic_in_kernel()) {

        kvm_pc_setup_irq_routing(pcmc->pci_enabled);

        pcms->gsi = qemu_allocate_irqs(kvm_pc_gsi_handler, gsi_state,

                                       GSI_NUM_PINS);

    } else {

        pcms->gsi = qemu_allocate_irqs(gsi_handler, gsi_state, GSI_NUM_PINS);

    }

    if (pcmc->pci_enabled) {

        pci_bus = i440fx_init(host_type,

                              pci_type,

                              &i440fx_state, &piix3_devfn, &isa_bus, pcms->gsi,

                              system_memory, system_io, machine->ram_size,

                              pcms->below_4g_mem_size,

                              pcms->above_4g_mem_size,

                              pci_memory, ram_memory);

        pcms->bus = pci_bus;

    } else {

        pci_bus = NULL;

        i440fx_state = NULL;

        isa_bus = isa_bus_new(NULL, get_system_memory(), system_io,

                              &error_abort);

        no_hpet = 1;

    }

    isa_bus_irqs(isa_bus, pcms->gsi);

    if (kvm_pic_in_kernel()) {

        i8259 = kvm_i8259_init(isa_bus);

    } else if (xen_enabled()) {

        i8259 = xen_interrupt_controller_init();

    } else {

        i8259 = i8259_init(isa_bus, pc_allocate_cpu_irq());

    }

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

        gsi_state->i8259_irq[i] = i8259[i];

    }

    g_free(i8259);

    if (pcmc->pci_enabled) {

        ioapic_init_gsi(gsi_state, "i440fx");

    }

    pc_register_ferr_irq(pcms->gsi[13]);

    pc_vga_init(isa_bus, pcmc->pci_enabled ? pci_bus : NULL);

    assert(pcms->vmport != ON_OFF_AUTO__MAX);

    if (pcms->vmport == ON_OFF_AUTO_AUTO) {

        pcms->vmport = xen_enabled() ? ON_OFF_AUTO_OFF : ON_OFF_AUTO_ON;

    }

    /* init basic PC hardware */

    pc_basic_device_init(isa_bus, pcms->gsi, &rtc_state, true,

                         (pcms->vmport != ON_OFF_AUTO_ON), pcms->pit, 0x4);

    pc_nic_init(isa_bus, pci_bus);

    ide_drive_get(hd, ARRAY_SIZE(hd));

    if (pcmc->pci_enabled) {

        PCIDevice *dev;

        if (xen_enabled()) {

            dev = pci_piix3_xen_ide_init(pci_bus, hd, piix3_devfn + 1);

        } else {

            dev = pci_piix3_ide_init(pci_bus, hd, piix3_devfn + 1);

        }

        idebus[0] = qdev_get_child_bus(&dev->qdev, "ide.0");

        idebus[1] = qdev_get_child_bus(&dev->qdev, "ide.1");

    } else {

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

            ISADevice *dev;

            char busname[] = "ide.0";

            dev = isa_ide_init(isa_bus, ide_iobase[i], ide_iobase2[i],

                               ide_irq[i],

                               hd[MAX_IDE_DEVS * i], hd[MAX_IDE_DEVS * i + 1]);

            /*

             * The ide bus name is ide.0 for the first bus and ide.1 for the

             * second one.

             */

            busname[4] = '0' + i;

            idebus[i] = qdev_get_child_bus(DEVICE(dev), busname);

        }

    }

    pc_cmos_init(pcms, idebus[0], idebus[1], rtc_state);

    if (pcmc->pci_enabled && machine_usb(machine)) {

        pci_create_simple(pci_bus, piix3_devfn + 2, "piix3-usb-uhci");

    }

    if (pcmc->pci_enabled && acpi_enabled) {

        DeviceState *piix4_pm;

        I2CBus *smbus;

        smi_irq = qemu_allocate_irq(pc_acpi_smi_interrupt, first_cpu, 0);

        /* TODO: Populate SPD eeprom data.  */

        smbus = piix4_pm_init(pci_bus, piix3_devfn + 3, 0xb100,

                              pcms->gsi[9], smi_irq,

                              pc_machine_is_smm_enabled(pcms),

                              &piix4_pm);

        smbus_eeprom_init(smbus, 8, NULL, 0);

        object_property_add_link(OBJECT(machine), PC_MACHINE_ACPI_DEVICE_PROP,

                                 TYPE_HOTPLUG_HANDLER,

                                 (Object **)&pcms->acpi_dev,

                                 object_property_allow_set_link,

                                 OBJ_PROP_LINK_UNREF_ON_RELEASE, &error_abort);

        object_property_set_link(OBJECT(machine), OBJECT(piix4_pm),

                                 PC_MACHINE_ACPI_DEVICE_PROP, &error_abort);

    }

    if (pcmc->pci_enabled) {

        pc_pci_device_init(pci_bus);

    }

    if (pcms->acpi_nvdimm_state.is_enabled) {

        nvdimm_init_acpi_state(&pcms->acpi_nvdimm_state, system_io,

                               pcms->fw_cfg, OBJECT(pcms));

    }

}


int ff_amf_get_field_value(const uint8_t *data, const uint8_t *data_end,

                           const uint8_t *name, uint8_t *dst, int dst_size)

{

    int namelen = strlen(name);

    int len;

    while (*data != AMF_DATA_TYPE_OBJECT && data < data_end) {

        len = ff_amf_tag_size(data, data_end);

        if (len < 0)

            len = data_end - data;

        data += len;

    }

    if (data_end - data < 3)

        return -1;

    data++;

    for (;;) {

        int size = bytestream_get_be16(&data);

        if (!size)

            break;

        if (size < 0 || size >= data_end - data)

            return -1;

        data += size;

        if (size == namelen && !memcmp(data-size, name, namelen)) {

            switch (*data++) {

            case AMF_DATA_TYPE_NUMBER:

                snprintf(dst, dst_size, "%g", av_int2double(AV_RB64(data)));

                break;

            case AMF_DATA_TYPE_BOOL:

                snprintf(dst, dst_size, "%s", *data ? "true" : "false");

                break;

            case AMF_DATA_TYPE_STRING:

                len = bytestream_get_be16(&data);

                av_strlcpy(dst, data, FFMIN(len+1, dst_size));

                break;

            default:

                return -1;

            }

            return 0;

        }

        len = ff_amf_tag_size(data, data_end);

        if (len < 0 || len >= data_end - data)

            return -1;

        data += len;

    }

    return -1;

}


static int raw_open(BlockDriverState *bs, const char *filename, int flags)

{

    BDRVRawState *s = bs->opaque;

    int access_flags, create_flags;

    DWORD overlapped;

    s->type = FTYPE_FILE;

    if ((flags & BDRV_O_ACCESS) == O_RDWR) {

        access_flags = GENERIC_READ | GENERIC_WRITE;

    } else {

        access_flags = GENERIC_READ;

    }

    if (flags & BDRV_O_CREAT) {

        create_flags = CREATE_ALWAYS;

    } else {

        create_flags = OPEN_EXISTING;

    }

#ifdef QEMU_TOOL

    overlapped = FILE_ATTRIBUTE_NORMAL;

#else

    overlapped = FILE_FLAG_OVERLAPPED;

#endif

    s->hfile = CreateFile(filename, access_flags,

                          FILE_SHARE_READ, NULL,

                          create_flags, overlapped, NULL);

    if (s->hfile == INVALID_HANDLE_VALUE)

        return -1;

    return 0;

}


static void isa_mmio_writeb (void *opaque, target_phys_addr_t addr,

                                  uint32_t val)

{

    cpu_outb(addr & IOPORTS_MASK, val);

}


static void kill_channel(DBDMA_channel *ch)

{

    DBDMA_DPRINTF("kill_channel\n");

    ch->regs[DBDMA_STATUS] |= cpu_to_be32(DEAD);

    ch->regs[DBDMA_STATUS] &= cpu_to_be32(~ACTIVE);

    qemu_irq_raise(ch->irq);

}


static void scsi_do_read(SCSIDiskReq *r, int ret)

{

    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);

    SCSIDiskClass *sdc = (SCSIDiskClass *) object_get_class(OBJECT(s));

    assert (r->req.aiocb == NULL);

    if (r->req.io_canceled) {

        scsi_req_cancel_complete(&r->req);

        goto done;

    }

    if (ret < 0) {

        if (scsi_handle_rw_error(r, -ret, false)) {

            goto done;

        }

    }

    /* The request is used as the AIO opaque value, so add a ref.  */

    scsi_req_ref(&r->req);

    if (r->req.sg) {

        dma_acct_start(s->qdev.conf.blk, &r->acct, r->req.sg, BLOCK_ACCT_READ);

        r->req.resid -= r->req.sg->size;

        r->req.aiocb = dma_blk_io(blk_get_aio_context(s->qdev.conf.blk),

                                  r->req.sg, r->sector << BDRV_SECTOR_BITS,

                                  sdc->dma_readv, r, scsi_dma_complete, r,

                                  DMA_DIRECTION_FROM_DEVICE);

    } else {

        scsi_init_iovec(r, SCSI_DMA_BUF_SIZE);

        block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct,

                         r->qiov.size, BLOCK_ACCT_READ);

        r->req.aiocb = sdc->dma_readv(r->sector, &r->qiov,

                                      scsi_read_complete, r, r);

    }

done:

    scsi_req_unref(&r->req);

}


static inline void _cpu_ppc_store_hdecr(PowerPCCPU *cpu, uint32_t hdecr,

                                        uint32_t value, int is_excp)

{

    ppc_tb_t *tb_env = cpu->env.tb_env;

    if (tb_env->hdecr_timer != NULL) {

        __cpu_ppc_store_decr(cpu, &tb_env->hdecr_next, tb_env->hdecr_timer,

                             &cpu_ppc_hdecr_excp, hdecr, value, is_excp);

    }

}


static void readline_printf_func(void *opaque, const char *fmt, ...)

{

    va_list ap;

    va_start(ap, fmt);

    vprintf(fmt, ap);

    va_end(ap);

}


static ssize_t virtio_net_receive(VLANClientState *vc, const uint8_t *buf, size_t size)

{

    VirtIONet *n = vc->opaque;

    struct virtio_net_hdr_mrg_rxbuf *mhdr = NULL;

    size_t hdr_len, offset, i;

    if (!do_virtio_net_can_receive(n, size))

        return 0;

    if (!receive_filter(n, buf, size))

        return size;

    /* hdr_len refers to the header we supply to the guest */

    hdr_len = n->mergeable_rx_bufs ?

        sizeof(struct virtio_net_hdr_mrg_rxbuf) : sizeof(struct virtio_net_hdr);

    offset = i = 0;

    while (offset < size) {

        VirtQueueElement elem;

        int len, total;

        struct iovec sg[VIRTQUEUE_MAX_SIZE];

        len = total = 0;

        if ((i != 0 && !n->mergeable_rx_bufs) ||

            virtqueue_pop(n->rx_vq, &elem) == 0) {

            if (i == 0)

                return -1;

            fprintf(stderr, "virtio-net truncating packet\n");

            exit(1);

        }

        if (elem.in_num < 1) {

            fprintf(stderr, "virtio-net receive queue contains no in buffers\n");

            exit(1);

        }

        if (!n->mergeable_rx_bufs && elem.in_sg[0].iov_len != hdr_len) {

            fprintf(stderr, "virtio-net header not in first element\n");

            exit(1);

        }

        memcpy(&sg, &elem.in_sg[0], sizeof(sg[0]) * elem.in_num);

        if (i == 0) {

            if (n->mergeable_rx_bufs)

                mhdr = (struct virtio_net_hdr_mrg_rxbuf *)sg[0].iov_base;

            offset += receive_header(n, sg, elem.in_num,

                                     buf + offset, size - offset, hdr_len);

            total += hdr_len;

        }

        /* copy in packet.  ugh */

        len = iov_fill(sg, elem.in_num,

                       buf + offset, size - offset);

        total += len;

        /* signal other side */

        virtqueue_fill(n->rx_vq, &elem, total, i++);

        offset += len;

    }

    if (mhdr)

        mhdr->num_buffers = i;

    virtqueue_flush(n->rx_vq, i);

    virtio_notify(&n->vdev, n->rx_vq);

    return size;

}


static CharDriverState *text_console_init(ChardevVC *vc, Error **errp)

{

    CharDriverState *chr;

    QemuConsole *s;

    unsigned width = 0;

    unsigned height = 0;

    chr = qemu_chr_alloc();

    if (vc->has_width) {

        width = vc->width;

    } else if (vc->has_cols) {

        width = vc->cols * FONT_WIDTH;

    }

    if (vc->has_height) {

        height = vc->height;

    } else if (vc->has_rows) {

        height = vc->rows * FONT_HEIGHT;

    }

    trace_console_txt_new(width, height);

    if (width == 0 || height == 0) {

        s = new_console(NULL, TEXT_CONSOLE, 0);

    } else {

        s = new_console(NULL, TEXT_CONSOLE_FIXED_SIZE, 0);

        s->surface = qemu_create_displaysurface(width, height);

    }

    if (!s) {

        g_free(chr);

        error_setg(errp, "cannot create text console");

        return NULL;

    }

    s->chr = chr;

    chr->opaque = s;

    chr->chr_set_echo = text_console_set_echo;

    /* console/chardev init sometimes completes elsewhere in a 2nd

     * stage, so defer OPENED events until they are fully initialized

     */

    chr->explicit_be_open = true;

    if (display_state) {

        text_console_do_init(chr, display_state);

    }

    return chr;

}


static int vhdx_log_flush(BlockDriverState *bs, BDRVVHDXState *s,

                          VHDXLogSequence *logs)

{

    int ret = 0;

    int i;

    uint32_t cnt, sectors_read;

    uint64_t new_file_size;

    void *data = NULL;

    int64_t file_length;

    VHDXLogDescEntries *desc_entries = NULL;

    VHDXLogEntryHeader hdr_tmp = { 0 };

    cnt = logs->count;

    data = qemu_blockalign(bs, VHDX_LOG_SECTOR_SIZE);

    ret = vhdx_user_visible_write(bs, s);

    if (ret < 0) {

        goto exit;

    }

    /* each iteration represents one log sequence, which may span multiple

     * sectors */

    while (cnt--) {

        ret = vhdx_log_peek_hdr(bs, &logs->log, &hdr_tmp);

        if (ret < 0) {

            goto exit;

        }

        file_length = bdrv_getlength(bs->file->bs);

        if (file_length < 0) {

            ret = file_length;

            goto exit;

        }

        /* if the log shows a FlushedFileOffset larger than our current file

         * size, then that means the file has been truncated / corrupted, and

         * we must refused to open it / use it */

        if (hdr_tmp.flushed_file_offset > file_length) {

            ret = -EINVAL;

            goto exit;

        }

        ret = vhdx_log_read_desc(bs, s, &logs->log, &desc_entries, true);

        if (ret < 0) {

            goto exit;

        }

        for (i = 0; i < desc_entries->hdr.descriptor_count; i++) {

            if (desc_entries->desc[i].signature == VHDX_LOG_DESC_SIGNATURE) {

                /* data sector, so read a sector to flush */

                ret = vhdx_log_read_sectors(bs, &logs->log, &sectors_read,

                                            data, 1, false);

                if (ret < 0) {

                    goto exit;

                }

                if (sectors_read != 1) {

                    ret = -EINVAL;

                    goto exit;

                }

                vhdx_log_data_le_import(data);

            }

            ret = vhdx_log_flush_desc(bs, &desc_entries->desc[i], data);

            if (ret < 0) {

                goto exit;

            }

        }

        if (file_length < desc_entries->hdr.last_file_offset) {

            new_file_size = desc_entries->hdr.last_file_offset;

            if (new_file_size % (1024*1024)) {

                /* round up to nearest 1MB boundary */

                new_file_size = QEMU_ALIGN_UP(new_file_size, MiB);

                if (new_file_size > INT64_MAX) {

                    ret = -EINVAL;

                    goto exit;

                }

                bdrv_truncate(bs->file, new_file_size, PREALLOC_MODE_OFF, NULL);

            }

        }

        qemu_vfree(desc_entries);

        desc_entries = NULL;

    }

    ret = bdrv_flush(bs);

    if (ret < 0) {

        goto exit;

    }

    /* once the log is fully flushed, indicate that we have an empty log

     * now.  This also sets the log guid to 0, to indicate an empty log */

    vhdx_log_reset(bs, s);

exit:

    qemu_vfree(data);

    qemu_vfree(desc_entries);

    return ret;

}


int ff_intel_h263_decode_picture_header(MpegEncContext *s)

{

    int format;

    /* picture header */

    if (get_bits_long(&s->gb, 22) != 0x20) {

        av_log(s->avctx, AV_LOG_ERROR, "Bad picture start code\n");

        return -1;

    }

    s->picture_number = get_bits(&s->gb, 8); /* picture timestamp */

    if (get_bits1(&s->gb) != 1) {

        av_log(s->avctx, AV_LOG_ERROR, "Bad marker\n");

        return -1;      /* marker */

    }

    if (get_bits1(&s->gb) != 0) {

        av_log(s->avctx, AV_LOG_ERROR, "Bad H263 id\n");

        return -1;      /* h263 id */

    }

    skip_bits1(&s->gb);         /* split screen off */

    skip_bits1(&s->gb);         /* camera  off */

    skip_bits1(&s->gb);         /* freeze picture release off */

    format = get_bits(&s->gb, 3);

    if (format == 0 || format == 6) {

        av_log(s->avctx, AV_LOG_ERROR, "Intel H263 free format not supported\n");

        return -1;

    }

    s->h263_plus = 0;

    s->pict_type = AV_PICTURE_TYPE_I + get_bits1(&s->gb);

    s->unrestricted_mv = get_bits1(&s->gb);

    s->h263_long_vectors = s->unrestricted_mv;

    if (get_bits1(&s->gb) != 0) {

        av_log(s->avctx, AV_LOG_ERROR, "SAC not supported\n");

        return -1;      /* SAC: off */

    }

    s->obmc= get_bits1(&s->gb);

    s->pb_frame = get_bits1(&s->gb);

    if (format < 6) {

        s->width = ff_h263_format[format][0];

        s->height = ff_h263_format[format][1];

        s->avctx->sample_aspect_ratio.num = 12;

        s->avctx->sample_aspect_ratio.den = 11;

    } else {

        format = get_bits(&s->gb, 3);

        if(format == 0 || format == 7){

            av_log(s->avctx, AV_LOG_ERROR, "Wrong Intel H263 format\n");

            return -1;

        }

        if(get_bits(&s->gb, 2))

            av_log(s->avctx, AV_LOG_ERROR, "Bad value for reserved field\n");

        s->loop_filter = get_bits1(&s->gb);

        if(get_bits1(&s->gb))

            av_log(s->avctx, AV_LOG_ERROR, "Bad value for reserved field\n");

        if(get_bits1(&s->gb))

            s->pb_frame = 2;

        if(get_bits(&s->gb, 5))

            av_log(s->avctx, AV_LOG_ERROR, "Bad value for reserved field\n");

        if(get_bits(&s->gb, 5) != 1)

            av_log(s->avctx, AV_LOG_ERROR, "Invalid marker\n");

    }

    if(format == 6){

        int ar = get_bits(&s->gb, 4);

        skip_bits(&s->gb, 9); // display width

        skip_bits1(&s->gb);

        skip_bits(&s->gb, 9); // display height

        if(ar == 15){

            s->avctx->sample_aspect_ratio.num = get_bits(&s->gb, 8); // aspect ratio - width

            s->avctx->sample_aspect_ratio.den = get_bits(&s->gb, 8); // aspect ratio - height

        } else {

            s->avctx->sample_aspect_ratio = ff_h263_pixel_aspect[ar];

        }

        if (s->avctx->sample_aspect_ratio.num == 0)

            av_log(s->avctx, AV_LOG_ERROR, "Invalid aspect ratio.\n");

    }

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

    skip_bits1(&s->gb); /* Continuous Presence Multipoint mode: off */

    if(s->pb_frame){

        skip_bits(&s->gb, 3); //temporal reference for B-frame

        skip_bits(&s->gb, 2); //dbquant

    }

    /* PEI */

    while (get_bits1(&s->gb) != 0) {

        skip_bits(&s->gb, 8);

    }

    s->f_code = 1;

    s->y_dc_scale_table=

    s->c_dc_scale_table= ff_mpeg1_dc_scale_table;

    ff_h263_show_pict_info(s);

    return 0;

}


static ssize_t nbd_co_send_reply(NBDRequest *req, struct nbd_reply *reply,

                                 int len)

{

    NBDClient *client = req->client;

    int csock = client->sock;

    ssize_t rc, ret;

    qemu_co_mutex_lock(&client->send_lock);

    qemu_set_fd_handler2(csock, nbd_can_read, nbd_read,

                         nbd_restart_write, client);

    client->send_coroutine = qemu_coroutine_self();

    if (!len) {

        rc = nbd_send_reply(csock, reply);

    } else {

        socket_set_cork(csock, 1);

        rc = nbd_send_reply(csock, reply);

        if (rc >= 0) {

            ret = qemu_co_send(csock, req->data, len);

            if (ret != len) {

                rc = -EIO;

            }

        }

        socket_set_cork(csock, 0);

    }

    client->send_coroutine = NULL;

    qemu_set_fd_handler2(csock, nbd_can_read, nbd_read, NULL, client);

    qemu_co_mutex_unlock(&client->send_lock);

    return rc;

}


int64_t qemu_file_set_rate_limit(QEMUFile *f, int64_t new_rate)

{

    /* any failed or completed migration keeps its state to allow probing of

     * migration data, but has no associated file anymore */

    if (f && f->ops->set_rate_limit)

        return f->ops->set_rate_limit(f->opaque, new_rate);

    return 0;

}


static uint64_t lance_mem_read(void *opaque, target_phys_addr_t addr,

                               unsigned size)

{

    SysBusPCNetState *d = opaque;

    uint32_t val;

    val = pcnet_ioport_readw(&d->state, addr);

    trace_lance_mem_readw(addr, val & 0xffff);

    return val & 0xffff;

}


int tcp_socket_outgoing_opts(QemuOpts *opts)

{

    Error *local_err = NULL;

    int fd = inet_connect_opts(opts, &local_err, NULL, NULL);

    if (local_err != NULL) {

        qerror_report_err(local_err);

        error_free(local_err);

    }

    return fd;

}


static inline int onenand_prog_spare(OneNANDState *s, int sec, int secn,

                void *src)

{

    int result = 0;

    if (secn > 0) {

        const uint8_t *sp = (const uint8_t *)src;

        uint8_t *dp = 0, *dpp = 0;

        if (s->bdrv_cur) {

            dp = g_malloc(512);

            if (!dp || bdrv_read(s->bdrv_cur,

                                 s->secs_cur + (sec >> 5),

                                 dp, 1) < 0) {

                result = 1;

            } else {

                dpp = dp + ((sec & 31) << 4);

            }

        } else {

            if (sec + secn > s->secs_cur) {

                result = 1;

            } else {

                dpp = s->current + (s->secs_cur << 9) + (sec << 4);

            }

        }

        if (!result) {

            uint32_t i;

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

                dpp[i] &= sp[i];

            }

            if (s->bdrv_cur) {

                result = bdrv_write(s->bdrv_cur, s->secs_cur + (sec >> 5),

                                    dp, 1) < 0;

            }

        }

        g_free(dp);

    }

    return result;

}


static void setup_rt_frame(int sig, struct target_sigaction *ka,

                           target_siginfo_t *info,

                           target_sigset_t *set, CPUM68KState *env)

{

    struct target_rt_sigframe *frame;

    abi_ulong frame_addr;

    abi_ulong retcode_addr;

    abi_ulong info_addr;

    abi_ulong uc_addr;

    int err = 0;

    int i;

    frame_addr = get_sigframe(ka, env, sizeof *frame);

    if (!lock_user_struct(VERIFY_WRITE, frame, frame_addr, 0))

	goto give_sigsegv;

    __put_user(sig, &frame->sig);

    info_addr = frame_addr + offsetof(struct target_rt_sigframe, info);

    __put_user(info_addr, &frame->pinfo);

    uc_addr = frame_addr + offsetof(struct target_rt_sigframe, uc);

    __put_user(uc_addr, &frame->puc);

    err |= copy_siginfo_to_user(&frame->info, info);

    /* Create the ucontext */

    __put_user(0, &frame->uc.tuc_flags);

    __put_user(0, &frame->uc.tuc_link);

    __put_user(target_sigaltstack_used.ss_sp,

               &frame->uc.tuc_stack.ss_sp);

    __put_user(sas_ss_flags(env->aregs[7]),

               &frame->uc.tuc_stack.ss_flags);

    __put_user(target_sigaltstack_used.ss_size,

               &frame->uc.tuc_stack.ss_size);

    err |= target_rt_setup_ucontext(&frame->uc, env);

    if (err)

            goto give_sigsegv;

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

        if (__put_user(set->sig[i], &frame->uc.tuc_sigmask.sig[i]))

            goto give_sigsegv;

    }

    /* Set up to return from userspace.  */

    retcode_addr = frame_addr + offsetof(struct target_sigframe, retcode);

    __put_user(retcode_addr, &frame->pretcode);

    /* moveq #,d0; notb d0; trap #0 */

    __put_user(0x70004600 + ((TARGET_NR_rt_sigreturn ^ 0xff) << 16),

               (long *)(frame->retcode + 0));

    __put_user(0x4e40, (short *)(frame->retcode + 4));

    if (err)

        goto give_sigsegv;

    /* Set up to return from userspace */

    env->aregs[7] = frame_addr;

    env->pc = ka->_sa_handler;

    unlock_user_struct(frame, frame_addr, 1);

    return;

give_sigsegv:

    unlock_user_struct(frame, frame_addr, 1);

    force_sig(TARGET_SIGSEGV);

}


static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom)

{

    AVStream *st;

    MOVStreamContext *sc;

    unsigned int i, entries, sample_size, field_size, num_bytes;

    GetBitContext gb;

    unsigned char* buf;

    if (c->fc->nb_streams < 1)

        return 0;

    st = c->fc->streams[c->fc->nb_streams-1];

    sc = st->priv_data;

    avio_r8(pb); /* version */

    avio_rb24(pb); /* flags */

    if (atom.type == MKTAG('s','t','s','z')) {

        sample_size = avio_rb32(pb);

        if (!sc->sample_size) /* do not overwrite value computed in stsd */

            sc->sample_size = sample_size;

        field_size = 32;

    } else {

        sample_size = 0;

        avio_rb24(pb); /* reserved */

        field_size = avio_r8(pb);

    }

    entries = avio_rb32(pb);

    av_dlog(c->fc, "sample_size = %d sample_count = %d\n", sc->sample_size, entries);

    sc->sample_count = entries;

    if (sample_size)

        return 0;

    if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) {

        av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %d\n", field_size);

        return AVERROR_INVALIDDATA;

    }

    if (!entries)

        return 0;

    if (entries >= UINT_MAX / sizeof(int) || entries >= (UINT_MAX - 4) / field_size)

        return AVERROR_INVALIDDATA;

    sc->sample_sizes = av_malloc(entries * sizeof(int));

    if (!sc->sample_sizes)

        return AVERROR(ENOMEM);

    num_bytes = (entries*field_size+4)>>3;

    buf = av_malloc(num_bytes+FF_INPUT_BUFFER_PADDING_SIZE);

    if (!buf) {

        av_freep(&sc->sample_sizes);

        return AVERROR(ENOMEM);

    }

    if (avio_read(pb, buf, num_bytes) < num_bytes) {

        av_freep(&sc->sample_sizes);

        av_free(buf);

        return AVERROR_INVALIDDATA;

    }

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

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

        sc->sample_sizes[i] = get_bits_long(&gb, field_size);

        sc->data_size += sc->sample_sizes[i];

    }

    av_free(buf);

    return 0;

}


static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)

{

    QEMUFile *f;

    f = qemu_mallocz(sizeof(QEMUFile));

    if (!f)

        return NULL;

    f->is_file = 0;

    f->bs = bs;

    f->is_writable = is_writable;

    f->base_offset = offset;

    return f;

}


static void virtio_setup(void)

{

    struct irb irb;

    int i;

    int r;

    bool found = false;

    blk_schid.one = 1;

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

        blk_schid.sch_no = i;

        r = tsch(blk_schid, &irb);

        if (r != 3) {

            if (virtio_is_blk(blk_schid)) {

                found = true;

                break;

            }

        }

    }

    if (!found) {

        virtio_panic("No virtio-blk device found!\n");

    }

    virtio_setup_block(blk_schid);

}


int if_encap(Slirp *slirp, struct mbuf *ifm)

{

    uint8_t buf[1600];

    struct ethhdr *eh = (struct ethhdr *)buf;

    uint8_t ethaddr[ETH_ALEN];

    const struct ip *iph = (const struct ip *)ifm->m_data;

    int ret;

    if (ifm->m_len + ETH_HLEN > sizeof(buf)) {

        return 1;

    }

    switch (iph->ip_v) {

    case IPVERSION:

        ret = if_encap4(slirp, ifm, eh, ethaddr);

        if (ret < 2) {

            return ret;

        }

        break;

    default:

        /* Do not assert while we don't manage IP6VERSION */

        /* assert(0); */

        break;

    }

    memcpy(eh->h_dest, ethaddr, ETH_ALEN);

    DEBUG_ARGS((dfd, " src = %02x:%02x:%02x:%02x:%02x:%02x\n",

                eh->h_source[0], eh->h_source[1], eh->h_source[2],

                eh->h_source[3], eh->h_source[4], eh->h_source[5]));

    DEBUG_ARGS((dfd, " dst = %02x:%02x:%02x:%02x:%02x:%02x\n",

                eh->h_dest[0], eh->h_dest[1], eh->h_dest[2],

                eh->h_dest[3], eh->h_dest[4], eh->h_dest[5]));

    memcpy(buf + sizeof(struct ethhdr), ifm->m_data, ifm->m_len);

    slirp_output(slirp->opaque, buf, ifm->m_len + ETH_HLEN);

    return 1;

}


static void fill_thread_info(struct elf_note_info *info, const CPUState *env)

{

    TaskState *ts = (TaskState *)env->opaque;

    struct elf_thread_status *ets;

    ets = qemu_mallocz(sizeof (*ets));

    ets->num_notes = 1; /* only prstatus is dumped */

    fill_prstatus(&ets->prstatus, ts, 0);

    elf_core_copy_regs(&ets->prstatus.pr_reg, env);

    fill_note(&ets->notes[0], "CORE", NT_PRSTATUS, sizeof (ets->prstatus),

        &ets->prstatus);

    TAILQ_INSERT_TAIL(&info->thread_list, ets, ets_link);

    info->notes_size += note_size(&ets->notes[0]);

}


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

                             Error **errp)

{

    struct omap_lcd_panel_s *omap_lcd = opaque;

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

    omap_update_display(opaque);

    if (omap_lcd && surface_data(surface))

        omap_ppm_save(filename, surface_data(surface),

                    omap_lcd->width, omap_lcd->height,

                    surface_stride(surface), errp);

}


static void con_disconnect(struct XenDevice *xendev)

{

    struct XenConsole *con = container_of(xendev, struct XenConsole, xendev);

    if (!xendev->dev) {

        return;

    }

    if (con->chr) {

        qemu_chr_add_handlers(con->chr, NULL, NULL, NULL, NULL);

        qemu_chr_fe_release(con->chr);

    }

    xen_be_unbind_evtchn(&con->xendev);

    if (con->sring) {

        if (!xendev->gnttabdev) {

            munmap(con->sring, XC_PAGE_SIZE);

        } else {

            xc_gnttab_munmap(xendev->gnttabdev, con->sring, 1);

        }

	con->sring = NULL;

    }

}


static int configure_input_video_filter(FilterGraph *fg, InputFilter *ifilter,

                                        AVFilterInOut *in)

{

    AVFilterContext *last_filter;

    const AVFilter *buffer_filt = avfilter_get_by_name("buffer");

    InputStream *ist = ifilter->ist;

    InputFile     *f = input_files[ist->file_index];

    AVRational tb = ist->framerate.num ? av_inv_q(ist->framerate) :

                                         ist->st->time_base;

    AVRational sar;

    char args[255], name[255];

    int ret, pad_idx = 0;

    sar = ist->st->sample_aspect_ratio.num ?

          ist->st->sample_aspect_ratio :

          ist->st->codec->sample_aspect_ratio;

    snprintf(args, sizeof(args), "%d:%d:%d:%d:%d:%d:%d", ist->st->codec->width,

             ist->st->codec->height, ist->st->codec->pix_fmt,

             tb.num, tb.den, sar.num, sar.den);

    snprintf(name, sizeof(name), "graph %d input from stream %d:%d", fg->index,

             ist->file_index, ist->st->index);

    if ((ret = avfilter_graph_create_filter(&ifilter->filter, buffer_filt, name,

                                            args, NULL, fg->graph)) < 0)

        return ret;

    last_filter = ifilter->filter;

    if (ist->framerate.num) {

        AVFilterContext *setpts;

        snprintf(name, sizeof(name), "force CFR for input from stream %d:%d",

                 ist->file_index, ist->st->index);

        if ((ret = avfilter_graph_create_filter(&setpts,

                                                avfilter_get_by_name("setpts"),

                                                name, "N", NULL,

                                                fg->graph)) < 0)

            return ret;

        if ((ret = avfilter_link(last_filter, 0, setpts, 0)) < 0)

            return ret;

        last_filter = setpts;

    }

    snprintf(name, sizeof(name), "trim for input stream %d:%d",

             ist->file_index, ist->st->index);

    ret = insert_trim(((f->start_time == AV_NOPTS_VALUE) || !f->accurate_seek) ?

                      AV_NOPTS_VALUE : 0, INT64_MAX, &last_filter, &pad_idx, name);

    if (ret < 0)

        return ret;

    if ((ret = avfilter_link(last_filter, 0, in->filter_ctx, in->pad_idx)) < 0)

        return ret;

    return 0;

}


void ff_put_h264_qpel16_mc33_msa(uint8_t *dst, const uint8_t *src,

                                 ptrdiff_t stride)

{

    avc_luma_hv_qrt_16w_msa(src + stride - 2,

                            src - (stride * 2) +

                            sizeof(uint8_t), stride, dst, stride, 16);

}


int qcow2_backing_read1(BlockDriverState *bs, QEMUIOVector *qiov,

                        int64_t offset, int bytes)

{

    uint64_t bs_size = bs->total_sectors * BDRV_SECTOR_SIZE;

    int n1;

    if ((offset + bytes) <= bs_size) {

        return bytes;

    }

    if (offset >= bs_size) {

        n1 = 0;

    } else {

        n1 = bs_size - offset;

    }

    qemu_iovec_memset(qiov, n1, 0, bytes - n1);

    return n1;

}


static void property_get_bool(Object *obj, Visitor *v, void *opaque,

                              const char *name, Error **errp)

{

    BoolProperty *prop = opaque;

    bool value;

    value = prop->get(obj, errp);

    visit_type_bool(v, &value, name, errp);

}


static int read_header(ShortenContext *s)

{

    int i, ret;

    int maxnlpc = 0;

    /* shorten signature */

    if (get_bits_long(&s->gb, 32) != AV_RB32("ajkg")) {

        av_log(s->avctx, AV_LOG_ERROR, "missing shorten magic 'ajkg'\n");

    s->lpcqoffset     = 0;

    s->blocksize      = DEFAULT_BLOCK_SIZE;

    s->nmean          = -1;

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

    s->internal_ftype = get_uint(s, TYPESIZE);

    s->channels = get_uint(s, CHANSIZE);

    if (!s->channels) {

        av_log(s->avctx, AV_LOG_ERROR, "No channels reported\n");

    if (s->channels > MAX_CHANNELS) {

        av_log(s->avctx, AV_LOG_ERROR, "too many channels: %d\n", s->channels);

        s->channels = 0;

    s->avctx->channels = s->channels;

    /* get blocksize if version > 0 */

    if (s->version > 0) {

        int skip_bytes;

        unsigned blocksize;

        blocksize = get_uint(s, av_log2(DEFAULT_BLOCK_SIZE));

        if (!blocksize || blocksize > MAX_BLOCKSIZE) {

            av_log(s->avctx, AV_LOG_ERROR,

                   "invalid or unsupported block size: %d\n",

                   blocksize);

            return AVERROR(EINVAL);

        s->blocksize = blocksize;

        maxnlpc  = get_uint(s, LPCQSIZE);

        s->nmean = get_uint(s, 0);

        skip_bytes = get_uint(s, NSKIPSIZE);

        if ((unsigned)skip_bytes > get_bits_left(&s->gb)/8) {

            av_log(s->avctx, AV_LOG_ERROR, "invalid skip_bytes: %d\n", skip_bytes);

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

            skip_bits(&s->gb, 8);

    s->nwrap = FFMAX(NWRAP, maxnlpc);

    if ((ret = allocate_buffers(s)) < 0)

        return ret;

    if ((ret = init_offset(s)) < 0)

        return ret;

    if (s->version > 1)

        s->lpcqoffset = V2LPCQOFFSET;

    if (s->avctx->extradata_size > 0)

        goto end;

    if (get_ur_golomb_shorten(&s->gb, FNSIZE) != FN_VERBATIM) {

        av_log(s->avctx, AV_LOG_ERROR,

               "missing verbatim section at beginning of stream\n");

    s->header_size = get_ur_golomb_shorten(&s->gb, VERBATIM_CKSIZE_SIZE);

    if (s->header_size >= OUT_BUFFER_SIZE ||

        s->header_size < CANONICAL_HEADER_SIZE) {

        av_log(s->avctx, AV_LOG_ERROR, "header is wrong size: %d\n",

               s->header_size);

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

        s->header[i] = (char)get_ur_golomb_shorten(&s->gb, VERBATIM_BYTE_SIZE);

    if (AV_RL32(s->header) == MKTAG('R','I','F','F')) {

        if ((ret = decode_wave_header(s->avctx, s->header, s->header_size)) < 0)

            return ret;

    } else if (AV_RL32(s->header) == MKTAG('F','O','R','M')) {

        if ((ret = decode_aiff_header(s->avctx, s->header, s->header_size)) < 0)

            return ret;

    } else {

        avpriv_report_missing_feature(s->avctx, "unsupported bit packing %"

                                      PRIX32, AV_RL32(s->header));

        return AVERROR_PATCHWELCOME;

end:

    s->cur_chan = 0;

    s->bitshift = 0;

    s->got_header = 1;

    return 0;


int avcodec_get_pix_fmt_loss(enum PixelFormat dst_pix_fmt, enum PixelFormat src_pix_fmt,

                             int has_alpha)

{

    const PixFmtInfo *pf, *ps;

    const AVPixFmtDescriptor *src_desc = &av_pix_fmt_descriptors[src_pix_fmt];

    const AVPixFmtDescriptor *dst_desc = &av_pix_fmt_descriptors[dst_pix_fmt];

    int loss;

    ps = &pix_fmt_info[src_pix_fmt];

    /* compute loss */

    loss = 0;

    pf = &pix_fmt_info[dst_pix_fmt];

    if (pf->depth < ps->depth ||

        ((dst_pix_fmt == PIX_FMT_RGB555BE || dst_pix_fmt == PIX_FMT_RGB555LE ||

          dst_pix_fmt == PIX_FMT_BGR555BE || dst_pix_fmt == PIX_FMT_BGR555LE) &&

         (src_pix_fmt == PIX_FMT_RGB565BE || src_pix_fmt == PIX_FMT_RGB565LE ||

          src_pix_fmt == PIX_FMT_BGR565BE || src_pix_fmt == PIX_FMT_BGR565LE)))

        loss |= FF_LOSS_DEPTH;

    if (dst_desc->log2_chroma_w > src_desc->log2_chroma_w ||

        dst_desc->log2_chroma_h > src_desc->log2_chroma_h)

        loss |= FF_LOSS_RESOLUTION;

    switch(pf->color_type) {

    case FF_COLOR_RGB:

        if (ps->color_type != FF_COLOR_RGB &&

            ps->color_type != FF_COLOR_GRAY)

            loss |= FF_LOSS_COLORSPACE;

        break;

    case FF_COLOR_GRAY:

        if (ps->color_type != FF_COLOR_GRAY)

            loss |= FF_LOSS_COLORSPACE;

        break;

    case FF_COLOR_YUV:

        if (ps->color_type != FF_COLOR_YUV)

            loss |= FF_LOSS_COLORSPACE;

        break;

    case FF_COLOR_YUV_JPEG:

        if (ps->color_type != FF_COLOR_YUV_JPEG &&

            ps->color_type != FF_COLOR_YUV &&

            ps->color_type != FF_COLOR_GRAY)

            loss |= FF_LOSS_COLORSPACE;

        break;

    default:

        /* fail safe test */

        if (ps->color_type != pf->color_type)

            loss |= FF_LOSS_COLORSPACE;

        break;

    }

    if (pf->color_type == FF_COLOR_GRAY &&

        ps->color_type != FF_COLOR_GRAY)

        loss |= FF_LOSS_CHROMA;

    if (!pf->is_alpha && (ps->is_alpha && has_alpha))

        loss |= FF_LOSS_ALPHA;

    if (pf->pixel_type == FF_PIXEL_PALETTE &&

        (ps->pixel_type != FF_PIXEL_PALETTE && ps->color_type != FF_COLOR_GRAY))

        loss |= FF_LOSS_COLORQUANT;

    return loss;

}


static void svq1_parse_string(GetBitContext *bitbuf, uint8_t *out)

{

    uint8_t seed;

    int i;

    out[0] = get_bits(bitbuf, 8);

    seed   = string_table[out[0]];

    for (i = 1; i <= out[0]; i++) {

        out[i] = get_bits(bitbuf, 8) ^ seed;

        seed   = string_table[out[i] ^ seed];

    }

}


static int vda_h264_end_frame(AVCodecContext *avctx)

{

    H264Context *h        = avctx->priv_data;

    VDAContext *vda       = avctx->internal->hwaccel_priv_data;

    AVVDAContext *vda_ctx = avctx->hwaccel_context;

    AVFrame *frame        = h->cur_pic_ptr->f;

    uint32_t flush_flags  = 1 << 0; ///< kVDADecoderFlush_emitFrames

    CFDataRef coded_frame;

    OSStatus status;

    if (!vda->bitstream_size)

        return AVERROR_INVALIDDATA;

    coded_frame = CFDataCreate(kCFAllocatorDefault,

                               vda->bitstream,

                               vda->bitstream_size);

    status = VDADecoderDecode(vda_ctx->decoder, 0, coded_frame, NULL);

    if (status == kVDADecoderNoErr)

        status = VDADecoderFlush(vda_ctx->decoder, flush_flags);

    CFRelease(coded_frame);

    if (!vda->frame)

        return AVERROR_UNKNOWN;

    if (status != kVDADecoderNoErr) {

        av_log(avctx, AV_LOG_ERROR, "Failed to decode frame (%d)\n", status);

        return AVERROR_UNKNOWN;

    }

    av_buffer_unref(&frame->buf[0]);

    frame->buf[0] = av_buffer_create((uint8_t*)vda->frame,

                                     sizeof(vda->frame),

                                     release_buffer, NULL,

                                     AV_BUFFER_FLAG_READONLY);

    if (!frame->buf)

        return AVERROR(ENOMEM);

    frame->data[3] = (uint8_t*)vda->frame;

    vda->frame = NULL;

    return 0;

}


int img_pad(AVPicture *dst, const AVPicture *src, int height, int width,

            int pix_fmt, int padtop, int padbottom, int padleft, int padright,

            int *color)

{

    uint8_t *optr, *iptr;

    int y_shift;

    int x_shift;

    int yheight;

    int i, y;

    if (pix_fmt < 0 || pix_fmt >= PIX_FMT_NB ||

        !is_yuv_planar(&pix_fmt_info[pix_fmt])) return -1;

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

        x_shift = i ? pix_fmt_info[pix_fmt].x_chroma_shift : 0;

        y_shift = i ? pix_fmt_info[pix_fmt].y_chroma_shift : 0;

        if (padtop || padleft) {

            memset(dst->data[i], color[i],

                dst->linesize[i] * (padtop >> y_shift) + (padleft >> x_shift));

        }

        if (padleft || padright || src) {

            if (src) { /* first line */

                iptr = src->data[i];

                optr = dst->data[i] + dst->linesize[i] * (padtop >> y_shift) +

                        (padleft >> x_shift);

                memcpy(optr, iptr, src->linesize[i]);

                iptr += src->linesize[i];

            }

            optr = dst->data[i] + dst->linesize[i] * (padtop >> y_shift) +

                (dst->linesize[i] - (padright >> x_shift));

            yheight = (height - 1 - (padtop + padbottom)) >> y_shift;

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

                memset(optr, color[i], (padleft + padright) >> x_shift);

                if (src) {

                    memcpy(optr + ((padleft + padright) >> x_shift), iptr,

                        src->linesize[i]);

                    iptr += src->linesize[i];

                }

                optr += dst->linesize[i];

            }

        }

        if (padbottom || padright) {

            optr = dst->data[i] + dst->linesize[i] *

                ((height - padbottom) >> y_shift) - (padright >> x_shift);

            memset(optr, color[i],dst->linesize[i] *

                (padbottom >> y_shift) + (padright >> x_shift));

        }

    }

    return 0;

}


void avfilter_draw_slice(AVFilterLink *link, int y, int h)

{

    uint8_t *src[4], *dst[4];

    int i, j, hsub, vsub;

    /* copy the slice if needed for permission reasons */

    if(link->srcpic) {

        avcodec_get_chroma_sub_sample(link->format, &hsub, &vsub);

        src[0] = link->srcpic-> data[0] + y * link->srcpic-> linesize[0];

        dst[0] = link->cur_pic->data[0] + y * link->cur_pic->linesize[0];

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

            if(link->srcpic->data[i]) {

                src[i] = link->srcpic-> data[i] + (y >> vsub) * link->srcpic-> linesize[i];

                dst[i] = link->cur_pic->data[i] + (y >> vsub) * link->cur_pic->linesize[i];

            } else

                src[i] = dst[i] = NULL;

        }

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

            memcpy(dst[0], src[0], link->cur_pic->linesize[0]);

            src[0] += link->srcpic ->linesize[0];

            dst[0] += link->cur_pic->linesize[0];

        }

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

            if(!src[i]) continue;

            for(j = 0; j < h >> vsub; j ++) {

                memcpy(dst[i], src[i], link->cur_pic->linesize[i]);

                src[i] += link->srcpic ->linesize[i];

                dst[i] += link->cur_pic->linesize[i];

            }

        }

    }

    if(!link_dpad(link).draw_slice)

        return;

    link_dpad(link).draw_slice(link, y, h);

}


static int ff_sctp_send(int s, const void *msg, size_t len,

                        const struct sctp_sndrcvinfo *sinfo, int flags)

{

    struct msghdr outmsg;

    struct iovec iov;

    outmsg.msg_name       = NULL;

    outmsg.msg_namelen    = 0;

    outmsg.msg_iov        = &iov;

    iov.iov_base          = msg;

    iov.iov_len           = len;

    outmsg.msg_iovlen     = 1;

    outmsg.msg_controllen = 0;

    if (sinfo) {

        char outcmsg[CMSG_SPACE(sizeof(struct sctp_sndrcvinfo))];

        struct cmsghdr *cmsg;

        outmsg.msg_control    = outcmsg;

        outmsg.msg_controllen = sizeof(outcmsg);

        outmsg.msg_flags      = 0;

        cmsg             = CMSG_FIRSTHDR(&outmsg);

        cmsg->cmsg_level = IPPROTO_SCTP;

        cmsg->cmsg_type  = SCTP_SNDRCV;

        cmsg->cmsg_len   = CMSG_LEN(sizeof(struct sctp_sndrcvinfo));

        outmsg.msg_controllen = cmsg->cmsg_len;

        memcpy(CMSG_DATA(cmsg), sinfo, sizeof(struct sctp_sndrcvinfo));

    }

    return sendmsg(s, &outmsg, flags | MSG_NOSIGNAL);

}


static int dxtory_decode_v1_420(AVCodecContext *avctx, AVFrame *pic,

                                const uint8_t *src, int src_size)

{

    int h, w;

    uint8_t *Y1, *Y2, *U, *V;

    int ret;

    if (src_size < avctx->width * avctx->height * 3LL / 2) {

        av_log(avctx, AV_LOG_ERROR, "packet too small\n");

        return AVERROR_INVALIDDATA;

    }

    avctx->pix_fmt = AV_PIX_FMT_YUV420P;

    if ((ret = ff_get_buffer(avctx, pic, 0)) < 0)

        return ret;

    Y1 = pic->data[0];

    Y2 = pic->data[0] + pic->linesize[0];

    U  = pic->data[1];

    V  = pic->data[2];

    for (h = 0; h < avctx->height; h += 2) {

        for (w = 0; w < avctx->width; w += 2) {

            AV_COPY16(Y1 + w, src);

            AV_COPY16(Y2 + w, src + 2);

            U[w >> 1] = src[4] + 0x80;

            V[w >> 1] = src[5] + 0x80;

            src += 6;

        }

        Y1 += pic->linesize[0] << 1;

        Y2 += pic->linesize[0] << 1;

        U  += pic->linesize[1];

        V  += pic->linesize[2];

    }

    return 0;

}


void ff_avg_h264_qpel16_mc13_msa(uint8_t *dst, const uint8_t *src,

                                 ptrdiff_t stride)

{

    avc_luma_hv_qrt_and_aver_dst_16x16_msa(src + stride - 2,

                                           src - (stride * 2),

                                           stride, dst, stride);

}