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

                            const AVFrame *frame, int *got_packet_ptr)

{

    G723_1_Context *p = avctx->priv_data;

    int16_t unq_lpc[LPC_ORDER * SUBFRAMES];

    int16_t qnt_lpc[LPC_ORDER * SUBFRAMES];

    int16_t cur_lsp[LPC_ORDER];

    int16_t weighted_lpc[LPC_ORDER * SUBFRAMES << 1];

    int16_t vector[FRAME_LEN + PITCH_MAX];

    int offset, ret;

    int16_t *in = (const int16_t *)frame->data[0];

    HFParam hf[4];

    int i, j;

    highpass_filter(in, &p->hpf_fir_mem, &p->hpf_iir_mem);

    memcpy(vector, p->prev_data, HALF_FRAME_LEN * sizeof(int16_t));

    memcpy(vector + HALF_FRAME_LEN, in, FRAME_LEN * sizeof(int16_t));

    comp_lpc_coeff(vector, unq_lpc);

    lpc2lsp(&unq_lpc[LPC_ORDER * 3], p->prev_lsp, cur_lsp);

    lsp_quantize(p->lsp_index, cur_lsp, p->prev_lsp);

    /* Update memory */

    memcpy(vector + LPC_ORDER, p->prev_data + SUBFRAME_LEN,

           sizeof(int16_t) * SUBFRAME_LEN);

    memcpy(vector + LPC_ORDER + SUBFRAME_LEN, in,

           sizeof(int16_t) * (HALF_FRAME_LEN + SUBFRAME_LEN));

    memcpy(p->prev_data, in + HALF_FRAME_LEN,

           sizeof(int16_t) * HALF_FRAME_LEN);

    memcpy(in, vector + LPC_ORDER, sizeof(int16_t) * FRAME_LEN);

    perceptual_filter(p, weighted_lpc, unq_lpc, vector);

    memcpy(in, vector + LPC_ORDER, sizeof(int16_t) * FRAME_LEN);

    memcpy(vector, p->prev_weight_sig, sizeof(int16_t) * PITCH_MAX);

    memcpy(vector + PITCH_MAX, in, sizeof(int16_t) * FRAME_LEN);

    scale_vector(vector, vector, FRAME_LEN + PITCH_MAX);

    p->pitch_lag[0] = estimate_pitch(vector, PITCH_MAX);

    p->pitch_lag[1] = estimate_pitch(vector, PITCH_MAX + HALF_FRAME_LEN);

    for (i = PITCH_MAX, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)

        comp_harmonic_coeff(vector + i, p->pitch_lag[j >> 1], hf + j);

    memcpy(vector, p->prev_weight_sig, sizeof(int16_t) * PITCH_MAX);

    memcpy(vector + PITCH_MAX, in, sizeof(int16_t) * FRAME_LEN);

    memcpy(p->prev_weight_sig, vector + FRAME_LEN, sizeof(int16_t) * PITCH_MAX);

    for (i = 0, j = 0; j < SUBFRAMES; i += SUBFRAME_LEN, j++)

        harmonic_filter(hf + j, vector + PITCH_MAX + i, in + i);

    inverse_quant(cur_lsp, p->prev_lsp, p->lsp_index, 0);

    lsp_interpolate(qnt_lpc, cur_lsp, p->prev_lsp);

    memcpy(p->prev_lsp, cur_lsp, sizeof(int16_t) * LPC_ORDER);

    offset = 0;

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

        int16_t impulse_resp[SUBFRAME_LEN];

        int16_t residual[SUBFRAME_LEN + PITCH_ORDER - 1];

        int16_t flt_in[SUBFRAME_LEN];

        int16_t zero[LPC_ORDER], fir[LPC_ORDER], iir[LPC_ORDER];

        /**

         * Compute the combined impulse response of the synthesis filter,

         * formant perceptual weighting filter and harmonic noise shaping filter

         */

        memset(zero, 0, sizeof(int16_t) * LPC_ORDER);

        memset(vector, 0, sizeof(int16_t) * PITCH_MAX);

        memset(flt_in, 0, sizeof(int16_t) * SUBFRAME_LEN);

        flt_in[0] = 1 << 13; /* Unit impulse */

        synth_percept_filter(qnt_lpc + offset, weighted_lpc + (offset << 1),

                             zero, zero, flt_in, vector + PITCH_MAX, 1);

        harmonic_filter(hf + i, vector + PITCH_MAX, impulse_resp);

         /* Compute the combined zero input response */

        flt_in[0] = 0;

        memcpy(fir, p->perf_fir_mem, sizeof(int16_t) * LPC_ORDER);

        memcpy(iir, p->perf_iir_mem, sizeof(int16_t) * LPC_ORDER);

        synth_percept_filter(qnt_lpc + offset, weighted_lpc + (offset << 1),

                             fir, iir, flt_in, vector + PITCH_MAX, 0);

        memcpy(vector, p->harmonic_mem, sizeof(int16_t) * PITCH_MAX);

        harmonic_noise_sub(hf + i, vector + PITCH_MAX, in);

        acb_search(p, residual, impulse_resp, in, i);

        gen_acb_excitation(residual, p->prev_excitation,p->pitch_lag[i >> 1],

                           &p->subframe[i], p->cur_rate);

        sub_acb_contrib(residual, impulse_resp, in);

        fcb_search(p, impulse_resp, in, i);

        /* Reconstruct the excitation */

        gen_acb_excitation(impulse_resp, p->prev_excitation, p->pitch_lag[i >> 1],

                           &p->subframe[i], RATE_6300);

        memmove(p->prev_excitation, p->prev_excitation + SUBFRAME_LEN,

               sizeof(int16_t) * (PITCH_MAX - SUBFRAME_LEN));

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

            in[j] = av_clip_int16((in[j] << 1) + impulse_resp[j]);

        memcpy(p->prev_excitation + PITCH_MAX - SUBFRAME_LEN, in,

               sizeof(int16_t) * SUBFRAME_LEN);

        /* Update filter memories */

        synth_percept_filter(qnt_lpc + offset, weighted_lpc + (offset << 1),

                             p->perf_fir_mem, p->perf_iir_mem,

                             in, vector + PITCH_MAX, 0);

        memmove(p->harmonic_mem, p->harmonic_mem + SUBFRAME_LEN,

                sizeof(int16_t) * (PITCH_MAX - SUBFRAME_LEN));

        memcpy(p->harmonic_mem + PITCH_MAX - SUBFRAME_LEN, vector + PITCH_MAX,

               sizeof(int16_t) * SUBFRAME_LEN);

        in += SUBFRAME_LEN;

        offset += LPC_ORDER;

    }

    if ((ret = ff_alloc_packet2(avctx, avpkt, 24)))

        return ret;

    *got_packet_ptr = 1;

    avpkt->size = pack_bitstream(p, avpkt->data, avpkt->size);

    return 0;

}


void ff_wmv2_idct_c(short * block){

    int i;

    for(i=0;i<64;i+=8){

        wmv2_idct_row(block+i);

    }

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

        wmv2_idct_col(block+i);

    }

}


type_init(parallel_register_types)

static bool parallel_init(ISABus *bus, int index, CharDriverState *chr)

{

    DeviceState *dev;

    ISADevice *isadev;

    isadev = isa_try_create(bus, "isa-parallel");

    if (!isadev) {

        return false;

    }

    dev = DEVICE(isadev);

    qdev_prop_set_uint32(dev, "index", index);

    qdev_prop_set_chr(dev, "chardev", chr);

    if (qdev_init(dev) < 0) {

        return false;

    }

    return true;

}


static void ehci_execute_complete(EHCIQueue *q)

{

    EHCIPacket *p = QTAILQ_FIRST(&q->packets);

    assert(p != NULL);

    assert(p->qtdaddr == q->qtdaddr);

    assert(p->async != EHCI_ASYNC_INFLIGHT);

    p->async = EHCI_ASYNC_NONE;

    DPRINTF("execute_complete: qhaddr 0x%x, next %x, qtdaddr 0x%x, status %d\n",

            q->qhaddr, q->qh.next, q->qtdaddr, q->usb_status);

    if (p->usb_status < 0) {

        switch (p->usb_status) {

        case USB_RET_IOERROR:

        case USB_RET_NODEV:

            q->qh.token |= (QTD_TOKEN_HALT | QTD_TOKEN_XACTERR);

            set_field(&q->qh.token, 0, QTD_TOKEN_CERR);

            ehci_record_interrupt(q->ehci, USBSTS_ERRINT);

            break;

        case USB_RET_STALL:

            q->qh.token |= QTD_TOKEN_HALT;

            ehci_record_interrupt(q->ehci, USBSTS_ERRINT);

            break;

        case USB_RET_NAK:

            set_field(&q->qh.altnext_qtd, 0, QH_ALTNEXT_NAKCNT);

            return; /* We're not done yet with this transaction */

        case USB_RET_BABBLE:

            q->qh.token |= (QTD_TOKEN_HALT | QTD_TOKEN_BABBLE);

            ehci_record_interrupt(q->ehci, USBSTS_ERRINT);

            break;

        default:

            /* should not be triggerable */

            fprintf(stderr, "USB invalid response %d\n", p->usb_status);

            assert(0);

            break;

        }

    } else if ((p->usb_status > p->tbytes) && (p->pid == USB_TOKEN_IN)) {

        p->usb_status = USB_RET_BABBLE;

        q->qh.token |= (QTD_TOKEN_HALT | QTD_TOKEN_BABBLE);

        ehci_record_interrupt(q->ehci, USBSTS_ERRINT);

    } else {

        // TODO check 4.12 for splits

        if (p->tbytes && p->pid == USB_TOKEN_IN) {

            p->tbytes -= p->usb_status;

        } else {

            p->tbytes = 0;

        }

        DPRINTF("updating tbytes to %d\n", p->tbytes);

        set_field(&q->qh.token, p->tbytes, QTD_TOKEN_TBYTES);

    }

    ehci_finish_transfer(q, p->usb_status);

    qemu_sglist_destroy(&p->sgl);

    usb_packet_unmap(&p->packet);

    q->qh.token ^= QTD_TOKEN_DTOGGLE;

    q->qh.token &= ~QTD_TOKEN_ACTIVE;

    if (q->qh.token & QTD_TOKEN_IOC) {

        ehci_record_interrupt(q->ehci, USBSTS_INT);

    }

}


static int64_t alloc_clusters_noref(BlockDriverState *bs, int64_t size)

{

    BDRVQcowState *s = bs->opaque;

    int i, nb_clusters, refcount;

    nb_clusters = size_to_clusters(s, size);

retry:

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

        int64_t next_cluster_index = s->free_cluster_index++;

        refcount = get_refcount(bs, next_cluster_index);

        if (refcount < 0) {

            return refcount;

        } else if (refcount != 0) {

            goto retry;

        }

    }

#ifdef DEBUG_ALLOC2

    fprintf(stderr, "alloc_clusters: size=%" PRId64 " -> %" PRId64 "\n",

            size,

            (s->free_cluster_index - nb_clusters) << s->cluster_bits);

#endif

    return (s->free_cluster_index - nb_clusters) << s->cluster_bits;

}


double parse_number_or_die(const char *context, const char *numstr, int type,

                           double min, double max)

{

    char *tail;

    const char *error;

    double d = av_strtod(numstr, &tail);

    if (*tail)

        error = "Expected number for %s but found: %s\n";

    else if (d < min || d > max)

        error = "The value for %s was %s which is not within %f - %f\n";

    else if (type == OPT_INT64 && (int64_t)d != d)

        error = "Expected int64 for %s but found %s\n";

    else if (type == OPT_INT && (int)d != d)

        error = "Expected int for %s but found %s\n";

    else

        return d;

    av_log(NULL, AV_LOG_FATAL, error, context, numstr, min, max);

    exit(1);

    return 0;

}


static int qemu_rbd_snap_list(BlockDriverState *bs,

                              QEMUSnapshotInfo **psn_tab)

{

    BDRVRBDState *s = bs->opaque;

    QEMUSnapshotInfo *sn_info, *sn_tab = NULL;

    int i, snap_count;

    rbd_snap_info_t *snaps;

    int max_snaps = RBD_MAX_SNAPS;

    do {

        snaps = g_malloc(sizeof(*snaps) * max_snaps);

        snap_count = rbd_snap_list(s->image, snaps, &max_snaps);

        if (snap_count <= 0) {

            g_free(snaps);

        }

    } while (snap_count == -ERANGE);

    if (snap_count <= 0) {

        goto done;

    }

    sn_tab = g_malloc0(snap_count * sizeof(QEMUSnapshotInfo));

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

        const char *snap_name = snaps[i].name;

        sn_info = sn_tab + i;

        pstrcpy(sn_info->id_str, sizeof(sn_info->id_str), snap_name);

        pstrcpy(sn_info->name, sizeof(sn_info->name), snap_name);

        sn_info->vm_state_size = snaps[i].size;

        sn_info->date_sec = 0;

        sn_info->date_nsec = 0;

        sn_info->vm_clock_nsec = 0;

    }

    rbd_snap_list_end(snaps);

    g_free(snaps);

 done:

    *psn_tab = sn_tab;

    return snap_count;

}


