static int qemu_rbd_open(BlockDriverState *bs, QDict *options, int flags)

{

    BDRVRBDState *s = bs->opaque;

    char pool[RBD_MAX_POOL_NAME_SIZE];

    char snap_buf[RBD_MAX_SNAP_NAME_SIZE];

    char conf[RBD_MAX_CONF_SIZE];

    char clientname_buf[RBD_MAX_CONF_SIZE];

    char *clientname;

    QemuOpts *opts;

    Error *local_err = NULL;

    const char *filename;

    int r;

    opts = qemu_opts_create_nofail(&runtime_opts);

    qemu_opts_absorb_qdict(opts, options, &local_err);

    if (error_is_set(&local_err)) {

        qerror_report_err(local_err);

        error_free(local_err);

        qemu_opts_del(opts);

        return -EINVAL;

    }

    filename = qemu_opt_get(opts, "filename");

    qemu_opts_del(opts);

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

                           snap_buf, sizeof(snap_buf),

                           s->name, sizeof(s->name),

                           conf, sizeof(conf)) < 0) {

        return -EINVAL;

    }

    clientname = qemu_rbd_parse_clientname(conf, clientname_buf);

    r = rados_create(&s->cluster, clientname);

    if (r < 0) {

        error_report("error initializing");

        return r;

    }

    s->snap = NULL;

    if (snap_buf[0] != '\0') {

        s->snap = g_strdup(snap_buf);

    }

    /*

     * Fallback to more conservative semantics if setting cache

     * options fails. Ignore errors from setting rbd_cache because the

     * only possible error is that the option does not exist, and

     * librbd defaults to no caching. If write through caching cannot

     * be set up, fall back to no caching.

     */

    if (flags & BDRV_O_NOCACHE) {

        rados_conf_set(s->cluster, "rbd_cache", "false");

    } else {

        rados_conf_set(s->cluster, "rbd_cache", "true");

    }

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

        /* try default location, but ignore failure */

        rados_conf_read_file(s->cluster, NULL);

    }

    if (conf[0] != '\0') {

        r = qemu_rbd_set_conf(s->cluster, conf);

        if (r < 0) {

            error_report("error setting config options");

            goto failed_shutdown;

        }

    }

    r = rados_connect(s->cluster);

    if (r < 0) {

        error_report("error connecting");

        goto failed_shutdown;

    }

    r = rados_ioctx_create(s->cluster, pool, &s->io_ctx);

    if (r < 0) {

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

        goto failed_shutdown;

    }

    r = rbd_open(s->io_ctx, s->name, &s->image, s->snap);

    if (r < 0) {

        error_report("error reading header from %s", s->name);

        goto failed_open;

    }

    bs->read_only = (s->snap != NULL);

    s->event_reader_pos = 0;

    r = qemu_pipe(s->fds);

    if (r < 0) {

        error_report("error opening eventfd");

        goto failed;

    }

    fcntl(s->fds[0], F_SETFL, O_NONBLOCK);

    fcntl(s->fds[1], F_SETFL, O_NONBLOCK);

    qemu_aio_set_fd_handler(s->fds[RBD_FD_READ], qemu_rbd_aio_event_reader,

                            NULL, qemu_rbd_aio_flush_cb, s);

    return 0;

failed:

    rbd_close(s->image);

failed_open:

    rados_ioctx_destroy(s->io_ctx);

failed_shutdown:

    rados_shutdown(s->cluster);

    g_free(s->snap);

    return r;

}


static void vnc_client_read(VncState *vs)

{

    ssize_t ret;

#ifdef CONFIG_VNC_SASL

    if (vs->sasl.conn && vs->sasl.runSSF)

        ret = vnc_client_read_sasl(vs);

    else

#endif /* CONFIG_VNC_SASL */

        ret = vnc_client_read_plain(vs);

    if (!ret) {

        if (vs->disconnecting) {

            vnc_disconnect_finish(vs);

        }

        return;

    }

    while (vs->read_handler && vs->input.offset >= vs->read_handler_expect) {

        size_t len = vs->read_handler_expect;

        int ret;

        ret = vs->read_handler(vs, vs->input.buffer, len);

        if (vs->disconnecting) {

            vnc_disconnect_finish(vs);

            return;

        }

        if (!ret) {

            buffer_advance(&vs->input, len);

        } else {

            vs->read_handler_expect = ret;

        }

    }

}


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

{

    int ret, size;

    int64_t left;

    AVStream *st;

    WAVDemuxContext *wav = s->priv_data;

    if (CONFIG_SPDIF_DEMUXER && wav->spdif == 0 &&

        s->streams[0]->codec->codec_tag == 1) {

        enum AVCodecID codec;

        ret = ff_spdif_probe(s->pb->buffer, s->pb->buf_end - s->pb->buffer,

                             &codec);

        if (ret > AVPROBE_SCORE_EXTENSION) {

            s->streams[0]->codec->codec_id = codec;

            wav->spdif = 1;

        } else {

            wav->spdif = -1;

        }

    }

    if (CONFIG_SPDIF_DEMUXER && wav->spdif == 1)

        return ff_spdif_read_packet(s, pkt);

    if (wav->smv_data_ofs > 0) {

        int64_t audio_dts, video_dts;

smv_retry:

        audio_dts = s->streams[0]->cur_dts;

        video_dts = s->streams[1]->cur_dts;

        if (audio_dts != AV_NOPTS_VALUE && video_dts != AV_NOPTS_VALUE) {

            audio_dts = av_rescale_q(audio_dts, s->streams[0]->time_base, AV_TIME_BASE_Q);

            video_dts = av_rescale_q(video_dts, s->streams[1]->time_base, AV_TIME_BASE_Q);

            /*We always return a video frame first to get the pixel format first*/

            wav->smv_last_stream = wav->smv_given_first ? video_dts > audio_dts : 0;

            wav->smv_given_first = 1;

        }

        wav->smv_last_stream = !wav->smv_last_stream;

        wav->smv_last_stream |= wav->audio_eof;

        wav->smv_last_stream &= !wav->smv_eof;

        if (wav->smv_last_stream) {

            uint64_t old_pos = avio_tell(s->pb);

            uint64_t new_pos = wav->smv_data_ofs +

                wav->smv_block * wav->smv_block_size;

            if (avio_seek(s->pb, new_pos, SEEK_SET) < 0) {

                ret = AVERROR_EOF;

                goto smv_out;

            }

            size = avio_rl24(s->pb);

            ret  = av_get_packet(s->pb, pkt, size);

            if (ret < 0)

                goto smv_out;

            pkt->pos -= 3;

            pkt->pts = wav->smv_block * wav->smv_frames_per_jpeg + wav->smv_cur_pt;

            wav->smv_cur_pt++;

            if (wav->smv_frames_per_jpeg > 0)

                wav->smv_cur_pt %= wav->smv_frames_per_jpeg;

            if (!wav->smv_cur_pt)

                wav->smv_block++;

            pkt->stream_index = 1;

smv_out:

            avio_seek(s->pb, old_pos, SEEK_SET);

            if (ret == AVERROR_EOF) {

                wav->smv_eof = 1;

                goto smv_retry;

            }

            return ret;

        }

    }

    st = s->streams[0];

    left = wav->data_end - avio_tell(s->pb);

    if (wav->ignore_length)

        left = INT_MAX;

    if (left <= 0) {

        if (CONFIG_W64_DEMUXER && wav->w64)

            left = find_guid(s->pb, ff_w64_guid_data) - 24;

        else

            left = find_tag(s->pb, MKTAG('d', 'a', 't', 'a'));

        if (left < 0) {

            wav->audio_eof = 1;

            if (wav->smv_data_ofs > 0 && !wav->smv_eof)

                goto smv_retry;

            return AVERROR_EOF;

        }

        wav->data_end = avio_tell(s->pb) + left;

    }

    size = MAX_SIZE;

    if (st->codec->block_align > 1) {

        if (size < st->codec->block_align)

            size = st->codec->block_align;

        size = (size / st->codec->block_align) * st->codec->block_align;

    }

    size = FFMIN(size, left);

    ret  = av_get_packet(s->pb, pkt, size);

    if (ret < 0)

        return ret;

    pkt->stream_index = 0;

    return ret;

}


static uint32_t hpet_time_after(uint64_t a, uint64_t b)

{

    return ((int32_t)(b) - (int32_t)(a) < 0);

}


static int xenfb_map_fb(struct XenFB *xenfb)

{

    struct xenfb_page *page = xenfb->c.page;

    char *protocol = xenfb->c.xendev.protocol;

    int n_fbdirs;

    xen_pfn_t *pgmfns = NULL;

    xen_pfn_t *fbmfns = NULL;

    void *map, *pd;

    int mode, ret = -1;

    /* default to native */

    pd = page->pd;

    mode = sizeof(unsigned long) * 8;

    if (!protocol) {

	/*

	 * Undefined protocol, some guesswork needed.

	 *

	 * Old frontends which don't set the protocol use

	 * one page directory only, thus pd[1] must be zero.

	 * pd[1] of the 32bit struct layout and the lower

	 * 32 bits of pd[0] of the 64bit struct layout have

	 * the same location, so we can check that ...

	 */

	uint32_t *ptr32 = NULL;

	uint32_t *ptr64 = NULL;

#if defined(__i386__)

	ptr32 = (void*)page->pd;

	ptr64 = ((void*)page->pd) + 4;

#elif defined(__x86_64__)

	ptr32 = ((void*)page->pd) - 4;

	ptr64 = (void*)page->pd;

#endif

	if (ptr32) {

	    if (ptr32[1] == 0) {

		mode = 32;

		pd   = ptr32;

	    } else {

		mode = 64;

		pd   = ptr64;

	    }

	}

#if defined(__x86_64__)

    } else if (strcmp(protocol, XEN_IO_PROTO_ABI_X86_32) == 0) {

	/* 64bit dom0, 32bit domU */

	mode = 32;

	pd   = ((void*)page->pd) - 4;

#elif defined(__i386__)

    } else if (strcmp(protocol, XEN_IO_PROTO_ABI_X86_64) == 0) {

	/* 32bit dom0, 64bit domU */

	mode = 64;

	pd   = ((void*)page->pd) + 4;

#endif

    }

    if (xenfb->pixels) {

        munmap(xenfb->pixels, xenfb->fbpages * XC_PAGE_SIZE);

        xenfb->pixels = NULL;

    }

    xenfb->fbpages = (xenfb->fb_len + (XC_PAGE_SIZE - 1)) / XC_PAGE_SIZE;

    n_fbdirs = xenfb->fbpages * mode / 8;

    n_fbdirs = (n_fbdirs + (XC_PAGE_SIZE - 1)) / XC_PAGE_SIZE;

    pgmfns = g_malloc0(sizeof(xen_pfn_t) * n_fbdirs);

    fbmfns = g_malloc0(sizeof(xen_pfn_t) * xenfb->fbpages);

    xenfb_copy_mfns(mode, n_fbdirs, pgmfns, pd);

    map = xc_map_foreign_pages(xen_xc, xenfb->c.xendev.dom,

			       PROT_READ, pgmfns, n_fbdirs);

    if (map == NULL)

	goto out;

    xenfb_copy_mfns(mode, xenfb->fbpages, fbmfns, map);

    munmap(map, n_fbdirs * XC_PAGE_SIZE);

    xenfb->pixels = xc_map_foreign_pages(xen_xc, xenfb->c.xendev.dom,

            PROT_READ, fbmfns, xenfb->fbpages);

    if (xenfb->pixels == NULL)

	goto out;

    ret = 0; /* all is fine */

out:

    g_free(pgmfns);

    g_free(fbmfns);

    return ret;

}


static int queue_picture(VideoState *is, AVFrame *src_frame, double pts)

