int ff_qsv_encode(AVCodecContext *avctx, QSVEncContext *q,

                  AVPacket *pkt, const AVFrame *frame, int *got_packet)

{

    mfxBitstream bs = { { { 0 } } };

    mfxFrameSurface1 *surf = NULL;

    mfxSyncPoint sync      = NULL;

    int ret;

    if (frame) {

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

        if (ret < 0) {

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

            return ret;

        }

    }

    ret = ff_alloc_packet(pkt, q->packet_size);

    if (ret < 0) {

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

        return ret;

    }

    bs.Data      = pkt->data;

    bs.MaxLength = pkt->size;

    do {

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

        if (ret == MFX_WRN_DEVICE_BUSY)

            av_usleep(1);

    } while (ret > 0);

    if (ret < 0)

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

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

        print_interlace_msg(avctx, q);

    if (sync) {

        MFXVideoCORE_SyncOperation(q->session, sync, 60000);

        if (bs.FrameType & MFX_FRAMETYPE_I || bs.FrameType & MFX_FRAMETYPE_xI)

            avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;

        else if (bs.FrameType & MFX_FRAMETYPE_P || bs.FrameType & MFX_FRAMETYPE_xP)

            avctx->coded_frame->pict_type = AV_PICTURE_TYPE_P;

        else if (bs.FrameType & MFX_FRAMETYPE_B || bs.FrameType & MFX_FRAMETYPE_xB)

            avctx->coded_frame->pict_type = AV_PICTURE_TYPE_B;

        pkt->dts  = av_rescale_q(bs.DecodeTimeStamp, (AVRational){1, 90000}, avctx->time_base);

        pkt->pts  = av_rescale_q(bs.TimeStamp,       (AVRational){1, 90000}, avctx->time_base);

        pkt->size = bs.DataLength;

        if (bs.FrameType & MFX_FRAMETYPE_IDR ||

            bs.FrameType & MFX_FRAMETYPE_xIDR)

            pkt->flags |= AV_PKT_FLAG_KEY;

        *got_packet = 1;

    }

    return 0;

}


static void nvram_writeb (void *opaque, target_phys_addr_t addr, uint32_t value)

{

    ds1225y_t *NVRAM = opaque;

    int64_t pos;

    pos = addr - NVRAM->mem_base;

    if (ds1225y_set_to_mode(NVRAM, writemode, "wb"))

    {

        qemu_fseek(NVRAM->file, pos, SEEK_SET);

        qemu_put_byte(NVRAM->file, (int)value);

    }

}


static av_cold int xvid_encode_close(AVCodecContext *avctx) {

    struct xvid_context *x = avctx->priv_data;

    xvid_encore(x->encoder_handle, XVID_ENC_DESTROY, NULL, NULL);

    if( avctx->extradata != NULL )

        av_free(avctx->extradata);

    if( x->twopassbuffer != NULL ) {

        av_free(x->twopassbuffer);

        av_free(x->old_twopassbuffer);

    }

    if( x->twopassfile != NULL )

        av_free(x->twopassfile);

    if( x->intra_matrix != NULL )

        av_free(x->intra_matrix);

    if( x->inter_matrix != NULL )

        av_free(x->inter_matrix);

    return 0;

}


int attribute_align_arg avcodec_open2(AVCodecContext *avctx, const AVCodec *codec, AVDictionary **options)

{

    int ret = 0;

    AVDictionary *tmp = NULL;

    if (avcodec_is_open(avctx))

        return 0;

    if ((!codec && !avctx->codec)) {

        av_log(avctx, AV_LOG_ERROR, "No codec provided to avcodec_open2()\n");

        return AVERROR(EINVAL);

    }

    if ((codec && avctx->codec && codec != avctx->codec)) {

        av_log(avctx, AV_LOG_ERROR, "This AVCodecContext was allocated for %s, "

                                    "but %s passed to avcodec_open2()\n", avctx->codec->name, codec->name);

        return AVERROR(EINVAL);

    }

    if (!codec)

        codec = avctx->codec;

    if (avctx->extradata_size < 0 || avctx->extradata_size >= FF_MAX_EXTRADATA_SIZE)

        return AVERROR(EINVAL);

    if (options)

        av_dict_copy(&tmp, *options, 0);

    ret = ff_lock_avcodec(avctx);

    if (ret < 0)

        return ret;

    avctx->internal = av_mallocz(sizeof(AVCodecInternal));

    if (!avctx->internal) {

        ret = AVERROR(ENOMEM);

        goto end;

    }

    avctx->internal->pool = av_mallocz(sizeof(*avctx->internal->pool));

    if (!avctx->internal->pool) {

        ret = AVERROR(ENOMEM);

        goto free_and_end;

    }

    if (codec->priv_data_size > 0) {

        if (!avctx->priv_data) {

            avctx->priv_data = av_mallocz(codec->priv_data_size);

            if (!avctx->priv_data) {

                ret = AVERROR(ENOMEM);

                goto end;

            }

            if (codec->priv_class) {

                *(const AVClass **)avctx->priv_data = codec->priv_class;

                av_opt_set_defaults(avctx->priv_data);

            }

        }

        if (codec->priv_class && (ret = av_opt_set_dict(avctx->priv_data, &tmp)) < 0)

            goto free_and_end;

    } else {

        avctx->priv_data = NULL;

    }

    if ((ret = av_opt_set_dict(avctx, &tmp)) < 0)

        goto free_and_end;

    //We only call avcodec_set_dimensions() for non h264 codecs so as not to overwrite previously setup dimensions

    if (!( avctx->coded_width && avctx->coded_height && avctx->width && avctx->height && avctx->codec_id == AV_CODEC_ID_H264)){

    if (avctx->coded_width && avctx->coded_height)

        avcodec_set_dimensions(avctx, avctx->coded_width, avctx->coded_height);

    else if (avctx->width && avctx->height)

        avcodec_set_dimensions(avctx, avctx->width, avctx->height);

    }

    if ((avctx->coded_width || avctx->coded_height || avctx->width || avctx->height)

        && (  av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx) < 0

           || av_image_check_size(avctx->width,       avctx->height,       0, avctx) < 0)) {

        av_log(avctx, AV_LOG_WARNING, "Ignoring invalid width/height values\n");

        avcodec_set_dimensions(avctx, 0, 0);

    }

    /* if the decoder init function was already called previously,

     * free the already allocated subtitle_header before overwriting it */

    if (av_codec_is_decoder(codec))

        av_freep(&avctx->subtitle_header);

    if (avctx->channels > FF_SANE_NB_CHANNELS) {

        ret = AVERROR(EINVAL);

        goto free_and_end;

    }

    avctx->codec = codec;

    if ((avctx->codec_type == AVMEDIA_TYPE_UNKNOWN || avctx->codec_type == codec->type) &&

        avctx->codec_id == AV_CODEC_ID_NONE) {

        avctx->codec_type = codec->type;

        avctx->codec_id   = codec->id;

    }

    if (avctx->codec_id != codec->id || (avctx->codec_type != codec->type

                                         && avctx->codec_type != AVMEDIA_TYPE_ATTACHMENT)) {

        av_log(avctx, AV_LOG_ERROR, "Codec type or id mismatches\n");

        ret = AVERROR(EINVAL);

        goto free_and_end;

    }

    avctx->frame_number = 0;

    avctx->codec_descriptor = avcodec_descriptor_get(avctx->codec_id);

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

        avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {

        const char *codec_string = av_codec_is_encoder(codec) ? "encoder" : "decoder";

        AVCodec *codec2;

        av_log(NULL, AV_LOG_ERROR,

               "The %s '%s' is experimental but experimental codecs are not enabled, "

               "add '-strict %d' if you want to use it.\n",

               codec_string, codec->name, FF_COMPLIANCE_EXPERIMENTAL);

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

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

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

                codec_string, codec2->name);

        ret = AVERROR_EXPERIMENTAL;

        goto free_and_end;

    }

    if (avctx->codec_type == AVMEDIA_TYPE_AUDIO &&

        (!avctx->time_base.num || !avctx->time_base.den)) {

        avctx->time_base.num = 1;

        avctx->time_base.den = avctx->sample_rate;

    }

    if (!HAVE_THREADS)

        av_log(avctx, AV_LOG_WARNING, "Warning: not compiled with thread support, using thread emulation\n");

    if (HAVE_THREADS) {

        ff_unlock_avcodec(); //we will instanciate a few encoders thus kick the counter to prevent false detection of a problem

        ret = ff_frame_thread_encoder_init(avctx, options ? *options : NULL);

        ff_lock_avcodec(avctx);

        if (ret < 0)

            goto free_and_end;

    }

    if (HAVE_THREADS && !avctx->thread_opaque

        && !(avctx->internal->frame_thread_encoder && (avctx->active_thread_type&FF_THREAD_FRAME))) {

        ret = ff_thread_init(avctx);

        if (ret < 0) {

            goto free_and_end;

        }

    }

    if (!HAVE_THREADS && !(codec->capabilities & CODEC_CAP_AUTO_THREADS))

        avctx->thread_count = 1;

    if (avctx->codec->max_lowres < avctx->lowres || avctx->lowres < 0) {

        av_log(avctx, AV_LOG_ERROR, "The maximum value for lowres supported by the decoder is %d\n",

               avctx->codec->max_lowres);

        ret = AVERROR(EINVAL);

        goto free_and_end;

    }

    if (av_codec_is_encoder(avctx->codec)) {

        int i;

        if (avctx->codec->sample_fmts) {

            for (i = 0; avctx->codec->sample_fmts[i] != AV_SAMPLE_FMT_NONE; i++) {

                if (avctx->sample_fmt == avctx->codec->sample_fmts[i])

                    break;

                if (avctx->channels == 1 &&

                    av_get_planar_sample_fmt(avctx->sample_fmt) ==

                    av_get_planar_sample_fmt(avctx->codec->sample_fmts[i])) {

                    avctx->sample_fmt = avctx->codec->sample_fmts[i];

                    break;

                }

            }

            if (avctx->codec->sample_fmts[i] == AV_SAMPLE_FMT_NONE) {

                char buf[128];

                snprintf(buf, sizeof(buf), "%d", avctx->sample_fmt);

                av_log(avctx, AV_LOG_ERROR, "Specified sample format %s is invalid or not supported\n",

                       (char *)av_x_if_null(av_get_sample_fmt_name(avctx->sample_fmt), buf));

                ret = AVERROR(EINVAL);

                goto free_and_end;

            }

        }

        if (avctx->codec->pix_fmts) {

            for (i = 0; avctx->codec->pix_fmts[i] != AV_PIX_FMT_NONE; i++)

                if (avctx->pix_fmt == avctx->codec->pix_fmts[i])

                    break;

            if (avctx->codec->pix_fmts[i] == AV_PIX_FMT_NONE

                && !((avctx->codec_id == AV_CODEC_ID_MJPEG || avctx->codec_id == AV_CODEC_ID_LJPEG)

                     && avctx->strict_std_compliance <= FF_COMPLIANCE_UNOFFICIAL)) {

                char buf[128];

                snprintf(buf, sizeof(buf), "%d", avctx->pix_fmt);

                av_log(avctx, AV_LOG_ERROR, "Specified pixel format %s is invalid or not supported\n",

                       (char *)av_x_if_null(av_get_pix_fmt_name(avctx->pix_fmt), buf));

                ret = AVERROR(EINVAL);

                goto free_and_end;

            }

        }

        if (avctx->codec->supported_samplerates) {

            for (i = 0; avctx->codec->supported_samplerates[i] != 0; i++)

                if (avctx->sample_rate == avctx->codec->supported_samplerates[i])

                    break;

            if (avctx->codec->supported_samplerates[i] == 0) {

                av_log(avctx, AV_LOG_ERROR, "Specified sample rate %d is not supported\n",

                       avctx->sample_rate);

                ret = AVERROR(EINVAL);

                goto free_and_end;

            }

        }

        if (avctx->codec->channel_layouts) {

            if (!avctx->channel_layout) {

                av_log(avctx, AV_LOG_WARNING, "Channel layout not specified\n");

            } else {

                for (i = 0; avctx->codec->channel_layouts[i] != 0; i++)

                    if (avctx->channel_layout == avctx->codec->channel_layouts[i])

                        break;

                if (avctx->codec->channel_layouts[i] == 0) {

                    char buf[512];

                    av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout);

                    av_log(avctx, AV_LOG_ERROR, "Specified channel layout '%s' is not supported\n", buf);

                    ret = AVERROR(EINVAL);

                    goto free_and_end;

                }

            }

        }

        if (avctx->channel_layout && avctx->channels) {

            int channels = av_get_channel_layout_nb_channels(avctx->channel_layout);

            if (channels != avctx->channels) {

                char buf[512];

                av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout);

                av_log(avctx, AV_LOG_ERROR,

                       "Channel layout '%s' with %d channels does not match number of specified channels %d\n",

                       buf, channels, avctx->channels);

                ret = AVERROR(EINVAL);

                goto free_and_end;

            }

        } else if (avctx->channel_layout) {

            avctx->channels = av_get_channel_layout_nb_channels(avctx->channel_layout);

        }

        if(avctx->codec_type == AVMEDIA_TYPE_VIDEO &&

           avctx->codec_id != AV_CODEC_ID_PNG // For mplayer

        ) {

            if (avctx->width <= 0 || avctx->height <= 0) {

                av_log(avctx, AV_LOG_ERROR, "dimensions not set\n");

                ret = AVERROR(EINVAL);

                goto free_and_end;

            }

        }

        if (   (avctx->codec_type == AVMEDIA_TYPE_VIDEO || avctx->codec_type == AVMEDIA_TYPE_AUDIO)

            && avctx->bit_rate>0 && avctx->bit_rate<1000) {

            av_log(avctx, AV_LOG_WARNING, "Bitrate %d is extremely low, maybe you mean %dk\n", avctx->bit_rate, avctx->bit_rate);

        }

        if (!avctx->rc_initial_buffer_occupancy)

            avctx->rc_initial_buffer_occupancy = avctx->rc_buffer_size * 3 / 4;

    }

    avctx->pts_correction_num_faulty_pts =

    avctx->pts_correction_num_faulty_dts = 0;

    avctx->pts_correction_last_pts =

    avctx->pts_correction_last_dts = INT64_MIN;

    if (   avctx->codec->init && (!(avctx->active_thread_type&FF_THREAD_FRAME)

        || avctx->internal->frame_thread_encoder)) {

        ret = avctx->codec->init(avctx);

        if (ret < 0) {

            goto free_and_end;

        }

    }

    ret=0;

    if (av_codec_is_decoder(avctx->codec)) {

        if (!avctx->bit_rate)

            avctx->bit_rate = get_bit_rate(avctx);

        /* validate channel layout from the decoder */

        if (avctx->channel_layout) {

            int channels = av_get_channel_layout_nb_channels(avctx->channel_layout);

            if (!avctx->channels)

                avctx->channels = channels;

            else if (channels != avctx->channels) {

                char buf[512];

                av_get_channel_layout_string(buf, sizeof(buf), -1, avctx->channel_layout);

                av_log(avctx, AV_LOG_WARNING,

                       "Channel layout '%s' with %d channels does not match specified number of channels %d: "

                       "ignoring specified channel layout\n",

                       buf, channels, avctx->channels);

                avctx->channel_layout = 0;

            }

        }

        if (avctx->channels && avctx->channels < 0 ||

            avctx->channels > FF_SANE_NB_CHANNELS) {

            ret = AVERROR(EINVAL);

            goto free_and_end;

        }

        if (avctx->sub_charenc) {

            if (avctx->codec_type != AVMEDIA_TYPE_SUBTITLE) {

                av_log(avctx, AV_LOG_ERROR, "Character encoding is only "

                       "supported with subtitles codecs\n");

                ret = AVERROR(EINVAL);

                goto free_and_end;

            } else if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB) {

                av_log(avctx, AV_LOG_WARNING, "Codec '%s' is bitmap-based, "

                       "subtitles character encoding will be ignored\n",

                       avctx->codec_descriptor->name);

                avctx->sub_charenc_mode = FF_SUB_CHARENC_MODE_DO_NOTHING;

            } else {

                /* input character encoding is set for a text based subtitle

                 * codec at this point */

                if (avctx->sub_charenc_mode == FF_SUB_CHARENC_MODE_AUTOMATIC)

                    avctx->sub_charenc_mode = FF_SUB_CHARENC_MODE_PRE_DECODER;

                if (avctx->sub_charenc_mode == FF_SUB_CHARENC_MODE_PRE_DECODER) {

#if CONFIG_ICONV

                    iconv_t cd = iconv_open("UTF-8", avctx->sub_charenc);

                    if (cd == (iconv_t)-1) {

                        av_log(avctx, AV_LOG_ERROR, "Unable to open iconv context "

                               "with input character encoding \"%s\"\n", avctx->sub_charenc);

                        ret = AVERROR(errno);

                        goto free_and_end;

                    }

                    iconv_close(cd);

#else

                    av_log(avctx, AV_LOG_ERROR, "Character encoding subtitles "

                           "conversion needs a libavcodec built with iconv support "

                           "for this codec\n");

                    ret = AVERROR(ENOSYS);

                    goto free_and_end;

#endif

                }

            }

        }

    }