static void init_fps(int bf, int audio_preroll, int fps)

{

    AVStream *st;

    ctx = avformat_alloc_context();

    if (!ctx)

        exit(1);

    ctx->oformat = av_guess_format(format, NULL, NULL);

    if (!ctx->oformat)

        exit(1);

    ctx->pb = avio_alloc_context(iobuf, sizeof(iobuf), AVIO_FLAG_WRITE, NULL, NULL, io_write, NULL);

    if (!ctx->pb)

        exit(1);

    ctx->flags |= AVFMT_FLAG_BITEXACT;

    st = avformat_new_stream(ctx, NULL);

    if (!st)

        exit(1);

    st->codec->codec_type = AVMEDIA_TYPE_VIDEO;

    st->codec->codec_id = AV_CODEC_ID_H264;

    st->codec->width = 640;

    st->codec->height = 480;

    st->time_base.num = 1;

    st->time_base.den = 30;

    st->codec->extradata_size = sizeof(h264_extradata);

    st->codec->extradata = av_mallocz(st->codec->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);

    if (!st->codec->extradata)

        exit(1);

    memcpy(st->codec->extradata, h264_extradata, sizeof(h264_extradata));

    st->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;

    video_st = st;

    st = avformat_new_stream(ctx, NULL);

    if (!st)

        exit(1);

    st->codec->codec_type = AVMEDIA_TYPE_AUDIO;

    st->codec->codec_id = AV_CODEC_ID_AAC;

    st->codec->sample_rate = 44100;

    st->codec->channels = 2;

    st->time_base.num = 1;

    st->time_base.den = 44100;

    st->codec->extradata_size = sizeof(aac_extradata);

    st->codec->extradata = av_mallocz(st->codec->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE);

    if (!st->codec->extradata)

        exit(1);

    memcpy(st->codec->extradata, aac_extradata, sizeof(aac_extradata));

    st->codec->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;

    audio_st = st;

    if (avformat_write_header(ctx, &opts) < 0)

        exit(1);

    av_dict_free(&opts);

    frames = 0;

    gop_size = 30;

    duration = video_st->time_base.den / fps;

    audio_duration = 1024 * audio_st->time_base.den / audio_st->codec->sample_rate;

    if (audio_preroll)

        audio_preroll = 2048 * audio_st->time_base.den / audio_st->codec->sample_rate;

    bframes = bf;

    video_dts = bframes ? -duration : 0;

    audio_dts = -audio_preroll;

}


GList *g_list_insert_sorted_merged(GList *list, gpointer data,

                                   GCompareFunc func)

{

    GList *l, *next = NULL;

    Range *r, *nextr;

    if (!list) {

        list = g_list_insert_sorted(list, data, func);

        return list;

    }

    nextr = data;

    l = list;

    while (l && l != next && nextr) {

        r = l->data;

        if (ranges_can_merge(r, nextr)) {

            range_merge(r, nextr);

            l = g_list_remove_link(l, next);

            next = g_list_next(l);

            if (next) {

                nextr = next->data;

            } else {

                nextr = NULL;

            }

        } else {

            l = g_list_next(l);

        }

    }

    if (!l) {

        list = g_list_insert_sorted(list, data, func);

    }

    return list;

}


static int matroska_parse_laces(MatroskaDemuxContext *matroska, uint8_t **buf,

                                int* buf_size, int type,

                                uint32_t **lace_buf, int *laces)

{

    int res = 0, n, size = *buf_size;

    uint8_t *data = *buf;

    uint32_t *lace_size;

    if (!type) {

        *laces = 1;

        *lace_buf = av_mallocz(sizeof(int));

        if (!*lace_buf)

            return AVERROR(ENOMEM);

        *lace_buf[0] = size;

        return 0;

    }

    av_assert0(size > 0);

    *laces = *data + 1;

    data += 1;

    size -= 1;

    lace_size = av_mallocz(*laces * sizeof(int));

    if (!lace_size)

        return AVERROR(ENOMEM);

    switch (type) {

    case 0x1: /* Xiph lacing */ {

        uint8_t temp;

        uint32_t total = 0;

        for (n = 0; res == 0 && n < *laces - 1; n++) {

            while (1) {

                if (size == 0) {

                    res = AVERROR_INVALIDDATA;

                    break;

                }

                temp = *data;

                lace_size[n] += temp;

                data += 1;

                size -= 1;

                if (temp != 0xff)

                    break;

            }

            total += lace_size[n];

        }

        if (size <= total) {

            res = AVERROR_INVALIDDATA;

            break;

        }

        lace_size[n] = size - total;

        break;

    }

    case 0x2: /* fixed-size lacing */

        if (size % (*laces)) {

            res = AVERROR_INVALIDDATA;

            break;

        }

        for (n = 0; n < *laces; n++)

            lace_size[n] = size / *laces;

        break;

    case 0x3: /* EBML lacing */ {

        uint64_t num;

        uint64_t total;

        n = matroska_ebmlnum_uint(matroska, data, size, &num);

        if (n < 0) {

            av_log(matroska->ctx, AV_LOG_INFO,

                   "EBML block data error\n");

            res = n;

            break;

        }

        data += n;

        size -= n;

        total = lace_size[0] = num;

        for (n = 1; res == 0 && n < *laces - 1; n++) {

            int64_t snum;

            int r;

            r = matroska_ebmlnum_sint(matroska, data, size, &snum);

            if (r < 0) {

                av_log(matroska->ctx, AV_LOG_INFO,

                       "EBML block data error\n");

                res = r;

                break;

            }

            data += r;

            size -= r;

            lace_size[n] = lace_size[n - 1] + snum;

            total += lace_size[n];

        }

        if (size <= total) {

            res = AVERROR_INVALIDDATA;

            break;

        }

        lace_size[*laces - 1] = size - total;

        break;

    }

    }

    *buf      = data;

    *lace_buf = lace_size;

    *buf_size = size;

    return res;

}


static av_cold int ape_decode_init(AVCodecContext * avctx)

{

    APEContext *s = avctx->priv_data;

    int i;

    if (avctx->extradata_size != 6) {

        av_log(avctx, AV_LOG_ERROR, "Incorrect extradata\n");

        return -1;

    }

    if (avctx->bits_per_coded_sample != 16) {

        av_log(avctx, AV_LOG_ERROR, "Only 16-bit samples are supported\n");

        return -1;

    }

    if (avctx->channels > 2) {

        av_log(avctx, AV_LOG_ERROR, "Only mono and stereo is supported\n");

        return -1;

    }

    s->avctx             = avctx;

    s->channels          = avctx->channels;

    s->fileversion       = AV_RL16(avctx->extradata);

    s->compression_level = AV_RL16(avctx->extradata + 2);

    s->flags             = AV_RL16(avctx->extradata + 4);

    av_log(avctx, AV_LOG_DEBUG, "Compression Level: %d - Flags: %d\n", s->compression_level, s->flags);

    if (s->compression_level % 1000 || s->compression_level > COMPRESSION_LEVEL_INSANE) {

        av_log(avctx, AV_LOG_ERROR, "Incorrect compression level %d\n", s->compression_level);

        return -1;

    }

    s->fset = s->compression_level / 1000 - 1;

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

        if (!ape_filter_orders[s->fset][i])

            break;

        s->filterbuf[i] = av_malloc((ape_filter_orders[s->fset][i] * 3 + HISTORY_SIZE) * 4);

    }

    dsputil_init(&s->dsp, avctx);

    avctx->sample_fmt = AV_SAMPLE_FMT_S16;

    avctx->channel_layout = (avctx->channels==2) ? AV_CH_LAYOUT_STEREO : AV_CH_LAYOUT_MONO;

    return 0;

}


void monitor_vprintf(Monitor *mon, const char *fmt, va_list ap)

{

    char buf[4096];

    if (!mon)

        return;

    if (monitor_ctrl_mode(mon)) {

        return;

    }

    vsnprintf(buf, sizeof(buf), fmt, ap);

    monitor_puts(mon, buf);

}


static void hScale16To19_c(SwsContext *c, int16_t *_dst, int dstW, const uint8_t *_src,

                           const int16_t *filter,

                           const int16_t *filterPos, int filterSize)

{

    int i;

    int32_t *dst = (int32_t *) _dst;

    const uint16_t *src = (const uint16_t *) _src;

    int bits = av_pix_fmt_descriptors[c->srcFormat].comp[0].depth_minus1;

    int sh = bits - 4;

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

        int j;

        int srcPos = filterPos[i];

        int val = 0;

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

            val += src[srcPos + j] * filter[filterSize * i + j];

        }

        // filter=14 bit, input=16 bit, output=30 bit, >> 11 makes 19 bit

        dst[i] = FFMIN(val >> sh, (1 << 19) - 1);

    }

}


static int milkymist_softusb_init(SysBusDevice *dev)

{

    MilkymistSoftUsbState *s = MILKYMIST_SOFTUSB(dev);

    sysbus_init_irq(dev, &s->irq);

    memory_region_init_io(&s->regs_region, OBJECT(s), &softusb_mmio_ops, s,

                          "milkymist-softusb", R_MAX * 4);

    sysbus_init_mmio(dev, &s->regs_region);

    /* register pmem and dmem */

    memory_region_init_ram(&s->pmem, OBJECT(s), "milkymist-softusb.pmem",

                           s->pmem_size, &error_abort);

    vmstate_register_ram_global(&s->pmem);

    s->pmem_ptr = memory_region_get_ram_ptr(&s->pmem);

    sysbus_init_mmio(dev, &s->pmem);

    memory_region_init_ram(&s->dmem, OBJECT(s), "milkymist-softusb.dmem",

                           s->dmem_size, &error_abort);

    vmstate_register_ram_global(&s->dmem);

    s->dmem_ptr = memory_region_get_ram_ptr(&s->dmem);

    sysbus_init_mmio(dev, &s->dmem);

    hid_init(&s->hid_kbd, HID_KEYBOARD, softusb_kbd_hid_datain);

    hid_init(&s->hid_mouse, HID_MOUSE, softusb_mouse_hid_datain);

    return 0;

}


static gnutls_certificate_credentials_t vnc_tls_initialize_x509_cred(VncDisplay *vd)

{

    gnutls_certificate_credentials_t x509_cred;

    int ret;

    if (!vd->tls.x509cacert) {

        VNC_DEBUG("No CA x509 certificate specified\n");

        return NULL;

    }

    if (!vd->tls.x509cert) {

        VNC_DEBUG("No server x509 certificate specified\n");

        return NULL;

    }

    if (!vd->tls.x509key) {

        VNC_DEBUG("No server private key specified\n");

        return NULL;

    }

    if ((ret = gnutls_certificate_allocate_credentials(&x509_cred)) < 0) {

        VNC_DEBUG("Cannot allocate credentials %s\n", gnutls_strerror(ret));

        return NULL;

    }

    if ((ret = gnutls_certificate_set_x509_trust_file(x509_cred,

                                                      vd->tls.x509cacert,

                                                      GNUTLS_X509_FMT_PEM)) < 0) {

        VNC_DEBUG("Cannot load CA certificate %s\n", gnutls_strerror(ret));

        gnutls_certificate_free_credentials(x509_cred);

        return NULL;

    }

    if ((ret = gnutls_certificate_set_x509_key_file (x509_cred,

                                                     vd->tls.x509cert,

                                                     vd->tls.x509key,

                                                     GNUTLS_X509_FMT_PEM)) < 0) {

        VNC_DEBUG("Cannot load certificate & key %s\n", gnutls_strerror(ret));

        gnutls_certificate_free_credentials(x509_cred);

        return NULL;

    }

    if (vd->tls.x509cacrl) {

        if ((ret = gnutls_certificate_set_x509_crl_file(x509_cred,

                                                        vd->tls.x509cacrl,

                                                        GNUTLS_X509_FMT_PEM)) < 0) {

            VNC_DEBUG("Cannot load CRL %s\n", gnutls_strerror(ret));

            gnutls_certificate_free_credentials(x509_cred);

            return NULL;

        }

    }

    gnutls_certificate_set_dh_params (x509_cred, dh_params);

    return x509_cred;

}


static int client_migrate_info(Monitor *mon, const QDict *qdict,

                               MonitorCompletion cb, void *opaque)

{

    const char *protocol = qdict_get_str(qdict, "protocol");

    const char *hostname = qdict_get_str(qdict, "hostname");

    const char *subject  = qdict_get_try_str(qdict, "cert-subject");

    int port             = qdict_get_try_int(qdict, "port", -1);

    int tls_port         = qdict_get_try_int(qdict, "tls-port", -1);

    Error *err;

    int ret;

    if (strcmp(protocol, "spice") == 0) {

        if (!qemu_using_spice(&err)) {

            qerror_report_err(err);

            return -1;

        }

        if (port == -1 && tls_port == -1) {

            qerror_report(QERR_MISSING_PARAMETER, "port/tls-port");

            return -1;

        }

        ret = qemu_spice_migrate_info(hostname, port, tls_port, subject,

                                      cb, opaque);

        if (ret != 0) {

            qerror_report(QERR_UNDEFINED_ERROR);

            return -1;

        }

        return 0;

    }

    qerror_report(QERR_INVALID_PARAMETER, "protocol");

    return -1;

}


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