{

    VideoPicture *vp;

    int dst_pix_fmt;

    AVPicture pict;

    static struct SwsContext *img_convert_ctx;

    /* wait until we have space to put a new picture */

    SDL_LockMutex(is->pictq_mutex);

    while (is->pictq_size >= VIDEO_PICTURE_QUEUE_SIZE &&

           !is->videoq.abort_request) {

        SDL_CondWait(is->pictq_cond, is->pictq_mutex);

    }

    SDL_UnlockMutex(is->pictq_mutex);

    if (is->videoq.abort_request)

        return -1;

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

    /* alloc or resize hardware picture buffer */

    if (!vp->bmp ||

        vp->width != is->video_st->codec->width ||

        vp->height != is->video_st->codec->height) {

        SDL_Event event;

        vp->allocated = 0;

        /* the allocation must be done in the main thread to avoid

           locking problems */

        event.type = FF_ALLOC_EVENT;

        event.user.data1 = is;

        SDL_PushEvent(&event);

        /* wait until the picture is allocated */

        SDL_LockMutex(is->pictq_mutex);

        while (!vp->allocated && !is->videoq.abort_request) {

            SDL_CondWait(is->pictq_cond, is->pictq_mutex);

        }

        SDL_UnlockMutex(is->pictq_mutex);

        if (is->videoq.abort_request)

            return -1;

    }

    /* if the frame is not skipped, then display it */

    if (vp->bmp) {

        /* get a pointer on the bitmap */

        SDL_LockYUVOverlay (vp->bmp);

        dst_pix_fmt = PIX_FMT_YUV420P;

        pict.data[0] = vp->bmp->pixels[0];

        pict.data[1] = vp->bmp->pixels[2];

        pict.data[2] = vp->bmp->pixels[1];

        pict.linesize[0] = vp->bmp->pitches[0];

        pict.linesize[1] = vp->bmp->pitches[2];

        pict.linesize[2] = vp->bmp->pitches[1];

        sws_flags = av_get_int(sws_opts, "sws_flags", NULL);

        img_convert_ctx = sws_getCachedContext(img_convert_ctx,

            is->video_st->codec->width, is->video_st->codec->height,

            is->video_st->codec->pix_fmt,

            is->video_st->codec->width, is->video_st->codec->height,

            dst_pix_fmt, sws_flags, NULL, NULL, NULL);

        if (img_convert_ctx == NULL) {

            fprintf(stderr, "Cannot initialize the conversion context\n");

            exit(1);

        }

        sws_scale(img_convert_ctx, src_frame->data, src_frame->linesize,

                  0, is->video_st->codec->height, pict.data, pict.linesize);

        /* update the bitmap content */

        SDL_UnlockYUVOverlay(vp->bmp);

        vp->pts = pts;

        /* now we can update the picture count */

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

            is->pictq_windex = 0;

        SDL_LockMutex(is->pictq_mutex);

        is->pictq_size++;

        SDL_UnlockMutex(is->pictq_mutex);

    }

    return 0;

}


static int mov_write_wave_tag(AVIOContext *pb, MOVTrack *track)

{

    int64_t pos = avio_tell(pb);

    avio_wb32(pb, 0);     /* size */

    ffio_wfourcc(pb, "wave");

    if (track->enc->codec_id != AV_CODEC_ID_QDM2) {

    avio_wb32(pb, 12);    /* size */

    ffio_wfourcc(pb, "frma");

    avio_wl32(pb, track->tag);

    }

    if (track->enc->codec_id == AV_CODEC_ID_AAC) {

        /* useless atom needed by mplayer, ipod, not needed by quicktime */

        avio_wb32(pb, 12); /* size */

        ffio_wfourcc(pb, "mp4a");

        avio_wb32(pb, 0);

        mov_write_esds_tag(pb, track);

    } else if (mov_pcm_le_gt16(track->enc->codec_id)) {

        mov_write_enda_tag(pb);

    } else if (track->enc->codec_id == AV_CODEC_ID_AMR_NB) {

        mov_write_amr_tag(pb, track);

    } else if (track->enc->codec_id == AV_CODEC_ID_AC3) {

        mov_write_ac3_tag(pb, track);

    } else if (track->enc->codec_id == AV_CODEC_ID_ALAC ||

               track->enc->codec_id == AV_CODEC_ID_QDM2) {

        mov_write_extradata_tag(pb, track);

    } else if (track->enc->codec_id == AV_CODEC_ID_ADPCM_MS ||

               track->enc->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {

        mov_write_ms_tag(pb, track);

    }

    avio_wb32(pb, 8);     /* size */

    avio_wb32(pb, 0);     /* null tag */

    return update_size(pb, pos);

}


int av_read_frame(AVFormatContext *s, AVPacket *pkt)

{

    const int genpts = s->flags & AVFMT_FLAG_GENPTS;

    int eof = 0;

    if (!genpts)

        return s->internal->packet_buffer

               ? read_from_packet_buffer(&s->internal->packet_buffer,

                                         &s->internal->packet_buffer_end, pkt)

               : read_frame_internal(s, pkt);

    for (;;) {

        int ret;

        AVPacketList *pktl = s->internal->packet_buffer;

        if (pktl) {

            AVPacket *next_pkt = &pktl->pkt;

            if (next_pkt->dts != AV_NOPTS_VALUE) {

                int wrap_bits = s->streams[next_pkt->stream_index]->pts_wrap_bits;

                while (pktl && next_pkt->pts == AV_NOPTS_VALUE) {

                    if (pktl->pkt.stream_index == next_pkt->stream_index &&

                        (av_compare_mod(next_pkt->dts, pktl->pkt.dts, 2LL << (wrap_bits - 1)) < 0) &&

                         av_compare_mod(pktl->pkt.pts, pktl->pkt.dts, 2LL << (wrap_bits - 1))) {

                        // not B-frame

                        next_pkt->pts = pktl->pkt.dts;

                    }

                    pktl = pktl->next;

                }

                pktl = s->internal->packet_buffer;

            }

            /* read packet from packet buffer, if there is data */

            if (!(next_pkt->pts == AV_NOPTS_VALUE &&

                  next_pkt->dts != AV_NOPTS_VALUE && !eof))

                return read_from_packet_buffer(&s->internal->packet_buffer,

                                               &s->internal->packet_buffer_end, pkt);

        }

        ret = read_frame_internal(s, pkt);

        if (ret < 0) {

            if (pktl && ret != AVERROR(EAGAIN)) {

                eof = 1;

                continue;

            } else

                return ret;

        }

        if (av_dup_packet(add_to_pktbuf(&s->internal->packet_buffer, pkt,

                                        &s->internal->packet_buffer_end)) < 0)

            return AVERROR(ENOMEM);

    }

}


static int coroutine_fn nfs_co_flush(BlockDriverState *bs)

{

    NFSClient *client = bs->opaque;

    NFSRPC task;

    nfs_co_init_task(client, &task);

    if (nfs_fsync_async(client->context, client->fh, nfs_co_generic_cb,

                        &task) != 0) {

        return -ENOMEM;

    }

    while (!task.complete) {

        nfs_set_events(client);

        qemu_coroutine_yield();

    }

    return task.ret;

}


static int qemu_rbd_create(const char *filename, QemuOpts *opts, Error **errp)

{

    Error *local_err = NULL;

    int64_t bytes = 0;

    int64_t objsize;

    int obj_order = 0;

    const char *pool, *name, *conf, *clientname, *keypairs;

    const char *secretid;

    rados_t cluster;

    rados_ioctx_t io_ctx;

    QDict *options = NULL;

    QemuOpts *rbd_opts = NULL;

    int ret = 0;

    secretid = qemu_opt_get(opts, "password-secret");

    /* Read out options */

    bytes = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),

                     BDRV_SECTOR_SIZE);

    objsize = qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE, 0);

    if (objsize) {

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

            error_setg(errp, "obj size needs to be power of 2");

            ret = -EINVAL;

            goto exit;

        }

        if (objsize < 4096) {

            error_setg(errp, "obj size too small");

            ret = -EINVAL;

            goto exit;

        }

        obj_order = ctz32(objsize);

    }

    options = qdict_new();

    qemu_rbd_parse_filename(filename, options, &local_err);

    if (local_err) {

        ret = -EINVAL;

        error_propagate(errp, local_err);

        goto exit;

    }

    rbd_opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);

    qemu_opts_absorb_qdict(rbd_opts, options, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        ret = -EINVAL;

        goto exit;

    }

    pool       = qemu_opt_get(rbd_opts, "pool");

    conf       = qemu_opt_get(rbd_opts, "conf");

    clientname = qemu_opt_get(rbd_opts, "user");

    name       = qemu_opt_get(rbd_opts, "image");

    keypairs   = qemu_opt_get(rbd_opts, "keyvalue-pairs");

    ret = rados_create(&cluster, clientname);

    if (ret < 0) {

        error_setg_errno(errp, -ret, "error initializing");

        goto exit;

    }

    /* try default location when conf=NULL, but ignore failure */

    ret = rados_conf_read_file(cluster, conf);

    if (conf && ret < 0) {

        error_setg_errno(errp, -ret, "error reading conf file %s", conf);

        ret = -EIO;

        goto shutdown;

    }

    ret = qemu_rbd_set_keypairs(cluster, keypairs, errp);

    if (ret < 0) {

        ret = -EIO;

        goto shutdown;

    }

    if (qemu_rbd_set_auth(cluster, secretid, errp) < 0) {

        ret = -EIO;

        goto shutdown;

    }

    ret = rados_connect(cluster);

    if (ret < 0) {

        error_setg_errno(errp, -ret, "error connecting");

        goto shutdown;

    }

    ret = rados_ioctx_create(cluster, pool, &io_ctx);

    if (ret < 0) {

        error_setg_errno(errp, -ret, "error opening pool %s", pool);

        goto shutdown;

    }

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

    if (ret < 0) {

        error_setg_errno(errp, -ret, "error rbd create");

    }

    rados_ioctx_destroy(io_ctx);

shutdown:

    rados_shutdown(cluster);

exit:

    QDECREF(options);

    qemu_opts_del(rbd_opts);

    return ret;

}


static void port92_init(ISADevice *dev, qemu_irq *a20_out)

{

    Port92State *s = PORT92(dev);

    s->a20_out = a20_out;

}


static TCGv gen_mulu_i64_i32(TCGv a, TCGv b)

{

    TCGv tmp1 = tcg_temp_new(TCG_TYPE_I64);

    TCGv tmp2 = tcg_temp_new(TCG_TYPE_I64);

    tcg_gen_extu_i32_i64(tmp1, a);

    dead_tmp(a);

    tcg_gen_extu_i32_i64(tmp2, b);

    dead_tmp(b);

    tcg_gen_mul_i64(tmp1, tmp1, tmp2);

    return tmp1;

}


static void pxa2xx_rtc_piupdate(PXA2xxRTCState *s)

{

    int64_t rt = qemu_get_clock(rt_clock);

    if (s->rtsr & (1 << 15))

        s->last_swcr += rt - s->last_pi;

    s->last_pi = rt;

}


int ioinst_handle_ssch(CPUS390XState *env, uint64_t reg1, uint32_t ipb)

{

    int cssid, ssid, schid, m;

    SubchDev *sch;

    ORB *orig_orb, orb;

    uint64_t addr;

    int ret = -ENODEV;

    int cc;

    hwaddr len = sizeof(*orig_orb);

    if (ioinst_disassemble_sch_ident(reg1, &m, &cssid, &ssid, &schid)) {

        program_interrupt(env, PGM_OPERAND, 2);

        return -EIO;

    }

    trace_ioinst_sch_id("ssch", cssid, ssid, schid);

    addr = decode_basedisp_s(env, ipb);

    if (addr & 3) {

        program_interrupt(env, PGM_SPECIFICATION, 2);

        return -EIO;

    }

    orig_orb = s390_cpu_physical_memory_map(env, addr, &len, 0);

    if (!orig_orb || len != sizeof(*orig_orb)) {

        program_interrupt(env, PGM_ADDRESSING, 2);

        cc = -EIO;

        goto out;

    }

    copy_orb_from_guest(&orb, orig_orb);

    if (!ioinst_orb_valid(&orb)) {

        program_interrupt(env, PGM_OPERAND, 2);

        cc = -EIO;

        goto out;

    }

    sch = css_find_subch(m, cssid, ssid, schid);

    if (sch && css_subch_visible(sch)) {

        ret = css_do_ssch(sch, &orb);

    }

    switch (ret) {

    case -ENODEV:

        cc = 3;

        break;

    case -EBUSY:

        cc = 2;

        break;

    case 0:

        cc = 0;

        break;

    default:

        cc = 1;

        break;

    }

out:

    s390_cpu_physical_memory_unmap(env, orig_orb, len, 0);

    return cc;

}


int ioinst_handle_tpi(S390CPU *cpu, uint32_t ipb)

{

    CPUS390XState *env = &cpu->env;

    uint64_t addr;

    int lowcore;

    IOIntCode int_code;

    hwaddr len;

    int ret;

    uint8_t ar;

    trace_ioinst("tpi");

    addr = decode_basedisp_s(env, ipb, &ar);

    if (addr & 3) {

        program_interrupt(env, PGM_SPECIFICATION, 2);

        return -EIO;

    }

    lowcore = addr ? 0 : 1;

    len = lowcore ? 8 /* two words */ : 12 /* three words */;

    ret = css_do_tpi(&int_code, lowcore);

    if (ret == 1) {

        s390_cpu_virt_mem_write(cpu, lowcore ? 184 : addr, ar, &int_code, len);

    }

    return ret;

}


static int do_quit(Monitor *mon, const QDict *qdict, QObject **ret_data)

{

    exit(0);

    return 0;

}


void helper_ctc1(CPUMIPSState *env, target_ulong arg1, uint32_t fs, uint32_t rt)