end:

    ff_unlock_avcodec();

    if (options) {

        av_dict_free(options);

        *options = tmp;

    }

    return ret;

free_and_end:

    av_dict_free(&tmp);

    av_freep(&avctx->priv_data);

    if (avctx->internal)

        av_freep(&avctx->internal->pool);

    av_freep(&avctx->internal);

    avctx->codec = NULL;

    goto end;

}


unsigned long av_adler32_update(unsigned long adler, const uint8_t * buf,

                                unsigned int len)

{

    unsigned long s1 = adler & 0xffff;

    unsigned long s2 = adler >> 16;

    while (len > 0) {

#if CONFIG_SMALL

        while (len > 4  && s2 < (1U << 31)) {

            DO4(buf);

            len -= 4;

        }

#else

        while (len > 16 && s2 < (1U << 31)) {

            DO16(buf);

            len -= 16;

        }

#endif

        DO1(buf); len--;

        s1 %= BASE;

        s2 %= BASE;

    }

    return (s2 << 16) | s1;

}


static int mpc_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)

{

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

    MPCContext *c = s->priv_data;

    AVPacket pkt1, *pkt = &pkt1;

    int ret;

    int index = av_index_search_timestamp(st, timestamp - DELAY_FRAMES, flags);

    uint32_t lastframe;

    /* if found, seek there */

    if (index >= 0){

        c->curframe = st->index_entries[index].pos;

        return 0;

    }

    /* if timestamp is out of bounds, return error */

    if(timestamp < 0 || timestamp >= c->fcount)

        return -1;

    timestamp -= DELAY_FRAMES;

    /* seek to the furthest known position and read packets until

       we reach desired position */

    lastframe = c->curframe;

    if(c->frames_noted) c->curframe = c->frames_noted - 1;

    while(c->curframe < timestamp){

        ret = av_read_frame(s, pkt);

        if (ret < 0){

            c->curframe = lastframe;

            return ret;

        }

        av_free_packet(pkt);

    }

    return 0;

}


av_cold void ff_gradfun_init_x86(GradFunContext *gf)

{

    int cpu_flags = av_get_cpu_flags();

    if (HAVE_MMX2 && cpu_flags & AV_CPU_FLAG_MMX2)

        gf->filter_line = gradfun_filter_line_mmx2;

    if (HAVE_SSSE3 && cpu_flags & AV_CPU_FLAG_SSSE3)

        gf->filter_line = gradfun_filter_line_ssse3;

    if (HAVE_SSE && cpu_flags & AV_CPU_FLAG_SSE2)

        gf->blur_line = gradfun_blur_line_sse2;

}


static int ioreq_map(struct ioreq *ioreq)

{

    int gnt = ioreq->blkdev->xendev.gnttabdev;

    int i;

    if (ioreq->v.niov == 0) {

        return 0;

    }

    if (batch_maps) {

        ioreq->pages = xc_gnttab_map_grant_refs

            (gnt, ioreq->v.niov, ioreq->domids, ioreq->refs, ioreq->prot);

        if (ioreq->pages == NULL) {

            xen_be_printf(&ioreq->blkdev->xendev, 0,

                          "can't map %d grant refs (%s, %d maps)\n",

                          ioreq->v.niov, strerror(errno), ioreq->blkdev->cnt_map);

            return -1;

        }

        for (i = 0; i < ioreq->v.niov; i++) {

            ioreq->v.iov[i].iov_base = ioreq->pages + i * XC_PAGE_SIZE +

                (uintptr_t)ioreq->v.iov[i].iov_base;

        }

        ioreq->blkdev->cnt_map += ioreq->v.niov;

    } else  {

        for (i = 0; i < ioreq->v.niov; i++) {

            ioreq->page[i] = xc_gnttab_map_grant_ref

                (gnt, ioreq->domids[i], ioreq->refs[i], ioreq->prot);

            if (ioreq->page[i] == NULL) {

                xen_be_printf(&ioreq->blkdev->xendev, 0,

                              "can't map grant ref %d (%s, %d maps)\n",

                              ioreq->refs[i], strerror(errno), ioreq->blkdev->cnt_map);

                ioreq_unmap(ioreq);

                return -1;

            }

            ioreq->v.iov[i].iov_base = ioreq->page[i] + (uintptr_t)ioreq->v.iov[i].iov_base;

            ioreq->blkdev->cnt_map++;

        }

    }

    return 0;

}


static CharDriverState *qemu_chr_open_ringbuf(ChardevRingbuf *opts,

                                              Error **errp)

{

    CharDriverState *chr;

    RingBufCharDriver *d;

    chr = g_malloc0(sizeof(CharDriverState));

    d = g_malloc(sizeof(*d));

    d->size = opts->has_size ? opts->size : 65536;

    /* The size must be power of 2 */

    if (d->size & (d->size - 1)) {

        error_setg(errp, "size of ringbuf chardev must be power of two");

        goto fail;

    }

    d->prod = 0;

    d->cons = 0;

    d->cbuf = g_malloc0(d->size);

    chr->opaque = d;

    chr->chr_write = ringbuf_chr_write;

    chr->chr_close = ringbuf_chr_close;

    return chr;

fail:

    g_free(d);

    g_free(chr);

    return NULL;

}


static void mcf_fec_write(void *opaque, hwaddr addr,

                          uint64_t value, unsigned size)