{

    int max_len = buf[4];

    buf[0] = 0x05; /* CD-ROM */

    buf[1] = 0x80; /* removable */

    buf[2] = 0x00; /* ISO */

    buf[3] = 0x21; /* ATAPI-2 (XXX: put ATAPI-4 ?) */

    buf[4] = 31; /* additional length */

    buf[5] = 0; /* reserved */

    buf[6] = 0; /* reserved */

    buf[7] = 0; /* reserved */

    padstr8(buf + 8, 8, "QEMU");

    padstr8(buf + 16, 16, "QEMU DVD-ROM");

    padstr8(buf + 32, 4, s->version);

    ide_atapi_cmd_reply(s, 36, max_len);

}


uint32 float32_to_uint32( float32 a STATUS_PARAM )

{

    int64_t v;

    uint32 res;

    v = float32_to_int64(a STATUS_VAR);

    if (v < 0) {

        res = 0;

        float_raise( float_flag_invalid STATUS_VAR);

    } else if (v > 0xffffffff) {

        res = 0xffffffff;

        float_raise( float_flag_invalid STATUS_VAR);

    } else {

        res = v;

    }

    return res;

}


sowrite(struct socket *so)

{

	int  n,nn;

	struct sbuf *sb = &so->so_rcv;

	int len = sb->sb_cc;

	struct iovec iov[2];

	DEBUG_CALL("sowrite");

	DEBUG_ARG("so = %p", so);

	if (so->so_urgc) {

		sosendoob(so);

		if (sb->sb_cc == 0)

			return 0;

	}

	/*

	 * No need to check if there's something to write,

	 * sowrite wouldn't have been called otherwise

	 */

	iov[0].iov_base = sb->sb_rptr;

        iov[1].iov_base = NULL;

        iov[1].iov_len = 0;

	if (sb->sb_rptr < sb->sb_wptr) {

		iov[0].iov_len = sb->sb_wptr - sb->sb_rptr;

		/* Should never succeed, but... */

		if (iov[0].iov_len > len) iov[0].iov_len = len;

		n = 1;

	} else {

		iov[0].iov_len = (sb->sb_data + sb->sb_datalen) - sb->sb_rptr;

		if (iov[0].iov_len > len) iov[0].iov_len = len;

		len -= iov[0].iov_len;

		if (len) {

			iov[1].iov_base = sb->sb_data;

			iov[1].iov_len = sb->sb_wptr - sb->sb_data;

			if (iov[1].iov_len > len) iov[1].iov_len = len;

			n = 2;

		} else

			n = 1;

	}

	/* Check if there's urgent data to send, and if so, send it */

#ifdef HAVE_READV

	nn = writev(so->s, (const struct iovec *)iov, n);

	DEBUG_MISC((dfd, "  ... wrote nn = %d bytes\n", nn));

#else

	nn = slirp_send(so, iov[0].iov_base, iov[0].iov_len,0);

#endif

	/* This should never happen, but people tell me it does *shrug* */

	if (nn < 0 && (errno == EAGAIN || errno == EINTR))

		return 0;

	if (nn <= 0) {

		DEBUG_MISC((dfd, " --- sowrite disconnected, so->so_state = %x, errno = %d\n",

			so->so_state, errno));

		sofcantsendmore(so);

		tcp_sockclosed(sototcpcb(so));

		return -1;

	}

#ifndef HAVE_READV

	if (n == 2 && nn == iov[0].iov_len) {

            int ret;

            ret = slirp_send(so, iov[1].iov_base, iov[1].iov_len,0);

            if (ret > 0)

                nn += ret;

        }

        DEBUG_MISC((dfd, "  ... wrote nn = %d bytes\n", nn));

#endif

	/* Update sbuf */

	sb->sb_cc -= nn;

	sb->sb_rptr += nn;

	if (sb->sb_rptr >= (sb->sb_data + sb->sb_datalen))

		sb->sb_rptr -= sb->sb_datalen;

	/*

	 * If in DRAIN mode, and there's no more data, set

	 * it CANTSENDMORE

	 */

	if ((so->so_state & SS_FWDRAIN) && sb->sb_cc == 0)

		sofcantsendmore(so);

	return nn;

}


static int64_t coroutine_fn raw_co_get_block_status(BlockDriverState *bs,

                                                    int64_t sector_num,

                                                    int nb_sectors, int *pnum)

{

    off_t start, data = 0, hole = 0;

    int64_t total_size;

    int ret;

    ret = fd_open(bs);

    if (ret < 0) {

        return ret;

    }

    start = sector_num * BDRV_SECTOR_SIZE;

    total_size = bdrv_getlength(bs);

    if (total_size < 0) {

        return total_size;

    } else if (start >= total_size) {

        *pnum = 0;

        return 0;

    } else if (start + nb_sectors * BDRV_SECTOR_SIZE > total_size) {

        nb_sectors = DIV_ROUND_UP(total_size - start, BDRV_SECTOR_SIZE);

    }

    ret = find_allocation(bs, start, &data, &hole);

    if (ret == -ENXIO) {

        /* Trailing hole */

        *pnum = nb_sectors;

        ret = BDRV_BLOCK_ZERO;

    } else if (ret < 0) {

        /* No info available, so pretend there are no holes */

        *pnum = nb_sectors;

        ret = BDRV_BLOCK_DATA;

    } else if (data == start) {

        /* On a data extent, compute sectors to the end of the extent.  */

        *pnum = MIN(nb_sectors, (hole - start) / BDRV_SECTOR_SIZE);

        ret = BDRV_BLOCK_DATA;

    } else {

        /* On a hole, compute sectors to the beginning of the next extent.  */

        assert(hole == start);

        *pnum = MIN(nb_sectors, (data - start) / BDRV_SECTOR_SIZE);

        ret = BDRV_BLOCK_ZERO;

    }

    return ret | BDRV_BLOCK_OFFSET_VALID | start;

}


int load_elf_binary(struct linux_binprm * bprm, struct target_pt_regs * regs,

                    struct image_info * info)

{

    struct elfhdr elf_ex;

    struct elfhdr interp_elf_ex;

    struct exec interp_ex;

    int interpreter_fd = -1; /* avoid warning */

    abi_ulong load_addr, load_bias;

    int load_addr_set = 0;

    unsigned int interpreter_type = INTERPRETER_NONE;

    unsigned char ibcs2_interpreter;

    int i;

    abi_ulong mapped_addr;

    struct elf_phdr * elf_ppnt;

    struct elf_phdr *elf_phdata;

    abi_ulong elf_bss, k, elf_brk;

    int retval;

    char * elf_interpreter;

    abi_ulong elf_entry, interp_load_addr = 0;

    int status;

    abi_ulong start_code, end_code, start_data, end_data;

    abi_ulong reloc_func_desc = 0;

    abi_ulong elf_stack;

    char passed_fileno[6];

    ibcs2_interpreter = 0;

    status = 0;

    load_addr = 0;

    load_bias = 0;

    elf_ex = *((struct elfhdr *) bprm->buf);          /* exec-header */

#ifdef BSWAP_NEEDED

    bswap_ehdr(&elf_ex);

#endif

    /* First of all, some simple consistency checks */

    if ((elf_ex.e_type != ET_EXEC && elf_ex.e_type != ET_DYN) ||

       				(! elf_check_arch(elf_ex.e_machine))) {

	    return -ENOEXEC;

    }

    bprm->p = copy_elf_strings(1, &bprm->filename, bprm->page, bprm->p);

    bprm->p = copy_elf_strings(bprm->envc,bprm->envp,bprm->page,bprm->p);

    bprm->p = copy_elf_strings(bprm->argc,bprm->argv,bprm->page,bprm->p);

    if (!bprm->p) {

        retval = -E2BIG;

    }

    /* Now read in all of the header information */

    elf_phdata = (struct elf_phdr *)malloc(elf_ex.e_phentsize*elf_ex.e_phnum);

    if (elf_phdata == NULL) {

	return -ENOMEM;

    }

    retval = lseek(bprm->fd, elf_ex.e_phoff, SEEK_SET);

    if(retval > 0) {

	retval = read(bprm->fd, (char *) elf_phdata,

				elf_ex.e_phentsize * elf_ex.e_phnum);

    }

    if (retval < 0) {

	perror("load_elf_binary");

	exit(-1);

	free (elf_phdata);

	return -errno;

    }

#ifdef BSWAP_NEEDED

    elf_ppnt = elf_phdata;

    for (i=0; i<elf_ex.e_phnum; i++, elf_ppnt++) {

        bswap_phdr(elf_ppnt);

    }

#endif

    elf_ppnt = elf_phdata;

    elf_bss = 0;

    elf_brk = 0;

    elf_stack = ~((abi_ulong)0UL);

    elf_interpreter = NULL;

    start_code = ~((abi_ulong)0UL);

    end_code = 0;

    start_data = 0;

    end_data = 0;

    for(i=0;i < elf_ex.e_phnum; i++) {

	if (elf_ppnt->p_type == PT_INTERP) {

	    if ( elf_interpreter != NULL )

	    {

		free (elf_phdata);

		free(elf_interpreter);

		close(bprm->fd);

		return -EINVAL;

	    }

	    /* This is the program interpreter used for

	     * shared libraries - for now assume that this

	     * is an a.out format binary

	     */

	    elf_interpreter = (char *)malloc(elf_ppnt->p_filesz);

	    if (elf_interpreter == NULL) {

		free (elf_phdata);

		close(bprm->fd);

		return -ENOMEM;

	    }

	    retval = lseek(bprm->fd, elf_ppnt->p_offset, SEEK_SET);

	    if(retval >= 0) {

		retval = read(bprm->fd, elf_interpreter, elf_ppnt->p_filesz);

	    }

	    if(retval < 0) {

	 	perror("load_elf_binary2");

		exit(-1);

	    }

	    /* If the program interpreter is one of these two,

	       then assume an iBCS2 image. Otherwise assume

	       a native linux image. */

	    /* JRP - Need to add X86 lib dir stuff here... */

	    if (strcmp(elf_interpreter,"/usr/lib/libc.so.1") == 0 ||

		strcmp(elf_interpreter,"/usr/lib/ld.so.1") == 0) {

	      ibcs2_interpreter = 1;

	    }

#if 0

	    printf("Using ELF interpreter %s\n", elf_interpreter);

#endif

	    if (retval >= 0) {

		retval = open(path(elf_interpreter), O_RDONLY);

		if(retval >= 0) {

		    interpreter_fd = retval;

		}

		else {

		    perror(elf_interpreter);

		    exit(-1);

		    /* retval = -errno; */

		}

	    }

	    if (retval >= 0) {

		retval = lseek(interpreter_fd, 0, SEEK_SET);

		if(retval >= 0) {

		    retval = read(interpreter_fd,bprm->buf,128);

		}

	    }

	    if (retval >= 0) {

		interp_ex = *((struct exec *) bprm->buf); /* aout exec-header */

		interp_elf_ex=*((struct elfhdr *) bprm->buf); /* elf exec-header */

	    }

	    if (retval < 0) {

		perror("load_elf_binary3");

		exit(-1);

		free (elf_phdata);

		free(elf_interpreter);

		close(bprm->fd);

		return retval;

	    }

	}

	elf_ppnt++;

    }

    /* Some simple consistency checks for the interpreter */

    if (elf_interpreter){

	interpreter_type = INTERPRETER_ELF | INTERPRETER_AOUT;

	/* Now figure out which format our binary is */

	if ((N_MAGIC(interp_ex) != OMAGIC) && (N_MAGIC(interp_ex) != ZMAGIC) &&

	    	(N_MAGIC(interp_ex) != QMAGIC)) {

	  interpreter_type = INTERPRETER_ELF;

	}

	if (interp_elf_ex.e_ident[0] != 0x7f ||

            strncmp((char *)&interp_elf_ex.e_ident[1], "ELF",3) != 0) {

	    interpreter_type &= ~INTERPRETER_ELF;

	}

	if (!interpreter_type) {

	    free(elf_interpreter);

	    free(elf_phdata);

	    close(bprm->fd);

	    return -ELIBBAD;

	}

    }

    /* OK, we are done with that, now set up the arg stuff,

       and then start this sucker up */

    {

	char * passed_p;

	if (interpreter_type == INTERPRETER_AOUT) {

	    snprintf(passed_fileno, sizeof(passed_fileno), "%d", bprm->fd);

	    passed_p = passed_fileno;

	    if (elf_interpreter) {

		bprm->p = copy_elf_strings(1,&passed_p,bprm->page,bprm->p);

		bprm->argc++;

	    }

	}

	if (!bprm->p) {

	    if (elf_interpreter) {

	        free(elf_interpreter);

	    }

	    free (elf_phdata);

	    close(bprm->fd);

	    return -E2BIG;

	}

    }

    /* OK, This is the point of no return */

    info->end_data = 0;

    info->end_code = 0;

    info->start_mmap = (abi_ulong)ELF_START_MMAP;

    info->mmap = 0;

    elf_entry = (abi_ulong) elf_ex.e_entry;

    /* Do this so that we can load the interpreter, if need be.  We will

       change some of these later */