{

    switch (fs) {

    case 1:

        /* UFR Alias - Reset Status FR */

        if (!((env->active_fpu.fcr0 & (1 << FCR0_UFRP)) && (rt == 0))) {

            return;

        }

        if (env->CP0_Config5 & (1 << CP0C5_UFR)) {

            env->CP0_Status &= ~(1 << CP0St_FR);

            compute_hflags(env);

        } else {

            helper_raise_exception(env, EXCP_RI);

        }

        break;

    case 4:

        /* UNFR Alias - Set Status FR */

        if (!((env->active_fpu.fcr0 & (1 << FCR0_UFRP)) && (rt == 0))) {

            return;

        }

        if (env->CP0_Config5 & (1 << CP0C5_UFR)) {

            env->CP0_Status |= (1 << CP0St_FR);

            compute_hflags(env);

        } else {

            helper_raise_exception(env, EXCP_RI);

        }

        break;

    case 25:

        if (arg1 & 0xffffff00)

            return;

        env->active_fpu.fcr31 = (env->active_fpu.fcr31 & 0x017fffff) | ((arg1 & 0xfe) << 24) |

                     ((arg1 & 0x1) << 23);

        break;

    case 26:

        if (arg1 & 0x007c0000)

            return;

        env->active_fpu.fcr31 = (env->active_fpu.fcr31 & 0xfffc0f83) | (arg1 & 0x0003f07c);

        break;

    case 28:

        if (arg1 & 0x007c0000)

            return;

        env->active_fpu.fcr31 = (env->active_fpu.fcr31 & 0xfefff07c) | (arg1 & 0x00000f83) |

                     ((arg1 & 0x4) << 22);

        break;

    case 31:

        if (arg1 & 0x007c0000)

            return;

        env->active_fpu.fcr31 = arg1;

        break;

    default:

        return;

    }

    /* set rounding mode */

    restore_rounding_mode(env);

    /* set flush-to-zero mode */

    restore_flush_mode(env);

    set_float_exception_flags(0, &env->active_fpu.fp_status);

    if ((GET_FP_ENABLE(env->active_fpu.fcr31) | 0x20) & GET_FP_CAUSE(env->active_fpu.fcr31))

        do_raise_exception(env, EXCP_FPE, GETPC());

}


static void predictor_decode_stereo(APEContext *ctx, int count)

{

    APEPredictor *p = &ctx->predictor;

    int32_t *decoded0 = ctx->decoded[0];

    int32_t *decoded1 = ctx->decoded[1];

    while (count--) {

        /* Predictor Y */

        *decoded0 = predictor_update_filter(p, *decoded0, 0, YDELAYA, YDELAYB,

                                            YADAPTCOEFFSA, YADAPTCOEFFSB);

        decoded0++;

        *decoded1 = predictor_update_filter(p, *decoded1, 1, XDELAYA, XDELAYB,

                                            XADAPTCOEFFSA, XADAPTCOEFFSB);

        decoded1++;

        /* Combined */

        p->buf++;

        /* Have we filled the history buffer? */

        if (p->buf == p->historybuffer + HISTORY_SIZE) {

            memmove(p->historybuffer, p->buf,

                    PREDICTOR_SIZE * sizeof(*p->historybuffer));

            p->buf = p->historybuffer;

        }

    }

}


static bool rtas_event_log_contains(uint32_t event_mask, bool exception)

{

    sPAPRMachineState *spapr = SPAPR_MACHINE(qdev_get_machine());

    sPAPREventLogEntry *entry = NULL;

    /* we only queue EPOW events atm. */

    if ((event_mask & EVENT_MASK_EPOW) == 0) {

        return false;

    }

    QTAILQ_FOREACH(entry, &spapr->pending_events, next) {

        if (entry->exception != exception) {

            continue;

        }

        /* EPOW and hotplug events are surfaced in the same manner */

        if (entry->log_type == RTAS_LOG_TYPE_EPOW ||

            entry->log_type == RTAS_LOG_TYPE_HOTPLUG) {

            return true;

        }

    }

    return false;

}


void helper_ldq_raw(uint64_t t0, uint64_t t1)

{

    ldq_raw(t1, t0);

}


void qemu_bh_update_timeout(int *timeout)

{

    QEMUBH *bh;

    for (bh = async_context->first_bh; bh; bh = bh->next) {

        if (!bh->deleted && bh->scheduled) {

            if (bh->idle) {

                /* idle bottom halves will be polled at least

                 * every 10ms */

                *timeout = MIN(10, *timeout);

            } else {

                /* non-idle bottom halves will be executed

                 * immediately */

                *timeout = 0;

                break;

            }

        }

    }

}


i2c_bus *piix4_pm_init(PCIBus *bus, int devfn, uint32_t smb_io_base,

                       qemu_irq sci_irq, qemu_irq cmos_s3, qemu_irq smi_irq,

                       int kvm_enabled)

{

    PCIDevice *dev;

    PIIX4PMState *s;

    dev = pci_create(bus, devfn, "PIIX4_PM");

    qdev_prop_set_uint32(&dev->qdev, "smb_io_base", smb_io_base);

    s = DO_UPCAST(PIIX4PMState, dev, dev);

    s->irq = sci_irq;

    acpi_pm1_cnt_init(&s->ar, cmos_s3);

    s->smi_irq = smi_irq;

    s->kvm_enabled = kvm_enabled;

    qdev_init_nofail(&dev->qdev);

    return s->smb.smbus;

}


static int get_phys_addr_v6(CPUARMState *env, uint32_t address, int access_type,

                            ARMMMUIdx mmu_idx, hwaddr *phys_ptr,

                            int *prot, target_ulong *page_size)

{

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

    int code;

    uint32_t table;

    uint32_t desc;

    uint32_t xn;

    uint32_t pxn = 0;

    int type;

    int ap;

    int domain = 0;

    int domain_prot;

    hwaddr phys_addr;

    uint32_t dacr;

    /* Pagetable walk.  */

    /* Lookup l1 descriptor.  */

    if (!get_level1_table_address(env, mmu_idx, &table, address)) {

        /* Section translation fault if page walk is disabled by PD0 or PD1 */

        code = 5;

        goto do_fault;

    }

    desc = ldl_phys(cs->as, table);

    type = (desc & 3);

    if (type == 0 || (type == 3 && !arm_feature(env, ARM_FEATURE_PXN))) {

        /* Section translation fault, or attempt to use the encoding

         * which is Reserved on implementations without PXN.

         */

        code = 5;

        goto do_fault;

    }

    if ((type == 1) || !(desc & (1 << 18))) {

        /* Page or Section.  */

        domain = (desc >> 5) & 0x0f;

    }

    if (regime_el(env, mmu_idx) == 1) {

        dacr = env->cp15.dacr_ns;

    } else {

        dacr = env->cp15.dacr_s;

    }

    domain_prot = (dacr >> (domain * 2)) & 3;

    if (domain_prot == 0 || domain_prot == 2) {

        if (type != 1) {

            code = 9; /* Section domain fault.  */

        } else {

            code = 11; /* Page domain fault.  */

        }

        goto do_fault;

    }

    if (type != 1) {

        if (desc & (1 << 18)) {

            /* Supersection.  */

            phys_addr = (desc & 0xff000000) | (address & 0x00ffffff);

            *page_size = 0x1000000;

        } else {

            /* Section.  */

            phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);

            *page_size = 0x100000;

        }

        ap = ((desc >> 10) & 3) | ((desc >> 13) & 4);

        xn = desc & (1 << 4);

        pxn = desc & 1;

        code = 13;

    } else {

        if (arm_feature(env, ARM_FEATURE_PXN)) {

            pxn = (desc >> 2) & 1;

        }

        /* Lookup l2 entry.  */

        table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);

        desc = ldl_phys(cs->as, table);

        ap = ((desc >> 4) & 3) | ((desc >> 7) & 4);

        switch (desc & 3) {

        case 0: /* Page translation fault.  */

            code = 7;

            goto do_fault;

        case 1: /* 64k page.  */

            phys_addr = (desc & 0xffff0000) | (address & 0xffff);

            xn = desc & (1 << 15);

            *page_size = 0x10000;

            break;

        case 2: case 3: /* 4k page.  */

            phys_addr = (desc & 0xfffff000) | (address & 0xfff);

            xn = desc & 1;

            *page_size = 0x1000;

            break;

        default:

            /* Never happens, but compiler isn't smart enough to tell.  */

            abort();

        }

        code = 15;

    }

    if (domain_prot == 3) {

        *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;

    } else {

        if (pxn && !regime_is_user(env, mmu_idx)) {

            xn = 1;

        }

        if (xn && access_type == 2)

            goto do_fault;

        /* The simplified model uses AP[0] as an access control bit.  */

        if ((regime_sctlr(env, mmu_idx) & SCTLR_AFE)

                && (ap & 1) == 0) {

            /* Access flag fault.  */

            code = (code == 15) ? 6 : 3;

            goto do_fault;

        }

        *prot = check_ap(env, mmu_idx, ap, domain_prot, access_type);

        if (!*prot) {

            /* Access permission fault.  */

            goto do_fault;

        }

        if (!xn) {

            *prot |= PAGE_EXEC;

        }

    }

    *phys_ptr = phys_addr;

    return 0;

do_fault:

    return code | (domain << 4);

}


static int vpc_create(const char *filename, QemuOpts *opts, Error **errp)

{

    uint8_t buf[1024];

    VHDFooter *footer = (VHDFooter *) buf;

    char *disk_type_param;

    int fd, i;

    uint16_t cyls = 0;

    uint8_t heads = 0;

    uint8_t secs_per_cyl = 0;

    int64_t total_sectors;

    int64_t total_size;

    int disk_type;

    int ret = -EIO;

    bool nocow = false;

    /* Read out options */

    total_size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);

    disk_type_param = qemu_opt_get_del(opts, BLOCK_OPT_SUBFMT);

    if (disk_type_param) {

        if (!strcmp(disk_type_param, "dynamic")) {

            disk_type = VHD_DYNAMIC;

        } else if (!strcmp(disk_type_param, "fixed")) {

            disk_type = VHD_FIXED;

        } else {

            ret = -EINVAL;

            goto out;

        }

    } else {

        disk_type = VHD_DYNAMIC;

    }

    nocow = qemu_opt_get_bool_del(opts, BLOCK_OPT_NOCOW, false);

    /* Create the file */

    fd = qemu_open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0644);

    if (fd < 0) {

        ret = -EIO;

        goto out;

    }

    if (nocow) {

#ifdef __linux__

        /* Set NOCOW flag to solve performance issue on fs like btrfs.

         * This is an optimisation. The FS_IOC_SETFLAGS ioctl return value will

         * be ignored since any failure of this operation should not block the

         * left work.

         */

        int attr;

        if (ioctl(fd, FS_IOC_GETFLAGS, &attr) == 0) {

            attr |= FS_NOCOW_FL;

            ioctl(fd, FS_IOC_SETFLAGS, &attr);

        }

#endif

    }

    /*

     * Calculate matching total_size and geometry. Increase the number of

     * sectors requested until we get enough (or fail). This ensures that

     * qemu-img convert doesn't truncate images, but rather rounds up.

     */

    total_sectors = total_size / BDRV_SECTOR_SIZE;

    for (i = 0; total_sectors > (int64_t)cyls * heads * secs_per_cyl; i++) {

        if (calculate_geometry(total_sectors + i, &cyls, &heads,

                               &secs_per_cyl))

        {

            ret = -EFBIG;

            goto fail;

        }

    }

    total_sectors = (int64_t) cyls * heads * secs_per_cyl;

    /* Prepare the Hard Disk Footer */

    memset(buf, 0, 1024);

    memcpy(footer->creator, "conectix", 8);

    /* TODO Check if "qemu" creator_app is ok for VPC */

    memcpy(footer->creator_app, "qemu", 4);

    memcpy(footer->creator_os, "Wi2k", 4);

    footer->features = be32_to_cpu(0x02);

    footer->version = be32_to_cpu(0x00010000);

    if (disk_type == VHD_DYNAMIC) {

        footer->data_offset = be64_to_cpu(HEADER_SIZE);

    } else {

        footer->data_offset = be64_to_cpu(0xFFFFFFFFFFFFFFFFULL);

    }

    footer->timestamp = be32_to_cpu(time(NULL) - VHD_TIMESTAMP_BASE);

    /* Version of Virtual PC 2007 */

    footer->major = be16_to_cpu(0x0005);

    footer->minor = be16_to_cpu(0x0003);

    if (disk_type == VHD_DYNAMIC) {

        footer->orig_size = be64_to_cpu(total_sectors * 512);

        footer->size = be64_to_cpu(total_sectors * 512);

    } else {

        footer->orig_size = be64_to_cpu(total_size);

        footer->size = be64_to_cpu(total_size);

    }

    footer->cyls = be16_to_cpu(cyls);

    footer->heads = heads;

    footer->secs_per_cyl = secs_per_cyl;

    footer->type = be32_to_cpu(disk_type);

#if defined(CONFIG_UUID)

    uuid_generate(footer->uuid);

#endif

    footer->checksum = be32_to_cpu(vpc_checksum(buf, HEADER_SIZE));

    if (disk_type == VHD_DYNAMIC) {

        ret = create_dynamic_disk(fd, buf, total_sectors);

    } else {

        ret = create_fixed_disk(fd, buf, total_size);

    }

fail:

    qemu_close(fd);