{

    mcf_fec_state *s = (mcf_fec_state *)opaque;

    switch (addr & 0x3ff) {

    case 0x004:

        s->eir &= ~value;

        break;

    case 0x008:

        s->eimr = value;

        break;

    case 0x010: /* RDAR */

        if ((s->ecr & FEC_EN) && !s->rx_enabled) {

            DPRINTF("RX enable\n");

            mcf_fec_enable_rx(s);

        }

        break;

    case 0x014: /* TDAR */

        if (s->ecr & FEC_EN) {

            mcf_fec_do_tx(s);

        }

        break;

    case 0x024:

        s->ecr = value;

        if (value & FEC_RESET) {

            DPRINTF("Reset\n");

            mcf_fec_reset(s);

        }

        if ((s->ecr & FEC_EN) == 0) {

            s->rx_enabled = 0;

        }

        break;

    case 0x040:

        s->mmfr = value;

        s->eir |= FEC_INT_MII;

        break;

    case 0x044:

        s->mscr = value & 0xfe;

        break;

    case 0x064:

        /* TODO: Implement MIB.  */

        break;

    case 0x084:

        s->rcr = value & 0x07ff003f;

        /* TODO: Implement LOOP mode.  */

        break;

    case 0x0c4: /* TCR */

        /* We transmit immediately, so raise GRA immediately.  */

        s->tcr = value;

        if (value & 1)

            s->eir |= FEC_INT_GRA;

        break;

    case 0x0e4: /* PALR */

        s->conf.macaddr.a[0] = value >> 24;

        s->conf.macaddr.a[1] = value >> 16;

        s->conf.macaddr.a[2] = value >> 8;

        s->conf.macaddr.a[3] = value;

        break;

    case 0x0e8: /* PAUR */

        s->conf.macaddr.a[4] = value >> 24;

        s->conf.macaddr.a[5] = value >> 16;

        break;

    case 0x0ec:

        /* OPD */

        break;

    case 0x118:

    case 0x11c:

    case 0x120:

    case 0x124:

        /* TODO: implement MAC hash filtering.  */

        break;

    case 0x144:

        s->tfwr = value & 3;

        break;

    case 0x14c:

        /* FRBR writes ignored.  */

        break;

    case 0x150:

        s->rfsr = (value & 0x3fc) | 0x400;

        break;

    case 0x180:

        s->erdsr = value & ~3;

        s->rx_descriptor = s->erdsr;

        break;

    case 0x184:

        s->etdsr = value & ~3;

        s->tx_descriptor = s->etdsr;

        break;

    case 0x188:

        s->emrbr = value & 0x7f0;

        break;

    default:

        hw_error("mcf_fec_write Bad address 0x%x\n", (int)addr);

    }

    mcf_fec_update(s);

}


static int vmdk_open_vmdk4(BlockDriverState *bs,

                           BlockDriverState *file,

                           int flags)

{

    int ret;

    uint32_t magic;

    uint32_t l1_size, l1_entry_sectors;

    VMDK4Header header;

    VmdkExtent *extent;

    int64_t l1_backup_offset = 0;

    ret = bdrv_pread(file, sizeof(magic), &header, sizeof(header));

    if (ret < 0) {

        return ret;

    }

    if (header.capacity == 0) {

        uint64_t desc_offset = le64_to_cpu(header.desc_offset);

        if (desc_offset) {

            return vmdk_open_desc_file(bs, flags, desc_offset << 9);

        }

    }

    if (le64_to_cpu(header.gd_offset) == VMDK4_GD_AT_END) {

        /*

         * The footer takes precedence over the header, so read it in. The

         * footer starts at offset -1024 from the end: One sector for the

         * footer, and another one for the end-of-stream marker.

         */

        struct {

            struct {

                uint64_t val;

                uint32_t size;

                uint32_t type;

                uint8_t pad[512 - 16];

            } QEMU_PACKED footer_marker;

            uint32_t magic;

            VMDK4Header header;

            uint8_t pad[512 - 4 - sizeof(VMDK4Header)];

            struct {

                uint64_t val;

                uint32_t size;

                uint32_t type;

                uint8_t pad[512 - 16];

            } QEMU_PACKED eos_marker;

        } QEMU_PACKED footer;

        ret = bdrv_pread(file,

            bs->file->total_sectors * 512 - 1536,

            &footer, sizeof(footer));

        if (ret < 0) {

            return ret;

        }

        /* Some sanity checks for the footer */

        if (be32_to_cpu(footer.magic) != VMDK4_MAGIC ||

            le32_to_cpu(footer.footer_marker.size) != 0  ||

            le32_to_cpu(footer.footer_marker.type) != MARKER_FOOTER ||

            le64_to_cpu(footer.eos_marker.val) != 0  ||

            le32_to_cpu(footer.eos_marker.size) != 0  ||

            le32_to_cpu(footer.eos_marker.type) != MARKER_END_OF_STREAM)

        {

            return -EINVAL;

        }

        header = footer.header;

    }

    if (le32_to_cpu(header.version) >= 3) {

        char buf[64];

        snprintf(buf, sizeof(buf), "VMDK version %d",

                 le32_to_cpu(header.version));

        qerror_report(QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,

                bs->device_name, "vmdk", buf);

        return -ENOTSUP;

    }

    l1_entry_sectors = le32_to_cpu(header.num_gtes_per_gte)

                        * le64_to_cpu(header.granularity);

    if (l1_entry_sectors == 0) {

        return -EINVAL;

    }

    l1_size = (le64_to_cpu(header.capacity) + l1_entry_sectors - 1)

                / l1_entry_sectors;

    if (le32_to_cpu(header.flags) & VMDK4_FLAG_RGD) {

        l1_backup_offset = le64_to_cpu(header.rgd_offset) << 9;

    }

    extent = vmdk_add_extent(bs, file, false,

                          le64_to_cpu(header.capacity),

                          le64_to_cpu(header.gd_offset) << 9,

                          l1_backup_offset,

                          l1_size,

                          le32_to_cpu(header.num_gtes_per_gte),

                          le64_to_cpu(header.granularity));

    extent->compressed =

        le16_to_cpu(header.compressAlgorithm) == VMDK4_COMPRESSION_DEFLATE;

    extent->has_marker = le32_to_cpu(header.flags) & VMDK4_FLAG_MARKER;

    extent->version = le32_to_cpu(header.version);

    extent->has_zero_grain = le32_to_cpu(header.flags) & VMDK4_FLAG_ZERO_GRAIN;

    ret = vmdk_init_tables(bs, extent);

    if (ret) {

        /* free extent allocated by vmdk_add_extent */

        vmdk_free_last_extent(bs);

    }

    return ret;

}


int bdrv_write_zeroes(BlockDriverState *bs, int64_t sector_num,

                      int nb_sectors, BdrvRequestFlags flags)

{

    return bdrv_rw_co(bs, sector_num, NULL, nb_sectors, true,

                      BDRV_REQ_ZERO_WRITE | flags);

}


static char *usb_get_fw_dev_path(DeviceState *qdev)

{

    USBDevice *dev = DO_UPCAST(USBDevice, qdev, qdev);

    char *fw_path, *in;

    int pos = 0;

    long nr;

    fw_path = qemu_malloc(32 + strlen(dev->port->path) * 6);

    in = dev->port->path;

    while (true) {

        nr = strtol(in, &in, 10);

        if (in[0] == '.') {

            /* some hub between root port and device */

            pos += sprintf(fw_path + pos, "hub@%ld/", nr);

            in++;

        } else {

            /* the device itself */

            pos += sprintf(fw_path + pos, "%s@%ld", qdev_fw_name(qdev), nr);

            break;

        }

    }

    return fw_path;

}


static void arm_sysctl_write(void *opaque, target_phys_addr_t offset,

                             uint64_t val, unsigned size)

{

    arm_sysctl_state *s = (arm_sysctl_state *)opaque;

    switch (offset) {

    case 0x08: /* LED */

        s->leds = val;

    case 0x0c: /* OSC0 */

    case 0x10: /* OSC1 */

    case 0x14: /* OSC2 */

    case 0x18: /* OSC3 */

    case 0x1c: /* OSC4 */

        /* ??? */

        break;

    case 0x20: /* LOCK */

        if (val == LOCK_VALUE)

            s->lockval = val;

        else

            s->lockval = val & 0x7fff;

        break;

    case 0x28: /* CFGDATA1 */

        /* ??? Need to implement this.  */

        s->cfgdata1 = val;

        break;

    case 0x2c: /* CFGDATA2 */

        /* ??? Need to implement this.  */

        s->cfgdata2 = val;

        break;

    case 0x30: /* FLAGSSET */

        s->flags |= val;

        break;

    case 0x34: /* FLAGSCLR */

        s->flags &= ~val;

        break;

    case 0x38: /* NVFLAGSSET */

        s->nvflags |= val;

        break;

    case 0x3c: /* NVFLAGSCLR */

        s->nvflags &= ~val;

        break;

    case 0x40: /* RESETCTL */

        switch (board_id(s)) {

        case BOARD_ID_PB926:

            if (s->lockval == LOCK_VALUE) {

                s->resetlevel = val;

                if (val & 0x100) {

                    qemu_system_reset_request();

                }

            }

            break;

        case BOARD_ID_PBX:

        case BOARD_ID_PBA8:

            if (s->lockval == LOCK_VALUE) {

                s->resetlevel = val;

                if (val & 0x04) {

                    qemu_system_reset_request();

                }

            }

            break;

        case BOARD_ID_VEXPRESS:

        case BOARD_ID_EB:

        default:

            /* reserved: RAZ/WI */

            break;

        }

        break;

    case 0x44: /* PCICTL */

        /* nothing to do.  */

        break;

    case 0x4c: /* FLASH */

        break;

    case 0x50: /* CLCD */

        switch (board_id(s)) {

        case BOARD_ID_PB926:

            /* On 926 bits 13:8 are R/O, bits 1:0 control

             * the mux that defines how to interpret the PL110

             * graphics format, and other bits are r/w but we

             * don't implement them to do anything.

             */

            s->sys_clcd &= 0x3f00;

            s->sys_clcd |= val & ~0x3f00;

            qemu_set_irq(s->pl110_mux_ctrl, val & 3);

            break;

        case BOARD_ID_EB:

            /* The EB is the same except that there is no mux since

             * the EB has a PL111.

             */

            s->sys_clcd &= 0x3f00;

            s->sys_clcd |= val & ~0x3f00;

            break;

        case BOARD_ID_PBA8:

        case BOARD_ID_PBX:

            /* On PBA8 and PBX bit 7 is r/w and all other bits

             * are either r/o or RAZ/WI.

             */

            s->sys_clcd &= (1 << 7);

            s->sys_clcd |= val & ~(1 << 7);

            break;

        case BOARD_ID_VEXPRESS:

        default:

            /* On VExpress this register is unimplemented and will RAZ/WI */

            break;

        }

    case 0x54: /* CLCDSER */

    case 0x64: /* DMAPSR0 */

    case 0x68: /* DMAPSR1 */

    case 0x6c: /* DMAPSR2 */

    case 0x70: /* IOSEL */

    case 0x74: /* PLDCTL */

    case 0x80: /* BUSID */

    case 0x84: /* PROCID0 */

    case 0x88: /* PROCID1 */

    case 0x8c: /* OSCRESET0 */

    case 0x90: /* OSCRESET1 */

    case 0x94: /* OSCRESET2 */

    case 0x98: /* OSCRESET3 */

    case 0x9c: /* OSCRESET4 */

        break;

    case 0xa0: /* SYS_CFGDATA */

        if (board_id(s) != BOARD_ID_VEXPRESS) {

            goto bad_reg;

        }

        s->sys_cfgdata = val;

        return;

    case 0xa4: /* SYS_CFGCTRL */

        if (board_id(s) != BOARD_ID_VEXPRESS) {

            goto bad_reg;

        }

        s->sys_cfgctrl = val & ~(3 << 18);

        s->sys_cfgstat = 1;            /* complete */

        switch (s->sys_cfgctrl) {

        case 0xc0800000:            /* SYS_CFG_SHUTDOWN to motherboard */

            qemu_system_shutdown_request();

            break;

        case 0xc0900000:            /* SYS_CFG_REBOOT to motherboard */

            qemu_system_reset_request();

            break;

        default:

            s->sys_cfgstat |= 2;        /* error */

        }

        return;

    case 0xa8: /* SYS_CFGSTAT */

        if (board_id(s) != BOARD_ID_VEXPRESS) {

            goto bad_reg;

        }

        s->sys_cfgstat = val & 3;

        return;

    default:

    bad_reg:

        printf ("arm_sysctl_write: Bad register offset 0x%x\n", (int)offset);

        return;

    }

}


uint32_t HELPER(msa)(CPUS390XState *env, uint32_t r1, uint32_t r2, uint32_t r3,

                     uint32_t type)