    info->rss = 0;

    bprm->p = setup_arg_pages(bprm->p, bprm, info);

    info->start_stack = bprm->p;

    /* Now we do a little grungy work by mmaping the ELF image into

     * the correct location in memory.  At this point, we assume that

     * the image should be loaded at fixed address, not at a variable

     * address.

     */

    for(i = 0, elf_ppnt = elf_phdata; i < elf_ex.e_phnum; i++, elf_ppnt++) {

        int elf_prot = 0;

        int elf_flags = 0;

        abi_ulong error;

	if (elf_ppnt->p_type != PT_LOAD)

            continue;

        if (elf_ppnt->p_flags & PF_R) elf_prot |= PROT_READ;

        if (elf_ppnt->p_flags & PF_W) elf_prot |= PROT_WRITE;

        if (elf_ppnt->p_flags & PF_X) elf_prot |= PROT_EXEC;

        elf_flags = MAP_PRIVATE | MAP_DENYWRITE;

        if (elf_ex.e_type == ET_EXEC || load_addr_set) {

            elf_flags |= MAP_FIXED;

        } else if (elf_ex.e_type == ET_DYN) {

            /* Try and get dynamic programs out of the way of the default mmap

               base, as well as whatever program they might try to exec.  This

               is because the brk will follow the loader, and is not movable.  */

            /* NOTE: for qemu, we do a big mmap to get enough space

               without hardcoding any address */

            error = target_mmap(0, ET_DYN_MAP_SIZE,

                                PROT_NONE, MAP_PRIVATE | MAP_ANON,

                                -1, 0);

            if (error == -1) {

                perror("mmap");

                exit(-1);

            }

            load_bias = TARGET_ELF_PAGESTART(error - elf_ppnt->p_vaddr);

        }

        error = target_mmap(TARGET_ELF_PAGESTART(load_bias + elf_ppnt->p_vaddr),

                            (elf_ppnt->p_filesz +

                             TARGET_ELF_PAGEOFFSET(elf_ppnt->p_vaddr)),

                            elf_prot,

                            (MAP_FIXED | MAP_PRIVATE | MAP_DENYWRITE),

                            bprm->fd,

                            (elf_ppnt->p_offset -

                             TARGET_ELF_PAGEOFFSET(elf_ppnt->p_vaddr)));

        if (error == -1) {

            perror("mmap");

            exit(-1);

        }

#ifdef LOW_ELF_STACK

        if (TARGET_ELF_PAGESTART(elf_ppnt->p_vaddr) < elf_stack)

            elf_stack = TARGET_ELF_PAGESTART(elf_ppnt->p_vaddr);

#endif

        if (!load_addr_set) {

            load_addr_set = 1;

            load_addr = elf_ppnt->p_vaddr - elf_ppnt->p_offset;

            if (elf_ex.e_type == ET_DYN) {

                load_bias += error -

                    TARGET_ELF_PAGESTART(load_bias + elf_ppnt->p_vaddr);

                load_addr += load_bias;

                reloc_func_desc = load_bias;

            }

        }

        k = elf_ppnt->p_vaddr;

        if (k < start_code)

            start_code = k;

        if (start_data < k)

            start_data = k;

        k = elf_ppnt->p_vaddr + elf_ppnt->p_filesz;

        if (k > elf_bss)

            elf_bss = k;

        if ((elf_ppnt->p_flags & PF_X) && end_code <  k)

            end_code = k;

        if (end_data < k)

            end_data = k;

        k = elf_ppnt->p_vaddr + elf_ppnt->p_memsz;

        if (k > elf_brk) elf_brk = k;

    }

    elf_entry += load_bias;

    elf_bss += load_bias;

    elf_brk += load_bias;

    start_code += load_bias;

    end_code += load_bias;

    start_data += load_bias;

    end_data += load_bias;

    if (elf_interpreter) {

	if (interpreter_type & 1) {

	    elf_entry = load_aout_interp(&interp_ex, interpreter_fd);

	}

	else if (interpreter_type & 2) {

	    elf_entry = load_elf_interp(&interp_elf_ex, interpreter_fd,

					    &interp_load_addr);

	}

        reloc_func_desc = interp_load_addr;

	close(interpreter_fd);

	free(elf_interpreter);

	if (elf_entry == ~((abi_ulong)0UL)) {

	    printf("Unable to load interpreter\n");

	    free(elf_phdata);

	    exit(-1);

	    return 0;

	}

    }

    free(elf_phdata);

    if (loglevel)

	load_symbols(&elf_ex, bprm->fd);

    if (interpreter_type != INTERPRETER_AOUT) close(bprm->fd);

    info->personality = (ibcs2_interpreter ? PER_SVR4 : PER_LINUX);

#ifdef LOW_ELF_STACK

    info->start_stack = bprm->p = elf_stack - 4;

#endif

    bprm->p = create_elf_tables(bprm->p,

		    bprm->argc,

		    bprm->envc,

                    &elf_ex,

                    load_addr, load_bias,

		    interp_load_addr,

		    (interpreter_type == INTERPRETER_AOUT ? 0 : 1),

		    info);

    info->load_addr = reloc_func_desc;

    info->start_brk = info->brk = elf_brk;

    info->end_code = end_code;

    info->start_code = start_code;

    info->start_data = start_data;

    info->end_data = end_data;

    info->start_stack = bprm->p;

    /* Calling set_brk effectively mmaps the pages that we need for the bss and break

       sections */

    set_brk(elf_bss, elf_brk);

    padzero(elf_bss, elf_brk);

#if 0

    printf("(start_brk) %x\n" , info->start_brk);

    printf("(end_code) %x\n" , info->end_code);

    printf("(start_code) %x\n" , info->start_code);

    printf("(end_data) %x\n" , info->end_data);

    printf("(start_stack) %x\n" , info->start_stack);

    printf("(brk) %x\n" , info->brk);

#endif

    if ( info->personality == PER_SVR4 )

    {

	    /* Why this, you ask???  Well SVr4 maps page 0 as read-only,

	       and some applications "depend" upon this behavior.

	       Since we do not have the power to recompile these, we

	       emulate the SVr4 behavior.  Sigh.  */

	    mapped_addr = target_mmap(0, qemu_host_page_size, PROT_READ | PROT_EXEC,

                                      MAP_FIXED | MAP_PRIVATE, -1, 0);

    }

    info->entry = elf_entry;

    return 0;

}


static bool hyperv_enabled(X86CPU *cpu)

{

    CPUState *cs = CPU(cpu);

    return kvm_check_extension(cs->kvm_state, KVM_CAP_HYPERV) > 0 &&

           (hyperv_hypercall_available(cpu) ||

            cpu->hyperv_time  ||

            cpu->hyperv_relaxed_timing);

}


static void test_butterflies_float(const float *src0, const float *src1)

{

    LOCAL_ALIGNED_16(float,  cdst,  [LEN]);

    LOCAL_ALIGNED_16(float,  odst,  [LEN]);

    LOCAL_ALIGNED_16(float,  cdst1, [LEN]);

    LOCAL_ALIGNED_16(float,  odst1, [LEN]);

    int i;

    declare_func(void, float *av_restrict src0, float *av_restrict src1,

    int len);

    memcpy(cdst,  src0, LEN * sizeof(*src0));

    memcpy(cdst1, src1, LEN * sizeof(*src1));

    memcpy(odst,  src0, LEN * sizeof(*src0));

    memcpy(odst1, src1, LEN * sizeof(*src1));

    call_ref(cdst, cdst1, LEN);

    call_new(odst, odst1, LEN);

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

        if (!float_near_abs_eps(cdst[i], odst[i], FLT_EPSILON)) {

            fprintf(stderr, "%d: %- .12f - %- .12f = % .12g\n",

                    i, cdst[i], odst[i], cdst[i] - odst[i]);

            fail();

            break;

        }

    }

    memcpy(odst,  src0, LEN * sizeof(*src0));

    memcpy(odst1, src1, LEN * sizeof(*src1));

    bench_new(odst, odst1, LEN);

}


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) {

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

            wav->smv_last_stream = wav->smv_given_first ?

                av_compare_ts(video_dts, s->streams[1]->time_base,

                              audio_dts, s->streams[0]->time_base) > 0 : 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;

}


int ff_new_chapter(AVFormatContext *s, int id, int64_t start, int64_t end, const char *title)

{

    AVChapter *chapter = NULL;

    int i;

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

        if(s->chapters[i]->id == id)

            chapter = s->chapters[i];

    if(!chapter){

        chapter= av_mallocz(sizeof(AVChapter));

        if(!chapter)

            return AVERROR(ENOMEM);

        dynarray_add(&s->chapters, &s->num_chapters, chapter);

    }

    if(chapter->title)

        av_free(chapter->title);

    if (title)

        chapter->title = av_strdup(title);

    chapter->id    = id;

    chapter->start = start;

    chapter->end = end;

    return 0;

}


static int flic_decode_frame_8BPP(AVCodecContext *avctx,

                                  void *data, int *got_frame,

                                  const uint8_t *buf, int buf_size)