out:

    g_free(disk_type_param);

    return ret;

}


static int rate_get_samples (struct audio_pcm_info *info, SpiceRateCtl *rate)

{

    int64_t now;

    int64_t ticks;

    int64_t bytes;

    int64_t samples;

    now = qemu_get_clock (vm_clock);

    ticks = now - rate->start_ticks;

    bytes = muldiv64 (ticks, info->bytes_per_second, get_ticks_per_sec ());

    samples = (bytes - rate->bytes_sent) >> info->shift;

    if (samples < 0 || samples > 65536) {

        fprintf (stderr, "Resetting rate control (%" PRId64 " samples)\n", samples);

        rate_start (rate);

        samples = 0;

    }

    rate->bytes_sent += samples << info->shift;

    return samples;

}


static void test_visitor_out_native_list_uint8(TestOutputVisitorData *data,

                                               const void *unused)

{

    test_native_list(data, unused, USER_DEF_NATIVE_LIST_UNION_KIND_U8);

}


static int alsa_run_out (HWVoiceOut *hw)

{

    ALSAVoiceOut *alsa = (ALSAVoiceOut *) hw;

    int rpos, live, decr;

    int samples;

    uint8_t *dst;

    st_sample_t *src;

    snd_pcm_sframes_t avail;

    live = audio_pcm_hw_get_live_out (hw);

    if (!live) {

        return 0;

    }

    avail = alsa_get_avail (alsa->handle);

    if (avail < 0) {

        dolog ("Could not get number of available playback frames\n");

        return 0;

    }

    decr = audio_MIN (live, avail);

    samples = decr;

    rpos = hw->rpos;

    while (samples) {

        int left_till_end_samples = hw->samples - rpos;

        int len = audio_MIN (samples, left_till_end_samples);

        snd_pcm_sframes_t written;

        src = hw->mix_buf + rpos;

        dst = advance (alsa->pcm_buf, rpos << hw->info.shift);

        hw->clip (dst, src, len);

        while (len) {

            written = snd_pcm_writei (alsa->handle, dst, len);

            if (written <= 0) {

                switch (written) {

                case 0:

                    if (conf.verbose) {

                        dolog ("Failed to write %d frames (wrote zero)\n", len);

                    }

                    goto exit;

                case -EPIPE:

                    if (alsa_recover (alsa->handle)) {

                        alsa_logerr (written, "Failed to write %d frames\n",

                                     len);

                        goto exit;

                    }

                    if (conf.verbose) {

                        dolog ("Recovering from playback xrun\n");

                    }

                    continue;

                case -EAGAIN:

                    goto exit;

                default:

                    alsa_logerr (written, "Failed to write %d frames to %p\n",

                                 len, dst);

                    goto exit;

                }

            }

            rpos = (rpos + written) % hw->samples;

            samples -= written;

            len -= written;

            dst = advance (dst, written << hw->info.shift);

            src += written;

        }

    }

 exit:

    hw->rpos = rpos;

    return decr;

}


static int local_symlink(FsContext *ctx, const char *oldpath,

                            const char *newpath)

{

    return symlink(oldpath, rpath(ctx, newpath));

}


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

                           target_siginfo_t *info,

			   target_sigset_t *set, CPUX86State *env)

{

        abi_ulong frame_addr, addr;

	struct rt_sigframe *frame;

	int i, err = 0;

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

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

		goto give_sigsegv;

    __put_user(current_exec_domain_sig(sig), &frame->sig);

        addr = frame_addr + offsetof(struct rt_sigframe, info);

    __put_user(addr, &frame->pinfo);

        addr = frame_addr + offsetof(struct rt_sigframe, uc);

    __put_user(addr, &frame->puc);

	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(get_sp_from_cpustate(env)),

               &frame->uc.tuc_stack.ss_flags);

    __put_user(target_sigaltstack_used.ss_size,

               &frame->uc.tuc_stack.ss_size);

    setup_sigcontext(&frame->uc.tuc_mcontext, &frame->fpstate, env,

            set->sig[0], frame_addr + offsetof(struct rt_sigframe, fpstate));

        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.  If provided, use a stub

	   already in userspace.  */

	if (ka->sa_flags & TARGET_SA_RESTORER) {

        __put_user(ka->sa_restorer, &frame->pretcode);

	} else {

                uint16_t val16;

                addr = frame_addr + offsetof(struct rt_sigframe, retcode);

        __put_user(addr, &frame->pretcode);

		/* This is movl $,%eax ; int $0x80 */

        __put_user(0xb8, (char *)(frame->retcode+0));

        __put_user(TARGET_NR_rt_sigreturn, (int *)(frame->retcode+1));

                val16 = 0x80cd;

        __put_user(val16, (uint16_t *)(frame->retcode+5));

	}

	if (err)

		goto give_sigsegv;

	/* Set up registers for signal handler */

	env->regs[R_ESP] = frame_addr;

	env->eip = ka->_sa_handler;

        cpu_x86_load_seg(env, R_DS, __USER_DS);

        cpu_x86_load_seg(env, R_ES, __USER_DS);

        cpu_x86_load_seg(env, R_SS, __USER_DS);

        cpu_x86_load_seg(env, R_CS, __USER_CS);

	env->eflags &= ~TF_MASK;

	unlock_user_struct(frame, frame_addr, 1);

	return;

give_sigsegv:

	unlock_user_struct(frame, frame_addr, 1);

	if (sig == TARGET_SIGSEGV)

		ka->_sa_handler = TARGET_SIG_DFL;

	force_sig(TARGET_SIGSEGV /* , current */);

}


static void search_for_pns(AACEncContext *s, AVCodecContext *avctx, SingleChannelElement *sce)

{

    FFPsyBand *band;

    int w, g, w2, i;

    float *PNS = &s->scoefs[0*128], *PNS34 = &s->scoefs[1*128];

    float *NOR34 = &s->scoefs[3*128];

    const float lambda = s->lambda;

    const float freq_mult = avctx->sample_rate/(1024.0f/sce->ics.num_windows)/2.0f;

    const float thr_mult = NOISE_LAMBDA_REPLACE*(100.0f/lambda);

    const float spread_threshold = NOISE_SPREAD_THRESHOLD*(lambda/100.f);

    if (sce->ics.window_sequence[0] == EIGHT_SHORT_SEQUENCE)

        return;

    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {

        for (g = 0;  g < sce->ics.num_swb; g++) {

            int noise_sfi;

            float dist1 = 0.0f, dist2 = 0.0f, noise_amp;

            float pns_energy = 0.0f, energy_ratio, dist_thresh;

            float sfb_energy = 0.0f, threshold = 0.0f, spread = 0.0f;

            const int start = sce->ics.swb_offset[w*16+g];

            const float freq = start*freq_mult;

            const float freq_boost = FFMAX(0.88f*freq/NOISE_LOW_LIMIT, 1.0f);

            if (freq < NOISE_LOW_LIMIT || avctx->cutoff && freq >= avctx->cutoff)

                continue;

            for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {

                band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g];

                sfb_energy += band->energy;

                spread     += band->spread;

                threshold  += band->threshold;

            }

            /* Ramps down at ~8000Hz and loosens the dist threshold */

            dist_thresh = FFMIN(2.5f*NOISE_LOW_LIMIT/freq, 1.27f);

            if (sce->zeroes[w*16+g] || spread < spread_threshold ||

                sfb_energy > threshold*thr_mult*freq_boost) {

                sce->pns_ener[w*16+g] = sfb_energy;

                continue;

            }

            noise_sfi = av_clip(roundf(log2f(sfb_energy)*2), -100, 155); /* Quantize */

            noise_amp = -ff_aac_pow2sf_tab[noise_sfi + POW_SF2_ZERO];    /* Dequantize */

            for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {

                float band_energy, scale;

                const int start_c = sce->ics.swb_offset[(w+w2)*16+g];

                band = &s->psy.ch[s->cur_channel].psy_bands[(w+w2)*16+g];

                for (i = 0; i < sce->ics.swb_sizes[g]; i++)

                    PNS[i] = s->random_state = lcg_random(s->random_state);

                band_energy = s->fdsp->scalarproduct_float(PNS, PNS, sce->ics.swb_sizes[g]);

                scale = noise_amp/sqrtf(band_energy);

                s->fdsp->vector_fmul_scalar(PNS, PNS, scale, sce->ics.swb_sizes[g]);

                pns_energy += s->fdsp->scalarproduct_float(PNS, PNS, sce->ics.swb_sizes[g]);

                abs_pow34_v(NOR34, &sce->coeffs[start_c], sce->ics.swb_sizes[g]);

                abs_pow34_v(PNS34, PNS, sce->ics.swb_sizes[g]);

                dist1 += quantize_band_cost(s, &sce->coeffs[start_c],

                                            NOR34,

                                            sce->ics.swb_sizes[g],

                                            sce->sf_idx[(w+w2)*16+g],

                                            sce->band_alt[(w+w2)*16+g],

                                            lambda/band->threshold, INFINITY, NULL, 0);

                dist2 += quantize_band_cost(s, PNS,

                                            PNS34,

                                            sce->ics.swb_sizes[g],

                                            noise_sfi,

                                            NOISE_BT,

                                            lambda/band->threshold, INFINITY, NULL, 0);

            }

            energy_ratio = sfb_energy/pns_energy; /* Compensates for quantization error */

            sce->pns_ener[w*16+g] = energy_ratio*sfb_energy;

            if (energy_ratio > 0.85f && energy_ratio < 1.25f && dist1/dist2 > dist_thresh) {

                sce->band_type[w*16+g] = NOISE_BT;

                sce->zeroes[w*16+g] = 0;

                if (sce->band_type[w*16+g-1] != NOISE_BT && /* Prevent holes */

                    sce->band_type[w*16+g-2] == NOISE_BT) {

                    sce->band_type[w*16+g-1] = NOISE_BT;

                    sce->zeroes[w*16+g-1] = 0;

                }

            }

        }

    }

}


static inline void dv_decode_video_segment(DVVideoContext *s,

                                           const uint8_t *buf_ptr1,

                                           const uint16_t *mb_pos_ptr)