{

    const uintptr_t ra = GETPC();

    const uint8_t mod = env->regs[0] & 0x80ULL;

    const uint8_t fc = env->regs[0] & 0x7fULL;

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

    uint8_t subfunc[16] = { 0 };

    uint64_t param_addr;

    int i;

    switch (type) {

    case S390_FEAT_TYPE_KMAC:

    case S390_FEAT_TYPE_KIMD:

    case S390_FEAT_TYPE_KLMD:

    case S390_FEAT_TYPE_PCKMO:

    case S390_FEAT_TYPE_PCC:

        if (mod) {

            cpu_restore_state(cs, ra);

            program_interrupt(env, PGM_SPECIFICATION, 4);

            return 0;

        }

        break;

    }

    s390_get_feat_block(type, subfunc);

    if (!test_be_bit(fc, subfunc)) {

        cpu_restore_state(cs, ra);

        program_interrupt(env, PGM_SPECIFICATION, 4);

        return 0;

    }

    switch (fc) {

    case 0: /* query subfunction */

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

            param_addr = wrap_address(env, env->regs[1] + i);

            cpu_stb_data_ra(env, param_addr, subfunc[i], ra);

        }

        break;

    default:

        /* we don't implement any other subfunction yet */

        g_assert_not_reached();

    }

    return 0;

}


void usb_desc_attach(USBDevice *dev)

{

    const USBDesc *desc = usb_device_get_usb_desc(dev);

    assert(desc != NULL);

    if (desc->super && (dev->port->speedmask & USB_SPEED_MASK_SUPER)) {

        dev->speed = USB_SPEED_SUPER;

    } else if (desc->high && (dev->port->speedmask & USB_SPEED_MASK_HIGH)) {

        dev->speed = USB_SPEED_HIGH;

    } else if (desc->full && (dev->port->speedmask & USB_SPEED_MASK_FULL)) {

        dev->speed = USB_SPEED_FULL;

    } else {

        return;

    }

    usb_desc_setdefaults(dev);

}


void register_displaychangelistener(DisplayChangeListener *dcl)

{

    static DisplaySurface *dummy;

    QemuConsole *con;

    trace_displaychangelistener_register(dcl, dcl->ops->dpy_name);

    dcl->ds = get_alloc_displaystate();

    QLIST_INSERT_HEAD(&dcl->ds->listeners, dcl, next);

    gui_setup_refresh(dcl->ds);

    if (dcl->con) {

        dcl->con->dcls++;

        con = dcl->con;

    } else {

        con = active_console;

    }

    if (dcl->ops->dpy_gfx_switch) {

        if (con) {

            dcl->ops->dpy_gfx_switch(dcl, con->surface);

        } else {

            if (!dummy) {

                dummy = qemu_create_dummy_surface();

            }

            dcl->ops->dpy_gfx_switch(dcl, dummy);

        }

    }

}


void bdrv_set_io_limits(BlockDriverState *bs,

                        ThrottleConfig *cfg)

{

    int i;

    throttle_config(&bs->throttle_state, cfg);

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

        qemu_co_enter_next(&bs->throttled_reqs[i]);

    }

}


void s390_init_cpus(MachineState *machine)

{

    int i;

    gchar *name;

    if (machine->cpu_model == NULL) {

        machine->cpu_model = "host";

    }

    cpu_states = g_malloc0(sizeof(S390CPU *) * max_cpus);

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

        name = g_strdup_printf("cpu[%i]", i);

        object_property_add_link(OBJECT(machine), name, TYPE_S390_CPU,

                                 (Object **) &cpu_states[i],

                                 object_property_allow_set_link,

                                 OBJ_PROP_LINK_UNREF_ON_RELEASE,

                                 &error_abort);

        g_free(name);

    }

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

        cpu_s390x_init(machine->cpu_model);

    }

}


static int qemu_rbd_create(const char *filename, QEMUOptionParameter *options)

{

    int64_t bytes = 0;

    int64_t objsize;

    int obj_order = 0;

    char pool[RBD_MAX_POOL_NAME_SIZE];

    char name[RBD_MAX_IMAGE_NAME_SIZE];

    char snap_buf[RBD_MAX_SNAP_NAME_SIZE];

    char conf[RBD_MAX_CONF_SIZE];

    rados_t cluster;

    rados_ioctx_t io_ctx;

    int ret;

    if (qemu_rbd_parsename(filename, pool, sizeof(pool),

                           snap_buf, sizeof(snap_buf),

                           name, sizeof(name),

                           conf, sizeof(conf)) < 0) {

        return -EINVAL;

    }

    /* Read out options */

    while (options && options->name) {

        if (!strcmp(options->name, BLOCK_OPT_SIZE)) {

            bytes = options->value.n;

        } else if (!strcmp(options->name, BLOCK_OPT_CLUSTER_SIZE)) {

            if (options->value.n) {

                objsize = options->value.n;

                if ((objsize - 1) & objsize) {    /* not a power of 2? */

                    error_report("obj size needs to be power of 2");

                    return -EINVAL;

                }

                if (objsize < 4096) {

                    error_report("obj size too small");

                    return -EINVAL;

                }

                obj_order = ffs(objsize) - 1;

            }

        }

        options++;

    }

    if (rados_create(&cluster, NULL) < 0) {

        error_report("error initializing");

        return -EIO;

    }

    if (strstr(conf, "conf=") == NULL) {

        if (rados_conf_read_file(cluster, NULL) < 0) {

            error_report("error reading config file");

            rados_shutdown(cluster);

            return -EIO;

        }

    }

    if (conf[0] != '\0' &&

        qemu_rbd_set_conf(cluster, conf) < 0) {

        error_report("error setting config options");

        rados_shutdown(cluster);

        return -EIO;

    }

    if (rados_connect(cluster) < 0) {

        error_report("error connecting");

        rados_shutdown(cluster);

        return -EIO;

    }

    if (rados_ioctx_create(cluster, pool, &io_ctx) < 0) {

        error_report("error opening pool %s", pool);

        rados_shutdown(cluster);

        return -EIO;

    }

    ret = rbd_create(io_ctx, name, bytes, &obj_order);

    rados_ioctx_destroy(io_ctx);

    rados_shutdown(cluster);

    return ret;

}


static void init_proc_401x2 (CPUPPCState *env)

{

}


static int check_pow_970FX (CPUPPCState *env)

{

    if (env->spr[SPR_HID0] & 0x00600000)

        return 1;

    return 0;

}


int ff_listen_bind(int fd, const struct sockaddr *addr,

                   socklen_t addrlen, int timeout)

{

    int ret;

    int reuse = 1;

    struct pollfd lp = { fd, POLLIN, 0 };

    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));

    ret = bind(fd, addr, addrlen);

    if (ret)

        return ff_neterrno();

    ret = listen(fd, 1);

    if (ret)

        return ff_neterrno();

    ret = poll(&lp, 1, timeout >= 0 ? timeout : -1);

    if (ret <= 0)

        return AVERROR(ETIMEDOUT);

    ret = accept(fd, NULL, NULL);

    if (ret < 0)

        return ff_neterrno();

    closesocket(fd);

    ff_socket_nonblock(ret, 1);

    return ret;

}


void qmp_x_blockdev_insert_medium(const char *device, const char *node_name,

                                  Error **errp)

{

    BlockDriverState *bs;

    bs = bdrv_find_node(node_name);

    if (!bs) {

        error_setg(errp, "Node '%s' not found", node_name);

        return;

    }

    if (bs->blk) {

        error_setg(errp, "Node '%s' is already in use by '%s'", node_name,

                   blk_name(bs->blk));

        return;

    }

    qmp_blockdev_insert_anon_medium(device, bs, errp);

}


int bdrv_pwritev(BlockDriverState *bs, int64_t offset, QEMUIOVector *qiov)

{

    int ret;

    ret = bdrv_prwv_co(bs, offset, qiov, true, 0);

    if (ret < 0) {

        return ret;

    }

    return qiov->size;

}


void qemu_input_event_send(QemuConsole *src, InputEvent *evt)

{

    QemuInputHandlerState *s;

    if (!runstate_is_running() && !runstate_check(RUN_STATE_SUSPENDED)) {

        return;

    }

    qemu_input_event_trace(src, evt);

    /* pre processing */

    if (graphic_rotate && (evt->type == INPUT_EVENT_KIND_ABS)) {

            qemu_input_transform_abs_rotate(evt);

    }

    /* send event */

    s = qemu_input_find_handler(1 << evt->type, src);

    if (!s) {

        return;

    }

    s->handler->event(s->dev, src, evt);

    s->events++;

}


static void omap_wd_timer_write(void *opaque, target_phys_addr_t addr,

                                uint64_t value, unsigned size)

{

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

    if (size != 2) {

        return omap_badwidth_write16(opaque, addr, value);

    }

    switch (addr) {

    case 0x00:	/* CNTL_TIMER */

        omap_timer_sync(&s->timer);

        s->timer.ptv = (value >> 9) & 7;

        s->timer.ar = (value >> 8) & 1;

        s->timer.st = (value >> 7) & 1;

        s->free = (value >> 1) & 1;

        omap_timer_update(&s->timer);

        break;

    case 0x04:	/* LOAD_TIMER */

        s->timer.reset_val = value & 0xffff;

        break;

    case 0x08:	/* TIMER_MODE */

        if (!s->mode && ((value >> 15) & 1))

            omap_clk_get(s->timer.clk);

        s->mode |= (value >> 15) & 1;

        if (s->last_wr == 0xf5) {

            if ((value & 0xff) == 0xa0) {

                if (s->mode) {

                    s->mode = 0;

                    omap_clk_put(s->timer.clk);

                }

            } else {

                /* XXX: on T|E hardware somehow this has no effect,

                 * on Zire 71 it works as specified.  */

                s->reset = 1;

                qemu_system_reset_request();

            }

        }

        s->last_wr = value & 0xff;

        break;

    default:

        OMAP_BAD_REG(addr);

    }

}


static void nested_struct_compare(UserDefNested *udnp1, UserDefNested *udnp2)

{

    g_assert(udnp1);

    g_assert(udnp2);

    g_assert_cmpstr(udnp1->string0, ==, udnp2->string0);

    g_assert_cmpstr(udnp1->dict1.string1, ==, udnp2->dict1.string1);

    g_assert_cmpint(udnp1->dict1.dict2.userdef1->base->integer, ==,

                    udnp2->dict1.dict2.userdef1->base->integer);

    g_assert_cmpstr(udnp1->dict1.dict2.userdef1->string, ==,

                    udnp2->dict1.dict2.userdef1->string);

    g_assert_cmpstr(udnp1->dict1.dict2.string2, ==, udnp2->dict1.dict2.string2);

    g_assert(udnp1->dict1.has_dict3 == udnp2->dict1.has_dict3);

    g_assert_cmpint(udnp1->dict1.dict3.userdef2->base->integer, ==,

                    udnp2->dict1.dict3.userdef2->base->integer);

    g_assert_cmpstr(udnp1->dict1.dict3.userdef2->string, ==,

                    udnp2->dict1.dict3.userdef2->string);

    g_assert_cmpstr(udnp1->dict1.dict3.string3, ==, udnp2->dict1.dict3.string3);

}


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

{

    CPUState *cs = CPU(dev);

    S390CPUClass *scc = S390_CPU_GET_CLASS(dev);

    S390CPU *cpu = S390_CPU(dev);

    CPUS390XState *env = &cpu->env;

    Error *err = NULL;

    cpu_exec_init(cs, &err);

    if (err != NULL) {

        error_propagate(errp, err);

        return;

    }

#if !defined(CONFIG_USER_ONLY)

    qemu_register_reset(s390_cpu_machine_reset_cb, cpu);

#endif

    env->cpu_num = scc->next_cpu_id++;

    s390_cpu_gdb_init(cs);

    qemu_init_vcpu(cs);

#if !defined(CONFIG_USER_ONLY)

    run_on_cpu(cs, s390_do_cpu_full_reset, cs);

#else

    cpu_reset(cs);

#endif

    scc->parent_realize(dev, errp);

}


static uint64_t musicpal_lcd_read(void *opaque, target_phys_addr_t offset,

                                  unsigned size)