{

    FlicDecodeContext *s = avctx->priv_data;

    GetByteContext g2;

    int pixel_ptr;

    int palette_ptr;

    unsigned char palette_idx1;

    unsigned char palette_idx2;

    unsigned int frame_size;

    int num_chunks;

    unsigned int chunk_size;

    int chunk_type;

    int i, j, ret;

    int color_packets;

    int color_changes;

    int color_shift;

    unsigned char r, g, b;

    int lines;

    int compressed_lines;

    int starting_line;

    signed short line_packets;

    int y_ptr;

    int byte_run;

    int pixel_skip;

    int pixel_countdown;

    unsigned char *pixels;

    unsigned int pixel_limit;

    bytestream2_init(&g2, buf, buf_size);

    if ((ret = ff_reget_buffer(avctx, &s->frame)) < 0)

        return ret;

    pixels = s->frame.data[0];

    pixel_limit = s->avctx->height * s->frame.linesize[0];

    if (buf_size < 16 || buf_size > INT_MAX - (3 * 256 + FF_INPUT_BUFFER_PADDING_SIZE))

        return AVERROR_INVALIDDATA;

    frame_size = bytestream2_get_le32(&g2);

    if (frame_size > buf_size)

        frame_size = buf_size;

    bytestream2_skip(&g2, 2); /* skip the magic number */

    num_chunks = bytestream2_get_le16(&g2);

    bytestream2_skip(&g2, 8);  /* skip padding */

    frame_size -= 16;

    /* iterate through the chunks */

    while ((frame_size >= 6) && (num_chunks > 0)) {

        int stream_ptr_after_chunk;

        chunk_size = bytestream2_get_le32(&g2);

        if (chunk_size > frame_size) {

            av_log(avctx, AV_LOG_WARNING,

                   "Invalid chunk_size = %u > frame_size = %u\n", chunk_size, frame_size);

            chunk_size = frame_size;

        }

        stream_ptr_after_chunk = bytestream2_tell(&g2) - 4 + chunk_size;

        chunk_type = bytestream2_get_le16(&g2);

        switch (chunk_type) {

        case FLI_256_COLOR:

        case FLI_COLOR:

            /* check special case: If this file is from the Magic Carpet

             * game and uses 6-bit colors even though it reports 256-color

             * chunks in a 0xAF12-type file (fli_type is set to 0xAF13 during

             * initialization) */

            if ((chunk_type == FLI_256_COLOR) && (s->fli_type != FLC_MAGIC_CARPET_SYNTHETIC_TYPE_CODE))

                color_shift = 0;

            else

                color_shift = 2;

            /* set up the palette */

            color_packets = bytestream2_get_le16(&g2);

            palette_ptr = 0;

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

                /* first byte is how many colors to skip */

                palette_ptr += bytestream2_get_byte(&g2);

                /* next byte indicates how many entries to change */

                color_changes = bytestream2_get_byte(&g2);

                /* if there are 0 color changes, there are actually 256 */

                if (color_changes == 0)

                    color_changes = 256;

                if (bytestream2_tell(&g2) + color_changes * 3 > stream_ptr_after_chunk)

                    break;

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

                    unsigned int entry;

                    /* wrap around, for good measure */

                    if ((unsigned)palette_ptr >= 256)

                        palette_ptr = 0;

                    r = bytestream2_get_byte(&g2) << color_shift;

                    g = bytestream2_get_byte(&g2) << color_shift;

                    b = bytestream2_get_byte(&g2) << color_shift;

                    entry = 0xFFU << 24 | r << 16 | g << 8 | b;

                    if (color_shift == 2)

                        entry |= entry >> 6 & 0x30303;

                    if (s->palette[palette_ptr] != entry)

                        s->new_palette = 1;

                    s->palette[palette_ptr++] = entry;

                }

            }

            break;

        case FLI_DELTA:

            y_ptr = 0;

            compressed_lines = bytestream2_get_le16(&g2);

            while (compressed_lines > 0) {

                if (bytestream2_tell(&g2) + 2 > stream_ptr_after_chunk)

                    break;

                line_packets = bytestream2_get_le16(&g2);

                if ((line_packets & 0xC000) == 0xC000) {

                    // line skip opcode

                    line_packets = -line_packets;

                    y_ptr += line_packets * s->frame.linesize[0];

                } else if ((line_packets & 0xC000) == 0x4000) {

                    av_log(avctx, AV_LOG_ERROR, "Undefined opcode (%x) in DELTA_FLI\n", line_packets);

                } else if ((line_packets & 0xC000) == 0x8000) {

                    // "last byte" opcode

                    pixel_ptr= y_ptr + s->frame.linesize[0] - 1;

                    CHECK_PIXEL_PTR(0);

                    pixels[pixel_ptr] = line_packets & 0xff;

                } else {

                    compressed_lines--;

                    pixel_ptr = y_ptr;

                    CHECK_PIXEL_PTR(0);

                    pixel_countdown = s->avctx->width;

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

                        if (bytestream2_tell(&g2) + 2 > stream_ptr_after_chunk)

                            break;

                        /* account for the skip bytes */

                        pixel_skip = bytestream2_get_byte(&g2);

                        pixel_ptr += pixel_skip;

                        pixel_countdown -= pixel_skip;

                        byte_run = sign_extend(bytestream2_get_byte(&g2), 8);

                        if (byte_run < 0) {

                            byte_run = -byte_run;

                            palette_idx1 = bytestream2_get_byte(&g2);

                            palette_idx2 = bytestream2_get_byte(&g2);

                            CHECK_PIXEL_PTR(byte_run * 2);

                            for (j = 0; j < byte_run; j++, pixel_countdown -= 2) {

                                pixels[pixel_ptr++] = palette_idx1;

                                pixels[pixel_ptr++] = palette_idx2;

                            }

                        } else {

                            CHECK_PIXEL_PTR(byte_run * 2);

                            if (bytestream2_tell(&g2) + byte_run * 2 > stream_ptr_after_chunk)

                                break;

                            for (j = 0; j < byte_run * 2; j++, pixel_countdown--) {

                                pixels[pixel_ptr++] = bytestream2_get_byte(&g2);

                            }

                        }

                    }

                    y_ptr += s->frame.linesize[0];

                }

            }

            break;

        case FLI_LC:

            /* line compressed */

            starting_line = bytestream2_get_le16(&g2);

            y_ptr = 0;

            y_ptr += starting_line * s->frame.linesize[0];

            compressed_lines = bytestream2_get_le16(&g2);

            while (compressed_lines > 0) {

                pixel_ptr = y_ptr;

                CHECK_PIXEL_PTR(0);

                pixel_countdown = s->avctx->width;

                if (bytestream2_tell(&g2) + 1 > stream_ptr_after_chunk)

                    break;

                line_packets = bytestream2_get_byte(&g2);

                if (line_packets > 0) {

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

                        /* account for the skip bytes */

                        if (bytestream2_tell(&g2) + 1 > stream_ptr_after_chunk)

                            break;

                        pixel_skip = bytestream2_get_byte(&g2);

                        pixel_ptr += pixel_skip;

                        pixel_countdown -= pixel_skip;

                        byte_run = sign_extend(bytestream2_get_byte(&g2),8);

                        if (byte_run > 0) {

                            CHECK_PIXEL_PTR(byte_run);

                            if (bytestream2_tell(&g2) + byte_run > stream_ptr_after_chunk)

                                break;

                            for (j = 0; j < byte_run; j++, pixel_countdown--) {

                                pixels[pixel_ptr++] = bytestream2_get_byte(&g2);

                            }

                        } else if (byte_run < 0) {

                            byte_run = -byte_run;

                            palette_idx1 = bytestream2_get_byte(&g2);

                            CHECK_PIXEL_PTR(byte_run);

                            for (j = 0; j < byte_run; j++, pixel_countdown--) {

                                pixels[pixel_ptr++] = palette_idx1;

                            }

                        }

                    }

                }

                y_ptr += s->frame.linesize[0];

                compressed_lines--;

            }

            break;

        case FLI_BLACK:

            /* set the whole frame to color 0 (which is usually black) */

            memset(pixels, 0,

                s->frame.linesize[0] * s->avctx->height);

            break;

        case FLI_BRUN:

            /* Byte run compression: This chunk type only occurs in the first

             * FLI frame and it will update the entire frame. */

            y_ptr = 0;

            for (lines = 0; lines < s->avctx->height; lines++) {

                pixel_ptr = y_ptr;

                /* disregard the line packets; instead, iterate through all

                 * pixels on a row */

                 bytestream2_skip(&g2, 1);

                pixel_countdown = s->avctx->width;

                while (pixel_countdown > 0) {

                    if (bytestream2_tell(&g2) + 1 > stream_ptr_after_chunk)

                        break;

                    byte_run = sign_extend(bytestream2_get_byte(&g2), 8);

                    if (!byte_run) {

                        av_log(avctx, AV_LOG_ERROR, "Invalid byte run value.\n");

                        return AVERROR_INVALIDDATA;

                    }

                    if (byte_run > 0) {

                        palette_idx1 = bytestream2_get_byte(&g2);

                        CHECK_PIXEL_PTR(byte_run);

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

                            pixels[pixel_ptr++] = palette_idx1;

                            pixel_countdown--;

                            if (pixel_countdown < 0)

                                av_log(avctx, AV_LOG_ERROR, "pixel_countdown < 0 (%d) at line %d\n",

                                       pixel_countdown, lines);

                        }

                    } else {  /* copy bytes if byte_run < 0 */

                        byte_run = -byte_run;

                        CHECK_PIXEL_PTR(byte_run);

                        if (bytestream2_tell(&g2) + byte_run > stream_ptr_after_chunk)

                            break;

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

                            pixels[pixel_ptr++] = bytestream2_get_byte(&g2);

                            pixel_countdown--;

                            if (pixel_countdown < 0)

                                av_log(avctx, AV_LOG_ERROR, "pixel_countdown < 0 (%d) at line %d\n",

                                       pixel_countdown, lines);

                        }

                    }

                }

                y_ptr += s->frame.linesize[0];

            }

            break;

        case FLI_COPY:

            /* copy the chunk (uncompressed frame) */

            if (chunk_size - 6 != s->avctx->width * s->avctx->height) {

                av_log(avctx, AV_LOG_ERROR, "In chunk FLI_COPY : source data (%d bytes) " \

                       "has incorrect size, skipping chunk\n", chunk_size - 6);

                bytestream2_skip(&g2, chunk_size - 6);

            } else {

                for (y_ptr = 0; y_ptr < s->frame.linesize[0] * s->avctx->height;

                     y_ptr += s->frame.linesize[0]) {

                    bytestream2_get_buffer(&g2, &pixels[y_ptr],

                                           s->avctx->width);

                }

            }

            break;

        case FLI_MINI:

            /* some sort of a thumbnail? disregard this chunk... */

            break;

        default:

            av_log(avctx, AV_LOG_ERROR, "Unrecognized chunk type: %d\n", chunk_type);

            break;

        }

        if (stream_ptr_after_chunk - bytestream2_tell(&g2) > 0)

            bytestream2_skip(&g2, stream_ptr_after_chunk - bytestream2_tell(&g2));

        frame_size -= chunk_size;

        num_chunks--;

    }

    /* by the end of the chunk, the stream ptr should equal the frame

     * size (minus 1 or 2, possibly); if it doesn't, issue a warning */

    if (bytestream2_get_bytes_left(&g2) > 2)

        av_log(avctx, AV_LOG_ERROR, "Processed FLI chunk where chunk size = %d " \

               "and final chunk ptr = %d\n", buf_size,

               buf_size - bytestream2_get_bytes_left(&g2));

    /* make the palette available on the way out */

    memcpy(s->frame.data[1], s->palette, AVPALETTE_SIZE);

    if (s->new_palette) {

        s->frame.palette_has_changed = 1;

        s->new_palette = 0;

    }

    if ((ret = av_frame_ref(data, &s->frame)) < 0)

        return ret;

    *got_frame = 1;

    return buf_size;

}


static int armv7m_nvic_init(SysBusDevice *dev)

{

    nvic_state *s = NVIC(dev);

    NVICClass *nc = NVIC_GET_CLASS(s);

    /* The NVIC always has only one CPU */

    s->gic.num_cpu = 1;

    /* Tell the common code we're an NVIC */

    s->gic.revision = 0xffffffff;

    s->num_irq = s->gic.num_irq;

    nc->parent_init(dev);

    gic_init_irqs_and_distributor(&s->gic, s->num_irq);

    /* The NVIC and system controller register area looks like this:

     *  0..0xff : system control registers, including systick

     *  0x100..0xcff : GIC-like registers

     *  0xd00..0xfff : system control registers

     * We use overlaying to put the GIC like registers

     * over the top of the system control register region.

     */

    memory_region_init(&s->container, "nvic", 0x1000);

    /* The system register region goes at the bottom of the priority

     * stack as it covers the whole page.

     */

    memory_region_init_io(&s->sysregmem, &nvic_sysreg_ops, s,

                          "nvic_sysregs", 0x1000);

    memory_region_add_subregion(&s->container, 0, &s->sysregmem);

    /* Alias the GIC region so we can get only the section of it

     * we need, and layer it on top of the system register region.

     */

    memory_region_init_alias(&s->gic_iomem_alias, "nvic-gic", &s->gic.iomem,

                             0x100, 0xc00);

    memory_region_add_subregion_overlap(&s->container, 0x100,

                                        &s->gic_iomem_alias, 1);

    /* Map the whole thing into system memory at the location required

     * by the v7M architecture.

     */

    memory_region_add_subregion(get_system_memory(), 0xe000e000, &s->container);

    s->systick.timer = qemu_new_timer_ns(vm_clock, systick_timer_tick, s);

    return 0;

}


static void nfs_co_generic_bh_cb(void *opaque)

{

    NFSRPC *task = opaque;

    task->complete = 1;

    qemu_bh_delete(task->bh);

    qemu_coroutine_enter(task->co, NULL);

}


static void vnc_resize(VncState *vs)

{

    DisplayState *ds = vs->ds;

    int size_changed;

    vs->old_data = qemu_realloc(vs->old_data, ds_get_linesize(ds) * ds_get_height(ds));

    if (vs->old_data == NULL) {

        fprintf(stderr, "vnc: memory allocation failed\n");

        exit(1);

    }

    if (ds_get_bytes_per_pixel(ds) != vs->serverds.pf.bytes_per_pixel)

        console_color_init(ds);

    vnc_colordepth(vs);

    size_changed = ds_get_width(ds) != vs->serverds.width ||

                   ds_get_height(ds) != vs->serverds.height;

    vs->serverds = *(ds->surface);

    if (size_changed) {

        if (vs->csock != -1 && vnc_has_feature(vs, VNC_FEATURE_RESIZE)) {

            vnc_write_u8(vs, 0);  /* msg id */

            vnc_write_u8(vs, 0);

            vnc_write_u16(vs, 1); /* number of rects */

            vnc_framebuffer_update(vs, 0, 0, ds_get_width(ds), ds_get_height(ds),

                                   VNC_ENCODING_DESKTOPRESIZE);

            vnc_flush(vs);

        }

    }

    memset(vs->dirty_row, 0xFF, sizeof(vs->dirty_row));

    memset(vs->old_data, 42, ds_get_linesize(vs->ds) * ds_get_height(vs->ds));

}


e1000_can_receive(VLANClientState *nc)

{

    E1000State *s = DO_UPCAST(NICState, nc, nc)->opaque;

    return (s->mac_reg[RCTL] & E1000_RCTL_EN);

}


static void access_with_adjusted_size(hwaddr addr,

                                      uint64_t *value,

                                      unsigned size,

                                      unsigned access_size_min,

                                      unsigned access_size_max,

                                      void (*access)(MemoryRegion *mr,

                                                     hwaddr addr,

                                                     uint64_t *value,

                                                     unsigned size,

                                                     unsigned shift,

                                                     uint64_t mask),

                                      MemoryRegion *mr)

{

    uint64_t access_mask;

    unsigned access_size;

    unsigned i;

    if (!access_size_min) {

        access_size_min = 1;

    }

    if (!access_size_max) {

        access_size_max = 4;

    }

    /* FIXME: support unaligned access? */

    access_size = MAX(MIN(size, access_size_max), access_size_min);

    access_mask = -1ULL >> (64 - access_size * 8);

    if (memory_region_big_endian(mr)) {

        for (i = 0; i < size; i += access_size) {

            access(mr, addr + i, value, access_size,

                   (size - access_size - i) * 8, access_mask);

        }

    } else {

        for (i = 0; i < size; i += access_size) {

            access(mr, addr + i, value, access_size, i * 8, access_mask);

        }

    }

}


static void drive_uninit(DriveInfo *dinfo)

{

    qemu_opts_del(dinfo->opts);

    bdrv_delete(dinfo->bdrv);

    QTAILQ_REMOVE(&drives, dinfo, next);

    qemu_free(dinfo);

}


static void mpeg_decode_sequence_extension(Mpeg1Context *s1)