{

    int quant, dc, dct_mode, class1, j;

    int mb_index, mb_x, mb_y, v, last_index;

    int y_stride, i;

    DCTELEM *block, *block1;

    int c_offset;

    uint8_t *y_ptr;

    const uint8_t *buf_ptr;

    PutBitContext pb, vs_pb;

    GetBitContext gb;

    BlockInfo mb_data[5 * DV_MAX_BPM], *mb, *mb1;

    DECLARE_ALIGNED_16(DCTELEM, sblock[5*DV_MAX_BPM][64]);

    DECLARE_ALIGNED_8(uint8_t, mb_bit_buffer[80 + 4]); /* allow some slack */

    DECLARE_ALIGNED_8(uint8_t, vs_bit_buffer[5 * 80 + 4]); /* allow some slack */

    const int log2_blocksize= 3-s->avctx->lowres;

    int is_field_mode[5];

    assert((((int)mb_bit_buffer)&7)==0);

    assert((((int)vs_bit_buffer)&7)==0);

    memset(sblock, 0, sizeof(sblock));

    /* pass 1 : read DC and AC coefficients in blocks */

    buf_ptr = buf_ptr1;

    block1 = &sblock[0][0];

    mb1 = mb_data;

    init_put_bits(&vs_pb, vs_bit_buffer, 5 * 80);

    for(mb_index = 0; mb_index < 5; mb_index++, mb1 += s->sys->bpm, block1 += s->sys->bpm * 64) {

        /* skip header */

        quant = buf_ptr[3] & 0x0f;

        buf_ptr += 4;

        init_put_bits(&pb, mb_bit_buffer, 80);

        mb = mb1;

        block = block1;

        is_field_mode[mb_index] = 0;

        for(j = 0;j < s->sys->bpm; j++) {

            last_index = s->sys->block_sizes[j];

            init_get_bits(&gb, buf_ptr, last_index);

            /* get the dc */

            dc = get_sbits(&gb, 9);

            dct_mode = get_bits1(&gb);

            class1 = get_bits(&gb, 2);

            if (DV_PROFILE_IS_HD(s->sys)) {

                mb->idct_put = s->idct_put[0];

                mb->scan_table = s->dv_zigzag[0];

                mb->factor_table = s->dv100_idct_factor[((s->sys->height == 720)<<1)&(j < 4)][class1][quant];

                is_field_mode[mb_index] |= !j && dct_mode;

            } else {

                mb->idct_put = s->idct_put[dct_mode && log2_blocksize==3];

                mb->scan_table = s->dv_zigzag[dct_mode];

                mb->factor_table = s->dv_idct_factor[class1 == 3][dct_mode]

                    [quant + dv_quant_offset[class1]];

            }

            dc = dc << 2;

            /* convert to unsigned because 128 is not added in the

               standard IDCT */

            dc += 1024;

            block[0] = dc;

            buf_ptr += last_index >> 3;

            mb->pos = 0;

            mb->partial_bit_count = 0;

#ifdef VLC_DEBUG

            printf("MB block: %d, %d ", mb_index, j);

#endif

            dv_decode_ac(&gb, mb, block);

            /* write the remaining bits  in a new buffer only if the

               block is finished */

            if (mb->pos >= 64)

                bit_copy(&pb, &gb);

            block += 64;

            mb++;

        }

        /* pass 2 : we can do it just after */

#ifdef VLC_DEBUG

        printf("***pass 2 size=%d MB#=%d\n", put_bits_count(&pb), mb_index);

#endif

        block = block1;

        mb = mb1;

        init_get_bits(&gb, mb_bit_buffer, put_bits_count(&pb));

        flush_put_bits(&pb);

        for(j = 0;j < s->sys->bpm; j++, block += 64, mb++) {

            if (mb->pos < 64 && get_bits_left(&gb) > 0) {

                dv_decode_ac(&gb, mb, block);

                /* if still not finished, no need to parse other blocks */

                if (mb->pos < 64)

                    break;

            }

        }

        /* all blocks are finished, so the extra bytes can be used at

           the video segment level */

        if (j >= s->sys->bpm)

            bit_copy(&vs_pb, &gb);

    }

    /* we need a pass other the whole video segment */

#ifdef VLC_DEBUG

    printf("***pass 3 size=%d\n", put_bits_count(&vs_pb));

#endif

    block = &sblock[0][0];

    mb = mb_data;

    init_get_bits(&gb, vs_bit_buffer, put_bits_count(&vs_pb));

    flush_put_bits(&vs_pb);

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

        for(j = 0;j < s->sys->bpm; j++) {

            if (mb->pos < 64) {

#ifdef VLC_DEBUG

                printf("start %d:%d\n", mb_index, j);

#endif

                dv_decode_ac(&gb, mb, block);

            }

            if (mb->pos >= 64 && mb->pos < 127)

                av_log(NULL, AV_LOG_ERROR, "AC EOB marker is absent pos=%d\n", mb->pos);

            block += 64;

            mb++;

        }

    }

    /* compute idct and place blocks */

    block = &sblock[0][0];

    mb = mb_data;

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

        v = *mb_pos_ptr++;

        mb_x = v & 0xff;

        mb_y = v >> 8;

        /* We work with 720p frames split in half. The odd half-frame (chan==2,3) is displaced :-( */

        if (s->sys->height == 720 && !(s->buf[1]&0x0C)) {

               mb_y -= (mb_y>17)?18:-72; /* shifting the Y coordinate down by 72/2 macroblocks */

        }

        /* idct_put'ting luminance */

        if ((s->sys->pix_fmt == PIX_FMT_YUV420P) ||

            (s->sys->pix_fmt == PIX_FMT_YUV411P && mb_x >= (704 / 8)) ||

            (s->sys->height >= 720 && mb_y != 134)) {

            y_stride = (s->picture.linesize[0]<<((!is_field_mode[mb_index])*log2_blocksize)) - (2<<log2_blocksize);

        } else {

            y_stride = 0;

        }

        y_ptr = s->picture.data[0] + ((mb_y * s->picture.linesize[0] + mb_x)<<log2_blocksize);

        for(j = 0; j < 2; j++, y_ptr += y_stride) {

            for (i=0; i<2; i++, block += 64, mb++, y_ptr += (1<<log2_blocksize))

                 if (s->sys->pix_fmt == PIX_FMT_YUV422P && s->sys->width == 720 && i)

                     y_ptr -= (1<<log2_blocksize);

                 else

                     mb->idct_put(y_ptr, s->picture.linesize[0]<<is_field_mode[mb_index], block);

        }

        /* idct_put'ting chrominance */

        c_offset = (((mb_y>>(s->sys->pix_fmt == PIX_FMT_YUV420P)) * s->picture.linesize[1] +

                     (mb_x>>((s->sys->pix_fmt == PIX_FMT_YUV411P)?2:1)))<<log2_blocksize);

        for(j=2; j; j--) {

            uint8_t *c_ptr = s->picture.data[j] + c_offset;

            if (s->sys->pix_fmt == PIX_FMT_YUV411P && mb_x >= (704 / 8)) {

                  uint64_t aligned_pixels[64/8];

                  uint8_t *pixels = (uint8_t*)aligned_pixels;

                  uint8_t *c_ptr1, *ptr1;

                  int x, y;

                  mb->idct_put(pixels, 8, block);

                  for(y = 0; y < (1<<log2_blocksize); y++, c_ptr += s->picture.linesize[j], pixels += 8) {

                      ptr1= pixels + (1<<(log2_blocksize-1));

                      c_ptr1 = c_ptr + (s->picture.linesize[j]<<log2_blocksize);

                      for(x=0; x < (1<<(log2_blocksize-1)); x++) {

                          c_ptr[x]= pixels[x];

                          c_ptr1[x]= ptr1[x];

                      }

                  }

                  block += 64; mb++;

            } else {

                  y_stride = (mb_y == 134) ? (1<<log2_blocksize) :

                                             s->picture.linesize[j]<<((!is_field_mode[mb_index])*log2_blocksize);

                  for (i=0; i<(1<<(s->sys->bpm==8)); i++, block += 64, mb++, c_ptr += y_stride)

                       mb->idct_put(c_ptr, s->picture.linesize[j]<<is_field_mode[mb_index], block);

            }

        }

    }

}


static void set_sensor_evt_enable(IPMIBmcSim *ibs,

                                  uint8_t *cmd, unsigned int cmd_len,

                                  uint8_t *rsp, unsigned int *rsp_len,

                                  unsigned int max_rsp_len)

{

    IPMISensor *sens;

    IPMI_CHECK_CMD_LEN(4);

    if ((cmd[2] > MAX_SENSORS) ||

            !IPMI_SENSOR_GET_PRESENT(ibs->sensors + cmd[2])) {

        rsp[2] = IPMI_CC_REQ_ENTRY_NOT_PRESENT;

        return;

    }

    sens = ibs->sensors + cmd[2];

    switch ((cmd[3] >> 4) & 0x3) {

    case 0: /* Do not change */

        break;

    case 1: /* Enable bits */

        if (cmd_len > 4) {

            sens->assert_enable |= cmd[4];

        }

        if (cmd_len > 5) {

            sens->assert_enable |= cmd[5] << 8;

        }

        if (cmd_len > 6) {

            sens->deassert_enable |= cmd[6];

        }

        if (cmd_len > 7) {

            sens->deassert_enable |= cmd[7] << 8;

        }

        break;

    case 2: /* Disable bits */

        if (cmd_len > 4) {

            sens->assert_enable &= ~cmd[4];

        }

        if (cmd_len > 5) {

            sens->assert_enable &= ~(cmd[5] << 8);

        }

        if (cmd_len > 6) {

            sens->deassert_enable &= ~cmd[6];

        }

        if (cmd_len > 7) {

            sens->deassert_enable &= ~(cmd[7] << 8);

        }

        break;

    case 3:

        rsp[2] = IPMI_CC_INVALID_DATA_FIELD;

        return;

    }

    IPMI_SENSOR_SET_RET_STATUS(sens, cmd[3]);

}


static inline void *host_from_stream_offset(QEMUFile *f,

                                            ram_addr_t offset,

                                            int flags)

{

    static RAMBlock *block = NULL;

    char id[256];

    uint8_t len;

    if (flags & RAM_SAVE_FLAG_CONTINUE) {

        if (!block) {

            error_report("Ack, bad migration stream!");

            return NULL;

        }

        return memory_region_get_ram_ptr(block->mr) + offset;

    }

    len = qemu_get_byte(f);

    qemu_get_buffer(f, (uint8_t *)id, len);

    id[len] = 0;

    QTAILQ_FOREACH(block, &ram_list.blocks, next) {

        if (!strncmp(id, block->idstr, sizeof(id)))

            return memory_region_get_ram_ptr(block->mr) + offset;

    }

    error_report("Can't find block %s!", id);

    return NULL;

}


static int decode_hq_slice_row(AVCodecContext *avctx, void *arg, int jobnr, int threadnr)

{

    int i;

    DiracContext *s = avctx->priv_data;

    DiracSlice *slices = ((DiracSlice *)arg) + s->num_x*jobnr;

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

        decode_hq_slice(avctx, &slices[i]);

    return 0;

}


static void qemu_fill_buffer(QEMUFile *f)

{

    int len;

    int pending;

    assert(!qemu_file_is_writable(f));

    pending = f->buf_size - f->buf_index;

    if (pending > 0) {

        memmove(f->buf, f->buf + f->buf_index, pending);

    }

    f->buf_index = 0;

    f->buf_size = pending;

    len = f->ops->get_buffer(f->opaque, f->buf + pending, f->pos,

                        IO_BUF_SIZE - pending);

    if (len > 0) {

        f->buf_size += len;

        f->pos += len;

    } else if (len == 0) {

        qemu_file_set_error(f, -EIO);

    } else if (len != -EAGAIN) {

        qemu_file_set_error(f, len);

    }

}


static int xen_pt_initfn(PCIDevice *d)

{

    XenPCIPassthroughState *s = XEN_PT_DEVICE(d);

    int rc = 0;

    uint8_t machine_irq = 0, scratch;

    uint16_t cmd = 0;

    int pirq = XEN_PT_UNASSIGNED_PIRQ;

    /* register real device */

    XEN_PT_LOG(d, "Assigning real physical device %02x:%02x.%d"

               " to devfn %#x\n",

               s->hostaddr.bus, s->hostaddr.slot, s->hostaddr.function,

               s->dev.devfn);

    rc = xen_host_pci_device_get(&s->real_device,

                                 s->hostaddr.domain, s->hostaddr.bus,

                                 s->hostaddr.slot, s->hostaddr.function);

    if (rc) {

        XEN_PT_ERR(d, "Failed to \"open\" the real pci device. rc: %i\n", rc);

        return -1;

    }

    s->is_virtfn = s->real_device.is_virtfn;

    if (s->is_virtfn) {

        XEN_PT_LOG(d, "%04x:%02x:%02x.%d is a SR-IOV Virtual Function\n",

                   s->real_device.domain, s->real_device.bus,

                   s->real_device.dev, s->real_device.func);

    }

    /* Initialize virtualized PCI configuration (Extended 256 Bytes) */

    if (xen_host_pci_get_block(&s->real_device, 0, d->config,

                               PCI_CONFIG_SPACE_SIZE) < 0) {

        xen_host_pci_device_put(&s->real_device);

        return -1;

    }

    s->memory_listener = xen_pt_memory_listener;

    s->io_listener = xen_pt_io_listener;

    /* Setup VGA bios for passthrough GFX */

    if ((s->real_device.domain == 0) && (s->real_device.bus == 0) &&

        (s->real_device.dev == 2) && (s->real_device.func == 0)) {

        if (!is_igd_vga_passthrough(&s->real_device)) {

            XEN_PT_ERR(d, "Need to enable igd-passthru if you're trying"

                       " to passthrough IGD GFX.\n");

            xen_host_pci_device_put(&s->real_device);

            return -1;

        }

        if (xen_pt_setup_vga(s, &s->real_device) < 0) {

            XEN_PT_ERR(d, "Setup VGA BIOS of passthrough GFX failed!\n");

            xen_host_pci_device_put(&s->real_device);

            return -1;

        }

        /* Register ISA bridge for passthrough GFX. */

        xen_igd_passthrough_isa_bridge_create(s, &s->real_device);

    }

    /* Handle real device's MMIO/PIO BARs */

    xen_pt_register_regions(s, &cmd);

    /* reinitialize each config register to be emulated */

    if (xen_pt_config_init(s)) {

        XEN_PT_ERR(d, "PCI Config space initialisation failed.\n");

        xen_host_pci_device_put(&s->real_device);

        return -1;

    }

    /* Bind interrupt */

    rc = xen_host_pci_get_byte(&s->real_device, PCI_INTERRUPT_PIN, &scratch);

    if (rc) {

        XEN_PT_ERR(d, "Failed to read PCI_INTERRUPT_PIN! (rc:%d)\n", rc);

        scratch = 0;

    }

    if (!scratch) {

        XEN_PT_LOG(d, "no pin interrupt\n");

        goto out;

    }

    machine_irq = s->real_device.irq;

    rc = xc_physdev_map_pirq(xen_xc, xen_domid, machine_irq, &pirq);

    if (rc < 0) {

        XEN_PT_ERR(d, "Mapping machine irq %u to pirq %i failed, (err: %d)\n",

                   machine_irq, pirq, errno);

        /* Disable PCI intx assertion (turn on bit10 of devctl) */

        cmd |= PCI_COMMAND_INTX_DISABLE;

        machine_irq = 0;

        s->machine_irq = 0;

    } else {

        machine_irq = pirq;

        s->machine_irq = pirq;

        xen_pt_mapped_machine_irq[machine_irq]++;

    }

    /* bind machine_irq to device */

    if (machine_irq != 0) {

        uint8_t e_intx = xen_pt_pci_intx(s);

        rc = xc_domain_bind_pt_pci_irq(xen_xc, xen_domid, machine_irq,

                                       pci_bus_num(d->bus),

                                       PCI_SLOT(d->devfn),

                                       e_intx);

        if (rc < 0) {

            XEN_PT_ERR(d, "Binding of interrupt %i failed! (err: %d)\n",

                       e_intx, errno);

            /* Disable PCI intx assertion (turn on bit10 of devctl) */

            cmd |= PCI_COMMAND_INTX_DISABLE;

            xen_pt_mapped_machine_irq[machine_irq]--;

            if (xen_pt_mapped_machine_irq[machine_irq] == 0) {

                if (xc_physdev_unmap_pirq(xen_xc, xen_domid, machine_irq)) {

                    XEN_PT_ERR(d, "Unmapping of machine interrupt %i failed!"

                               " (err: %d)\n", machine_irq, errno);

                }

            }

            s->machine_irq = 0;

        }

    }

out:

    if (cmd) {

        uint16_t val;

        rc = xen_host_pci_get_word(&s->real_device, PCI_COMMAND, &val);

        if (rc) {

            XEN_PT_ERR(d, "Failed to read PCI_COMMAND! (rc: %d)\n", rc);

        } else {

            val |= cmd;

            rc = xen_host_pci_set_word(&s->real_device, PCI_COMMAND, val);

            if (rc) {

                XEN_PT_ERR(d, "Failed to write PCI_COMMAND val=0x%x!(rc: %d)\n",

                           val, rc);

            }

        }

    }

    memory_listener_register(&s->memory_listener, &s->dev.bus_master_as);

    memory_listener_register(&s->io_listener, &address_space_io);

    s->listener_set = true;

    XEN_PT_LOG(d,

               "Real physical device %02x:%02x.%d registered successfully!\n",

               s->hostaddr.bus, s->hostaddr.slot, s->hostaddr.function);

    return 0;

}