{

    musicpal_lcd_state *s = opaque;

    switch (offset) {

    case MP_LCD_IRQCTRL:

        return s->irqctrl;

    default:

        return 0;

    }

}


static void cmd_seek(IDEState *s, uint8_t* buf)

{

    unsigned int lba;

    uint64_t total_sectors = s->nb_sectors >> 2;

    if (total_sectors == 0) {

        ide_atapi_cmd_error(s, SENSE_NOT_READY, ASC_MEDIUM_NOT_PRESENT);

        return;

    }

    lba = ube32_to_cpu(buf + 2);

    if (lba >= total_sectors) {

        ide_atapi_cmd_error(s, SENSE_ILLEGAL_REQUEST, ASC_LOGICAL_BLOCK_OOR);

        return;

    }

    ide_atapi_cmd_ok(s);

}


static void test_visitor_in_alternate(TestInputVisitorData *data,

                                      const void *unused)

{

    Visitor *v;

    Error *err = NULL;

    UserDefAlternate *tmp;

    WrapAlternate *wrap;

    v = visitor_input_test_init(data, "42");

    visit_type_UserDefAlternate(v, NULL, &tmp, &error_abort);

    g_assert_cmpint(tmp->type, ==, QTYPE_QINT);

    g_assert_cmpint(tmp->u.i, ==, 42);

    qapi_free_UserDefAlternate(tmp);

    v = visitor_input_test_init(data, "'string'");

    visit_type_UserDefAlternate(v, NULL, &tmp, &error_abort);

    g_assert_cmpint(tmp->type, ==, QTYPE_QSTRING);

    g_assert_cmpstr(tmp->u.s, ==, "string");

    qapi_free_UserDefAlternate(tmp);

    v = visitor_input_test_init(data, "{'integer':1, 'string':'str', "

                                "'enum1':'value1', 'boolean':true}");

    visit_type_UserDefAlternate(v, NULL, &tmp, &error_abort);

    g_assert_cmpint(tmp->type, ==, QTYPE_QDICT);

    g_assert_cmpint(tmp->u.udfu->integer, ==, 1);

    g_assert_cmpstr(tmp->u.udfu->string, ==, "str");

    g_assert_cmpint(tmp->u.udfu->enum1, ==, ENUM_ONE_VALUE1);

    g_assert_cmpint(tmp->u.udfu->u.value1->boolean, ==, true);

    g_assert_cmpint(tmp->u.udfu->u.value1->has_a_b, ==, false);

    qapi_free_UserDefAlternate(tmp);

    v = visitor_input_test_init(data, "false");

    visit_type_UserDefAlternate(v, NULL, &tmp, &err);

    error_free_or_abort(&err);

    qapi_free_UserDefAlternate(tmp);

    v = visitor_input_test_init(data, "{ 'alt': 42 }");

    visit_type_WrapAlternate(v, NULL, &wrap, &error_abort);

    g_assert_cmpint(wrap->alt->type, ==, QTYPE_QINT);

    g_assert_cmpint(wrap->alt->u.i, ==, 42);

    qapi_free_WrapAlternate(wrap);

    v = visitor_input_test_init(data, "{ 'alt': 'string' }");

    visit_type_WrapAlternate(v, NULL, &wrap, &error_abort);

    g_assert_cmpint(wrap->alt->type, ==, QTYPE_QSTRING);

    g_assert_cmpstr(wrap->alt->u.s, ==, "string");

    qapi_free_WrapAlternate(wrap);

    v = visitor_input_test_init(data, "{ 'alt': {'integer':1, 'string':'str', "

                                "'enum1':'value1', 'boolean':true} }");

    visit_type_WrapAlternate(v, NULL, &wrap, &error_abort);

    g_assert_cmpint(wrap->alt->type, ==, QTYPE_QDICT);

    g_assert_cmpint(wrap->alt->u.udfu->integer, ==, 1);

    g_assert_cmpstr(wrap->alt->u.udfu->string, ==, "str");

    g_assert_cmpint(wrap->alt->u.udfu->enum1, ==, ENUM_ONE_VALUE1);

    g_assert_cmpint(wrap->alt->u.udfu->u.value1->boolean, ==, true);

    g_assert_cmpint(wrap->alt->u.udfu->u.value1->has_a_b, ==, false);

    qapi_free_WrapAlternate(wrap);

}


static int hls_read_header(AVFormatContext *s)

{

    void *u = (s->flags & AVFMT_FLAG_CUSTOM_IO) ? NULL : s->pb;

    HLSContext *c = s->priv_data;

    int ret = 0, i;

    int highest_cur_seq_no = 0;

    c->ctx                = s;

    c->interrupt_callback = &s->interrupt_callback;

    c->strict_std_compliance = s->strict_std_compliance;

    c->first_packet = 1;

    c->first_timestamp = AV_NOPTS_VALUE;

    c->cur_timestamp = AV_NOPTS_VALUE;

    if (u) {

        // get the previous user agent & set back to null if string size is zero

        update_options(&c->user_agent, "user-agent", u);

        // get the previous cookies & set back to null if string size is zero

        update_options(&c->cookies, "cookies", u);

        // get the previous headers & set back to null if string size is zero

        update_options(&c->headers, "headers", u);

        // get the previous http proxt & set back to null if string size is zero

        update_options(&c->http_proxy, "http_proxy", u);

    }

    if ((ret = parse_playlist(c, s->filename, NULL, s->pb)) < 0)

        goto fail;

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

        goto fail;

    /* Some HLS servers don't like being sent the range header */

    av_dict_set(&c->avio_opts, "seekable", "0", 0);

    if (c->n_variants == 0) {

        av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");

        ret = AVERROR_EOF;

        goto fail;

    }

    /* If the playlist only contained playlists (Master Playlist),

     * parse each individual playlist. */

    if (c->n_playlists > 1 || c->playlists[0]->n_segments == 0) {

        for (i = 0; i < c->n_playlists; i++) {

            struct playlist *pls = c->playlists[i];

            if ((ret = parse_playlist(c, pls->url, pls, NULL)) < 0)

                goto fail;

        }

    }

    if (c->variants[0]->playlists[0]->n_segments == 0) {

        av_log(NULL, AV_LOG_WARNING, "Empty playlist\n");

        ret = AVERROR_EOF;

        goto fail;

    }

    /* If this isn't a live stream, calculate the total duration of the

     * stream. */

    if (c->variants[0]->playlists[0]->finished) {

        int64_t duration = 0;

        for (i = 0; i < c->variants[0]->playlists[0]->n_segments; i++)

            duration += c->variants[0]->playlists[0]->segments[i]->duration;

        s->duration = duration;

    }

    /* Associate renditions with variants */

    for (i = 0; i < c->n_variants; i++) {

        struct variant *var = c->variants[i];

        if (var->audio_group[0])

            add_renditions_to_variant(c, var, AVMEDIA_TYPE_AUDIO, var->audio_group);

        if (var->video_group[0])

            add_renditions_to_variant(c, var, AVMEDIA_TYPE_VIDEO, var->video_group);

        if (var->subtitles_group[0])

            add_renditions_to_variant(c, var, AVMEDIA_TYPE_SUBTITLE, var->subtitles_group);

    }

    /* Create a program for each variant */

    for (i = 0; i < c->n_variants; i++) {

        struct variant *v = c->variants[i];

        AVProgram *program;

        program = av_new_program(s, i);

        if (!program)

            goto fail;

        av_dict_set_int(&program->metadata, "variant_bitrate", v->bandwidth, 0);

    }

    /* Select the starting segments */

    for (i = 0; i < c->n_playlists; i++) {

        struct playlist *pls = c->playlists[i];

        if (pls->n_segments == 0)

            continue;

        pls->cur_seq_no = select_cur_seq_no(c, pls);

        highest_cur_seq_no = FFMAX(highest_cur_seq_no, pls->cur_seq_no);

    }

    /* Open the demuxer for each playlist */

    for (i = 0; i < c->n_playlists; i++) {

        struct playlist *pls = c->playlists[i];

        AVInputFormat *in_fmt = NULL;

        if (!(pls->ctx = avformat_alloc_context())) {

            ret = AVERROR(ENOMEM);

            goto fail;

        }

        if (pls->n_segments == 0)

            continue;

        pls->index  = i;

        pls->needed = 1;

        pls->parent = s;

        /*

         * If this is a live stream and this playlist looks like it is one segment

         * behind, try to sync it up so that every substream starts at the same

         * time position (so e.g. avformat_find_stream_info() will see packets from

         * all active streams within the first few seconds). This is not very generic,

         * though, as the sequence numbers are technically independent.

         */

        if (!pls->finished && pls->cur_seq_no == highest_cur_seq_no - 1 &&

            highest_cur_seq_no < pls->start_seq_no + pls->n_segments) {

            pls->cur_seq_no = highest_cur_seq_no;

        }

        pls->read_buffer = av_malloc(INITIAL_BUFFER_SIZE);

        if (!pls->read_buffer){

            ret = AVERROR(ENOMEM);

            avformat_free_context(pls->ctx);

            pls->ctx = NULL;

            goto fail;

        }

        ffio_init_context(&pls->pb, pls->read_buffer, INITIAL_BUFFER_SIZE, 0, pls,

                          read_data, NULL, NULL);

        pls->pb.seekable = 0;

        ret = av_probe_input_buffer(&pls->pb, &in_fmt, pls->segments[0]->url,

                                    NULL, 0, 0);

        if (ret < 0) {

            /* Free the ctx - it isn't initialized properly at this point,

             * so avformat_close_input shouldn't be called. If

             * avformat_open_input fails below, it frees and zeros the

             * context, so it doesn't need any special treatment like this. */

            av_log(s, AV_LOG_ERROR, "Error when loading first segment '%s'\n", pls->segments[0]->url);

            avformat_free_context(pls->ctx);

            pls->ctx = NULL;

            goto fail;

        }

        pls->ctx->pb       = &pls->pb;

        pls->ctx->io_open  = nested_io_open;

        if ((ret = ff_copy_whiteblacklists(pls->ctx, s)) < 0)

            goto fail;

        ret = avformat_open_input(&pls->ctx, pls->segments[0]->url, in_fmt, NULL);

        if (ret < 0)

            goto fail;

        if (pls->id3_deferred_extra && pls->ctx->nb_streams == 1) {

            ff_id3v2_parse_apic(pls->ctx, &pls->id3_deferred_extra);

            avformat_queue_attached_pictures(pls->ctx);

            ff_id3v2_free_extra_meta(&pls->id3_deferred_extra);

            pls->id3_deferred_extra = NULL;

        }

        pls->ctx->ctx_flags &= ~AVFMTCTX_NOHEADER;

        ret = avformat_find_stream_info(pls->ctx, NULL);

        if (ret < 0)

            goto fail;

        if (pls->is_id3_timestamped == -1)

            av_log(s, AV_LOG_WARNING, "No expected HTTP requests have been made\n");

        /* Create new AVStreams for each stream in this playlist */

        ret = update_streams_from_subdemuxer(s, pls);

        if (ret < 0)

            goto fail;

        add_metadata_from_renditions(s, pls, AVMEDIA_TYPE_AUDIO);

        add_metadata_from_renditions(s, pls, AVMEDIA_TYPE_VIDEO);

        add_metadata_from_renditions(s, pls, AVMEDIA_TYPE_SUBTITLE);

    }

    return 0;

fail:

    free_playlist_list(c);

    free_variant_list(c);

    free_rendition_list(c);

    return ret;

}


void spapr_register_hypercall(target_ulong opcode, spapr_hcall_fn fn)

{

    spapr_hcall_fn old_fn;

    assert(opcode <= MAX_HCALL_OPCODE);

    assert((opcode & 0x3) == 0);

    old_fn = hypercall_table[opcode / 4];

    assert(!old_fn || (fn == old_fn));

    hypercall_table[opcode / 4] = fn;

}