{

    MpegEncContext *s = &s1->mpeg_enc_ctx;

    int horiz_size_ext, vert_size_ext;

    int bit_rate_ext;

    skip_bits(&s->gb, 1); /* profile and level esc*/

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

    s->avctx->level         = get_bits(&s->gb, 4);

    s->progressive_sequence = get_bits1(&s->gb);   /* progressive_sequence */

    s->chroma_format        = get_bits(&s->gb, 2); /* chroma_format 1=420, 2=422, 3=444 */

    if (!s->chroma_format) {

        s->chroma_format = 1;

        av_log(s->avctx, AV_LOG_WARNING, "Chroma format invalid\n");

    }

    horiz_size_ext          = get_bits(&s->gb, 2);

    vert_size_ext           = get_bits(&s->gb, 2);

    s->width  |= (horiz_size_ext << 12);

    s->height |= (vert_size_ext  << 12);

    bit_rate_ext = get_bits(&s->gb, 12);  /* XXX: handle it */

    s->bit_rate += (bit_rate_ext << 18) * 400;

    check_marker(&s->gb, "after bit rate extension");

    s->avctx->rc_buffer_size += get_bits(&s->gb, 8) * 1024 * 16 << 10;

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

    if (s->avctx->flags & AV_CODEC_FLAG_LOW_DELAY)

        s->low_delay = 1;

    s1->frame_rate_ext.num = get_bits(&s->gb, 2) + 1;

    s1->frame_rate_ext.den = get_bits(&s->gb, 5) + 1;

    ff_dlog(s->avctx, "sequence extension\n");

    s->codec_id = s->avctx->codec_id = AV_CODEC_ID_MPEG2VIDEO;

    if (s->avctx->debug & FF_DEBUG_PICT_INFO)

        av_log(s->avctx, AV_LOG_DEBUG,

               "profile: %d, level: %d ps: %d cf:%d vbv buffer: %d, bitrate:%"PRId64"\n",

               s->avctx->profile, s->avctx->level, s->progressive_sequence, s->chroma_format,

               s->avctx->rc_buffer_size, s->bit_rate);

}


static void get_pixels_altivec(int16_t *restrict block, const uint8_t *pixels, int line_size)

{

    int i;

    vector unsigned char perm = vec_lvsl(0, pixels);

    vector unsigned char bytes;

    const vector unsigned char zero = (const vector unsigned char)vec_splat_u8(0);

    vector signed short shorts;

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

        // Read potentially unaligned pixels.

        // We're reading 16 pixels, and actually only want 8,

        // but we simply ignore the extras.

        vector unsigned char pixl = vec_ld( 0, pixels);

        vector unsigned char pixr = vec_ld(15, pixels);

        bytes = vec_perm(pixl, pixr, perm);

        // convert the bytes into shorts

        shorts = (vector signed short)vec_mergeh(zero, bytes);

        // save the data to the block, we assume the block is 16-byte aligned

        vec_st(shorts, i*16, (vector signed short*)block);

        pixels += line_size;

    }

}


static void pc_q35_init_1_5(QEMUMachineInitArgs *args)

{

    has_pci_info = false;

    pc_q35_init(args);

}


static int sap_write_close(AVFormatContext *s)

{

    struct SAPState *sap = s->priv_data;

    int i;

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

        AVFormatContext *rtpctx = s->streams[i]->priv_data;

        if (!rtpctx)

            continue;

        av_write_trailer(rtpctx);

        url_fclose(rtpctx->pb);

        av_metadata_free(&rtpctx->streams[0]->metadata);

        av_metadata_free(&rtpctx->metadata);

        av_free(rtpctx->streams[0]);

        av_free(rtpctx);

        s->streams[i]->priv_data = NULL;

    }

    if (sap->last_time && sap->ann && sap->ann_fd) {

        sap->ann[0] |= 4; /* Session deletion*/

        url_write(sap->ann_fd, sap->ann, sap->ann_size);

    }

    av_freep(&sap->ann);

    if (sap->ann_fd)

        url_close(sap->ann_fd);

    ff_network_close();

    return 0;

}


void ahci_hba_enable(AHCIQState *ahci)

{

    /* Bits of interest in this section:

     * GHC.AE     Global Host Control / AHCI Enable

     * PxCMD.ST   Port Command: Start

     * PxCMD.SUD  "Spin Up Device"

     * PxCMD.POD  "Power On Device"

     * PxCMD.FRE  "FIS Receive Enable"

     * PxCMD.FR   "FIS Receive Running"

     * PxCMD.CR   "Command List Running"

     */

    uint32_t reg, ports_impl;

    uint16_t i;

    uint8_t num_cmd_slots;

    g_assert(ahci != NULL);

    /* Set GHC.AE to 1 */

    ahci_set(ahci, AHCI_GHC, AHCI_GHC_AE);

    reg = ahci_rreg(ahci, AHCI_GHC);

    ASSERT_BIT_SET(reg, AHCI_GHC_AE);

    /* Cache CAP and CAP2. */

    ahci->cap = ahci_rreg(ahci, AHCI_CAP);

    ahci->cap2 = ahci_rreg(ahci, AHCI_CAP2);

    /* Read CAP.NCS, how many command slots do we have? */

    num_cmd_slots = ((ahci->cap & AHCI_CAP_NCS) >> ctzl(AHCI_CAP_NCS)) + 1;

    g_test_message("Number of Command Slots: %u", num_cmd_slots);

    /* Determine which ports are implemented. */

    ports_impl = ahci_rreg(ahci, AHCI_PI);

    for (i = 0; ports_impl; ports_impl >>= 1, ++i) {

        if (!(ports_impl & 0x01)) {

            continue;

        }

        g_test_message("Initializing port %u", i);

        reg = ahci_px_rreg(ahci, i, AHCI_PX_CMD);

        if (BITCLR(reg, AHCI_PX_CMD_ST | AHCI_PX_CMD_CR |

                   AHCI_PX_CMD_FRE | AHCI_PX_CMD_FR)) {

            g_test_message("port is idle");

        } else {

            g_test_message("port needs to be idled");

            ahci_px_clr(ahci, i, AHCI_PX_CMD,

                        (AHCI_PX_CMD_ST | AHCI_PX_CMD_FRE));

            /* The port has 500ms to disengage. */

            usleep(500000);

            reg = ahci_px_rreg(ahci, i, AHCI_PX_CMD);

            ASSERT_BIT_CLEAR(reg, AHCI_PX_CMD_CR);

            ASSERT_BIT_CLEAR(reg, AHCI_PX_CMD_FR);

            g_test_message("port is now idle");

            /* The spec does allow for possibly needing a PORT RESET

             * or HBA reset if we fail to idle the port. */

        }

        /* Allocate Memory for the Command List Buffer & FIS Buffer */

        /* PxCLB space ... 0x20 per command, as in 4.2.2 p 36 */

        ahci->port[i].clb = ahci_alloc(ahci, num_cmd_slots * 0x20);

        qmemset(ahci->port[i].clb, 0x00, num_cmd_slots * 0x20);

        g_test_message("CLB: 0x%08" PRIx64, ahci->port[i].clb);

        ahci_px_wreg(ahci, i, AHCI_PX_CLB, ahci->port[i].clb);

        g_assert_cmphex(ahci->port[i].clb, ==,

                        ahci_px_rreg(ahci, i, AHCI_PX_CLB));

        /* PxFB space ... 0x100, as in 4.2.1 p 35 */

        ahci->port[i].fb = ahci_alloc(ahci, 0x100);

        qmemset(ahci->port[i].fb, 0x00, 0x100);

        g_test_message("FB: 0x%08" PRIx64, ahci->port[i].fb);

        ahci_px_wreg(ahci, i, AHCI_PX_FB, ahci->port[i].fb);

        g_assert_cmphex(ahci->port[i].fb, ==,

                        ahci_px_rreg(ahci, i, AHCI_PX_FB));

        /* Clear PxSERR, PxIS, then IS.IPS[x] by writing '1's. */

        ahci_px_wreg(ahci, i, AHCI_PX_SERR, 0xFFFFFFFF);

        ahci_px_wreg(ahci, i, AHCI_PX_IS, 0xFFFFFFFF);

        ahci_wreg(ahci, AHCI_IS, (1 << i));

        /* Verify Interrupts Cleared */

        reg = ahci_px_rreg(ahci, i, AHCI_PX_SERR);

        g_assert_cmphex(reg, ==, 0);

        reg = ahci_px_rreg(ahci, i, AHCI_PX_IS);

        g_assert_cmphex(reg, ==, 0);

        reg = ahci_rreg(ahci, AHCI_IS);

        ASSERT_BIT_CLEAR(reg, (1 << i));

        /* Enable All Interrupts: */

        ahci_px_wreg(ahci, i, AHCI_PX_IE, 0xFFFFFFFF);

        reg = ahci_px_rreg(ahci, i, AHCI_PX_IE);

        g_assert_cmphex(reg, ==, ~((uint32_t)AHCI_PX_IE_RESERVED));

        /* Enable the FIS Receive Engine. */

        ahci_px_set(ahci, i, AHCI_PX_CMD, AHCI_PX_CMD_FRE);

        reg = ahci_px_rreg(ahci, i, AHCI_PX_CMD);

        ASSERT_BIT_SET(reg, AHCI_PX_CMD_FR);

        /* AHCI 1.3 spec: if !STS.BSY, !STS.DRQ and PxSSTS.DET indicates

         * physical presence, a device is present and may be started. However,

         * PxSERR.DIAG.X /may/ need to be cleared a priori. */

        reg = ahci_px_rreg(ahci, i, AHCI_PX_SERR);

        if (BITSET(reg, AHCI_PX_SERR_DIAG_X)) {

            ahci_px_set(ahci, i, AHCI_PX_SERR, AHCI_PX_SERR_DIAG_X);

        }

        reg = ahci_px_rreg(ahci, i, AHCI_PX_TFD);

        if (BITCLR(reg, AHCI_PX_TFD_STS_BSY | AHCI_PX_TFD_STS_DRQ)) {

            reg = ahci_px_rreg(ahci, i, AHCI_PX_SSTS);

            if ((reg & AHCI_PX_SSTS_DET) == SSTS_DET_ESTABLISHED) {

                /* Device Found: set PxCMD.ST := 1 */

                ahci_px_set(ahci, i, AHCI_PX_CMD, AHCI_PX_CMD_ST);

                ASSERT_BIT_SET(ahci_px_rreg(ahci, i, AHCI_PX_CMD),

                               AHCI_PX_CMD_CR);

                g_test_message("Started Device %u", i);

            } else if ((reg & AHCI_PX_SSTS_DET)) {

                /* Device present, but in some unknown state. */

                g_assert_not_reached();

            }

        }

    }

    /* Enable GHC.IE */

    ahci_set(ahci, AHCI_GHC, AHCI_GHC_IE);

    reg = ahci_rreg(ahci, AHCI_GHC);

    ASSERT_BIT_SET(reg, AHCI_GHC_IE);

    /* TODO: The device should now be idling and waiting for commands.

     * In the future, a small test-case to inspect the Register D2H FIS

     * and clear the initial interrupts might be good. */

}


static void ppc6xx_set_irq (void *opaque, int pin, int level)

{

    CPUState *env = opaque;

    int cur_level;

#if defined(PPC_DEBUG_IRQ)

    if (loglevel & CPU_LOG_INT) {

        fprintf(logfile, "%s: env %p pin %d level %d\n", __func__,

                env, pin, level);

    }

#endif

    cur_level = (env->irq_input_state >> pin) & 1;

    /* Don't generate spurious events */

    if ((cur_level == 1 && level == 0) || (cur_level == 0 && level != 0)) {

        switch (pin) {

        case PPC6xx_INPUT_TBEN:

            /* Level sensitive - active high */

#if defined(PPC_DEBUG_IRQ)

            if (loglevel & CPU_LOG_INT) {

                fprintf(logfile, "%s: %s the time base\n",

                        __func__, level ? "start" : "stop");

            }

#endif

            if (level) {

                cpu_ppc_tb_start(env);

            } else {

                cpu_ppc_tb_stop(env);

            }

        case PPC6xx_INPUT_INT:

            /* Level sensitive - active high */

#if defined(PPC_DEBUG_IRQ)

            if (loglevel & CPU_LOG_INT) {

                fprintf(logfile, "%s: set the external IRQ state to %d\n",

                        __func__, level);

            }

#endif

            ppc_set_irq(env, PPC_INTERRUPT_EXT, level);

            break;

        case PPC6xx_INPUT_SMI:

            /* Level sensitive - active high */

#if defined(PPC_DEBUG_IRQ)

            if (loglevel & CPU_LOG_INT) {

                fprintf(logfile, "%s: set the SMI IRQ state to %d\n",

                        __func__, level);

            }

#endif

            ppc_set_irq(env, PPC_INTERRUPT_SMI, level);

            break;

        case PPC6xx_INPUT_MCP:

            /* Negative edge sensitive */

            /* XXX: TODO: actual reaction may depends on HID0 status

             *            603/604/740/750: check HID0[EMCP]

             */

            if (cur_level == 1 && level == 0) {

#if defined(PPC_DEBUG_IRQ)

                if (loglevel & CPU_LOG_INT) {

                    fprintf(logfile, "%s: raise machine check state\n",

                            __func__);

                }

#endif

                ppc_set_irq(env, PPC_INTERRUPT_MCK, 1);

            }

            break;

        case PPC6xx_INPUT_CKSTP_IN:

            /* Level sensitive - active low */

            /* XXX: TODO: relay the signal to CKSTP_OUT pin */

            /* XXX: Note that the only way to restart the CPU is to reset it */

            if (level) {

#if defined(PPC_DEBUG_IRQ)

                if (loglevel & CPU_LOG_INT) {

                    fprintf(logfile, "%s: stop the CPU\n", __func__);

                }

#endif

                env->halted = 1;

            }

            break;

        case PPC6xx_INPUT_HRESET:

            /* Level sensitive - active low */

            if (level) {

#if 0 // XXX: TOFIX

#if defined(PPC_DEBUG_IRQ)

                if (loglevel & CPU_LOG_INT) {

                    fprintf(logfile, "%s: reset the CPU\n", __func__);

                }

#endif

                cpu_reset(env);

#endif

            }

            break;

        case PPC6xx_INPUT_SRESET:

#if defined(PPC_DEBUG_IRQ)

            if (loglevel & CPU_LOG_INT) {

                fprintf(logfile, "%s: set the RESET IRQ state to %d\n",

                        __func__, level);

            }

#endif

            ppc_set_irq(env, PPC_INTERRUPT_RESET, level);

            break;

        default:

            /* Unknown pin - do nothing */

#if defined(PPC_DEBUG_IRQ)

            if (loglevel & CPU_LOG_INT) {

                fprintf(logfile, "%s: unknown IRQ pin %d\n", __func__, pin);

            }

#endif

            return;

        }

        if (level)

            env->irq_input_state |= 1 << pin;

        else

            env->irq_input_state &= ~(1 << pin);

    }

}