static inline void RENAME(rgb24tobgr15)(const uint8_t *src, uint8_t *dst, long src_size)

{

	const uint8_t *s = src;

	const uint8_t *end;

#ifdef HAVE_MMX

	const uint8_t *mm_end;

#endif

	uint16_t *d = (uint16_t *)dst;

	end = s + src_size;

#ifdef HAVE_MMX

	__asm __volatile(PREFETCH"	%0"::"m"(*src):"memory");

	__asm __volatile(

	    "movq	%0, %%mm7\n\t"

	    "movq	%1, %%mm6\n\t"

	    ::"m"(red_15mask),"m"(green_15mask));

	mm_end = end - 15;

	while(s < mm_end)

	{

	    __asm __volatile(

		PREFETCH" 32%1\n\t"

		"movd	%1, %%mm0\n\t"

		"movd	3%1, %%mm3\n\t"

		"punpckldq 6%1, %%mm0\n\t"

		"punpckldq 9%1, %%mm3\n\t"

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

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

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

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

		"psllq	$7, %%mm0\n\t"

		"psllq	$7, %%mm3\n\t"

		"pand	%%mm7, %%mm0\n\t"

		"pand	%%mm7, %%mm3\n\t"

		"psrlq	$6, %%mm1\n\t"

		"psrlq	$6, %%mm4\n\t"

		"pand	%%mm6, %%mm1\n\t"

		"pand	%%mm6, %%mm4\n\t"

		"psrlq	$19, %%mm2\n\t"

		"psrlq	$19, %%mm5\n\t"

		"pand	%2, %%mm2\n\t"

		"pand	%2, %%mm5\n\t"

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

		"por	%%mm4, %%mm3\n\t"

		"por	%%mm2, %%mm0\n\t"

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

		"psllq	$16, %%mm3\n\t"

		"por	%%mm3, %%mm0\n\t"

		MOVNTQ"	%%mm0, %0\n\t"

		:"=m"(*d):"m"(*s),"m"(blue_15mask):"memory");

		d += 4;

		s += 12;

	}

	__asm __volatile(SFENCE:::"memory");

	__asm __volatile(EMMS:::"memory");

#endif

	while(s < end)

	{

		const int r= *s++;

		const int g= *s++;

		const int b= *s++;

		*d++ = (b>>3) | ((g&0xF8)<<2) | ((r&0xF8)<<7);

	}

}


int avformat_seek_file(AVFormatContext *s, int stream_index, int64_t min_ts, int64_t ts, int64_t max_ts, int flags)

{

    if(min_ts > ts || max_ts < ts)

        return -1;

    ff_read_frame_flush(s);

    if (s->iformat->read_seek2)

        return s->iformat->read_seek2(s, stream_index, min_ts, ts, max_ts, flags);

    if(s->iformat->read_timestamp){

        //try to seek via read_timestamp()

    }

    //Fallback to old API if new is not implemented but old is

    //Note the old has somewat different sematics

    if(s->iformat->read_seek || 1)

        return av_seek_frame(s, stream_index, ts, flags | (ts - min_ts > (uint64_t)(max_ts - ts) ? AVSEEK_FLAG_BACKWARD : 0));

    // try some generic seek like seek_frame_generic() but with new ts semantics

}


static int mov_read_stsz(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, sample_size, field_size, num_bytes;

    GetBitContext gb;

    unsigned char* buf;

    get_byte(pb); /* version */

    get_be24(pb); /* flags */

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

        sample_size = get_be32(pb);

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

            sc->sample_size = sample_size;

        field_size = 32;

    } else {

        sample_size = 0;

        get_be24(pb); /* reserved */

        field_size = get_byte(pb);

    }

    entries = get_be32(pb);

    dprintf(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 -1;

    }

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

        return -1;

    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 (get_buffer(pb, buf, num_bytes) < num_bytes) {

        av_freep(&sc->sample_sizes);

        av_free(buf);

        return -1;

    }

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

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

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

    av_free(buf);

    return 0;

}


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

{

    AVFrame *decoded_frame, *f;

    AVCodecContext *avctx = ist->dec_ctx;

    int i, ret, err = 0, resample_changed;

    AVRational decoded_frame_tb;

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

        return AVERROR(ENOMEM);

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

        return AVERROR(ENOMEM);

    decoded_frame = ist->decoded_frame;

    update_benchmark(NULL);

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

    update_benchmark("decode_audio %d.%d", ist->file_index, ist->st->index);

    if (ret >= 0 && avctx->sample_rate <= 0) {

        av_log(avctx, AV_LOG_ERROR, "Sample rate %d invalid\n", avctx->sample_rate);

        ret = AVERROR_INVALIDDATA;

    }

    if (*got_output || ret<0)

        decode_error_stat[ret<0] ++;

    if (ret < 0 && exit_on_error)

        exit_program(1);

    if (!*got_output || ret < 0)

        return ret;

    ist->samples_decoded += decoded_frame->nb_samples;

    ist->frames_decoded++;

#if 1

    /* increment next_dts to use for the case where the input stream does not

       have timestamps or there are multiple frames in the packet */

    ist->next_pts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /

                     avctx->sample_rate;

    ist->next_dts += ((int64_t)AV_TIME_BASE * decoded_frame->nb_samples) /

                     avctx->sample_rate;

#endif

    resample_changed = ist->resample_sample_fmt     != decoded_frame->format         ||

                       ist->resample_channels       != avctx->channels               ||

                       ist->resample_channel_layout != decoded_frame->channel_layout ||

                       ist->resample_sample_rate    != decoded_frame->sample_rate;

    if (resample_changed) {

        char layout1[64], layout2[64];

        if (!guess_input_channel_layout(ist)) {

            av_log(NULL, AV_LOG_FATAL, "Unable to find default channel "

                   "layout for Input Stream #%d.%d\n", ist->file_index,

                   ist->st->index);

            exit_program(1);

        }

        decoded_frame->channel_layout = avctx->channel_layout;

        av_get_channel_layout_string(layout1, sizeof(layout1), ist->resample_channels,

                                     ist->resample_channel_layout);

        av_get_channel_layout_string(layout2, sizeof(layout2), avctx->channels,

                                     decoded_frame->channel_layout);

        av_log(NULL, AV_LOG_INFO,

               "Input stream #%d:%d frame changed from rate:%d fmt:%s ch:%d chl:%s to rate:%d fmt:%s ch:%d chl:%s\n",

               ist->file_index, ist->st->index,

               ist->resample_sample_rate,  av_get_sample_fmt_name(ist->resample_sample_fmt),

               ist->resample_channels, layout1,

               decoded_frame->sample_rate, av_get_sample_fmt_name(decoded_frame->format),

               avctx->channels, layout2);

        ist->resample_sample_fmt     = decoded_frame->format;

        ist->resample_sample_rate    = decoded_frame->sample_rate;

        ist->resample_channel_layout = decoded_frame->channel_layout;

        ist->resample_channels       = avctx->channels;

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

            if (ist_in_filtergraph(filtergraphs[i], ist)) {

                FilterGraph *fg = filtergraphs[i];

                if (configure_filtergraph(fg) < 0) {

                    av_log(NULL, AV_LOG_FATAL, "Error reinitializing filters!\n");

                    exit_program(1);

                }

            }

    }

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

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

    if (decoded_frame->pts != AV_NOPTS_VALUE) {

        ist->dts = ist->next_dts = ist->pts = ist->next_pts = av_rescale_q(decoded_frame->pts, avctx->time_base, AV_TIME_BASE_Q);

        decoded_frame_tb   = avctx->time_base;

    } else if (decoded_frame->pkt_pts != AV_NOPTS_VALUE) {

        decoded_frame->pts = decoded_frame->pkt_pts;

        decoded_frame_tb   = ist->st->time_base;

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

        decoded_frame->pts = pkt->pts;

        decoded_frame_tb   = ist->st->time_base;

    }else {

        decoded_frame->pts = ist->dts;

        decoded_frame_tb   = AV_TIME_BASE_Q;

    }

    pkt->pts           = AV_NOPTS_VALUE;

    if (decoded_frame->pts != AV_NOPTS_VALUE)

        decoded_frame->pts = av_rescale_delta(decoded_frame_tb, decoded_frame->pts,

                                              (AVRational){1, avctx->sample_rate}, decoded_frame->nb_samples, &ist->filter_in_rescale_delta_last,

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

    ist->nb_samples = decoded_frame->nb_samples;

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

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

            f = ist->filter_frame;

            err = av_frame_ref(f, decoded_frame);

            if (err < 0)

                break;

        } else

            f = decoded_frame;

        err = av_buffersrc_add_frame_flags(ist->filters[i]->filter, f,

                                     AV_BUFFERSRC_FLAG_PUSH);

        if (err == AVERROR_EOF)

            err = 0; /* ignore */

        if (err < 0)

            break;

    }

    decoded_frame->pts = AV_NOPTS_VALUE;

    av_frame_unref(ist->filter_frame);

    av_frame_unref(decoded_frame);

    return err < 0 ? err : ret;

}


static void quantize(SnowContext *s, SubBand *b, DWTELEM *src, int stride, int bias){

    const int level= b->level;

    const int w= b->width;

    const int h= b->height;

    const int qlog= clip(s->qlog + b->qlog, 0, 128);

    const int qmul= qexp[qlog&7]<<(qlog>>3);

    int x,y;

    assert(QROOT==8);

    bias= bias ? 0 : (3*qmul)>>3;

    if(!bias){

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

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

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

                //FIXME use threshold

                //FIXME optimize

                //FIXME bias

                if(i>=0){

                    i<<= QEXPSHIFT;

                    i/= qmul;

                    src[x + y*stride]=  i;

                }else{

                    i= -i;

                    i<<= QEXPSHIFT;

                    i/= qmul;

                    src[x + y*stride]= -i;

                }

            }

        }

    }else{

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

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

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

                //FIXME use threshold

                //FIXME optimize

                //FIXME bias

                if(i>=0){

                    i<<= QEXPSHIFT;

                    i= (i + bias) / qmul;

                    src[x + y*stride]=  i;

                }else{

                    i= -i;

                    i<<= QEXPSHIFT;

                    i= (i + bias) / qmul;

                    src[x + y*stride]= -i;

                }

            }

        }

    }

}


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