static av_cold int init_subtitles(AVFilterContext *ctx, const char *args)

{

    int ret, sid;

    AVFormatContext *fmt = NULL;

    AVCodecContext *dec_ctx = NULL;

    AVCodec *dec = NULL;

    AVStream *st;

    AVPacket pkt;

    AssContext *ass = ctx->priv;

    /* Init libass */

    ret = init(ctx, args, &subtitles_class);

    if (ret < 0)

        return ret;

    ass->track = ass_new_track(ass->library);

    if (!ass->track) {

        av_log(ctx, AV_LOG_ERROR, "Could not create a libass track\n");

        return AVERROR(EINVAL);

    }

    /* Open subtitles file */

    ret = avformat_open_input(&fmt, ass->filename, NULL, NULL);

    if (ret < 0) {

        av_log(ctx, AV_LOG_ERROR, "Unable to open %s\n", ass->filename);

        goto end;

    }

    ret = avformat_find_stream_info(fmt, NULL);

    if (ret < 0)

        goto end;

    /* Locate subtitles stream */

    ret = av_find_best_stream(fmt, AVMEDIA_TYPE_SUBTITLE, -1, -1, NULL, 0);

    if (ret < 0) {

        av_log(ctx, AV_LOG_ERROR, "Unable to locate subtitle stream in %s\n",

               ass->filename);

        goto end;

    }

    sid = ret;

    st = fmt->streams[sid];

    /* Open decoder */

    dec_ctx = st->codec;

    dec = avcodec_find_decoder(dec_ctx->codec_id);

    if (!dec) {

        av_log(ctx, AV_LOG_ERROR, "Failed to find subtitle codec %s\n",

               avcodec_get_name(dec_ctx->codec_id));

        return AVERROR(EINVAL);

    }

    ret = avcodec_open2(dec_ctx, dec, NULL);

    if (ret < 0)

        goto end;

    /* Decode subtitles and push them into the renderer (libass) */

    if (dec_ctx->subtitle_header)

        ass_process_codec_private(ass->track,

                                  dec_ctx->subtitle_header,

                                  dec_ctx->subtitle_header_size);

    av_init_packet(&pkt);

    pkt.data = NULL;

    pkt.size = 0;

    while (av_read_frame(fmt, &pkt) >= 0) {

        int i, got_subtitle;

        AVSubtitle sub;

        if (pkt.stream_index == sid) {

            ret = avcodec_decode_subtitle2(dec_ctx, &sub, &got_subtitle, &pkt);

            if (ret < 0 || !got_subtitle)

                break;

            for (i = 0; i < sub.num_rects; i++) {

                char *ass_line = sub.rects[i]->ass;

                if (!ass_line)

                    break;

                ass_process_data(ass->track, ass_line, strlen(ass_line));

            }

        }

        av_free_packet(&pkt);

        avsubtitle_free(&sub);

    }

end:

    if (fmt)

        avformat_close_input(&fmt);

    if (dec_ctx)

        avcodec_close(dec_ctx);

    return ret;

}


static void start_ahci_device(AHCIQState *ahci)

{

    /* Map AHCI's ABAR (BAR5) */

    ahci->hba_base = qpci_iomap(ahci->dev, 5, &ahci->barsize);

    /* turns on pci.cmd.iose, pci.cmd.mse and pci.cmd.bme */

    qpci_device_enable(ahci->dev);

}


static void rv30_loop_filter(RV34DecContext *r, int row)

{

    MpegEncContext *s = &r->s;

    int mb_pos, mb_x;

    int i, j, k;

    uint8_t *Y, *C;

    int loc_lim, cur_lim, left_lim = 0, top_lim = 0;

    mb_pos = row * s->mb_stride;

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

        int mbtype = s->current_picture_ptr->mb_type[mb_pos];

        if(IS_INTRA(mbtype) || IS_SEPARATE_DC(mbtype))

            r->deblock_coefs[mb_pos] = 0xFFFF;

        if(IS_INTRA(mbtype))

            r->cbp_chroma[mb_pos] = 0xFF;

    }

    /* all vertical edges are filtered first

     * and horizontal edges are filtered on the next iteration

     */

    mb_pos = row * s->mb_stride;

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

        cur_lim = rv30_loop_filt_lim[s->current_picture_ptr->qscale_table[mb_pos]];

        if(mb_x)

            left_lim = rv30_loop_filt_lim[s->current_picture_ptr->qscale_table[mb_pos - 1]];

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

            Y = s->current_picture_ptr->f.data[0] + mb_x*16 + (row*16 + j) * s->linesize + 4 * !mb_x;

            for(i = !mb_x; i < 4; i++, Y += 4){

                int ij = i + j;

                loc_lim = 0;

                if(r->deblock_coefs[mb_pos] & (1 << ij))

                    loc_lim = cur_lim;

                else if(!i && r->deblock_coefs[mb_pos - 1] & (1 << (ij + 3)))

                    loc_lim = left_lim;

                else if( i && r->deblock_coefs[mb_pos]     & (1 << (ij - 1)))

                    loc_lim = cur_lim;

                if(loc_lim)

                    rv30_weak_loop_filter(Y, 1, s->linesize, loc_lim);

            }

        }

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

            int cur_cbp, left_cbp = 0;

            cur_cbp = (r->cbp_chroma[mb_pos] >> (k*4)) & 0xF;

            if(mb_x)

                left_cbp = (r->cbp_chroma[mb_pos - 1] >> (k*4)) & 0xF;

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

                C = s->current_picture_ptr->f.data[k + 1] + mb_x*8 + (row*8 + j) * s->uvlinesize + 4 * !mb_x;

                for(i = !mb_x; i < 2; i++, C += 4){

                    int ij = i + (j >> 1);

                    loc_lim = 0;

                    if (cur_cbp & (1 << ij))

                        loc_lim = cur_lim;

                    else if(!i && left_cbp & (1 << (ij + 1)))

                        loc_lim = left_lim;

                    else if( i && cur_cbp  & (1 << (ij - 1)))

                        loc_lim = cur_lim;

                    if(loc_lim)

                        rv30_weak_loop_filter(C, 1, s->uvlinesize, loc_lim);

                }

            }

        }

    }

    mb_pos = row * s->mb_stride;

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

        cur_lim = rv30_loop_filt_lim[s->current_picture_ptr->qscale_table[mb_pos]];

        if(row)

            top_lim = rv30_loop_filt_lim[s->current_picture_ptr->qscale_table[mb_pos - s->mb_stride]];

        for(j = 4*!row; j < 16; j += 4){

            Y = s->current_picture_ptr->f.data[0] + mb_x*16 + (row*16 + j) * s->linesize;

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

                int ij = i + j;

                loc_lim = 0;

                if(r->deblock_coefs[mb_pos] & (1 << ij))

                    loc_lim = cur_lim;

                else if(!j && r->deblock_coefs[mb_pos - s->mb_stride] & (1 << (ij + 12)))

                    loc_lim = top_lim;

                else if( j && r->deblock_coefs[mb_pos]                & (1 << (ij - 4)))

                    loc_lim = cur_lim;

                if(loc_lim)

                    rv30_weak_loop_filter(Y, s->linesize, 1, loc_lim);

            }

        }

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

            int cur_cbp, top_cbp = 0;

            cur_cbp = (r->cbp_chroma[mb_pos] >> (k*4)) & 0xF;

            if(row)

                top_cbp = (r->cbp_chroma[mb_pos - s->mb_stride] >> (k*4)) & 0xF;

            for(j = 4*!row; j < 8; j += 4){

                C = s->current_picture_ptr->f.data[k+1] + mb_x*8 + (row*8 + j) * s->uvlinesize;

                for(i = 0; i < 2; i++, C += 4){

                    int ij = i + (j >> 1);

                    loc_lim = 0;

                    if (r->cbp_chroma[mb_pos] & (1 << ij))

                        loc_lim = cur_lim;

                    else if(!j && top_cbp & (1 << (ij + 2)))

                        loc_lim = top_lim;

                    else if( j && cur_cbp & (1 << (ij - 2)))

                        loc_lim = cur_lim;

                    if(loc_lim)

                        rv30_weak_loop_filter(C, s->uvlinesize, 1, loc_lim);

                }

            }

        }

    }

}


static void alac_linear_predictor(AlacEncodeContext *s, int ch)

{

    int i;

    LPCContext lpc = s->lpc[ch];

    if(lpc.lpc_order == 31) {

        s->predictor_buf[0] = s->sample_buf[ch][0];

        for(i=1; i<s->avctx->frame_size; i++)

            s->predictor_buf[i] = s->sample_buf[ch][i] - s->sample_buf[ch][i-1];

        return;

    }

    // generalised linear predictor

    if(lpc.lpc_order > 0) {

        int32_t *samples  = s->sample_buf[ch];

        int32_t *residual = s->predictor_buf;

        // generate warm-up samples

        residual[0] = samples[0];

        for(i=1;i<=lpc.lpc_order;i++)

            residual[i] = samples[i] - samples[i-1];

        // perform lpc on remaining samples

        for(i = lpc.lpc_order + 1; i < s->avctx->frame_size; i++) {

            int sum = 1 << (lpc.lpc_quant - 1), res_val, j;

            for (j = 0; j < lpc.lpc_order; j++) {

                sum += (samples[lpc.lpc_order-j] - samples[0]) *

                        lpc.lpc_coeff[j];

            }

            sum >>= lpc.lpc_quant;

            sum += samples[0];

            residual[i] = samples[lpc.lpc_order+1] - sum;

            res_val = residual[i];

            if(res_val) {

                int index = lpc.lpc_order - 1;

                int neg = (res_val < 0);

                while(index >= 0 && (neg ? (res_val < 0):(res_val > 0))) {

                    int val = samples[0] - samples[lpc.lpc_order - index];

                    int sign = (val ? FFSIGN(val) : 0);

                    if(neg)

                        sign*=-1;

                    lpc.lpc_coeff[index] -= sign;

                    val *= sign;

                    res_val -= ((val >> lpc.lpc_quant) *

                            (lpc.lpc_order - index));

                    index--;

                }

            }

            samples++;

        }

    }

}