static void do_order_test(void)

{

    Coroutine *co;

    co = qemu_coroutine_create(co_order_test);

    record_push(1, 1);

    qemu_coroutine_enter(co, NULL);

    record_push(1, 2);

    g_assert(!qemu_in_coroutine());

    qemu_coroutine_enter(co, NULL);

    record_push(1, 3);

    g_assert(!qemu_in_coroutine());

}


static int get_cod(Jpeg2000DecoderContext *s, Jpeg2000CodingStyle *c,

                   uint8_t *properties)

{

    Jpeg2000CodingStyle tmp;

    int compno;

    if (s->buf_end - s->buf < 5)

        return AVERROR_INVALIDDATA;

    tmp.log2_prec_width  =

    tmp.log2_prec_height = 15;

    tmp.csty = bytestream_get_byte(&s->buf);

    // get progression order

    tmp.prog_order = bytestream_get_byte(&s->buf);

    tmp.nlayers = bytestream_get_be16(&s->buf);

    tmp.mct     = bytestream_get_byte(&s->buf); // multiple component transformation

    get_cox(s, &tmp);

    for (compno = 0; compno < s->ncomponents; compno++)

        if (!(properties[compno] & HAD_COC))

            memcpy(c + compno, &tmp, sizeof(tmp));

    return 0;

}


static void qtest_process_command(CharDriverState *chr, gchar **words)

{

    const gchar *command;

    g_assert(words);

    command = words[0];

    if (qtest_log_fp) {

        qemu_timeval tv;

        int i;

        qtest_get_time(&tv);

        fprintf(qtest_log_fp, "[R +" FMT_timeval "]",

                (long) tv.tv_sec, (long) tv.tv_usec);

        for (i = 0; words[i]; i++) {

            fprintf(qtest_log_fp, " %s", words[i]);

        }

        fprintf(qtest_log_fp, "\n");

    }

    g_assert(command);

    if (strcmp(words[0], "irq_intercept_out") == 0

        || strcmp(words[0], "irq_intercept_in") == 0) {

        DeviceState *dev;

        NamedGPIOList *ngl;

        g_assert(words[1]);

        dev = DEVICE(object_resolve_path(words[1], NULL));

        if (!dev) {

            qtest_send_prefix(chr);

            qtest_send(chr, "FAIL Unknown device\n");

	    return;

        }

        if (irq_intercept_dev) {

            qtest_send_prefix(chr);

            if (irq_intercept_dev != dev) {

                qtest_send(chr, "FAIL IRQ intercept already enabled\n");

            } else {

                qtest_send(chr, "OK\n");

            }

	    return;

        }

        QLIST_FOREACH(ngl, &dev->gpios, node) {

            /* We don't support intercept of named GPIOs yet */

            if (ngl->name) {

                continue;

            }

            if (words[0][14] == 'o') {

                int i;

                for (i = 0; i < ngl->num_out; ++i) {

                    qemu_irq *disconnected = g_new0(qemu_irq, 1);

                    qemu_irq icpt = qemu_allocate_irq(qtest_irq_handler,

                                                      disconnected, i);

                    *disconnected = qdev_intercept_gpio_out(dev, icpt,

                                                            ngl->name, i);

                }

            } else {

                qemu_irq_intercept_in(ngl->in, qtest_irq_handler,

                                      ngl->num_in);

            }

        }

        irq_intercept_dev = dev;

        qtest_send_prefix(chr);

        qtest_send(chr, "OK\n");

    } else if (strcmp(words[0], "outb") == 0 ||

               strcmp(words[0], "outw") == 0 ||

               strcmp(words[0], "outl") == 0) {

        uint16_t addr;

        uint32_t value;

        g_assert(words[1] && words[2]);

        addr = strtoul(words[1], NULL, 0);

        value = strtoul(words[2], NULL, 0);

        if (words[0][3] == 'b') {

            cpu_outb(addr, value);

        } else if (words[0][3] == 'w') {

            cpu_outw(addr, value);

        } else if (words[0][3] == 'l') {

            cpu_outl(addr, value);

        }

        qtest_send_prefix(chr);

        qtest_send(chr, "OK\n");

    } else if (strcmp(words[0], "inb") == 0 ||

        strcmp(words[0], "inw") == 0 ||

        strcmp(words[0], "inl") == 0) {

        uint16_t addr;

        uint32_t value = -1U;

        g_assert(words[1]);

        addr = strtoul(words[1], NULL, 0);

        if (words[0][2] == 'b') {

            value = cpu_inb(addr);

        } else if (words[0][2] == 'w') {

            value = cpu_inw(addr);

        } else if (words[0][2] == 'l') {

            value = cpu_inl(addr);

        }

        qtest_send_prefix(chr);

        qtest_send(chr, "OK 0x%04x\n", value);

    } else if (strcmp(words[0], "writeb") == 0 ||

               strcmp(words[0], "writew") == 0 ||

               strcmp(words[0], "writel") == 0 ||

               strcmp(words[0], "writeq") == 0) {

        uint64_t addr;

        uint64_t value;

        g_assert(words[1] && words[2]);

        addr = strtoull(words[1], NULL, 0);

        value = strtoull(words[2], NULL, 0);

        if (words[0][5] == 'b') {

            uint8_t data = value;

            cpu_physical_memory_write(addr, &data, 1);

        } else if (words[0][5] == 'w') {

            uint16_t data = value;

            tswap16s(&data);

            cpu_physical_memory_write(addr, &data, 2);

        } else if (words[0][5] == 'l') {

            uint32_t data = value;

            tswap32s(&data);

            cpu_physical_memory_write(addr, &data, 4);

        } else if (words[0][5] == 'q') {

            uint64_t data = value;

            tswap64s(&data);

            cpu_physical_memory_write(addr, &data, 8);

        }

        qtest_send_prefix(chr);

        qtest_send(chr, "OK\n");

    } else if (strcmp(words[0], "readb") == 0 ||

               strcmp(words[0], "readw") == 0 ||

               strcmp(words[0], "readl") == 0 ||

               strcmp(words[0], "readq") == 0) {

        uint64_t addr;

        uint64_t value = UINT64_C(-1);

        g_assert(words[1]);

        addr = strtoull(words[1], NULL, 0);

        if (words[0][4] == 'b') {

            uint8_t data;

            cpu_physical_memory_read(addr, &data, 1);

            value = data;

        } else if (words[0][4] == 'w') {

            uint16_t data;

            cpu_physical_memory_read(addr, &data, 2);

            value = tswap16(data);

        } else if (words[0][4] == 'l') {

            uint32_t data;

            cpu_physical_memory_read(addr, &data, 4);

            value = tswap32(data);

        } else if (words[0][4] == 'q') {

            cpu_physical_memory_read(addr, &value, 8);

            tswap64s(&value);

        }

        qtest_send_prefix(chr);

        qtest_send(chr, "OK 0x%016" PRIx64 "\n", value);

    } else if (strcmp(words[0], "read") == 0) {

        uint64_t addr, len, i;

        uint8_t *data;

        g_assert(words[1] && words[2]);

        addr = strtoull(words[1], NULL, 0);

        len = strtoull(words[2], NULL, 0);

        data = g_malloc(len);

        cpu_physical_memory_read(addr, data, len);

        qtest_send_prefix(chr);

        qtest_send(chr, "OK 0x");

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

            qtest_send(chr, "%02x", data[i]);

        }

        qtest_send(chr, "\n");

        g_free(data);

    } else if (strcmp(words[0], "write") == 0) {

        uint64_t addr, len, i;

        uint8_t *data;

        size_t data_len;

        g_assert(words[1] && words[2] && words[3]);

        addr = strtoull(words[1], NULL, 0);

        len = strtoull(words[2], NULL, 0);

        data_len = strlen(words[3]);

        if (data_len < 3) {

            qtest_send(chr, "ERR invalid argument size\n");

            return;

        }

        data = g_malloc(len);

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

            if ((i * 2 + 4) <= data_len) {

                data[i] = hex2nib(words[3][i * 2 + 2]) << 4;

                data[i] |= hex2nib(words[3][i * 2 + 3]);

            } else {

                data[i] = 0;

            }

        }

        cpu_physical_memory_write(addr, data, len);

        g_free(data);

        qtest_send_prefix(chr);

        qtest_send(chr, "OK\n");

    } else if (qtest_enabled() && strcmp(words[0], "clock_step") == 0) {

        int64_t ns;

        if (words[1]) {

            ns = strtoll(words[1], NULL, 0);

        } else {

            ns = qemu_clock_deadline_ns_all(QEMU_CLOCK_VIRTUAL);

        }

        qtest_clock_warp(qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + ns);

        qtest_send_prefix(chr);

        qtest_send(chr, "OK %"PRIi64"\n", (int64_t)qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL));

    } else if (qtest_enabled() && strcmp(words[0], "clock_set") == 0) {

        int64_t ns;

        g_assert(words[1]);

        ns = strtoll(words[1], NULL, 0);

        qtest_clock_warp(ns);

        qtest_send_prefix(chr);

        qtest_send(chr, "OK %"PRIi64"\n", (int64_t)qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL));

    } else {

        qtest_send_prefix(chr);

        qtest_send(chr, "FAIL Unknown command `%s'\n", words[0]);

    }

}


static target_long monitor_get_msr (const struct MonitorDef *md, int val)

{

    CPUState *env = mon_get_cpu();

    if (!env)

        return 0;

    return env->msr;

}