{

    VirtIOPCIProxy *proxy = VIRTIO_PCI(d);

    VirtioBusState *bus = &proxy->bus;

    bool legacy = virtio_pci_legacy(proxy);

    bool modern;

    bool modern_pio = proxy->flags & VIRTIO_PCI_FLAG_MODERN_PIO_NOTIFY;

    uint8_t *config;

    uint32_t size;

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

    /*

     * Virtio capabilities present without

     * VIRTIO_F_VERSION_1 confuses guests

     */

    if (!proxy->ignore_backend_features &&

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

        virtio_pci_disable_modern(proxy);

        if (!legacy) {

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

                             " mode is disabled");

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

            return;

        }

    }

    modern = virtio_pci_modern(proxy);

    config = proxy->pci_dev.config;

    if (proxy->class_code) {

        pci_config_set_class(config, proxy->class_code);

    }

    if (legacy) {

        if (virtio_host_has_feature(vdev, VIRTIO_F_IOMMU_PLATFORM)) {

            error_setg(errp, "VIRTIO_F_IOMMU_PLATFORM was supported by"

                       "neither legacy nor transitional device.");

            return ;

        }

        /* legacy and transitional */

        pci_set_word(config + PCI_SUBSYSTEM_VENDOR_ID,

                     pci_get_word(config + PCI_VENDOR_ID));

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

    } else {

        /* pure virtio-1.0 */

        pci_set_word(config + PCI_VENDOR_ID,

                     PCI_VENDOR_ID_REDHAT_QUMRANET);

        pci_set_word(config + PCI_DEVICE_ID,

                     0x1040 + virtio_bus_get_vdev_id(bus));

        pci_config_set_revision(config, 1);

    }

    config[PCI_INTERRUPT_PIN] = 1;

    if (modern) {

        struct virtio_pci_cap cap = {

            .cap_len = sizeof cap,

        };

        struct virtio_pci_notify_cap notify = {

            .cap.cap_len = sizeof notify,

            .notify_off_multiplier =

                cpu_to_le32(virtio_pci_queue_mem_mult(proxy)),

        };

        struct virtio_pci_cfg_cap cfg = {

            .cap.cap_len = sizeof cfg,

            .cap.cfg_type = VIRTIO_PCI_CAP_PCI_CFG,

        };

        struct virtio_pci_notify_cap notify_pio = {

            .cap.cap_len = sizeof notify,

            .notify_off_multiplier = cpu_to_le32(0x0),

        };

        struct virtio_pci_cfg_cap *cfg_mask;

        virtio_pci_modern_regions_init(proxy);

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

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

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

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

        if (modern_pio) {

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

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

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

                             PCI_BASE_ADDRESS_SPACE_IO, &proxy->io_bar);

            virtio_pci_modern_io_region_map(proxy, &proxy->notify_pio,

                                            &notify_pio.cap);

        }

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

                         PCI_BASE_ADDRESS_SPACE_MEMORY |

                         PCI_BASE_ADDRESS_MEM_PREFETCH |

                         PCI_BASE_ADDRESS_MEM_TYPE_64,

                         &proxy->modern_bar);

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

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

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

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

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

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

    }

    if (proxy->nvectors) {

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

                                          proxy->msix_bar_idx);

        if (err) {

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

            if (err != -ENOTSUP) {

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

                             proxy->nvectors);

            }

            proxy->nvectors = 0;

        }

    }

    proxy->pci_dev.config_write = virtio_write_config;

    proxy->pci_dev.config_read = virtio_read_config;

    if (legacy) {

        size = VIRTIO_PCI_REGION_SIZE(&proxy->pci_dev)

            + virtio_bus_get_vdev_config_len(bus);

        size = pow2ceil(size);

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

                              &virtio_pci_config_ops,

                              proxy, "virtio-pci", size);

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

                         PCI_BASE_ADDRESS_SPACE_IO, &proxy->bar);

    }

}


static void update_cursor_data_virgl(VirtIOGPU *g,

                                     struct virtio_gpu_scanout *s,

                                     uint32_t resource_id)

{

    uint32_t width, height;

    uint32_t pixels, *data;

    data = virgl_renderer_get_cursor_data(resource_id, &width, &height);

    if (!data) {

        return;

    }

    if (width != s->current_cursor->width ||

        height != s->current_cursor->height) {

        return;

    }

    pixels = s->current_cursor->width * s->current_cursor->height;

    memcpy(s->current_cursor->data, data, pixels * sizeof(uint32_t));

}


static void gen_addc(DisasContext *dc, TCGv dest, TCGv srca, TCGv srcb)

{

    TCGv t0 = tcg_const_tl(0);

    TCGv res = tcg_temp_new();

    TCGv sr_cy = tcg_temp_new();

    TCGv sr_ov = tcg_temp_new();

    tcg_gen_shri_tl(sr_cy, cpu_sr, ctz32(SR_CY));

    tcg_gen_andi_tl(sr_cy, sr_cy, 1);

    tcg_gen_add2_tl(res, sr_cy, srca, t0, sr_cy, t0);

    tcg_gen_add2_tl(res, sr_cy, res, sr_cy, srcb, t0);

    tcg_gen_xor_tl(sr_ov, srca, srcb);

    tcg_gen_xor_tl(t0, res, srcb);

    tcg_gen_andc_tl(sr_ov, t0, sr_ov);

    tcg_temp_free(t0);

    tcg_gen_mov_tl(dest, res);

    tcg_temp_free(res);

    tcg_gen_shri_tl(sr_ov, sr_ov, TARGET_LONG_BITS - 1);

    tcg_gen_deposit_tl(cpu_sr, cpu_sr, sr_cy, ctz32(SR_CY), 1);

    tcg_gen_deposit_tl(cpu_sr, cpu_sr, sr_ov, ctz32(SR_OV), 1);

    gen_ove_cyov(dc, sr_ov, sr_cy);

    tcg_temp_free(sr_ov);

    tcg_temp_free(sr_cy);

}


static int tls_open(URLContext *h, const char *uri, int flags, AVDictionary **options)

{

    TLSContext *c = h->priv_data;

    TLSShared *s = &c->tls_shared;

    int ret;

    if ((ret = ff_tls_open_underlying(s, h, uri, options)) < 0)

        goto fail;

    c->ssl_context = SSLCreateContext(NULL, s->listen ? kSSLServerSide : kSSLClientSide, kSSLStreamType);

    if (!c->ssl_context) {

        av_log(h, AV_LOG_ERROR, "Unable to create SSL context\n");

        ret = AVERROR(ENOMEM);

        goto fail;

    }

    if (s->ca_file) {

        if ((ret = load_ca(h)) < 0)

            goto fail;

        CHECK_ERROR(SSLSetSessionOption, c->ssl_context, kSSLSessionOptionBreakOnServerAuth, true);

    }

    if (s->cert_file)

        if ((ret = load_cert(h)) < 0)

            goto fail;

    if (s->verify)

        CHECK_ERROR(SSLSetPeerDomainName, c->ssl_context, s->host, strlen(s->host));

    CHECK_ERROR(SSLSetIOFuncs, c->ssl_context, tls_read_cb, tls_write_cb);

    CHECK_ERROR(SSLSetConnection, c->ssl_context, h);

    while (1) {

        OSStatus status = SSLHandshake(c->ssl_context);

        if (status == errSSLServerAuthCompleted) {

            SecTrustRef peerTrust;

            SecTrustResultType trustResult;

            if (!s->verify)

                continue;

            if (SSLCopyPeerTrust(c->ssl_context, &peerTrust) != noErr) {

                ret = AVERROR(ENOMEM);

                goto fail;

            }

            if (SecTrustSetAnchorCertificates(peerTrust, c->ca_array) != noErr) {

                ret = AVERROR_UNKNOWN;

                goto fail;

            }

            if (SecTrustEvaluate(peerTrust, &trustResult) != noErr) {

                ret = AVERROR_UNKNOWN;

                goto fail;

            }

            if (trustResult == kSecTrustResultProceed ||

                trustResult == kSecTrustResultUnspecified) {

                // certificate is trusted

                status = errSSLWouldBlock; // so we call SSLHandshake again

            } else if (trustResult == kSecTrustResultRecoverableTrustFailure) {

                // not trusted, for some reason other than being expired

                status = errSSLXCertChainInvalid;

            } else {

                // cannot use this certificate (fatal)

                status = errSSLBadCert;

            }

            if (peerTrust)

                CFRelease(peerTrust);

        }

        if (status == noErr)

            break;

        av_log(h, AV_LOG_ERROR, "Unable to negotiate TLS/SSL session: %i\n", (int)status);

        ret = AVERROR(EIO);

        goto fail;

    }

    return 0;

fail:

    tls_close(h);

    return ret;

}


abi_long do_brk(abi_ulong new_brk)

{

    abi_ulong brk_page;

    abi_long mapped_addr;

    int	new_alloc_size;

    if (!new_brk)

        return target_brk;

    if (new_brk < target_original_brk)

        return target_brk;

    brk_page = HOST_PAGE_ALIGN(target_brk);

    /* If the new brk is less than this, set it and we're done... */

    if (new_brk < brk_page) {

	target_brk = new_brk;

    	return target_brk;

    }

    /* We need to allocate more memory after the brk... Note that

     * we don't use MAP_FIXED because that will map over the top of

     * any existing mapping (like the one with the host libc or qemu

     * itself); instead we treat "mapped but at wrong address" as

     * a failure and unmap again.

     */

    new_alloc_size = HOST_PAGE_ALIGN(new_brk - brk_page + 1);

    mapped_addr = get_errno(target_mmap(brk_page, new_alloc_size,

                                        PROT_READ|PROT_WRITE,

                                        MAP_ANON|MAP_PRIVATE, 0, 0));

    if (mapped_addr == brk_page) {

        target_brk = new_brk;

        return target_brk;

    } else if (mapped_addr != -1) {

        /* Mapped but at wrong address, meaning there wasn't actually

         * enough space for this brk.

         */

        target_munmap(mapped_addr, new_alloc_size);

        mapped_addr = -1;

    }

#if defined(TARGET_ALPHA)

    /* We (partially) emulate OSF/1 on Alpha, which requires we

       return a proper errno, not an unchanged brk value.  */

    return -TARGET_ENOMEM;

#endif

    /* For everything else, return the previous break. */

    return target_brk;

}


static int mkv_write_tracks(AVFormatContext *s)