static void decode_opc_special3(CPUMIPSState *env, DisasContext *ctx)
{
    int rs, rt, rd, sa;
    uint32_t op1, op2;
    rs = (ctx->opcode >> 21) & 0x1f;
    rt = (ctx->opcode >> 16) & 0x1f;
    rd = (ctx->opcode >> 11) & 0x1f;
    sa = (ctx->opcode >> 6) & 0x1f;
    op1 = MASK_SPECIAL3(ctx->opcode);
    case OPC_EXT:
    case OPC_INS:
        check_insn(ctx, ISA_MIPS32R2);
        gen_bitops(ctx, op1, rt, rs, sa, rd);
        break;
    case OPC_BSHFL:
        op2 = MASK_BSHFL(ctx->opcode);
        switch (op2) {
        case OPC_ALIGN ... OPC_ALIGN_END:
        case OPC_BITSWAP:
            check_insn(ctx, ISA_MIPS32R6);
            decode_opc_special3_r6(env, ctx);
            break;
        default:
            check_insn(ctx, ISA_MIPS32R2);
            gen_bshfl(ctx, op2, rt, rd);
            break;
        break;
#if defined(TARGET_MIPS64)
    case OPC_DEXTM ... OPC_DEXT:
    case OPC_DINSM ... OPC_DINS:
        check_insn(ctx, ISA_MIPS64R2);
        check_mips_64(ctx);
        gen_bitops(ctx, op1, rt, rs, sa, rd);
        break;
    case OPC_DBSHFL:
        op2 = MASK_DBSHFL(ctx->opcode);
        switch (op2) {
        case OPC_DALIGN ... OPC_DALIGN_END:
        case OPC_DBITSWAP:
            check_insn(ctx, ISA_MIPS32R6);
            decode_opc_special3_r6(env, ctx);
            break;
        default:
            check_insn(ctx, ISA_MIPS64R2);
            check_mips_64(ctx);
            op2 = MASK_DBSHFL(ctx->opcode);
            gen_bshfl(ctx, op2, rt, rd);
            break;
        break;
#endif
    case OPC_RDHWR:
        gen_rdhwr(ctx, rt, rd, extract32(ctx->opcode, 6, 3));
        break;
    case OPC_FORK:
        check_insn(ctx, ASE_MT);
        {
            TCGv t0 = tcg_temp_new();
            TCGv t1 = tcg_temp_new();
            gen_load_gpr(t0, rt);
            gen_load_gpr(t1, rs);
            gen_helper_fork(t0, t1);
            tcg_temp_free(t0);
            tcg_temp_free(t1);
        break;
    case OPC_YIELD:
        check_insn(ctx, ASE_MT);
        {
            TCGv t0 = tcg_temp_new();
            gen_load_gpr(t0, rs);
            gen_helper_yield(t0, cpu_env, t0);
            gen_store_gpr(t0, rd);
            tcg_temp_free(t0);
        break;
    default:
        if (ctx->insn_flags & ISA_MIPS32R6) {
            decode_opc_special3_r6(env, ctx);
        } else {
            decode_opc_special3_legacy(env, ctx);


static int parse_psfile(AVFilterContext *ctx, const char *fname)

{

    CurvesContext *curves = ctx->priv;

    uint8_t *buf;

    size_t size;

    int i, ret, av_unused(version), nb_curves;

    AVBPrint ptstr;

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

    av_bprint_init(&ptstr, 0, AV_BPRINT_SIZE_AUTOMATIC);

    ret = av_file_map(fname, &buf, &size, 0, NULL);

    if (ret < 0)

        return ret;

#define READ16(dst) do {                \

    if (size < 2)                       \

        return AVERROR_INVALIDDATA;     \

    dst = AV_RB16(buf);                 \

    buf  += 2;                          \

    size -= 2;                          \

} while (0)

    READ16(version);

    READ16(nb_curves);

    for (i = 0; i < FFMIN(nb_curves, FF_ARRAY_ELEMS(comp_ids)); i++) {

        int nb_points, n;

        av_bprint_clear(&ptstr);

        READ16(nb_points);

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

            int y, x;

            READ16(y);

            READ16(x);

            av_bprintf(&ptstr, "%f/%f ", x / 255., y / 255.);

        }

        if (*ptstr.str) {

            char **pts = &curves->comp_points_str[comp_ids[i]];

            if (!*pts) {

                *pts = av_strdup(ptstr.str);

                av_log(ctx, AV_LOG_DEBUG, "curves %d (intid=%d) [%d points]: [%s]\n",

                       i, comp_ids[i], nb_points, *pts);

                if (!*pts) {

                    ret = AVERROR(ENOMEM);

                    goto end;

                }

            }

        }

    }

end:

    av_bprint_finalize(&ptstr, NULL);

    av_file_unmap(buf, size);

    return ret;

}


static int svq3_decode_slice_header(AVCodecContext *avctx)

{

    SVQ3Context *svq3 = avctx->priv_data;

    H264Context *h    = &svq3->h;

    MpegEncContext *s = &h->s;

    const int mb_xy   = h->mb_xy;

    int i, header;

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

    if (((header & 0x9F) != 1 && (header & 0x9F) != 2) || (header & 0x60) == 0) {

        /* TODO: what? */

        av_log(avctx, AV_LOG_ERROR, "unsupported slice header (%02X)\n", header);

        return -1;

    } else {

        int length = header >> 5 & 3;

        svq3->next_slice_index = get_bits_count(&s->gb) +

                                 8 * show_bits(&s->gb, 8 * length) +

                                 8 * length;

        if (svq3->next_slice_index > s->gb.size_in_bits) {

            av_log(avctx, AV_LOG_ERROR, "slice after bitstream end\n");

            return -1;

        }

        s->gb.size_in_bits = svq3->next_slice_index - 8 * (length - 1);

        skip_bits(&s->gb, 8);

        if (svq3->watermark_key) {

            uint32_t header = AV_RL32(&s->gb.buffer[(get_bits_count(&s->gb) >> 3) + 1]);

            AV_WL32(&s->gb.buffer[(get_bits_count(&s->gb) >> 3) + 1],

                    header ^ svq3->watermark_key);

        }

        if (length > 0) {

            memcpy((uint8_t *) &s->gb.buffer[get_bits_count(&s->gb) >> 3],

                   &s->gb.buffer[s->gb.size_in_bits >> 3], length - 1);

        }

        skip_bits_long(&s->gb, 0);

    }

    if ((i = svq3_get_ue_golomb(&s->gb)) == INVALID_VLC || i >= 3) {

        av_log(h->s.avctx, AV_LOG_ERROR, "illegal slice type %d \n", i);

        return -1;

    }

    h->slice_type = golomb_to_pict_type[i];

    if ((header & 0x9F) == 2) {

        i              = (s->mb_num < 64) ? 6 : (1 + av_log2(s->mb_num - 1));

        s->mb_skip_run = get_bits(&s->gb, i) -

                         (s->mb_y * s->mb_width + s->mb_x);

    } else {

        skip_bits1(&s->gb);

        s->mb_skip_run = 0;

    }

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

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

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

    /* unknown fields */

    skip_bits1(&s->gb);

    if (svq3->unknown_flag)

        skip_bits1(&s->gb);

    skip_bits1(&s->gb);

    skip_bits(&s->gb, 2);

    while (get_bits1(&s->gb))

        skip_bits(&s->gb, 8);

    /* reset intra predictors and invalidate motion vector references */

    if (s->mb_x > 0) {

        memset(h->intra4x4_pred_mode + h->mb2br_xy[mb_xy - 1] + 3,

               -1, 4 * sizeof(int8_t));

        memset(h->intra4x4_pred_mode + h->mb2br_xy[mb_xy - s->mb_x],

               -1, 8 * sizeof(int8_t) * s->mb_x);

    }

    if (s->mb_y > 0) {

        memset(h->intra4x4_pred_mode + h->mb2br_xy[mb_xy - s->mb_stride],

               -1, 8 * sizeof(int8_t) * (s->mb_width - s->mb_x));

        if (s->mb_x > 0)

            h->intra4x4_pred_mode[h->mb2br_xy[mb_xy - s->mb_stride - 1] + 3] = -1;

    }

    return 0;

}


static int blk_send_response_one(struct ioreq *ioreq)

{

    struct XenBlkDev  *blkdev = ioreq->blkdev;

    int               send_notify   = 0;

    int               have_requests = 0;

    blkif_response_t  resp;

    void              *dst;

    resp.id        = ioreq->req.id;

    resp.operation = ioreq->req.operation;

    resp.status    = ioreq->status;

    /* Place on the response ring for the relevant domain. */

    switch (blkdev->protocol) {

    case BLKIF_PROTOCOL_NATIVE:

        dst = RING_GET_RESPONSE(&blkdev->rings.native, blkdev->rings.native.rsp_prod_pvt);

        break;

    case BLKIF_PROTOCOL_X86_32:

        dst = RING_GET_RESPONSE(&blkdev->rings.x86_32_part,

                                blkdev->rings.x86_32_part.rsp_prod_pvt);

        break;

    case BLKIF_PROTOCOL_X86_64:

        dst = RING_GET_RESPONSE(&blkdev->rings.x86_64_part,

                                blkdev->rings.x86_64_part.rsp_prod_pvt);

        break;

    default:

        dst = NULL;

    }

    memcpy(dst, &resp, sizeof(resp));

    blkdev->rings.common.rsp_prod_pvt++;

    RING_PUSH_RESPONSES_AND_CHECK_NOTIFY(&blkdev->rings.common, send_notify);

    if (blkdev->rings.common.rsp_prod_pvt == blkdev->rings.common.req_cons) {

        /*

         * Tail check for pending requests. Allows frontend to avoid

         * notifications if requests are already in flight (lower

         * overheads and promotes batching).

         */

        RING_FINAL_CHECK_FOR_REQUESTS(&blkdev->rings.common, have_requests);

    } else if (RING_HAS_UNCONSUMED_REQUESTS(&blkdev->rings.common)) {

        have_requests = 1;

    }

    if (have_requests) {

        blkdev->more_work++;

    }

    return send_notify;

}


void s390_ipl_prepare_cpu(S390CPU *cpu)

{

    S390IPLState *ipl = get_ipl_device();

    cpu->env.psw.addr = ipl->start_addr;

    cpu->env.psw.mask = IPL_PSW_MASK;

    if (!ipl->kernel || ipl->iplb_valid) {

        cpu->env.psw.addr = ipl->bios_start_addr;

        if (!ipl->iplb_valid) {

            ipl->iplb_valid = s390_gen_initial_iplb(ipl);

        }

    }

    if (ipl->netboot) {

        if (load_netboot_image(&err) < 0) {

            error_report_err(err);

            vm_stop(RUN_STATE_INTERNAL_ERROR);

        }

        ipl->iplb.ccw.netboot_start_addr = ipl->start_addr;

    }

}


static void rtas_ibm_os_term(PowerPCCPU *cpu,

                            sPAPRMachineState *spapr,

                            uint32_t token, uint32_t nargs,

                            target_ulong args,

                            uint32_t nret, target_ulong rets)

{

    target_ulong ret = 0;

    qapi_event_send_guest_panicked(GUEST_PANIC_ACTION_PAUSE, &error_abort);

    rtas_st(rets, 0, ret);

}


int av_probe_input_buffer(AVIOContext *pb, AVInputFormat **fmt,

                          const char *filename, void *logctx,

                          unsigned int offset, unsigned int max_probe_size)

{

    AVProbeData pd = { filename ? filename : "", NULL, -offset };

    unsigned char *buf = NULL;

    int ret = 0, probe_size;

    if (!max_probe_size) {

        max_probe_size = PROBE_BUF_MAX;

    } else if (max_probe_size > PROBE_BUF_MAX) {

        max_probe_size = PROBE_BUF_MAX;

    } else if (max_probe_size < PROBE_BUF_MIN) {

        return AVERROR(EINVAL);

    }

    if (offset >= max_probe_size) {

        return AVERROR(EINVAL);

    }

    for(probe_size= PROBE_BUF_MIN; probe_size<=max_probe_size && !*fmt;

        probe_size = FFMIN(probe_size<<1, FFMAX(max_probe_size, probe_size+1))) {

        int score = probe_size < max_probe_size ? AVPROBE_SCORE_RETRY : 0;

        int buf_offset = (probe_size == PROBE_BUF_MIN) ? 0 : probe_size>>1;

        void *buftmp;

        if (probe_size < offset) {

            continue;

        }

        /* read probe data */

        buftmp = av_realloc(buf, probe_size + AVPROBE_PADDING_SIZE);

        if(!buftmp){

            av_free(buf);

            return AVERROR(ENOMEM);

        }

        buf=buftmp;

        if ((ret = avio_read(pb, buf + buf_offset, probe_size - buf_offset)) < 0) {

            /* fail if error was not end of file, otherwise, lower score */

            if (ret != AVERROR_EOF) {

                av_free(buf);

                return ret;

            }

            score = 0;

            ret = 0;            /* error was end of file, nothing read */

        }

        pd.buf_size += ret;

        pd.buf = &buf[offset];

        memset(pd.buf + pd.buf_size, 0, AVPROBE_PADDING_SIZE);

        /* guess file format */

        *fmt = av_probe_input_format2(&pd, 1, &score);

        if(*fmt){

            if(score <= AVPROBE_SCORE_RETRY){ //this can only be true in the last iteration

                av_log(logctx, AV_LOG_WARNING, "Format %s detected only with low score of %d, misdetection possible!\n", (*fmt)->name, score);

            }else

                av_log(logctx, AV_LOG_DEBUG, "Format %s probed with size=%d and score=%d\n", (*fmt)->name, probe_size, score);

        }

    }

    if (!*fmt) {

        av_free(buf);

        return AVERROR_INVALIDDATA;

    }

    /* rewind. reuse probe buffer to avoid seeking */

    if ((ret = ffio_rewind_with_probe_data(pb, buf, pd.buf_size)) < 0)

        av_free(buf);

    return ret;

}


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_log(c->fc, AV_LOG_TRACE, "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 && !pb->eof_reached; i++) {

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

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

    }

    sc->sample_count = i;

    av_free(buf);

    if (pb->eof_reached)

        return AVERROR_EOF;

    return 0;

}


static inline void writer_print_string(WriterContext *wctx,

                                       const char *key, const char *val, int opt)

{

    const struct section *section = wctx->section[wctx->level];

    if (opt && !(wctx->writer->flags & WRITER_FLAG_DISPLAY_OPTIONAL_FIELDS))

        return;

    if (section->show_all_entries || av_dict_get(section->entries_to_show, key, NULL, 0)) {

        wctx->writer->print_string(wctx, key, val);

        wctx->nb_item[wctx->level]++;

    }

}


static int verify_expr(AVExpr *e)

{

    if (!e) return 0;

    switch (e->type) {

        case e_value:

        case e_const: return 1;

        case e_func0:

        case e_func1:

        case e_squish:

        case e_ld:

        case e_gauss:

        case e_isnan:

        case e_floor:

        case e_ceil:

        case e_trunc:

        case e_sqrt:

        case e_not:

        case e_random:

            return verify_expr(e->param[0]) && !e->param[2];

        case e_taylor:

            return verify_expr(e->param[0]) && verify_expr(e->param[1])

                   && (!e->param[2] || verify_expr(e->param[2]));

        default: return verify_expr(e->param[0]) && verify_expr(e->param[1]) && !e->param[2];

    }

}


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

                                ptrdiff_t stride)

{

    avc_luma_hz_qrt_4w_msa(src - 2, stride, dst, stride, 4, 0);

}


static int mov_read_stco(MOVContext *c, ByteIOContext *pb, MOVAtom atom)

{

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

    MOVStreamContext *sc = st->priv_data;

    unsigned int i, entries;

    get_byte(pb); /* version */

    get_be24(pb); /* flags */

    entries = get_be32(pb);

    if(entries >= UINT_MAX/sizeof(int64_t))

        return -1;

    sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));

    if (!sc->chunk_offsets)

        return AVERROR(ENOMEM);

    sc->chunk_count = entries;

    if      (atom.type == MKTAG('s','t','c','o'))

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

            sc->chunk_offsets[i] = get_be32(pb);

    else if (atom.type == MKTAG('c','o','6','4'))

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

            sc->chunk_offsets[i] = get_be64(pb);

    else

        return -1;

    return 0;

}