static inline int RENAME(yuv420_rgb32)(SwsContext *c, uint8_t* src[], int srcStride[], int srcSliceY,

             int srcSliceH, uint8_t* dst[], int dstStride[]){

    int y, h_size;

    if(c->srcFormat == PIX_FMT_YUV422P){

	srcStride[1] *= 2;

	srcStride[2] *= 2;

    }

    h_size= (c->dstW+7)&~7;

    if(h_size*4 > FFABS(dstStride[0])) h_size-=8;

    __asm__ __volatile__ ("pxor %mm4, %mm4;" /* zero mm4 */ );

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

	uint8_t *_image = dst[0] + (y+srcSliceY)*dstStride[0];

	uint8_t *_py = src[0] + y*srcStride[0];

	uint8_t *_pu = src[1] + (y>>1)*srcStride[1];

	uint8_t *_pv = src[2] + (y>>1)*srcStride[2];

	long index= -h_size/2;

	    /* this mmx assembly code deals with SINGLE scan line at a time, it convert 8

	       pixels in each iteration */

	    __asm__ __volatile__ (

	/* load data for start of next scan line */

		     "movd (%2, %0), %%mm0;" /* Load 4 Cb 00 00 00 00 u3 u2 u1 u0 */

		     "movd (%3, %0), %%mm1;" /* Load 4 Cr 00 00 00 00 v3 v2 v1 v0 */

		     "movq (%5, %0, 2), %%mm6;" /* Load 8  Y Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y0 */

//		    ".balign 16			\n\t"

		    "1:				\n\t"

YUV2RGB

		     /* convert RGB plane to RGB packed format,

			mm0 -> B, mm1 -> R, mm2 -> G, mm3 -> 0,

			mm4 -> GB, mm5 -> AR pixel 4-7,

			mm6 -> GB, mm7 -> AR pixel 0-3 */

		     "pxor %%mm3, %%mm3;" /* zero mm3 */

		     "movq %%mm0, %%mm6;" /* B7 B6 B5 B4 B3 B2 B1 B0 */

		     "movq %%mm1, %%mm7;" /* R7 R6 R5 R4 R3 R2 R1 R0 */

		     "movq %%mm0, %%mm4;" /* B7 B6 B5 B4 B3 B2 B1 B0 */

		     "movq %%mm1, %%mm5;" /* R7 R6 R5 R4 R3 R2 R1 R0 */

		     "punpcklbw %%mm2, %%mm6;" /* G3 B3 G2 B2 G1 B1 G0 B0 */

		     "punpcklbw %%mm3, %%mm7;" /* 00 R3 00 R2 00 R1 00 R0 */

		     "punpcklwd %%mm7, %%mm6;" /* 00 R1 B1 G1 00 R0 B0 G0 */

		     MOVNTQ " %%mm6, (%1);" /* Store ARGB1 ARGB0 */

		     "movq %%mm0, %%mm6;" /* B7 B6 B5 B4 B3 B2 B1 B0 */

		     "punpcklbw %%mm2, %%mm6;" /* G3 B3 G2 B2 G1 B1 G0 B0 */

		     "punpckhwd %%mm7, %%mm6;" /* 00 R3 G3 B3 00 R2 B3 G2 */

		     MOVNTQ " %%mm6, 8 (%1);" /* Store ARGB3 ARGB2 */

		     "punpckhbw %%mm2, %%mm4;" /* G7 B7 G6 B6 G5 B5 G4 B4 */

		     "punpckhbw %%mm3, %%mm5;" /* 00 R7 00 R6 00 R5 00 R4 */

		     "punpcklwd %%mm5, %%mm4;" /* 00 R5 B5 G5 00 R4 B4 G4 */

		     MOVNTQ " %%mm4, 16 (%1);" /* Store ARGB5 ARGB4 */

		     "movq %%mm0, %%mm4;" /* B7 B6 B5 B4 B3 B2 B1 B0 */

		     "punpckhbw %%mm2, %%mm4;" /* G7 B7 G6 B6 G5 B5 G4 B4 */

		     "punpckhwd %%mm5, %%mm4;" /* 00 R7 G7 B7 00 R6 B6 G6 */

		     MOVNTQ " %%mm4, 24 (%1);" /* Store ARGB7 ARGB6 */

		     "movd 4 (%2, %0), %%mm0;" /* Load 4 Cb 00 00 00 00 u3 u2 u1 u0 */

		     "movd 4 (%3, %0), %%mm1;" /* Load 4 Cr 00 00 00 00 v3 v2 v1 v0 */

		     "pxor %%mm4, %%mm4;" /* zero mm4 */

		     "movq 8 (%5, %0, 2), %%mm6;" /* Load 8 Y Y7 Y6 Y5 Y4 Y3 Y2 Y1 Y0 */

		     "add $32, %1			\n\t"

		     "add $4, %0			\n\t"

		     " js 1b				\n\t"

		     : "+r" (index), "+r" (_image)

		     : "r" (_pu - index), "r" (_pv - index), "r"(&c->redDither), "r" (_py - 2*index)

		     );

    }

    __asm__ __volatile__ (EMMS);

    return srcSliceH;

}


static void gen_ld (CPUState *env, DisasContext *ctx, uint32_t opc,

                    int rt, int base, int16_t offset)

{

    const char *opn = "ld";

    TCGv t0, t1;

    if (rt == 0 && env->insn_flags & (INSN_LOONGSON2E | INSN_LOONGSON2F)) {

        /* Loongson CPU uses a load to zero register for prefetch.

           We emulate it as a NOP. On other CPU we must perform the

           actual memory access. */

        MIPS_DEBUG("NOP");

        return;

    }

    t0 = tcg_temp_new();

    t1 = tcg_temp_new();

    gen_base_offset_addr(ctx, t0, base, offset);

    switch (opc) {

#if defined(TARGET_MIPS64)

    case OPC_LWU:

        save_cpu_state(ctx, 0);

        op_ld_lwu(t0, t0, ctx);

        gen_store_gpr(t0, rt);

        opn = "lwu";

        break;

    case OPC_LD:

        save_cpu_state(ctx, 0);

        op_ld_ld(t0, t0, ctx);

        gen_store_gpr(t0, rt);

        opn = "ld";

        break;

    case OPC_LLD:

        save_cpu_state(ctx, 0);

        op_ld_lld(t0, t0, ctx);

        gen_store_gpr(t0, rt);

        opn = "lld";

        break;

    case OPC_LDL:

        save_cpu_state(ctx, 1);

        gen_load_gpr(t1, rt);

        gen_helper_3i(ldl, t1, t1, t0, ctx->mem_idx);

        gen_store_gpr(t1, rt);

        opn = "ldl";

        break;

    case OPC_LDR:

        save_cpu_state(ctx, 1);

        gen_load_gpr(t1, rt);

        gen_helper_3i(ldr, t1, t1, t0, ctx->mem_idx);

        gen_store_gpr(t1, rt);

        opn = "ldr";

        break;

    case OPC_LDPC:

        save_cpu_state(ctx, 1);

        tcg_gen_movi_tl(t1, pc_relative_pc(ctx));

        gen_op_addr_add(ctx, t0, t0, t1);

        op_ld_ld(t0, t0, ctx);

        gen_store_gpr(t0, rt);

        opn = "ldpc";

        break;

#endif

    case OPC_LWPC:

        save_cpu_state(ctx, 1);

        tcg_gen_movi_tl(t1, pc_relative_pc(ctx));

        gen_op_addr_add(ctx, t0, t0, t1);

        op_ld_lw(t0, t0, ctx);

        gen_store_gpr(t0, rt);

        opn = "lwpc";

        break;

    case OPC_LW:

        save_cpu_state(ctx, 0);

        op_ld_lw(t0, t0, ctx);

        gen_store_gpr(t0, rt);

        opn = "lw";

        break;

    case OPC_LH:

        save_cpu_state(ctx, 0);

        op_ld_lh(t0, t0, ctx);

        gen_store_gpr(t0, rt);

        opn = "lh";

        break;

    case OPC_LHU:

        save_cpu_state(ctx, 0);

        op_ld_lhu(t0, t0, ctx);

        gen_store_gpr(t0, rt);

        opn = "lhu";

        break;

    case OPC_LB:

        save_cpu_state(ctx, 0);

        op_ld_lb(t0, t0, ctx);

        gen_store_gpr(t0, rt);

        opn = "lb";

        break;

    case OPC_LBU:

        save_cpu_state(ctx, 0);

        op_ld_lbu(t0, t0, ctx);

        gen_store_gpr(t0, rt);

        opn = "lbu";

        break;

    case OPC_LWL:

        save_cpu_state(ctx, 1);

        gen_load_gpr(t1, rt);

        gen_helper_3i(lwl, t1, t1, t0, ctx->mem_idx);

        gen_store_gpr(t1, rt);

        opn = "lwl";

        break;

    case OPC_LWR:

        save_cpu_state(ctx, 1);

        gen_load_gpr(t1, rt);

        gen_helper_3i(lwr, t1, t1, t0, ctx->mem_idx);

        gen_store_gpr(t1, rt);

        opn = "lwr";

        break;

    case OPC_LL:

        save_cpu_state(ctx, 1);

        op_ld_ll(t0, t0, ctx);

        gen_store_gpr(t0, rt);

        opn = "ll";

        break;

    }

    (void)opn; /* avoid a compiler warning */

    MIPS_DEBUG("%s %s, %d(%s)", opn, regnames[rt], offset, regnames[base]);

    tcg_temp_free(t0);

    tcg_temp_free(t1);

}


static int latm_decode_audio_specific_config(struct LATMContext *latmctx,

                                             GetBitContext *gb, int asclen)

{

    AACContext *ac        = &latmctx->aac_ctx;

    AVCodecContext *avctx = ac->avctx;

    MPEG4AudioConfig m4ac = {0};

    int config_start_bit  = get_bits_count(gb);

    int sync_extension    = 0;

    int bits_consumed, esize;

    if (asclen) {

        sync_extension = 1;

        asclen         = FFMIN(asclen, get_bits_left(gb));

    } else

        asclen         = get_bits_left(gb);

    if (config_start_bit % 8) {

        av_log_missing_feature(latmctx->aac_ctx.avctx, "audio specific "

                               "config not byte aligned.\n", 1);

    }

    bits_consumed = decode_audio_specific_config(NULL, avctx, &m4ac,

                                         gb->buffer + (config_start_bit / 8),

                                         asclen, sync_extension);

    if (bits_consumed < 0)

    if (ac->m4ac.sample_rate != m4ac.sample_rate ||

        ac->m4ac.chan_config != m4ac.chan_config) {

        av_log(avctx, AV_LOG_INFO, "audio config changed\n");

        latmctx->initialized = 0;

        esize = (bits_consumed+7) / 8;

        if (avctx->extradata_size < esize) {

            av_free(avctx->extradata);

            avctx->extradata = av_malloc(esize + FF_INPUT_BUFFER_PADDING_SIZE);

            if (!avctx->extradata)

                return AVERROR(ENOMEM);

        }

        avctx->extradata_size = esize;

        memcpy(avctx->extradata, gb->buffer + (config_start_bit/8), esize);

        memset(avctx->extradata+esize, 0, FF_INPUT_BUFFER_PADDING_SIZE);

    }

    skip_bits_long(gb, bits_consumed);

    return bits_consumed;

}


static void ehci_frame_timer(void *opaque)

{

    EHCIState *ehci = opaque;

    int need_timer = 0;

    int64_t expire_time, t_now;

    uint64_t ns_elapsed;

    uint64_t uframes, skipped_uframes;

    int i;

    t_now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);

    ns_elapsed = t_now - ehci->last_run_ns;

    uframes = ns_elapsed / UFRAME_TIMER_NS;

    if (ehci_periodic_enabled(ehci) || ehci->pstate != EST_INACTIVE) {

        need_timer++;

        if (uframes > (ehci->maxframes * 8)) {

            skipped_uframes = uframes - (ehci->maxframes * 8);

            ehci_update_frindex(ehci, skipped_uframes);

            ehci->last_run_ns += UFRAME_TIMER_NS * skipped_uframes;

            uframes -= skipped_uframes;

            DPRINTF("WARNING - EHCI skipped %d uframes\n", skipped_uframes);

        }

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

            /*

             * If we're running behind schedule, we should not catch up

             * too fast, as that will make some guests unhappy:

             * 1) We must process a minimum of MIN_UFR_PER_TICK frames,

             *    otherwise we will never catch up

             * 2) Process frames until the guest has requested an irq (IOC)

             */

            if (i >= MIN_UFR_PER_TICK) {

                ehci_commit_irq(ehci);

                if ((ehci->usbsts & USBINTR_MASK) & ehci->usbintr) {

                    break;

                }

            }

            if (ehci->periodic_sched_active) {

                ehci->periodic_sched_active--;

            }

            ehci_update_frindex(ehci, 1);

            if ((ehci->frindex & 7) == 0) {

                ehci_advance_periodic_state(ehci);

            }

            ehci->last_run_ns += UFRAME_TIMER_NS;

        }

    } else {

        ehci->periodic_sched_active = 0;

        ehci_update_frindex(ehci, uframes);

        ehci->last_run_ns += UFRAME_TIMER_NS * uframes;

    }

    if (ehci->periodic_sched_active) {

        ehci->async_stepdown = 0;

    } else if (ehci->async_stepdown < ehci->maxframes / 2) {

        ehci->async_stepdown++;

    }

    /*  Async is not inside loop since it executes everything it can once

     *  called

     */

    if (ehci_async_enabled(ehci) || ehci->astate != EST_INACTIVE) {

        need_timer++;

        ehci_advance_async_state(ehci);

    }

    ehci_commit_irq(ehci);

    if (ehci->usbsts_pending) {

        need_timer++;

        ehci->async_stepdown = 0;

    }

    if (ehci_enabled(ehci) && (ehci->usbintr & USBSTS_FLR)) {

        need_timer++;

    }

    if (need_timer) {

        /* If we've raised int, we speed up the timer, so that we quickly

         * notice any new packets queued up in response */

        if (ehci->int_req_by_async && (ehci->usbsts & USBSTS_INT)) {

            expire_time = t_now +

                NANOSECONDS_PER_SECOND / (FRAME_TIMER_FREQ * 4);

            ehci->int_req_by_async = false;

        } else {

            expire_time = t_now + (NANOSECONDS_PER_SECOND

                               * (ehci->async_stepdown+1) / FRAME_TIMER_FREQ);

        }

        timer_mod(ehci->frame_timer, expire_time);

    }

}


int bdrv_inactivate_all(void)

{

    BlockDriverState *bs = NULL;

    BdrvNextIterator it;

    int ret = 0;

    int pass;

    for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {

        aio_context_acquire(bdrv_get_aio_context(bs));

    }

    /* We do two passes of inactivation. The first pass calls to drivers'

     * .bdrv_inactivate callbacks recursively so all cache is flushed to disk;

     * the second pass sets the BDRV_O_INACTIVE flag so that no further write

     * is allowed. */

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

        for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {

            ret = bdrv_inactivate_recurse(bs, pass);

            if (ret < 0) {

                goto out;

            }

        }

    }

out:

    for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {

        aio_context_release(bdrv_get_aio_context(bs));

    }

    return ret;

}