{

    MatroskaMuxContext *mkv = s->priv_data;

    AVIOContext *pb = s->pb;

    ebml_master tracks;

    int i, j, ret;

    ret = mkv_add_seekhead_entry(mkv->main_seekhead, MATROSKA_ID_TRACKS, avio_tell(pb));

    if (ret < 0) return ret;

    tracks = start_ebml_master(pb, MATROSKA_ID_TRACKS, 0);

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

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

        AVCodecContext *codec = st->codec;

        ebml_master subinfo, track;

        int native_id = 0;

        int qt_id = 0;

        int bit_depth = av_get_bits_per_sample(codec->codec_id);

        int sample_rate = codec->sample_rate;

        int output_sample_rate = 0;

        AVDictionaryEntry *tag;

        if (codec->codec_type == AVMEDIA_TYPE_ATTACHMENT) {

            mkv->have_attachments = 1;

            continue;

        }

        if (!bit_depth)

            bit_depth = av_get_bytes_per_sample(codec->sample_fmt) << 3;

        if (codec->codec_id == AV_CODEC_ID_AAC)

            get_aac_sample_rates(s, codec, &sample_rate, &output_sample_rate);

        track = start_ebml_master(pb, MATROSKA_ID_TRACKENTRY, 0);

        put_ebml_uint (pb, MATROSKA_ID_TRACKNUMBER     , i + 1);

        put_ebml_uint (pb, MATROSKA_ID_TRACKUID        , i + 1);

        put_ebml_uint (pb, MATROSKA_ID_TRACKFLAGLACING , 0);    // no lacing (yet)

        if ((tag = av_dict_get(st->metadata, "title", NULL, 0)))

            put_ebml_string(pb, MATROSKA_ID_TRACKNAME, tag->value);

        tag = av_dict_get(st->metadata, "language", NULL, 0);

        put_ebml_string(pb, MATROSKA_ID_TRACKLANGUAGE, tag ? tag->value:"und");

        if (st->disposition)

            put_ebml_uint(pb, MATROSKA_ID_TRACKFLAGDEFAULT, !!(st->disposition & AV_DISPOSITION_DEFAULT));

        // look for a codec ID string specific to mkv to use,

        // if none are found, use AVI codes

        for (j = 0; ff_mkv_codec_tags[j].id != AV_CODEC_ID_NONE; j++) {

            if (ff_mkv_codec_tags[j].id == codec->codec_id) {

                put_ebml_string(pb, MATROSKA_ID_CODECID, ff_mkv_codec_tags[j].str);

                native_id = 1;

                break;

            }

        }

        if (mkv->mode == MODE_WEBM && !(codec->codec_id == AV_CODEC_ID_VP8 ||

                                        codec->codec_id == AV_CODEC_ID_VORBIS)) {

            av_log(s, AV_LOG_ERROR,

                   "Only VP8 video and Vorbis audio are supported for WebM.\n");

            return AVERROR(EINVAL);

        }

        switch (codec->codec_type) {

            case AVMEDIA_TYPE_VIDEO:

                put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_VIDEO);

                if(st->avg_frame_rate.num && st->avg_frame_rate.den && 1.0/av_q2d(st->avg_frame_rate) > av_q2d(codec->time_base))

                    put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, 1E9/av_q2d(st->avg_frame_rate));

                else

                    put_ebml_uint(pb, MATROSKA_ID_TRACKDEFAULTDURATION, av_q2d(codec->time_base)*1E9);

                if (!native_id &&

                      ff_codec_get_tag(ff_codec_movvideo_tags, codec->codec_id) &&

                    (!ff_codec_get_tag(ff_codec_bmp_tags,   codec->codec_id)

                     || codec->codec_id == AV_CODEC_ID_SVQ1

                     || codec->codec_id == AV_CODEC_ID_SVQ3

                     || codec->codec_id == AV_CODEC_ID_CINEPAK))

                    qt_id = 1;

                if (qt_id)

                    put_ebml_string(pb, MATROSKA_ID_CODECID, "V_QUICKTIME");

                else if (!native_id) {

                    // if there is no mkv-specific codec ID, use VFW mode

                    put_ebml_string(pb, MATROSKA_ID_CODECID, "V_MS/VFW/FOURCC");

                    mkv->tracks[i].write_dts = 1;

                }

                subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKVIDEO, 0);

                // XXX: interlace flag?

                put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELWIDTH , codec->width);

                put_ebml_uint (pb, MATROSKA_ID_VIDEOPIXELHEIGHT, codec->height);

                if ((tag = av_dict_get(st->metadata, "stereo_mode", NULL, 0)) ||

                    (tag = av_dict_get( s->metadata, "stereo_mode", NULL, 0))) {

                    // save stereo mode flag

                    uint64_t st_mode = MATROSKA_VIDEO_STEREO_MODE_COUNT;

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

                        if (!strcmp(tag->value, ff_matroska_video_stereo_mode[j])){

                            st_mode = j;

                            break;

                        }

                    if ((mkv->mode == MODE_WEBM && st_mode > 3 && st_mode != 11)

                        || st_mode >= MATROSKA_VIDEO_STEREO_MODE_COUNT) {

                        av_log(s, AV_LOG_ERROR,

                               "The specified stereo mode is not valid.\n");

                        return AVERROR(EINVAL);

                    } else

                        put_ebml_uint(pb, MATROSKA_ID_VIDEOSTEREOMODE, st_mode);

                }

                if (st->sample_aspect_ratio.num) {

                    int d_width = av_rescale(codec->width, st->sample_aspect_ratio.num, st->sample_aspect_ratio.den);

                    put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYWIDTH , d_width);

                    put_ebml_uint(pb, MATROSKA_ID_VIDEODISPLAYHEIGHT, codec->height);

                }

                if (codec->codec_id == AV_CODEC_ID_RAWVIDEO) {

                    uint32_t color_space = av_le2ne32(codec->codec_tag);

                    put_ebml_binary(pb, MATROSKA_ID_VIDEOCOLORSPACE, &color_space, sizeof(color_space));

                }

                end_ebml_master(pb, subinfo);

                break;

            case AVMEDIA_TYPE_AUDIO:

                put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_AUDIO);

                if (!native_id)

                    // no mkv-specific ID, use ACM mode

                    put_ebml_string(pb, MATROSKA_ID_CODECID, "A_MS/ACM");

                subinfo = start_ebml_master(pb, MATROSKA_ID_TRACKAUDIO, 0);

                put_ebml_uint  (pb, MATROSKA_ID_AUDIOCHANNELS    , codec->channels);

                put_ebml_float (pb, MATROSKA_ID_AUDIOSAMPLINGFREQ, sample_rate);

                if (output_sample_rate)

                    put_ebml_float(pb, MATROSKA_ID_AUDIOOUTSAMPLINGFREQ, output_sample_rate);

                if (bit_depth)

                    put_ebml_uint(pb, MATROSKA_ID_AUDIOBITDEPTH, bit_depth);

                end_ebml_master(pb, subinfo);

                break;

            case AVMEDIA_TYPE_SUBTITLE:

                put_ebml_uint(pb, MATROSKA_ID_TRACKTYPE, MATROSKA_TRACK_TYPE_SUBTITLE);

                if (!native_id) {

                    av_log(s, AV_LOG_ERROR, "Subtitle codec %d is not supported.\n", codec->codec_id);

                    return AVERROR(ENOSYS);

                }

                break;

            default:

                av_log(s, AV_LOG_ERROR, "Only audio, video, and subtitles are supported for Matroska.\n");

                break;

        }

        ret = mkv_write_codecprivate(s, pb, codec, native_id, qt_id);

        if (ret < 0) return ret;

        end_ebml_master(pb, track);

        // ms precision is the de-facto standard timescale for mkv files

        avpriv_set_pts_info(st, 64, 1, 1000);

    }

    end_ebml_master(pb, tracks);

    return 0;

}


int qemu_savevm_state_complete(Monitor *mon, QEMUFile *f)
{
    SaveStateEntry *se;
    QTAILQ_FOREACH(se, &savevm_handlers, entry) {
        if (se->save_live_state == NULL)
            continue;
        /* Section type */
        qemu_put_byte(f, QEMU_VM_SECTION_END);
        qemu_put_be32(f, se->section_id);
        se->save_live_state(mon, f, QEMU_VM_SECTION_END, se->opaque);
    }
    QTAILQ_FOREACH(se, &savevm_handlers, entry) {
        int len;
	if (se->save_state == NULL && se->vmsd == NULL)
	    continue;
        /* Section type */
        qemu_put_byte(f, QEMU_VM_SECTION_FULL);
        qemu_put_be32(f, se->section_id);
        /* ID string */
        len = strlen(se->idstr);
        qemu_put_byte(f, len);
        qemu_put_buffer(f, (uint8_t *)se->idstr, len);
        qemu_put_be32(f, se->instance_id);
        qemu_put_be32(f, se->version_id);
        vmstate_save(f, se);
    }
    qemu_put_byte(f, QEMU_VM_EOF);
    if (qemu_file_has_error(f))
        return -EIO;
    return 0;
}


static int scsi_hot_add(Monitor *mon, DeviceState *adapter,

                        DriveInfo *dinfo, int printinfo)

{

    SCSIBus *scsibus;

    SCSIDevice *scsidev;

    scsibus = DO_UPCAST(SCSIBus, qbus, QLIST_FIRST(&adapter->child_bus));

    if (!scsibus || strcmp(scsibus->qbus.info->name, "SCSI") != 0) {

        error_report("Device is not a SCSI adapter");

    /*

     * drive_init() tries to find a default for dinfo->unit.  Doesn't

     * work at all for hotplug though as we assign the device to a

     * specific bus instead of the first bus with spare scsi ids.

     *

     * Ditch the calculated value and reload from option string (if

     * specified).

     */

    dinfo->unit = qemu_opt_get_number(dinfo->opts, "unit", -1);

    scsidev = scsi_bus_legacy_add_drive(scsibus, dinfo, dinfo->unit);

    dinfo->unit = scsidev->id;

    if (printinfo)

        monitor_printf(mon, "OK bus %d, unit %d\n",

                       scsibus->busnr, scsidev->id);

    return 0;


static void blk_mig_cleanup(void)

{

    BlkMigDevState *bmds;

    BlkMigBlock *blk;

    bdrv_drain_all();

    unset_dirty_tracking();

    blk_mig_lock();

    while ((bmds = QSIMPLEQ_FIRST(&block_mig_state.bmds_list)) != NULL) {

        QSIMPLEQ_REMOVE_HEAD(&block_mig_state.bmds_list, entry);

        bdrv_op_unblock_all(bmds->bs, bmds->blocker);

        error_free(bmds->blocker);

        bdrv_unref(bmds->bs);

        g_free(bmds->aio_bitmap);

        g_free(bmds);

    }

    while ((blk = QSIMPLEQ_FIRST(&block_mig_state.blk_list)) != NULL) {

        QSIMPLEQ_REMOVE_HEAD(&block_mig_state.blk_list, entry);

        g_free(blk->buf);

        g_free(blk);

    }

    blk_mig_unlock();

}


static void do_drive_backup(DriveBackup *backup, BlockJobTxn *txn, Error **errp)

{

    BlockDriverState *bs;

    BlockDriverState *target_bs;

    BlockDriverState *source = NULL;

    BdrvDirtyBitmap *bmap = NULL;

    AioContext *aio_context;

    QDict *options = NULL;

    Error *local_err = NULL;

    int flags;

    int64_t size;

    if (!backup->has_speed) {

        backup->speed = 0;

    }

    if (!backup->has_on_source_error) {

        backup->on_source_error = BLOCKDEV_ON_ERROR_REPORT;

    }

    if (!backup->has_on_target_error) {

        backup->on_target_error = BLOCKDEV_ON_ERROR_REPORT;

    }

    if (!backup->has_mode) {

        backup->mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;

    }

    if (!backup->has_job_id) {

        backup->job_id = NULL;

    }

    if (!backup->has_compress) {

        backup->compress = false;

    }

    bs = qmp_get_root_bs(backup->device, errp);

    if (!bs) {

        return;

    }

    aio_context = bdrv_get_aio_context(bs);

    aio_context_acquire(aio_context);

    if (!backup->has_format) {

        backup->format = backup->mode == NEW_IMAGE_MODE_EXISTING ?

                         NULL : (char*) bs->drv->format_name;

    }

    /* Early check to avoid creating target */

    if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_BACKUP_SOURCE, errp)) {

        goto out;

    }

    flags = bs->open_flags | BDRV_O_RDWR;

    /* See if we have a backing HD we can use to create our new image

     * on top of. */

    if (backup->sync == MIRROR_SYNC_MODE_TOP) {

        source = backing_bs(bs);

        if (!source) {

            backup->sync = MIRROR_SYNC_MODE_FULL;

        }

    }

    if (backup->sync == MIRROR_SYNC_MODE_NONE) {

        source = bs;

    }

    size = bdrv_getlength(bs);

    if (size < 0) {

        error_setg_errno(errp, -size, "bdrv_getlength failed");

        goto out;

    }

    if (backup->mode != NEW_IMAGE_MODE_EXISTING) {

        assert(backup->format);

        if (source) {

            bdrv_img_create(backup->target, backup->format, source->filename,

                            source->drv->format_name, NULL,

                            size, flags, &local_err, false);

        } else {

            bdrv_img_create(backup->target, backup->format, NULL, NULL, NULL,

                            size, flags, &local_err, false);

        }

    }

    if (local_err) {

        error_propagate(errp, local_err);

        goto out;

    }

    if (backup->format) {

        options = qdict_new();

        qdict_put(options, "driver", qstring_from_str(backup->format));

    }

    target_bs = bdrv_open(backup->target, NULL, options, flags, errp);

    if (!target_bs) {

        goto out;

    }

    bdrv_set_aio_context(target_bs, aio_context);

    if (backup->has_bitmap) {

        bmap = bdrv_find_dirty_bitmap(bs, backup->bitmap);

        if (!bmap) {

            error_setg(errp, "Bitmap '%s' could not be found", backup->bitmap);

            bdrv_unref(target_bs);

            goto out;

        }

    }

    backup_start(backup->job_id, bs, target_bs, backup->speed, backup->sync,

                 bmap, backup->compress, backup->on_source_error,

                 backup->on_target_error, BLOCK_JOB_DEFAULT,

                 NULL, NULL, txn, &local_err);

    bdrv_unref(target_bs);

    if (local_err != NULL) {

        error_propagate(errp, local_err);

        goto out;

    }

out:

    aio_context_release(aio_context);

}


static inline int get16(const uint8_t **pp, const uint8_t *p_end)

{

    const uint8_t *p;

    int c;

    p = *pp;

    if ((p + 1) >= p_end)

        return AVERROR_INVALIDDATA;

    c   = AV_RB16(p);

    p  += 2;

    *pp = p;

    return c;

}


static void test_visitor_out_null(TestOutputVisitorData *data,

                                  const void *unused)

{

    QObject *arg;

    QDict *qdict;

    QObject *nil;

    visit_start_struct(data->ov, NULL, NULL, 0, &error_abort);

    visit_type_null(data->ov, "a", &error_abort);

    visit_end_struct(data->ov, &error_abort);

    arg = qmp_output_get_qobject(data->qov);

    g_assert(qobject_type(arg) == QTYPE_QDICT);

    qdict = qobject_to_qdict(arg);

    g_assert_cmpint(qdict_size(qdict), ==, 1);

    nil = qdict_get(qdict, "a");

    g_assert(nil);

    g_assert(qobject_type(nil) == QTYPE_QNULL);

    qobject_decref(arg);

}


void vnc_client_error(VncState *vs)

{

    vnc_client_io_error(vs, -1, EINVAL);

}


static void test_yield(void)

{

    Coroutine *coroutine;

    bool done = false;

    int i = -1; /* one extra time to return from coroutine */

    coroutine = qemu_coroutine_create(yield_5_times);

    while (!done) {

        qemu_coroutine_enter(coroutine, &done);

        i++;

    }

    g_assert_cmpint(i, ==, 5); /* coroutine must yield 5 times */

}


static inline int l3_unscale(int value, int exponent)

{

    unsigned int m;

    int e;

    e  = table_4_3_exp  [4 * value + (exponent & 3)];

    m  = table_4_3_value[4 * value + (exponent & 3)];

    e -= exponent >> 2;

    assert(e >= 1);

    if (e > 31)

        return 0;

    m = (m + (1 << (e - 1))) >> e;

    return m;

}