void ff_acelp_lspd2lpc(const double *lsp, float *lpc)

{

    double pa[6], qa[6];

    int   i;

    lsp2polyf(lsp,     pa, 5);

    lsp2polyf(lsp + 1, qa, 5);

    for (i=4; i>=0; i--)

    {

        double paf = pa[i+1] + pa[i];

        double qaf = qa[i+1] - qa[i];

        lpc[i  ] = 0.5*(paf+qaf);

        lpc[9-i] = 0.5*(paf-qaf);

    }

}


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

                                ptrdiff_t stride)

{

    avc_luma_hv_qrt_8w_msa(src + stride - 2,

                           src - (stride * 2) +

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

}


static void gen_load_store_alignment(DisasContext *dc, int shift,

        TCGv_i32 addr, bool no_hw_alignment)

{

    if (!option_enabled(dc, XTENSA_OPTION_UNALIGNED_EXCEPTION)) {

        tcg_gen_andi_i32(addr, addr, ~0 << shift);

    } else if (option_enabled(dc, XTENSA_OPTION_HW_ALIGNMENT) &&

            no_hw_alignment) {

        int label = gen_new_label();

        TCGv_i32 tmp = tcg_temp_new_i32();

        tcg_gen_andi_i32(tmp, addr, ~(~0 << shift));

        tcg_gen_brcondi_i32(TCG_COND_EQ, tmp, 0, label);

        gen_exception_cause_vaddr(dc, LOAD_STORE_ALIGNMENT_CAUSE, addr);

        gen_set_label(label);

        tcg_temp_free(tmp);

    }

}


DISAS_INSN(cas2w)

{

    uint16_t ext1, ext2;

    TCGv addr1, addr2;

    TCGv regs;

    /* cas2 Dc1:Dc2,Du1:Du2,(Rn1):(Rn2) */

    ext1 = read_im16(env, s);

    if (ext1 & 0x8000) {

        /* Address Register */

        addr1 = AREG(ext1, 12);

    } else {

        /* Data Register */

        addr1 = DREG(ext1, 12);

    }

    ext2 = read_im16(env, s);

    if (ext2 & 0x8000) {

        /* Address Register */

        addr2 = AREG(ext2, 12);

    } else {

        /* Data Register */

        addr2 = DREG(ext2, 12);

    }

    /* if (R1) == Dc1 && (R2) == Dc2 then

     *     (R1) = Du1

     *     (R2) = Du2

     * else

     *     Dc1 = (R1)

     *     Dc2 = (R2)

     */

    regs = tcg_const_i32(REG(ext2, 6) |

                         (REG(ext1, 6) << 3) |

                         (REG(ext2, 0) << 6) |

                         (REG(ext1, 0) << 9));

    gen_helper_cas2w(cpu_env, regs, addr1, addr2);

    tcg_temp_free(regs);

    /* Note that cas2w also assigned to env->cc_op.  */

    s->cc_op = CC_OP_CMPW;

    s->cc_op_synced = 1;

}


bool timerlist_run_timers(QEMUTimerList *timer_list)

{

    QEMUTimer *ts;

    int64_t current_time;

    bool progress = false;

    QEMUTimerCB *cb;

    void *opaque;

    if (!atomic_read(&timer_list->active_timers)) {

        return false;

    }

    qemu_event_reset(&timer_list->timers_done_ev);

    if (!timer_list->clock->enabled) {

        goto out;

    }

    switch (timer_list->clock->type) {

    case QEMU_CLOCK_REALTIME:

        break;

    default:

    case QEMU_CLOCK_VIRTUAL:

        if (!replay_checkpoint(CHECKPOINT_CLOCK_VIRTUAL)) {

            goto out;

        }

        break;

    case QEMU_CLOCK_HOST:

        if (!replay_checkpoint(CHECKPOINT_CLOCK_HOST)) {

            goto out;

        }

        break;

    case QEMU_CLOCK_VIRTUAL_RT:

        if (!replay_checkpoint(CHECKPOINT_CLOCK_VIRTUAL_RT)) {

            goto out;

        }

        break;

    }

    current_time = qemu_clock_get_ns(timer_list->clock->type);

    for(;;) {

        qemu_mutex_lock(&timer_list->active_timers_lock);

        ts = timer_list->active_timers;

        if (!timer_expired_ns(ts, current_time)) {

            qemu_mutex_unlock(&timer_list->active_timers_lock);

            break;

        }

        /* remove timer from the list before calling the callback */

        timer_list->active_timers = ts->next;

        ts->next = NULL;

        ts->expire_time = -1;

        cb = ts->cb;

        opaque = ts->opaque;

        qemu_mutex_unlock(&timer_list->active_timers_lock);

        /* run the callback (the timer list can be modified) */

        cb(opaque);

        progress = true;

    }

out:

    qemu_event_set(&timer_list->timers_done_ev);

    return progress;

}


static int qemu_rdma_broken_ipv6_kernel(Error **errp, struct ibv_context *verbs)

{

    struct ibv_port_attr port_attr;

    /* This bug only exists in linux, to our knowledge. */

#ifdef CONFIG_LINUX

    /*

     * Verbs are only NULL if management has bound to '[::]'.

     *

     * Let's iterate through all the devices and see if there any pure IB

     * devices (non-ethernet).

     *

     * If not, then we can safely proceed with the migration.

     * Otherwise, there are no guarantees until the bug is fixed in linux.

     */

    if (!verbs) {

	    int num_devices, x;

        struct ibv_device ** dev_list = ibv_get_device_list(&num_devices);

        bool roce_found = false;

        bool ib_found = false;

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

            verbs = ibv_open_device(dev_list[x]);

            if (ibv_query_port(verbs, 1, &port_attr)) {

                ibv_close_device(verbs);

                ERROR(errp, "Could not query initial IB port");

                return -EINVAL;

            }

            if (port_attr.link_layer == IBV_LINK_LAYER_INFINIBAND) {

                ib_found = true;

            } else if (port_attr.link_layer == IBV_LINK_LAYER_ETHERNET) {

                roce_found = true;

            }

            ibv_close_device(verbs);

        }

        if (roce_found) {

            if (ib_found) {

                fprintf(stderr, "WARN: migrations may fail:"

                                " IPv6 over RoCE / iWARP in linux"

                                " is broken. But since you appear to have a"

                                " mixed RoCE / IB environment, be sure to only"

                                " migrate over the IB fabric until the kernel "

                                " fixes the bug.\n");

            } else {

                ERROR(errp, "You only have RoCE / iWARP devices in your systems"

                            " and your management software has specified '[::]'"

                            ", but IPv6 over RoCE / iWARP is not supported in Linux.");

                return -ENONET;

            }

        }

        return 0;

    }

    /*

     * If we have a verbs context, that means that some other than '[::]' was

     * used by the management software for binding. In which case we can actually

     * warn the user about a potential broken kernel;

     */

    /* IB ports start with 1, not 0 */

    if (ibv_query_port(verbs, 1, &port_attr)) {

        ERROR(errp, "Could not query initial IB port");

        return -EINVAL;

    }

    if (port_attr.link_layer == IBV_LINK_LAYER_ETHERNET) {

        ERROR(errp, "Linux kernel's RoCE / iWARP does not support IPv6 "

                    "(but patches on linux-rdma in progress)");

        return -ENONET;

    }

#endif

    return 0;

}


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

{

    SLAVIO_INTCTLState *s = opaque;

    DPRINTF("Set cpu %d irq %d level %d\n", s->target_cpu, irq, level);

    if (irq < 32) {

	uint32_t mask = 1 << irq;

	uint32_t pil = s->intbit_to_level[irq];

	if (pil > 0) {

	    if (level) {

		s->intregm_pending |= mask;

		s->intreg_pending[s->target_cpu] |= 1 << pil;

		slavio_check_interrupts(s);

	    }

	    else {

		s->intregm_pending &= ~mask;

		s->intreg_pending[s->target_cpu] &= ~(1 << pil);

	    }

	}

    }

}


int css_register_io_adapter(CssIoAdapterType type, uint8_t isc, bool swap,

                            bool maskable, uint32_t *id)

{

    IoAdapter *adapter;

    bool found = false;

    int ret;

    S390FLICState *fs = s390_get_flic();

    S390FLICStateClass *fsc = S390_FLIC_COMMON_GET_CLASS(fs);

    *id = 0;

    QTAILQ_FOREACH(adapter, &channel_subsys.io_adapters, sibling) {

        if ((adapter->type == type) && (adapter->isc == isc)) {

            *id = adapter->id;

            found = true;

            ret = 0;

            break;

        }

        if (adapter->id >= *id) {

            *id = adapter->id + 1;

        }

    }

    if (found) {

        goto out;

    }

    adapter = g_new0(IoAdapter, 1);

    ret = fsc->register_io_adapter(fs, *id, isc, swap, maskable);

    if (ret == 0) {

        adapter->id = *id;

        adapter->isc = isc;

        adapter->type = type;

        QTAILQ_INSERT_TAIL(&channel_subsys.io_adapters, adapter, sibling);

    } else {

        g_free(adapter);

        fprintf(stderr, "Unexpected error %d when registering adapter %d\n",

                ret, *id);

    }

out:

    return ret;

}