static void decode_lowdelay(DiracContext *s)

{

    AVCodecContext *avctx = s->avctx;

    int slice_x, slice_y, bytes, bufsize;

    const uint8_t *buf;

    struct lowdelay_slice *slices;

    int slice_num = 0;

    slices = av_mallocz_array(s->lowdelay.num_x, s->lowdelay.num_y * sizeof(struct lowdelay_slice));

    align_get_bits(&s->gb);

    /*[DIRAC_STD] 13.5.2 Slices. slice(sx,sy) */

    buf = s->gb.buffer + get_bits_count(&s->gb)/8;

    bufsize = get_bits_left(&s->gb);

    for (slice_y = 0; bufsize > 0 && slice_y < s->lowdelay.num_y; slice_y++)

        for (slice_x = 0; bufsize > 0 && slice_x < s->lowdelay.num_x; slice_x++) {

            bytes = (slice_num+1) * s->lowdelay.bytes.num / s->lowdelay.bytes.den

                - slice_num    * s->lowdelay.bytes.num / s->lowdelay.bytes.den;

            slices[slice_num].bytes   = bytes;

            slices[slice_num].slice_x = slice_x;

            slices[slice_num].slice_y = slice_y;

            init_get_bits(&slices[slice_num].gb, buf, bufsize);

            slice_num++;

            buf     += bytes;

            bufsize -= bytes*8;

        }

    avctx->execute(avctx, decode_lowdelay_slice, slices, NULL, slice_num,

                   sizeof(struct lowdelay_slice)); /* [DIRAC_STD] 13.5.2 Slices */

    intra_dc_prediction(&s->plane[0].band[0][0]);  /* [DIRAC_STD] 13.3 intra_dc_prediction() */

    intra_dc_prediction(&s->plane[1].band[0][0]);  /* [DIRAC_STD] 13.3 intra_dc_prediction() */

    intra_dc_prediction(&s->plane[2].band[0][0]);  /* [DIRAC_STD] 13.3 intra_dc_prediction() */

    av_free(slices);

}


static void copy_video_props(AVFilterBufferRefVideoProps *dst, AVFilterBufferRefVideoProps *src) {

    *dst = *src;

    if (src->qp_table) {

        int qsize = src->qp_table_size;

        dst->qp_table = av_malloc(qsize);

        memcpy(dst->qp_table, src->qp_table, qsize);

    }

}


void qmp_blockdev_backup(BlockdevBackup *arg, Error **errp)

{

    do_blockdev_backup(arg, NULL, errp);

}


int attribute_align_arg avcodec_encode_audio2(AVCodecContext *avctx,

                                              AVPacket *avpkt,

                                              const AVFrame *frame,

                                              int *got_packet_ptr)

{

    int ret;

    int user_packet = !!avpkt->data;

    int nb_samples;

    *got_packet_ptr = 0;

    if (!(avctx->codec->capabilities & CODEC_CAP_DELAY) && !frame) {

        av_free_packet(avpkt);

        av_init_packet(avpkt);

        avpkt->size = 0;

        return 0;

    }

    /* check for valid frame size */

    if (frame) {

        nb_samples = frame->nb_samples;

        if (avctx->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) {

            if (nb_samples > avctx->frame_size)

                return AVERROR(EINVAL);

        } else if (!(avctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE)) {

            if (nb_samples != avctx->frame_size)

                return AVERROR(EINVAL);

        }

    } else {

        nb_samples = avctx->frame_size;

    }

    if (avctx->codec->encode2) {

        ret = avctx->codec->encode2(avctx, avpkt, frame, got_packet_ptr);

        if (!ret && *got_packet_ptr) {

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

                if (avpkt->pts == AV_NOPTS_VALUE)

                    avpkt->pts = frame->pts;

                if (!avpkt->duration)

                    avpkt->duration = ff_samples_to_time_base(avctx,

                                                              frame->nb_samples);

            }

            avpkt->dts = avpkt->pts;

        } else {

            avpkt->size = 0;

        }

    } else {

        /* for compatibility with encoders not supporting encode2(), we need to

           allocate a packet buffer if the user has not provided one or check

           the size otherwise */

        int fs_tmp   = 0;

        int buf_size = avpkt->size;

        if (!user_packet) {

            if (avctx->codec->capabilities & CODEC_CAP_VARIABLE_FRAME_SIZE) {

                av_assert0(av_get_bits_per_sample(avctx->codec_id) != 0);

                buf_size = nb_samples * avctx->channels *

                           av_get_bits_per_sample(avctx->codec_id) / 8;

            } else {

                /* this is a guess as to the required size.

                   if an encoder needs more than this, it should probably

                   implement encode2() */

                buf_size = 2 * avctx->frame_size * avctx->channels *

                           av_get_bytes_per_sample(avctx->sample_fmt);

                buf_size += FF_MIN_BUFFER_SIZE;

            }

        }

        if ((ret = ff_alloc_packet(avpkt, buf_size)))

            return ret;

        /* Encoders using AVCodec.encode() that support

           CODEC_CAP_SMALL_LAST_FRAME require avctx->frame_size to be set to

           the smaller size when encoding the last frame.

           This code can be removed once all encoders supporting

           CODEC_CAP_SMALL_LAST_FRAME use encode2() */

        if ((avctx->codec->capabilities & CODEC_CAP_SMALL_LAST_FRAME) &&

            nb_samples < avctx->frame_size) {

            fs_tmp = avctx->frame_size;

            avctx->frame_size = nb_samples;

        }

        /* encode the frame */

        ret = avctx->codec->encode(avctx, avpkt->data, avpkt->size,

                                   frame ? frame->data[0] : NULL);

        if (ret >= 0) {

            if (!ret) {

                /* no output. if the packet data was allocated by libavcodec,

                   free it */

                if (!user_packet)

                    av_freep(&avpkt->data);

            } else {

                if (avctx->coded_frame)

                    avpkt->pts = avpkt->dts = avctx->coded_frame->pts;

                /* Set duration for final small packet. This can be removed

                   once all encoders supporting CODEC_CAP_SMALL_LAST_FRAME use

                   encode2() */

                if (fs_tmp) {

                    avpkt->duration = ff_samples_to_time_base(avctx,

                                                              avctx->frame_size);

                }

            }

            avpkt->size = ret;

            *got_packet_ptr = (ret > 0);

            ret = 0;

        }

        if (fs_tmp)

            avctx->frame_size = fs_tmp;

    }

    if (!ret) {

        if (!user_packet && avpkt->data) {

            uint8_t *new_data = av_realloc(avpkt->data, avpkt->size);

            if (new_data)

                avpkt->data = new_data;

        }

        avctx->frame_number++;

    }

    if (ret < 0 || !*got_packet_ptr)

        av_free_packet(avpkt);

    /* NOTE: if we add any audio encoders which output non-keyframe packets,

             this needs to be moved to the encoders, but for now we can do it

             here to simplify things */

    avpkt->flags |= AV_PKT_FLAG_KEY;

    return ret;

}


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

{

    DeviceClass *dc = DEVICE_CLASS(oc);

    dc->realize = fsl_imx6_realize;

    dc->desc = "i.MX6 SOC";

}


static void test_endianness_split(gconstpointer data)

{

    const TestCase *test = data;

    char *args;

    args = g_strdup_printf("-display none -M %s%s%s -device pc-testdev",

                           test->machine,

                           test->superio ? " -device " : "",

                           test->superio ?: "");

    qtest_start(args);

    isa_outl(test, 0xe8, 0x87654321);

    g_assert_cmphex(isa_inl(test, 0xe0), ==, 0x87654321);

    g_assert_cmphex(isa_inw(test, 0xe2), ==, 0x8765);

    g_assert_cmphex(isa_inw(test, 0xe0), ==, 0x4321);

    isa_outw(test, 0xea, 0x8866);

    g_assert_cmphex(isa_inl(test, 0xe0), ==, 0x88664321);

    g_assert_cmphex(isa_inw(test, 0xe2), ==, 0x8866);

    g_assert_cmphex(isa_inw(test, 0xe0), ==, 0x4321);

    isa_outw(test, 0xe8, 0x4422);

    g_assert_cmphex(isa_inl(test, 0xe0), ==, 0x88664422);

    g_assert_cmphex(isa_inw(test, 0xe2), ==, 0x8866);

    g_assert_cmphex(isa_inw(test, 0xe0), ==, 0x4422);

    isa_outb(test, 0xeb, 0x87);

    g_assert_cmphex(isa_inl(test, 0xe0), ==, 0x87664422);

    g_assert_cmphex(isa_inw(test, 0xe2), ==, 0x8766);

    isa_outb(test, 0xea, 0x65);

    g_assert_cmphex(isa_inl(test, 0xe0), ==, 0x87654422);

    g_assert_cmphex(isa_inw(test, 0xe2), ==, 0x8765);

    g_assert_cmphex(isa_inw(test, 0xe0), ==, 0x4422);

    isa_outb(test, 0xe9, 0x43);

    g_assert_cmphex(isa_inl(test, 0xe0), ==, 0x87654322);

    g_assert_cmphex(isa_inw(test, 0xe2), ==, 0x8765);

    g_assert_cmphex(isa_inw(test, 0xe0), ==, 0x4322);

    isa_outb(test, 0xe8, 0x21);

    g_assert_cmphex(isa_inl(test, 0xe0), ==, 0x87654321);

    g_assert_cmphex(isa_inw(test, 0xe2), ==, 0x8765);

    g_assert_cmphex(isa_inw(test, 0xe0), ==, 0x4321);

    qtest_quit(global_qtest);

    g_free(args);

}


static void test_qemu_strtoull_whitespace(void)

{

    const char *str = "  \t  ";

    char f = 'X';

    const char *endptr = &f;

    uint64_t res = 999;

    int err;

    err = qemu_strtoull(str, &endptr, 0, &res);

    g_assert_cmpint(err, ==, 0);

    g_assert_cmpint(res, ==, 0);

    g_assert(endptr == str);

}


static int matroska_parse_frame(MatroskaDemuxContext *matroska,

                                MatroskaTrack *track, AVStream *st,

                                uint8_t *data, int pkt_size,

                                uint64_t timecode, uint64_t duration,

                                int64_t pos, int is_keyframe)

{

    MatroskaTrackEncoding *encodings = track->encodings.elem;

    uint8_t *pkt_data = data;

    int offset = 0, res;

    AVPacket *pkt;

    if (encodings && encodings->scope & 1) {

        res = matroska_decode_buffer(&pkt_data, &pkt_size, track);

        if (res < 0)

            return res;

    }

    if (st->codec->codec_id == AV_CODEC_ID_WAVPACK) {

        uint8_t *wv_data;

        res = matroska_parse_wavpack(track, pkt_data, &wv_data, &pkt_size);

        if (res < 0) {

            av_log(matroska->ctx, AV_LOG_ERROR,

                   "Error parsing a wavpack block.\n");

            goto fail;

        }

        if (pkt_data != data)

        pkt_data = wv_data;

    }

    if (st->codec->codec_id == AV_CODEC_ID_PRORES)

        offset = 8;

    pkt = av_mallocz(sizeof(AVPacket));

    /* XXX: prevent data copy... */

    if (av_new_packet(pkt, pkt_size + offset) < 0) {

        av_free(pkt);

        return AVERROR(ENOMEM);

    }

    if (st->codec->codec_id == AV_CODEC_ID_PRORES) {

        uint8_t *buf = pkt->data;

        bytestream_put_be32(&buf, pkt_size);

        bytestream_put_be32(&buf, MKBETAG('i', 'c', 'p', 'f'));

    }

    memcpy(pkt->data + offset, pkt_data, pkt_size);

    if (pkt_data != data)

        av_free(pkt_data);

    pkt->flags        = is_keyframe;

    pkt->stream_index = st->index;

    if (track->ms_compat)

        pkt->dts = timecode;

    else

        pkt->pts = timecode;

    pkt->pos = pos;

    if (st->codec->codec_id == AV_CODEC_ID_TEXT)

        pkt->convergence_duration = duration;

    else if (track->type != MATROSKA_TRACK_TYPE_SUBTITLE)

        pkt->duration = duration;

    if (st->codec->codec_id == AV_CODEC_ID_SSA)

        matroska_fix_ass_packet(matroska, pkt, duration);

    if (matroska->prev_pkt                                 &&

        timecode                         != AV_NOPTS_VALUE &&

        matroska->prev_pkt->pts          == timecode       &&

        matroska->prev_pkt->stream_index == st->index      &&

        st->codec->codec_id == AV_CODEC_ID_SSA)

        matroska_merge_packets(matroska->prev_pkt, pkt);

    else {

        dynarray_add(&matroska->packets, &matroska->num_packets, pkt);

        matroska->prev_pkt = pkt;

    }

    return 0;

fail:

    if (pkt_data != data)

    return res;

}


void *av_fast_realloc(void *ptr, unsigned int *size, unsigned int min_size)

{

    if(min_size < *size)

        return ptr;

    *size= 17*min_size/16 + 32;

    return av_realloc(ptr, *size);

}


static int get_video_frame(VideoState *is, AVFrame *frame, int64_t *pts, AVPacket *pkt, int *serial)

{

    int got_picture;

    if (packet_queue_get(&is->videoq, pkt, 1, serial) < 0)

        return -1;

    if (pkt->data == flush_pkt.data) {

        avcodec_flush_buffers(is->video_st->codec);

        SDL_LockMutex(is->pictq_mutex);

        // Make sure there are no long delay timers (ideally we should just flush the queue but that's harder)

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

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

        }

        is->video_current_pos = -1;

        is->frame_last_pts = AV_NOPTS_VALUE;

        is->frame_last_duration = 0;

        is->frame_timer = (double)av_gettime() / 1000000.0;

        is->frame_last_dropped_pts = AV_NOPTS_VALUE;

        SDL_UnlockMutex(is->pictq_mutex);

        return 0;

    }

    if(avcodec_decode_video2(is->video_st->codec, frame, &got_picture, pkt) < 0)

        return 0;

    if (got_picture) {

        int ret = 1;

        if (decoder_reorder_pts == -1) {

            *pts = av_frame_get_best_effort_timestamp(frame);

        } else if (decoder_reorder_pts) {

            *pts = frame->pkt_pts;

        } else {

            *pts = frame->pkt_dts;

        }

        if (*pts == AV_NOPTS_VALUE) {

            *pts = 0;

        }

        if (framedrop>0 || (framedrop && get_master_sync_type(is) != AV_SYNC_VIDEO_MASTER)) {

            SDL_LockMutex(is->pictq_mutex);

            if (is->frame_last_pts != AV_NOPTS_VALUE && *pts) {

                double clockdiff = get_video_clock(is) - get_master_clock(is);

                double dpts = av_q2d(is->video_st->time_base) * *pts;

                double ptsdiff = dpts - is->frame_last_pts;

                if (fabs(clockdiff) < AV_NOSYNC_THRESHOLD &&

                     ptsdiff > 0 && ptsdiff < AV_NOSYNC_THRESHOLD &&

                     clockdiff + ptsdiff - is->frame_last_filter_delay < 0) {

                    is->frame_last_dropped_pos = pkt->pos;

                    is->frame_last_dropped_pts = dpts;

                    is->frame_drops_early++;

                    ret = 0;

                }

            }

            SDL_UnlockMutex(is->pictq_mutex);

        }

        return ret;

    }

    return 0;

}


static void msix_mmio_write(void *opaque, target_phys_addr_t addr,
                            uint64_t val, unsigned size)
{
    PCIDevice *dev = opaque;
    unsigned int offset = addr & (MSIX_PAGE_SIZE - 1) & ~0x3;
    int vector = offset / PCI_MSIX_ENTRY_SIZE;
    pci_set_long(dev->msix_table_page + offset, val);
    msix_handle_mask_update(dev, vector);


static void vfio_msix_enable(VFIOPCIDevice *vdev)

{

    vfio_disable_interrupts(vdev);

    vdev->msi_vectors = g_malloc0(vdev->msix->entries * sizeof(VFIOMSIVector));

    vdev->interrupt = VFIO_INT_MSIX;

    /*

     * Some communication channels between VF & PF or PF & fw rely on the

     * physical state of the device and expect that enabling MSI-X from the

     * guest enables the same on the host.  When our guest is Linux, the

     * guest driver call to pci_enable_msix() sets the enabling bit in the

     * MSI-X capability, but leaves the vector table masked.  We therefore

     * can't rely on a vector_use callback (from request_irq() in the guest)

     * to switch the physical device into MSI-X mode because that may come a

     * long time after pci_enable_msix().  This code enables vector 0 with

     * triggering to userspace, then immediately release the vector, leaving

     * the physical device with no vectors enabled, but MSI-X enabled, just

     * like the guest view.

     */

    vfio_msix_vector_do_use(&vdev->pdev, 0, NULL, NULL);

    vfio_msix_vector_release(&vdev->pdev, 0);

    if (msix_set_vector_notifiers(&vdev->pdev, vfio_msix_vector_use,

                                  vfio_msix_vector_release, NULL)) {

        error_report("vfio: msix_set_vector_notifiers failed");

    }

    trace_vfio_msix_enable(vdev->vbasedev.name);

}


static int check_bind(struct sockaddr *sa, socklen_t salen, bool *has_proto)

{

    int fd;

    fd = socket(sa->sa_family, SOCK_STREAM, 0);

    if (fd < 0) {

        return -1;

    }

    if (bind(fd, sa, salen) < 0) {

        close(fd);

        if (errno == EADDRNOTAVAIL) {

            *has_proto = false;

            return 0;

        }

        return -1;

    }

    close(fd);

    *has_proto = true;

    return 0;

}


int ff_fft_init(FFTContext *s, int nbits, int inverse)

{

    int i, j, m, n;

    float alpha, c1, s1, s2;

    int shuffle = 0;

    int av_unused has_vectors;

    s->nbits = nbits;

    n = 1 << nbits;

    s->exptab = av_malloc((n / 2) * sizeof(FFTComplex));

    if (!s->exptab)

        goto fail;

    s->revtab = av_malloc(n * sizeof(uint16_t));

    if (!s->revtab)

        goto fail;

    s->inverse = inverse;

    s2 = inverse ? 1.0 : -1.0;

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

        alpha = 2 * M_PI * (float)i / (float)n;

        c1 = cos(alpha);

        s1 = sin(alpha) * s2;

        s->exptab[i].re = c1;

        s->exptab[i].im = s1;

    }

    s->fft_calc = ff_fft_calc_c;

    s->imdct_calc = ff_imdct_calc;

    s->imdct_half = ff_imdct_half;

    s->exptab1 = NULL;

#ifdef HAVE_MMX

    has_vectors = mm_support();

    shuffle = 1;

    if (has_vectors & MM_3DNOWEXT) {

        /* 3DNowEx for K7/K8 */

        s->imdct_calc = ff_imdct_calc_3dn2;

        s->fft_calc = ff_fft_calc_3dn2;

    } else if (has_vectors & MM_3DNOW) {

        /* 3DNow! for K6-2/3 */

        s->fft_calc = ff_fft_calc_3dn;

    } else if (has_vectors & MM_SSE) {

        /* SSE for P3/P4 */

        s->imdct_calc = ff_imdct_calc_sse;

        s->imdct_half = ff_imdct_half_sse;

        s->fft_calc = ff_fft_calc_sse;

    } else {

        shuffle = 0;

    }

#elif defined HAVE_ALTIVEC && !defined ALTIVEC_USE_REFERENCE_C_CODE

    has_vectors = mm_support();

    if (has_vectors & MM_ALTIVEC) {

        s->fft_calc = ff_fft_calc_altivec;

        shuffle = 1;

    }

#endif

    /* compute constant table for HAVE_SSE version */

    if (shuffle) {

        int np, nblocks, np2, l;

        FFTComplex *q;

        np = 1 << nbits;

        nblocks = np >> 3;

        np2 = np >> 1;

        s->exptab1 = av_malloc(np * 2 * sizeof(FFTComplex));

        if (!s->exptab1)

            goto fail;

        q = s->exptab1;

        do {

            for(l = 0; l < np2; l += 2 * nblocks) {

                *q++ = s->exptab[l];

                *q++ = s->exptab[l + nblocks];

                q->re = -s->exptab[l].im;

                q->im = s->exptab[l].re;

                q++;

                q->re = -s->exptab[l + nblocks].im;

                q->im = s->exptab[l + nblocks].re;

                q++;

            }

            nblocks = nblocks >> 1;

        } while (nblocks != 0);

        av_freep(&s->exptab);

    }

    /* compute bit reverse table */

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

        m=0;

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

            m |= ((i >> j) & 1) << (nbits-j-1);

        }

        s->revtab[i]=m;

    }

    return 0;

 fail:

    av_freep(&s->revtab);

    av_freep(&s->exptab);

    av_freep(&s->exptab1);

    return -1;

}


static void write_mainheader(NUTContext *nut, AVIOContext *bc)

{

    int i, j, tmp_pts, tmp_flags, tmp_stream, tmp_mul, tmp_size, tmp_fields,

        tmp_head_idx;

    int64_t tmp_match;

    ff_put_v(bc, nut->version);

    if (nut->version > 3)

        ff_put_v(bc, nut->minor_version);

    ff_put_v(bc, nut->avf->nb_streams);

    ff_put_v(bc, nut->max_distance);

    ff_put_v(bc, nut->time_base_count);

    for (i = 0; i < nut->time_base_count; i++) {

        ff_put_v(bc, nut->time_base[i].num);

        ff_put_v(bc, nut->time_base[i].den);

    }

    tmp_pts      = 0;

    tmp_mul      = 1;

    tmp_stream   = 0;

    tmp_match    = 1 - (1LL << 62);

    tmp_head_idx = 0;

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

        tmp_fields = 0;

        tmp_size   = 0;

//        tmp_res=0;

        if (tmp_pts      != nut->frame_code[i].pts_delta ) tmp_fields = 1;

        if (tmp_mul      != nut->frame_code[i].size_mul  ) tmp_fields = 2;

        if (tmp_stream   != nut->frame_code[i].stream_id ) tmp_fields = 3;

        if (tmp_size     != nut->frame_code[i].size_lsb  ) tmp_fields = 4;

//        if (tmp_res    != nut->frame_code[i].res            ) tmp_fields=5;

        if (tmp_head_idx != nut->frame_code[i].header_idx) tmp_fields = 8;

        tmp_pts    = nut->frame_code[i].pts_delta;

        tmp_flags  = nut->frame_code[i].flags;

        tmp_stream = nut->frame_code[i].stream_id;

        tmp_mul    = nut->frame_code[i].size_mul;

        tmp_size   = nut->frame_code[i].size_lsb;

//        tmp_res   = nut->frame_code[i].res;

        tmp_head_idx = nut->frame_code[i].header_idx;

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

            if (i == 'N') {

                j--;

                continue;

            }

            if (nut->frame_code[i].pts_delta  != tmp_pts      ||

                nut->frame_code[i].flags      != tmp_flags    ||

                nut->frame_code[i].stream_id  != tmp_stream   ||

                nut->frame_code[i].size_mul   != tmp_mul      ||

                nut->frame_code[i].size_lsb   != tmp_size + j ||

//              nut->frame_code[i].res        != tmp_res      ||

                nut->frame_code[i].header_idx != tmp_head_idx)

                break;

        }

        if (j != tmp_mul - tmp_size)

            tmp_fields = 6;

        ff_put_v(bc, tmp_flags);

        ff_put_v(bc, tmp_fields);

        if (tmp_fields > 0) put_s(bc, tmp_pts);

        if (tmp_fields > 1) ff_put_v(bc, tmp_mul);

        if (tmp_fields > 2) ff_put_v(bc, tmp_stream);

        if (tmp_fields > 3) ff_put_v(bc, tmp_size);

        if (tmp_fields > 4) ff_put_v(bc, 0 /*tmp_res*/);

        if (tmp_fields > 5) ff_put_v(bc, j);

        if (tmp_fields > 6) ff_put_v(bc, tmp_match);

        if (tmp_fields > 7) ff_put_v(bc, tmp_head_idx);

    }

    ff_put_v(bc, nut->header_count - 1);

    for (i = 1; i < nut->header_count; i++) {

        ff_put_v(bc, nut->header_len[i]);

        avio_write(bc, nut->header[i], nut->header_len[i]);

    }

    // flags had been effectively introduced in version 4

    if (nut->version > NUT_STABLE_VERSION)

        ff_put_v(bc, nut->flags);

}


static void mmubooke_create_initial_mapping(CPUPPCState *env,

                                     target_ulong va,

                                     hwaddr pa)

{

    ppcemb_tlb_t *tlb = &env->tlb.tlbe[0];

    tlb->attr = 0;

    tlb->prot = PAGE_VALID | ((PAGE_READ | PAGE_WRITE | PAGE_EXEC) << 4);

    tlb->size = 1 << 31; /* up to 0x80000000  */

    tlb->EPN = va & TARGET_PAGE_MASK;

    tlb->RPN = pa & TARGET_PAGE_MASK;

    tlb->PID = 0;

    tlb = &env->tlb.tlbe[1];

    tlb->attr = 0;

    tlb->prot = PAGE_VALID | ((PAGE_READ | PAGE_WRITE | PAGE_EXEC) << 4);

    tlb->size = 1 << 31; /* up to 0xffffffff  */

    tlb->EPN = 0x80000000 & TARGET_PAGE_MASK;

    tlb->RPN = 0x80000000 & TARGET_PAGE_MASK;

    tlb->PID = 0;

}


struct pxa2xx_pcmcia_s *pxa2xx_pcmcia_init(target_phys_addr_t base)

{

    int iomemtype;

    struct pxa2xx_pcmcia_s *s;

    s = (struct pxa2xx_pcmcia_s *)

            qemu_mallocz(sizeof(struct pxa2xx_pcmcia_s));

    /* Socket I/O Memory Space */

    s->io_base = base | 0x00000000;

    iomemtype = cpu_register_io_memory(0, pxa2xx_pcmcia_io_readfn,

                    pxa2xx_pcmcia_io_writefn, s);

    cpu_register_physical_memory(s->io_base, 0x03ffffff, iomemtype);

    /* Then next 64 MB is reserved */

    /* Socket Attribute Memory Space */

    s->attr_base = base | 0x08000000;

    iomemtype = cpu_register_io_memory(0, pxa2xx_pcmcia_attr_readfn,

                    pxa2xx_pcmcia_attr_writefn, s);

    cpu_register_physical_memory(s->attr_base, 0x03ffffff, iomemtype);

    /* Socket Common Memory Space */

    s->common_base = base | 0x0c000000;

    iomemtype = cpu_register_io_memory(0, pxa2xx_pcmcia_common_readfn,

                    pxa2xx_pcmcia_common_writefn, s);

    cpu_register_physical_memory(s->common_base, 0x03ffffff, iomemtype);

    if (base == 0x30000000)

        s->slot.slot_string = "PXA PC Card Socket 1";

    else

        s->slot.slot_string = "PXA PC Card Socket 0";

    s->slot.irq = qemu_allocate_irqs(pxa2xx_pcmcia_set_irq, s, 1)[0];

    pcmcia_socket_register(&s->slot);

    return s;

}


static int mov_text_decode_frame(AVCodecContext *avctx,
                            void *data, int *got_sub_ptr, AVPacket *avpkt)
{
    AVSubtitle *sub = data;
    MovTextContext *m = avctx->priv_data;
    int ret;
    AVBPrint buf;
    char *ptr = avpkt->data;
    char *end;
    int text_length, tsmb_type, ret_tsmb;
    uint64_t tsmb_size;
    const uint8_t *tsmb;
    if (!ptr || avpkt->size < 2)
        return AVERROR_INVALIDDATA;
    /*
     * A packet of size two with value zero is an empty subtitle
     * used to mark the end of the previous non-empty subtitle.
     * We can just drop them here as we have duration information
     * already. If the value is non-zero, then it's technically a
     * bad packet.
     */
    if (avpkt->size == 2)
        return AV_RB16(ptr) == 0 ? 0 : AVERROR_INVALIDDATA;
    /*
     * The first two bytes of the packet are the length of the text string
     * In complex cases, there are style descriptors appended to the string
     * so we can't just assume the packet size is the string size.
     */
    text_length = AV_RB16(ptr);
    end = ptr + FFMIN(2 + text_length, avpkt->size);
    ptr += 2;
    tsmb_size = 0;
    m->tracksize = 2 + text_length;
    m->style_entries = 0;
    m->box_flags = 0;
    m->count_s = 0;
    // Note that the spec recommends lines be no longer than 2048 characters.
    av_bprint_init(&buf, 0, AV_BPRINT_SIZE_UNLIMITED);
    if (text_length + 2 != avpkt->size) {
        while (m->tracksize + 8 <= avpkt->size) {
            // A box is a minimum of 8 bytes.
            tsmb = ptr + m->tracksize - 2;
            tsmb_size = AV_RB32(tsmb);
            tsmb += 4;
            tsmb_type = AV_RB32(tsmb);
            tsmb += 4;
            if (tsmb_size == 1) {
                if (m->tracksize + 16 > avpkt->size)
                    break;
                tsmb_size = AV_RB64(tsmb);
                tsmb += 8;
                m->size_var = 16;
            } else
                m->size_var = 8;
            //size_var is equal to 8 or 16 depending on the size of box
            if (tsmb_size == 0) {
                av_log(avctx, AV_LOG_ERROR, "tsmb_size is 0\n");
                return AVERROR_INVALIDDATA;
            }
            if (tsmb_size > avpkt->size - m->tracksize)
                break;
            for (size_t i = 0; i < box_count; i++) {
                if (tsmb_type == box_types[i].type) {
                    if (m->tracksize + m->size_var + box_types[i].base_size > avpkt->size)
                        break;
                    ret_tsmb = box_types[i].decode(tsmb, m, avpkt);
                    if (ret_tsmb == -1)
                        break;
                }
            }
            m->tracksize = m->tracksize + tsmb_size;
        }
        text_to_ass(&buf, ptr, end, m);
    } else
        text_to_ass(&buf, ptr, end, m);
    ret = ff_ass_add_rect(sub, buf.str, m->readorder++, 0, NULL, NULL);
    av_bprint_finalize(&buf, NULL);
    if (ret < 0)
        return ret;
    *got_sub_ptr = sub->num_rects > 0;
    return avpkt->size;
}


static int ra144_decode_frame(AVCodecContext * avctx, void *data,

                              int *got_frame_ptr, AVPacket *avpkt)

{

    AVFrame *frame     = data;

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    static const uint8_t sizes[LPC_ORDER] = {6, 5, 5, 4, 4, 3, 3, 3, 3, 2};

    unsigned int refl_rms[NBLOCKS];           // RMS of the reflection coefficients

    int16_t block_coefs[NBLOCKS][LPC_ORDER];  // LPC coefficients of each sub-block

    unsigned int lpc_refl[LPC_ORDER];         // LPC reflection coefficients of the frame

    int i, j;

    int ret;

    int16_t *samples;

    unsigned int energy;

    RA144Context *ractx = avctx->priv_data;

    GetBitContext gb;

    if (buf_size < FRAME_SIZE) {

        av_log(avctx, AV_LOG_ERROR,

               "Frame too small (%d bytes). Truncated file?\n", buf_size);

        *got_frame_ptr = 0;

        return AVERROR_INVALIDDATA;

    }

    /* get output buffer */

    frame->nb_samples = NBLOCKS * BLOCKSIZE;

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

        return ret;

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

    init_get_bits8(&gb, buf, FRAME_SIZE);

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

        lpc_refl[i] = ff_lpc_refl_cb[i][get_bits(&gb, sizes[i])];

    ff_eval_coefs(ractx->lpc_coef[0], lpc_refl);

    ractx->lpc_refl_rms[0] = ff_rms(lpc_refl);

    energy = ff_energy_tab[get_bits(&gb, 5)];

    refl_rms[0] = ff_interp(ractx, block_coefs[0], 1, 1, ractx->old_energy);

    refl_rms[1] = ff_interp(ractx, block_coefs[1], 2,

                            energy <= ractx->old_energy,

                            ff_t_sqrt(energy*ractx->old_energy) >> 12);

    refl_rms[2] = ff_interp(ractx, block_coefs[2], 3, 0, energy);

    refl_rms[3] = ff_rescale_rms(ractx->lpc_refl_rms[0], energy);

    ff_int_to_int16(block_coefs[3], ractx->lpc_coef[0]);

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

        do_output_subblock(ractx, block_coefs[i], refl_rms[i], &gb);

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

            *samples++ = av_clip_int16(ractx->curr_sblock[j + 10] << 2);

    }

    ractx->old_energy = energy;

    ractx->lpc_refl_rms[1] = ractx->lpc_refl_rms[0];

    FFSWAP(unsigned int *, ractx->lpc_coef[0], ractx->lpc_coef[1]);

    *got_frame_ptr = 1;

    return FRAME_SIZE;

}


static void iscsi_timed_set_events(void *opaque)

{

    IscsiLun *iscsilun = opaque;

    iscsi_set_events(iscsilun);

}


void mips_cpu_dump_state(CPUState *cs, FILE *f, fprintf_function cpu_fprintf,

                         int flags)

{

    MIPSCPU *cpu = MIPS_CPU(cs);

    CPUMIPSState *env = &cpu->env;

    int i;

    cpu_fprintf(f, "pc=0x" TARGET_FMT_lx " HI=0x" TARGET_FMT_lx

                " LO=0x" TARGET_FMT_lx " ds %04x "

                TARGET_FMT_lx " " TARGET_FMT_ld "\n",

                env->active_tc.PC, env->active_tc.HI[0], env->active_tc.LO[0],

                env->hflags, env->btarget, env->bcond);

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

        if ((i & 3) == 0)

            cpu_fprintf(f, "GPR%02d:", i);

        cpu_fprintf(f, " %s " TARGET_FMT_lx, regnames[i], env->active_tc.gpr[i]);

        if ((i & 3) == 3)

            cpu_fprintf(f, "\n");

    }

    cpu_fprintf(f, "CP0 Status  0x%08x Cause   0x%08x EPC    0x" TARGET_FMT_lx "\n",

                env->CP0_Status, env->CP0_Cause, env->CP0_EPC);

    cpu_fprintf(f, "    Config0 0x%08x Config1 0x%08x LLAddr 0x%016"

                PRIx64 "\n",

                env->CP0_Config0, env->CP0_Config1, env->lladdr);

    cpu_fprintf(f, "    Config2 0x%08x Config3 0x%08x\n",

                env->CP0_Config2, env->CP0_Config3);

    cpu_fprintf(f, "    Config4 0x%08x Config5 0x%08x\n",

                env->CP0_Config4, env->CP0_Config5);

    if (env->hflags & MIPS_HFLAG_FPU)

        fpu_dump_state(env, f, cpu_fprintf, flags);

#if defined(TARGET_MIPS64) && defined(MIPS_DEBUG_SIGN_EXTENSIONS)

    cpu_mips_check_sign_extensions(env, f, cpu_fprintf, flags);

#endif

}


static gboolean serial_xmit(GIOChannel *chan, GIOCondition cond, void *opaque)

{

    SerialState *s = opaque;

    do {

        if (s->tsr_retry <= 0) {

            if (s->fcr & UART_FCR_FE) {

                if (fifo8_is_empty(&s->xmit_fifo)) {

                    return FALSE;

                }

                s->tsr = fifo8_pop(&s->xmit_fifo);

                if (!s->xmit_fifo.num) {

                    s->lsr |= UART_LSR_THRE;

                }

            } else if ((s->lsr & UART_LSR_THRE)) {

                return FALSE;

            } else {

                s->tsr = s->thr;

                s->lsr |= UART_LSR_THRE;

                s->lsr &= ~UART_LSR_TEMT;

            }

        }

        if (s->mcr & UART_MCR_LOOP) {

            /* in loopback mode, say that we just received a char */

            serial_receive1(s, &s->tsr, 1);

        } else if (qemu_chr_fe_write(s->chr, &s->tsr, 1) != 1) {

            if (s->tsr_retry >= 0 && s->tsr_retry < MAX_XMIT_RETRY &&

                qemu_chr_fe_add_watch(s->chr, G_IO_OUT|G_IO_HUP,

                                      serial_xmit, s) > 0) {

                s->tsr_retry++;

                return FALSE;

            }

            s->tsr_retry = 0;

        } else {

            s->tsr_retry = 0;

        }

        /* Transmit another byte if it is already available. It is only

           possible when FIFO is enabled and not empty. */

    } while ((s->fcr & UART_FCR_FE) && !fifo8_is_empty(&s->xmit_fifo));

    s->last_xmit_ts = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);

    if (s->lsr & UART_LSR_THRE) {

        s->lsr |= UART_LSR_TEMT;

        s->thr_ipending = 1;

        serial_update_irq(s);

    }

    return FALSE;

}


static int decode_sequence_header_adv(VC1Context *v, GetBitContext *gb)

{

    v->res_rtm_flag = 1;

    v->level = get_bits(gb, 3);

    if (v->level >= 5) {

        av_log(v->s.avctx, AV_LOG_ERROR, "Reserved LEVEL %i\n",v->level);

    }

    v->chromaformat = get_bits(gb, 2);

    if (v->chromaformat != 1) {

        av_log(v->s.avctx, AV_LOG_ERROR,

               "Only 4:2:0 chroma format supported\n");

        return -1;

    }

    // (fps-2)/4 (->30)

    v->frmrtq_postproc       = get_bits(gb, 3); //common

    // (bitrate-32kbps)/64kbps

    v->bitrtq_postproc       = get_bits(gb, 5); //common

    v->postprocflag          = get_bits1(gb);   //common

    v->s.avctx->coded_width  = (get_bits(gb, 12) + 1) << 1;

    v->s.avctx->coded_height = (get_bits(gb, 12) + 1) << 1;

    v->s.avctx->width        = v->s.avctx->coded_width;

    v->s.avctx->height       = v->s.avctx->coded_height;

    v->broadcast             = get_bits1(gb);

    v->interlace             = get_bits1(gb);

    v->tfcntrflag            = get_bits1(gb);

    v->finterpflag           = get_bits1(gb);

    skip_bits1(gb); // reserved

    av_log(v->s.avctx, AV_LOG_DEBUG,

           "Advanced Profile level %i:\nfrmrtq_postproc=%i, bitrtq_postproc=%i\n"

           "LoopFilter=%i, ChromaFormat=%i, Pulldown=%i, Interlace: %i\n"

           "TFCTRflag=%i, FINTERPflag=%i\n",

           v->level, v->frmrtq_postproc, v->bitrtq_postproc,

           v->s.loop_filter, v->chromaformat, v->broadcast, v->interlace,

           v->tfcntrflag, v->finterpflag);

    v->psf = get_bits1(gb);

    if (v->psf) { //PsF, 6.1.13

        av_log(v->s.avctx, AV_LOG_ERROR, "Progressive Segmented Frame mode: not supported (yet)\n");

        return -1;

    }

    v->s.max_b_frames = v->s.avctx->max_b_frames = 7;

    if (get_bits1(gb)) { //Display Info - decoding is not affected by it

        int w, h, ar = 0;

        av_log(v->s.avctx, AV_LOG_DEBUG, "Display extended info:\n");

        w = get_bits(gb, 14) + 1;

        h = get_bits(gb, 14) + 1;

        av_log(v->s.avctx, AV_LOG_DEBUG, "Display dimensions: %ix%i\n", w, h);

        if (get_bits1(gb))

            ar = get_bits(gb, 4);

        if (ar && ar < 14) {

            v->s.avctx->sample_aspect_ratio = ff_vc1_pixel_aspect[ar];

        } else if (ar == 15) {

            w = get_bits(gb, 8) + 1;

            h = get_bits(gb, 8) + 1;

            v->s.avctx->sample_aspect_ratio = (AVRational){w, h};

        } else {

            av_reduce(&v->s.avctx->sample_aspect_ratio.num,

                      &v->s.avctx->sample_aspect_ratio.den,

                      v->s.avctx->height * w,

                      v->s.avctx->width * h,

                      1 << 30);

        }

        av_log(v->s.avctx, AV_LOG_DEBUG, "Aspect: %i:%i\n",

               v->s.avctx->sample_aspect_ratio.num,

               v->s.avctx->sample_aspect_ratio.den);

        if (get_bits1(gb)) { //framerate stuff

            if (get_bits1(gb)) {

                v->s.avctx->time_base.num = 32;

                v->s.avctx->time_base.den = get_bits(gb, 16) + 1;

            } else {

                int nr, dr;

                nr = get_bits(gb, 8);

                dr = get_bits(gb, 4);

                if (nr && nr < 8 && dr && dr < 3) {

                    v->s.avctx->time_base.num = ff_vc1_fps_dr[dr - 1];

                    v->s.avctx->time_base.den = ff_vc1_fps_nr[nr - 1] * 1000;

                }

            }

            if (v->broadcast) { // Pulldown may be present

                v->s.avctx->time_base.den  *= 2;

                v->s.avctx->ticks_per_frame = 2;

            }

        }

        if (get_bits1(gb)) {

            v->color_prim    = get_bits(gb, 8);

            v->transfer_char = get_bits(gb, 8);

            v->matrix_coef   = get_bits(gb, 8);

        }

    }

    v->hrd_param_flag = get_bits1(gb);

    if (v->hrd_param_flag) {

        int i;

        v->hrd_num_leaky_buckets = get_bits(gb, 5);

        skip_bits(gb, 4); //bitrate exponent

        skip_bits(gb, 4); //buffer size exponent

        for (i = 0; i < v->hrd_num_leaky_buckets; i++) {

            skip_bits(gb, 16); //hrd_rate[n]

            skip_bits(gb, 16); //hrd_buffer[n]

        }

    }

    return 0;

}


static int qemu_gluster_parse_json(BlockdevOptionsGluster *gconf,

                                  QDict *options, Error **errp)

{

    QemuOpts *opts;

    SocketAddress *gsconf = NULL;

    SocketAddressList *curr = NULL;

    QDict *backing_options = NULL;

    Error *local_err = NULL;

    char *str = NULL;

    const char *ptr;

    size_t num_servers;

    int i, type;

    /* create opts info from runtime_json_opts list */

    opts = qemu_opts_create(&runtime_json_opts, NULL, 0, &error_abort);

    qemu_opts_absorb_qdict(opts, options, &local_err);

    if (local_err) {

        goto out;

    }

    num_servers = qdict_array_entries(options, GLUSTER_OPT_SERVER_PATTERN);

    if (num_servers < 1) {

        error_setg(&local_err, QERR_MISSING_PARAMETER, "server");

        goto out;

    }

    ptr = qemu_opt_get(opts, GLUSTER_OPT_VOLUME);

    if (!ptr) {

        error_setg(&local_err, QERR_MISSING_PARAMETER, GLUSTER_OPT_VOLUME);

        goto out;

    }

    gconf->volume = g_strdup(ptr);

    ptr = qemu_opt_get(opts, GLUSTER_OPT_PATH);

    if (!ptr) {

        error_setg(&local_err, QERR_MISSING_PARAMETER, GLUSTER_OPT_PATH);

        goto out;

    }

    gconf->path = g_strdup(ptr);

    qemu_opts_del(opts);

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

        str = g_strdup_printf(GLUSTER_OPT_SERVER_PATTERN"%d.", i);

        qdict_extract_subqdict(options, &backing_options, str);

        /* create opts info from runtime_type_opts list */

        opts = qemu_opts_create(&runtime_type_opts, NULL, 0, &error_abort);

        qemu_opts_absorb_qdict(opts, backing_options, &local_err);

        if (local_err) {

            goto out;

        }

        ptr = qemu_opt_get(opts, GLUSTER_OPT_TYPE);

        if (!ptr) {

            error_setg(&local_err, QERR_MISSING_PARAMETER, GLUSTER_OPT_TYPE);

            error_append_hint(&local_err, GERR_INDEX_HINT, i);

            goto out;

        }

        gsconf = g_new0(SocketAddress, 1);

        if (!strcmp(ptr, "tcp")) {

            ptr = "inet";       /* accept legacy "tcp" */

        }

        type = qapi_enum_parse(SocketAddressType_lookup, ptr,

                               SOCKET_ADDRESS_TYPE__MAX, -1, NULL);

        if (type != SOCKET_ADDRESS_TYPE_INET

            && type != SOCKET_ADDRESS_TYPE_UNIX) {

            error_setg(&local_err,

                       "Parameter '%s' may be 'inet' or 'unix'",

                       GLUSTER_OPT_TYPE);

            error_append_hint(&local_err, GERR_INDEX_HINT, i);

            goto out;

        }

        gsconf->type = type;

        qemu_opts_del(opts);

        if (gsconf->type == SOCKET_ADDRESS_TYPE_INET) {

            /* create opts info from runtime_inet_opts list */

            opts = qemu_opts_create(&runtime_inet_opts, NULL, 0, &error_abort);

            qemu_opts_absorb_qdict(opts, backing_options, &local_err);

            if (local_err) {

                goto out;

            }

            ptr = qemu_opt_get(opts, GLUSTER_OPT_HOST);

            if (!ptr) {

                error_setg(&local_err, QERR_MISSING_PARAMETER,

                           GLUSTER_OPT_HOST);

                error_append_hint(&local_err, GERR_INDEX_HINT, i);

                goto out;

            }

            gsconf->u.inet.host = g_strdup(ptr);

            ptr = qemu_opt_get(opts, GLUSTER_OPT_PORT);

            if (!ptr) {

                error_setg(&local_err, QERR_MISSING_PARAMETER,

                           GLUSTER_OPT_PORT);

                error_append_hint(&local_err, GERR_INDEX_HINT, i);

                goto out;

            }

            gsconf->u.inet.port = g_strdup(ptr);

            /* defend for unsupported fields in InetSocketAddress,

             * i.e. @ipv4, @ipv6  and @to

             */

            ptr = qemu_opt_get(opts, GLUSTER_OPT_TO);

            if (ptr) {

                gsconf->u.inet.has_to = true;

            }

            ptr = qemu_opt_get(opts, GLUSTER_OPT_IPV4);

            if (ptr) {

                gsconf->u.inet.has_ipv4 = true;

            }

            ptr = qemu_opt_get(opts, GLUSTER_OPT_IPV6);

            if (ptr) {

                gsconf->u.inet.has_ipv6 = true;

            }

            if (gsconf->u.inet.has_to) {

                error_setg(&local_err, "Parameter 'to' not supported");

                goto out;

            }

            if (gsconf->u.inet.has_ipv4 || gsconf->u.inet.has_ipv6) {

                error_setg(&local_err, "Parameters 'ipv4/ipv6' not supported");

                goto out;

            }

            qemu_opts_del(opts);

        } else {

            /* create opts info from runtime_unix_opts list */

            opts = qemu_opts_create(&runtime_unix_opts, NULL, 0, &error_abort);

            qemu_opts_absorb_qdict(opts, backing_options, &local_err);

            if (local_err) {

                goto out;

            }

            ptr = qemu_opt_get(opts, GLUSTER_OPT_SOCKET);

            if (!ptr) {

                error_setg(&local_err, QERR_MISSING_PARAMETER,

                           GLUSTER_OPT_SOCKET);

                error_append_hint(&local_err, GERR_INDEX_HINT, i);

                goto out;

            }

            gsconf->u.q_unix.path = g_strdup(ptr);

            qemu_opts_del(opts);

        }

        if (gconf->server == NULL) {

            gconf->server = g_new0(SocketAddressList, 1);

            gconf->server->value = gsconf;

            curr = gconf->server;

        } else {

            curr->next = g_new0(SocketAddressList, 1);

            curr->next->value = gsconf;

            curr = curr->next;

        }

        gsconf = NULL;

        QDECREF(backing_options);

        backing_options = NULL;

        g_free(str);

        str = NULL;

    }

    return 0;

out:

    error_propagate(errp, local_err);

    qapi_free_SocketAddress(gsconf);

    qemu_opts_del(opts);

    g_free(str);

    QDECREF(backing_options);

    errno = EINVAL;

    return -errno;

}


static int try_seek_hole(BlockDriverState *bs, off_t start, off_t *data,

                         off_t *hole)

{

#if defined SEEK_HOLE && defined SEEK_DATA

    BDRVRawState *s = bs->opaque;

    *hole = lseek(s->fd, start, SEEK_HOLE);

    if (*hole == -1) {

        return -errno;

    }

    if (*hole > start) {

        *data = start;

    } else {

        /* On a hole.  We need another syscall to find its end.  */

        *data = lseek(s->fd, start, SEEK_DATA);

        if (*data == -1) {

            *data = lseek(s->fd, 0, SEEK_END);

        }

    }

    return 0;

#else

    return -ENOTSUP;

#endif

}


static int net_client_init(const char *str)

{

    const char *p;

    char *q;

    char device[64];

    char buf[1024];

    int vlan_id, ret;

    VLANState *vlan;

    p = str;

    q = device;

    while (*p != '\0' && *p != ',') {

        if ((q - device) < sizeof(device) - 1)

            *q++ = *p;

        p++;

    }

    *q = '\0';

    if (*p == ',')

        p++;

    vlan_id = 0;

    if (get_param_value(buf, sizeof(buf), "vlan", p)) {

        vlan_id = strtol(buf, NULL, 0);

    }

    vlan = qemu_find_vlan(vlan_id);

    if (!vlan) {

        fprintf(stderr, "Could not create vlan %d\n", vlan_id);

        return -1;

    }

    if (!strcmp(device, "nic")) {

        NICInfo *nd;

        uint8_t *macaddr;

        if (nb_nics >= MAX_NICS) {

            fprintf(stderr, "Too Many NICs\n");

            return -1;

        }

        nd = &nd_table[nb_nics];

        macaddr = nd->macaddr;

        macaddr[0] = 0x52;

        macaddr[1] = 0x54;

        macaddr[2] = 0x00;

        macaddr[3] = 0x12;

        macaddr[4] = 0x34;

        macaddr[5] = 0x56 + nb_nics;

        if (get_param_value(buf, sizeof(buf), "macaddr", p)) {

            if (parse_macaddr(macaddr, buf) < 0) {

                fprintf(stderr, "invalid syntax for ethernet address\n");

                return -1;

            }

        }

        if (get_param_value(buf, sizeof(buf), "model", p)) {

            nd->model = strdup(buf);

        }

        nd->vlan = vlan;

        nb_nics++;

        vlan->nb_guest_devs++;

        ret = 0;

    } else

    if (!strcmp(device, "none")) {

        /* does nothing. It is needed to signal that no network cards

           are wanted */

        ret = 0;

    } else

#ifdef CONFIG_SLIRP

    if (!strcmp(device, "user")) {

        if (get_param_value(buf, sizeof(buf), "hostname", p)) {

            pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);

        }

        ret = net_slirp_init(vlan);

    } else

#endif

#ifdef _WIN32

    if (!strcmp(device, "tap")) {

        char ifname[64];

        if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {

            fprintf(stderr, "tap: no interface name\n");

            return -1;

        }

        ret = tap_win32_init(vlan, ifname);

    } else

#else

    if (!strcmp(device, "tap")) {

        char ifname[64];

        char setup_script[1024];

        int fd;

        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {

            fd = strtol(buf, NULL, 0);

            ret = -1;

            if (net_tap_fd_init(vlan, fd))

                ret = 0;

        } else {

            if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {

                ifname[0] = '\0';

            }

            if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {

                pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);

            }

            ret = net_tap_init(vlan, ifname, setup_script);

        }

    } else

#endif

    if (!strcmp(device, "socket")) {

        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {

            int fd;

            fd = strtol(buf, NULL, 0);

            ret = -1;

            if (net_socket_fd_init(vlan, fd, 1))

                ret = 0;

        } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {

            ret = net_socket_listen_init(vlan, buf);

        } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {

            ret = net_socket_connect_init(vlan, buf);

        } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {

            ret = net_socket_mcast_init(vlan, buf);

        } else {

            fprintf(stderr, "Unknown socket options: %s\n", p);

            return -1;

        }

    } else

    {

        fprintf(stderr, "Unknown network device: %s\n", device);

        return -1;

    }

    if (ret < 0) {

        fprintf(stderr, "Could not initialize device '%s'\n", device);

    }

    return ret;

}


static void kvm_io_ioeventfd_add(MemoryListener *listener,

                                 MemoryRegionSection *section,

                                 bool match_data, uint64_t data,

                                 EventNotifier *e)

{

    int fd = event_notifier_get_fd(e);

    int r;

    r = kvm_set_ioeventfd_pio(fd, section->offset_within_address_space,

                              data, true, int128_get64(section->size),

                              match_data);

    if (r < 0) {

        abort();

    }

}


void opt_input_file(const char *filename)

{

    AVFormatContext *ic;

    AVFormatParameters params, *ap = &params;

    int err, i, ret, rfps;

    /* get default parameters from command line */

    memset(ap, 0, sizeof(*ap));

    ap->sample_rate = audio_sample_rate;

    ap->channels = audio_channels;

    ap->frame_rate = frame_rate;

    ap->width = frame_width;

    ap->height = frame_height;

    /* open the input file with generic libav function */

    err = av_open_input_file(&ic, filename, file_iformat, 0, ap);

    if (err < 0) {

        print_error(filename, err);

        exit(1);

    }

    /* If not enough info to get the stream parameters, we decode the

       first frames to get it. (used in mpeg case for example) */

    ret = av_find_stream_info(ic);

    if (ret < 0) {

        fprintf(stderr, "%s: could not find codec parameters\n", filename);

        exit(1);

    }

    /* update the current parameters so that they match the one of the input stream */

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

        AVCodecContext *enc = &ic->streams[i]->codec;

        switch(enc->codec_type) {

        case CODEC_TYPE_AUDIO:

            //fprintf(stderr, "\nInput Audio channels: %d", enc->channels);

            audio_channels = enc->channels;

            audio_sample_rate = enc->sample_rate;

            break;

        case CODEC_TYPE_VIDEO:

            frame_height = enc->height;

            frame_width = enc->width;

            rfps = ic->streams[i]->r_frame_rate;

            if (enc->frame_rate != rfps) {

                fprintf(stderr,"\nSeems that stream %d comes from film source: %2.2f->%2.2f\n",

                    i, (float)enc->frame_rate / FRAME_RATE_BASE,

                    (float)rfps / FRAME_RATE_BASE);

            }

            /* update the current frame rate to match the stream frame rate */

            frame_rate = rfps;

            break;

        default:

            abort();

        }

    }

    input_files[nb_input_files] = ic;

    /* dump the file content */

    dump_format(ic, nb_input_files, filename, 0);

    nb_input_files++;

    file_iformat = NULL;

    file_oformat = NULL;

}


static inline bool regime_is_secure(CPUARMState *env, ARMMMUIdx mmu_idx)

{

    switch (mmu_idx) {

    case ARMMMUIdx_S12NSE0:

    case ARMMMUIdx_S12NSE1:

    case ARMMMUIdx_S1NSE0:

    case ARMMMUIdx_S1NSE1:

    case ARMMMUIdx_S1E2:

    case ARMMMUIdx_S2NS:

        return false;

    case ARMMMUIdx_S1E3:

    case ARMMMUIdx_S1SE0:

    case ARMMMUIdx_S1SE1:

        return true;

    default:

        g_assert_not_reached();

    }

}


static int parse_iplconvkernel(IplConvKernel **kernel, char *buf, void *log_ctx)

{

    char shape_filename[128] = "", shape_str[32] = "rect";

    int cols = 0, rows = 0, anchor_x = 0, anchor_y = 0, shape = CV_SHAPE_RECT;

    int *values = NULL, ret;

    sscanf(buf, "%dx%d+%dx%d/%32[^=]=%127s", &cols, &rows, &anchor_x, &anchor_y, shape_str, shape_filename);

    if      (!strcmp(shape_str, "rect"   )) shape = CV_SHAPE_RECT;

    else if (!strcmp(shape_str, "cross"  )) shape = CV_SHAPE_CROSS;

    else if (!strcmp(shape_str, "ellipse")) shape = CV_SHAPE_ELLIPSE;

    else if (!strcmp(shape_str, "custom" )) {

        shape = CV_SHAPE_CUSTOM;

        if ((ret = read_shape_from_file(&cols, &rows, &values, shape_filename, log_ctx)) < 0)

            return ret;

    } else {

        av_log(log_ctx, AV_LOG_ERROR,

               "Shape unspecified or type '%s' unknown.\n", shape_str);

        return AVERROR(EINVAL);

    }

    if (rows <= 0 || cols <= 0) {

        av_log(log_ctx, AV_LOG_ERROR,

               "Invalid non-positive values for shape size %dx%d\n", cols, rows);

        return AVERROR(EINVAL);

    }

    if (anchor_x < 0 || anchor_y < 0 || anchor_x >= cols || anchor_y >= rows) {

        av_log(log_ctx, AV_LOG_ERROR,

               "Shape anchor %dx%d is not inside the rectangle with size %dx%d.\n",

               anchor_x, anchor_y, cols, rows);

        return AVERROR(EINVAL);

    }

    *kernel = cvCreateStructuringElementEx(cols, rows, anchor_x, anchor_y, shape, values);

    av_freep(&values);

    if (!*kernel)

        return AVERROR(ENOMEM);

    av_log(log_ctx, AV_LOG_VERBOSE, "Structuring element: w:%d h:%d x:%d y:%d shape:%s\n",

           rows, cols, anchor_x, anchor_y, shape_str);

    return 0;

}


static uint32_t pci_up_read(void *opaque, uint32_t addr)

{

    PIIX4PMState *s = opaque;

    uint32_t val = s->pci0_status.up;

    PIIX4_DPRINTF("pci_up_read %x\n", val);

    return val;

}


static int amovie_request_frame(AVFilterLink *outlink)

{

    MovieContext *movie = outlink->src->priv;

    int ret;

    if (movie->is_done)

        return AVERROR_EOF;

    if ((ret = amovie_get_samples(outlink)) < 0)

        return ret;

    avfilter_filter_samples(outlink, avfilter_ref_buffer(movie->samplesref, ~0));

    avfilter_unref_buffer(movie->samplesref);

    movie->samplesref = NULL;

    return 0;

}


inline static void RENAME(hcscale)(uint16_t *dst, long dstWidth, uint8_t *src1, uint8_t *src2,

				   int srcW, int xInc, int flags, int canMMX2BeUsed, int16_t *hChrFilter,

				   int16_t *hChrFilterPos, int hChrFilterSize, void *funnyUVCode,

				   int srcFormat, uint8_t *formatConvBuffer, int16_t *mmx2Filter,

				   int32_t *mmx2FilterPos, uint8_t *pal)

{

    if(srcFormat==PIX_FMT_YUYV422)

    {

	RENAME(yuy2ToUV)(formatConvBuffer, formatConvBuffer+2048, src1, src2, srcW);

	src1= formatConvBuffer;

	src2= formatConvBuffer+2048;

    }

    else if(srcFormat==PIX_FMT_UYVY422)

    {

	RENAME(uyvyToUV)(formatConvBuffer, formatConvBuffer+2048, src1, src2, srcW);

	src1= formatConvBuffer;

	src2= formatConvBuffer+2048;

    }

    else if(srcFormat==PIX_FMT_RGB32)

    {

	RENAME(bgr32ToUV)(formatConvBuffer, formatConvBuffer+2048, src1, src2, srcW);

	src1= formatConvBuffer;

	src2= formatConvBuffer+2048;

    }

    else if(srcFormat==PIX_FMT_BGR24)

    {

	RENAME(bgr24ToUV)(formatConvBuffer, formatConvBuffer+2048, src1, src2, srcW);

	src1= formatConvBuffer;

	src2= formatConvBuffer+2048;

    }

    else if(srcFormat==PIX_FMT_BGR565)

    {

	RENAME(bgr16ToUV)(formatConvBuffer, formatConvBuffer+2048, src1, src2, srcW);

	src1= formatConvBuffer;

	src2= formatConvBuffer+2048;

    }

    else if(srcFormat==PIX_FMT_BGR555)

    {

	RENAME(bgr15ToUV)(formatConvBuffer, formatConvBuffer+2048, src1, src2, srcW);

	src1= formatConvBuffer;

	src2= formatConvBuffer+2048;

    }

    else if(srcFormat==PIX_FMT_BGR32)

    {

	RENAME(rgb32ToUV)(formatConvBuffer, formatConvBuffer+2048, src1, src2, srcW);

	src1= formatConvBuffer;

	src2= formatConvBuffer+2048;

    }

    else if(srcFormat==PIX_FMT_RGB24)

    {

	RENAME(rgb24ToUV)(formatConvBuffer, formatConvBuffer+2048, src1, src2, srcW);

	src1= formatConvBuffer;

	src2= formatConvBuffer+2048;

    }

    else if(srcFormat==PIX_FMT_RGB565)

    {

	RENAME(rgb16ToUV)(formatConvBuffer, formatConvBuffer+2048, src1, src2, srcW);

	src1= formatConvBuffer;

	src2= formatConvBuffer+2048;

    }

    else if(srcFormat==PIX_FMT_RGB555)

    {

	RENAME(rgb15ToUV)(formatConvBuffer, formatConvBuffer+2048, src1, src2, srcW);

	src1= formatConvBuffer;

	src2= formatConvBuffer+2048;

    }

    else if(isGray(srcFormat))

    {

    	return;

    }

    else if(srcFormat==PIX_FMT_RGB8 || srcFormat==PIX_FMT_BGR8 || srcFormat==PIX_FMT_PAL8 || srcFormat==PIX_FMT_BGR4_BYTE  || srcFormat==PIX_FMT_RGB4_BYTE)

    {

	RENAME(palToUV)(formatConvBuffer, formatConvBuffer+2048, src1, src2, srcW, pal);

	src1= formatConvBuffer;

	src2= formatConvBuffer+2048;

    }

#ifdef HAVE_MMX

	// use the new MMX scaler if the mmx2 can't be used (its faster than the x86asm one)

    if(!(flags&SWS_FAST_BILINEAR) || (!canMMX2BeUsed))

#else

    if(!(flags&SWS_FAST_BILINEAR))

#endif

    {

    	RENAME(hScale)(dst     , dstWidth, src1, srcW, xInc, hChrFilter, hChrFilterPos, hChrFilterSize);

    	RENAME(hScale)(dst+2048, dstWidth, src2, srcW, xInc, hChrFilter, hChrFilterPos, hChrFilterSize);

    }

    else // Fast Bilinear upscale / crap downscale

    {

#if defined(ARCH_X86)

#ifdef HAVE_MMX2

	int i;

#if defined(PIC)

	uint64_t ebxsave __attribute__((aligned(8)));

#endif

	if(canMMX2BeUsed)

	{

		asm volatile(

#if defined(PIC)

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

#endif

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

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

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

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

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

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

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

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

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

#ifdef ARCH_X86_64

#define FUNNY_UV_CODE \

			"movl (%%"REG_b"), %%esi	\n\t"\

			"call *%4			\n\t"\

			"movl (%%"REG_b", %%"REG_a"), %%esi\n\t"\

			"add %%"REG_S", %%"REG_c"	\n\t"\

			"add %%"REG_a", %%"REG_D"	\n\t"\

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

#else

#define FUNNY_UV_CODE \

			"movl (%%"REG_b"), %%esi	\n\t"\

			"call *%4			\n\t"\

			"addl (%%"REG_b", %%"REG_a"), %%"REG_c"\n\t"\

			"add %%"REG_a", %%"REG_D"	\n\t"\

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

#endif

FUNNY_UV_CODE

FUNNY_UV_CODE

FUNNY_UV_CODE

FUNNY_UV_CODE

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

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

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

			"add $4096, %%"REG_D"		\n\t"

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

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

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

FUNNY_UV_CODE

FUNNY_UV_CODE

FUNNY_UV_CODE

FUNNY_UV_CODE

#if defined(PIC)

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

#endif

			:: "m" (src1), "m" (dst), "m" (mmx2Filter), "m" (mmx2FilterPos),

			"m" (funnyUVCode), "m" (src2)

#if defined(PIC)

			,"m" (ebxsave)

#endif

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

#if !defined(PIC)

			 ,"%"REG_b

#endif

		);

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

		{

//			printf("%d %d %d\n", dstWidth, i, srcW);

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

			dst[i+2048] = src2[srcW-1]*128;

		}

	}

	else

	{

#endif

	long xInc_shr16 = (long) (xInc >> 16);

	uint16_t xInc_mask = xInc & 0xffff;

	asm volatile(

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

		"xor %%"REG_d", %%"REG_d"		\n\t" // xx

		"xorl %%ecx, %%ecx		\n\t" // 2*xalpha

		ASMALIGN(4)

		"1:				\n\t"

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

		"movzbl  (%%"REG_S", %%"REG_d"), %%edi	\n\t" //src[xx]

		"movzbl 1(%%"REG_S", %%"REG_d"), %%esi	\n\t" //src[xx+1]

		"subl %%edi, %%esi		\n\t" //src[xx+1] - src[xx]

		"imull %%ecx, %%esi		\n\t" //(src[xx+1] - src[xx])*2*xalpha

		"shll $16, %%edi		\n\t"

		"addl %%edi, %%esi		\n\t" //src[xx+1]*2*xalpha + src[xx]*(1-2*xalpha)

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

		"shrl $9, %%esi			\n\t"

		"movw %%si, (%%"REG_D", %%"REG_a", 2)\n\t"

		"movzbl  (%5, %%"REG_d"), %%edi	\n\t" //src[xx]

		"movzbl 1(%5, %%"REG_d"), %%esi	\n\t" //src[xx+1]

		"subl %%edi, %%esi		\n\t" //src[xx+1] - src[xx]

		"imull %%ecx, %%esi		\n\t" //(src[xx+1] - src[xx])*2*xalpha

		"shll $16, %%edi		\n\t"

		"addl %%edi, %%esi		\n\t" //src[xx+1]*2*xalpha + src[xx]*(1-2*xalpha)

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

		"shrl $9, %%esi			\n\t"

		"movw %%si, 4096(%%"REG_D", %%"REG_a", 2)\n\t"

		"addw %4, %%cx			\n\t" //2*xalpha += xInc&0xFF

		"adc %3, %%"REG_d"		\n\t" //xx+= xInc>>8 + carry

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

		"cmp %2, %%"REG_a"		\n\t"

		" jb 1b				\n\t"

/* GCC-3.3 makes MPlayer crash on IA-32 machines when using "g" operand here,

   which is needed to support GCC-4.0 */

#if defined(ARCH_X86_64) && ((__GNUC__ > 3) || ( __GNUC__ == 3 && __GNUC_MINOR__ >= 4))

		:: "m" (src1), "m" (dst), "g" ((long)dstWidth), "m" (xInc_shr16), "m" (xInc_mask),

#else

		:: "m" (src1), "m" (dst), "m" ((long)dstWidth), "m" (xInc_shr16), "m" (xInc_mask),

#endif

		"r" (src2)

		: "%"REG_a, "%"REG_d, "%ecx", "%"REG_D, "%esi"

		);

#ifdef HAVE_MMX2

	} //if MMX2 can't be used

#endif

#else

	int i;

	unsigned int xpos=0;

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

	{

		register unsigned int xx=xpos>>16;

		register unsigned int xalpha=(xpos&0xFFFF)>>9;

		dst[i]=(src1[xx]*(xalpha^127)+src1[xx+1]*xalpha);

		dst[i+2048]=(src2[xx]*(xalpha^127)+src2[xx+1]*xalpha);

/* slower

	  dst[i]= (src1[xx]<<7) + (src1[xx+1] - src1[xx])*xalpha;

	  dst[i+2048]=(src2[xx]<<7) + (src2[xx+1] - src2[xx])*xalpha;

*/

		xpos+=xInc;

	}

#endif

   }

}


static void virtio_blk_rw_complete(void *opaque, int ret)

{

    VirtIOBlockReq *next = opaque;

    while (next) {

        VirtIOBlockReq *req = next;

        next = req->mr_next;

        trace_virtio_blk_rw_complete(req, ret);

        if (req->qiov.nalloc != -1) {

            /* If nalloc is != 1 req->qiov is a local copy of the original

             * external iovec. It was allocated in submit_merged_requests

             * to be able to merge requests. */

            qemu_iovec_destroy(&req->qiov);

        }

        if (ret) {

            int p = virtio_ldl_p(VIRTIO_DEVICE(req->dev), &req->out.type);

            bool is_read = !(p & VIRTIO_BLK_T_OUT);

            /* Note that memory may be dirtied on read failure.  If the

             * virtio request is not completed here, as is the case for

             * BLOCK_ERROR_ACTION_STOP, the memory may not be copied

             * correctly during live migration.  While this is ugly,

             * it is acceptable because the device is free to write to

             * the memory until the request is completed (which will

             * happen on the other side of the migration).

            if (virtio_blk_handle_rw_error(req, -ret, is_read)) {

                continue;

            }

        }

        virtio_blk_req_complete(req, VIRTIO_BLK_S_OK);

        block_acct_done(blk_get_stats(req->dev->blk), &req->acct);

        virtio_blk_free_request(req);

    }

}


static void qmp_input_type_str(Visitor *v, const char *name, char **obj,

                               Error **errp)

{

    QmpInputVisitor *qiv = to_qiv(v);

    QString *qstr = qobject_to_qstring(qmp_input_get_object(qiv, name, true));

    if (!qstr) {

        error_setg(errp, QERR_INVALID_PARAMETER_TYPE, name ? name : "null",

                   "string");

        return;

    }

    *obj = g_strdup(qstring_get_str(qstr));

}


static int wavpack_decode_block(AVCodecContext *avctx, int block_no,

                                void *data, int *got_frame_ptr,

                                const uint8_t *buf, int buf_size)

{

    WavpackContext *wc = avctx->priv_data;

    WavpackFrameContext *s;

    void *samples = data;

    int samplecount;

    int got_terms = 0, got_weights = 0, got_samples = 0, got_entropy = 0, got_bs = 0, got_float = 0;

    int got_hybrid = 0;

    const uint8_t* orig_buf = buf;

    const uint8_t* buf_end = buf + buf_size;

    int i, j, id, size, ssize, weights, t;

    int bpp, chan, chmask;

    if (buf_size == 0){

        *got_frame_ptr = 0;

        return 0;

    }

    if(block_no >= wc->fdec_num && wv_alloc_frame_context(wc) < 0){

        av_log(avctx, AV_LOG_ERROR, "Error creating frame decode context\n");

        return -1;

    }

    s = wc->fdec[block_no];

    if(!s){

        av_log(avctx, AV_LOG_ERROR, "Context for block %d is not present\n", block_no);

        return -1;

    }

        memset(s->decorr, 0, MAX_TERMS * sizeof(Decorr));

        memset(s->ch, 0, sizeof(s->ch));

        s->extra_bits = 0;

        s->and = s->or = s->shift = 0;

        s->got_extra_bits = 0;

    if(!wc->mkv_mode){

        s->samples = AV_RL32(buf); buf += 4;

        if(!s->samples){

            *got_frame_ptr = 0;

            return 0;

        }

    }else{

        s->samples = wc->samples;

    }

    s->frame_flags = AV_RL32(buf); buf += 4;

    if(s->frame_flags&0x80){

        avctx->sample_fmt = AV_SAMPLE_FMT_FLT;

    } else if((s->frame_flags&0x03) <= 1){

        avctx->sample_fmt = AV_SAMPLE_FMT_S16;

    } else {

        avctx->sample_fmt = AV_SAMPLE_FMT_S32;

    }

    bpp = av_get_bytes_per_sample(avctx->sample_fmt);

    samples = (uint8_t*)samples + bpp * wc->ch_offset;

    s->stereo = !(s->frame_flags & WV_MONO);

    s->stereo_in = (s->frame_flags & WV_FALSE_STEREO) ? 0 : s->stereo;

    s->joint = s->frame_flags & WV_JOINT_STEREO;

    s->hybrid = s->frame_flags & WV_HYBRID_MODE;

    s->hybrid_bitrate = s->frame_flags & WV_HYBRID_BITRATE;

    s->hybrid_maxclip = 1 << ((((s->frame_flags & 0x03) + 1) << 3) - 1);

    s->post_shift = 8 * (bpp-1-(s->frame_flags&0x03)) + ((s->frame_flags >> 13) & 0x1f);

    s->CRC = AV_RL32(buf); buf += 4;

    if(wc->mkv_mode)

        buf += 4; //skip block size;

    wc->ch_offset += 1 + s->stereo;

    // parse metadata blocks

    while(buf < buf_end){

        id = *buf++;

        size = *buf++;

        if(id & WP_IDF_LONG) {

            size |= (*buf++) << 8;

            size |= (*buf++) << 16;

        }

        size <<= 1; // size is specified in words

        ssize = size;

        if(id & WP_IDF_ODD) size--;

        if(size < 0){

            av_log(avctx, AV_LOG_ERROR, "Got incorrect block %02X with size %i\n", id, size);

            break;

        }

        if(buf + ssize > buf_end){

            av_log(avctx, AV_LOG_ERROR, "Block size %i is out of bounds\n", size);

            break;

        }

        if(id & WP_IDF_IGNORE){

            buf += ssize;

            continue;

        }

        switch(id & WP_IDF_MASK){

        case WP_ID_DECTERMS:

            if(size > MAX_TERMS){

                av_log(avctx, AV_LOG_ERROR, "Too many decorrelation terms\n");

                s->terms = 0;

                buf += ssize;

                continue;

            }

            s->terms = size;

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

                s->decorr[s->terms - i - 1].value = (*buf & 0x1F) - 5;

                s->decorr[s->terms - i - 1].delta = *buf >> 5;

                buf++;

            }

            got_terms = 1;

            break;

        case WP_ID_DECWEIGHTS:

            if(!got_terms){

                av_log(avctx, AV_LOG_ERROR, "No decorrelation terms met\n");

                continue;

            }

            weights = size >> s->stereo_in;

            if(weights > MAX_TERMS || weights > s->terms){

                av_log(avctx, AV_LOG_ERROR, "Too many decorrelation weights\n");

                buf += ssize;

                continue;

            }

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

                t = (int8_t)(*buf++);

                s->decorr[s->terms - i - 1].weightA = t << 3;

                if(s->decorr[s->terms - i - 1].weightA > 0)

                    s->decorr[s->terms - i - 1].weightA += (s->decorr[s->terms - i - 1].weightA + 64) >> 7;

                if(s->stereo_in){

                    t = (int8_t)(*buf++);

                    s->decorr[s->terms - i - 1].weightB = t << 3;

                    if(s->decorr[s->terms - i - 1].weightB > 0)

                        s->decorr[s->terms - i - 1].weightB += (s->decorr[s->terms - i - 1].weightB + 64) >> 7;

                }

            }

            got_weights = 1;

            break;

        case WP_ID_DECSAMPLES:

            if(!got_terms){

                av_log(avctx, AV_LOG_ERROR, "No decorrelation terms met\n");

                continue;

            }

            t = 0;

            for(i = s->terms - 1; (i >= 0) && (t < size); i--) {

                if(s->decorr[i].value > 8){

                    s->decorr[i].samplesA[0] = wp_exp2(AV_RL16(buf)); buf += 2;

                    s->decorr[i].samplesA[1] = wp_exp2(AV_RL16(buf)); buf += 2;

                    if(s->stereo_in){

                        s->decorr[i].samplesB[0] = wp_exp2(AV_RL16(buf)); buf += 2;

                        s->decorr[i].samplesB[1] = wp_exp2(AV_RL16(buf)); buf += 2;

                        t += 4;

                    }

                    t += 4;

                }else if(s->decorr[i].value < 0){

                    s->decorr[i].samplesA[0] = wp_exp2(AV_RL16(buf)); buf += 2;

                    s->decorr[i].samplesB[0] = wp_exp2(AV_RL16(buf)); buf += 2;

                    t += 4;

                }else{

                    for(j = 0; j < s->decorr[i].value; j++){

                        s->decorr[i].samplesA[j] = wp_exp2(AV_RL16(buf)); buf += 2;

                        if(s->stereo_in){

                            s->decorr[i].samplesB[j] = wp_exp2(AV_RL16(buf)); buf += 2;

                        }

                    }

                    t += s->decorr[i].value * 2 * (s->stereo_in + 1);

                }

            }

            got_samples = 1;

            break;

        case WP_ID_ENTROPY:

            if(size != 6 * (s->stereo_in + 1)){

                av_log(avctx, AV_LOG_ERROR, "Entropy vars size should be %i, got %i", 6 * (s->stereo_in + 1), size);

                buf += ssize;

                continue;

            }

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

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

                    s->ch[j].median[i] = wp_exp2(AV_RL16(buf));

                    buf += 2;

                }

            }

            got_entropy = 1;

            break;

        case WP_ID_HYBRID:

            if(s->hybrid_bitrate){

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

                    s->ch[i].slow_level = wp_exp2(AV_RL16(buf));

                    buf += 2;

                    size -= 2;

                }

            }

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

                s->ch[i].bitrate_acc = AV_RL16(buf) << 16;

                buf += 2;

                size -= 2;

            }

            if(size > 0){

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

                    s->ch[i].bitrate_delta = wp_exp2((int16_t)AV_RL16(buf));

                    buf += 2;

                }

            }else{

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

                    s->ch[i].bitrate_delta = 0;

            }

            got_hybrid = 1;

            break;

        case WP_ID_INT32INFO:

            if(size != 4){

                av_log(avctx, AV_LOG_ERROR, "Invalid INT32INFO, size = %i, sent_bits = %i\n", size, *buf);

                buf += ssize;

                continue;

            }

            if(buf[0])

                s->extra_bits = buf[0];

            else if(buf[1])

                s->shift = buf[1];

            else if(buf[2]){

                s->and = s->or = 1;

                s->shift = buf[2];

            }else if(buf[3]){

                s->and = 1;

                s->shift = buf[3];

            }

            buf += 4;

            break;

        case WP_ID_FLOATINFO:

            if(size != 4){

                av_log(avctx, AV_LOG_ERROR, "Invalid FLOATINFO, size = %i\n", size);

                buf += ssize;

                continue;

            }

            s->float_flag = buf[0];

            s->float_shift = buf[1];

            s->float_max_exp = buf[2];

            buf += 4;

            got_float = 1;

            break;

        case WP_ID_DATA:

            s->sc.offset = buf - orig_buf;

            s->sc.size   = size * 8;

            init_get_bits(&s->gb, buf, size * 8);

            s->data_size = size * 8;

            buf += size;

            got_bs = 1;

            break;

        case WP_ID_EXTRABITS:

            if(size <= 4){

                av_log(avctx, AV_LOG_ERROR, "Invalid EXTRABITS, size = %i\n", size);

                buf += size;

                continue;

            }

            s->extra_sc.offset = buf - orig_buf;

            s->extra_sc.size   = size * 8;

            init_get_bits(&s->gb_extra_bits, buf, size * 8);

            s->crc_extra_bits = get_bits_long(&s->gb_extra_bits, 32);

            buf += size;

            s->got_extra_bits = 1;

            break;

        case WP_ID_CHANINFO:

            if(size <= 1){

                av_log(avctx, AV_LOG_ERROR, "Insufficient channel information\n");

                return -1;

            }

            chan = *buf++;

            switch(size - 2){

            case 0:

                chmask = *buf;

                break;

            case 1:

                chmask = AV_RL16(buf);

                break;

            case 2:

                chmask = AV_RL24(buf);

                break;

            case 3:

                chmask = AV_RL32(buf);

                break;

            case 5:

                chan |= (buf[1] & 0xF) << 8;

                chmask = AV_RL24(buf + 2);

                break;

            default:

                av_log(avctx, AV_LOG_ERROR, "Invalid channel info size %d\n", size);

                chan = avctx->channels;

                chmask = avctx->channel_layout;

            }

            if(chan != avctx->channels){

                av_log(avctx, AV_LOG_ERROR, "Block reports total %d channels, decoder believes it's %d channels\n",

                       chan, avctx->channels);

                return -1;

            }

            if(!avctx->channel_layout)

                avctx->channel_layout = chmask;

            buf += size - 1;

            break;

        default:

            buf += size;

        }

        if(id & WP_IDF_ODD) buf++;

    }

        if(!got_terms){

            av_log(avctx, AV_LOG_ERROR, "No block with decorrelation terms\n");

            return -1;

        }

        if(!got_weights){

            av_log(avctx, AV_LOG_ERROR, "No block with decorrelation weights\n");

            return -1;

        }

        if(!got_samples){

            av_log(avctx, AV_LOG_ERROR, "No block with decorrelation samples\n");

            return -1;

        }

        if(!got_entropy){

            av_log(avctx, AV_LOG_ERROR, "No block with entropy info\n");

            return -1;

        }

        if(s->hybrid && !got_hybrid){

            av_log(avctx, AV_LOG_ERROR, "Hybrid config not found\n");

            return -1;

        }

        if(!got_bs){

            av_log(avctx, AV_LOG_ERROR, "Packed samples not found\n");

            return -1;

        }

        if(!got_float && avctx->sample_fmt == AV_SAMPLE_FMT_FLT){

            av_log(avctx, AV_LOG_ERROR, "Float information not found\n");

            return -1;

        }

        if(s->got_extra_bits && avctx->sample_fmt != AV_SAMPLE_FMT_FLT){

            const int size = get_bits_left(&s->gb_extra_bits);

            const int wanted = s->samples * s->extra_bits << s->stereo_in;

            if(size < wanted){

                av_log(avctx, AV_LOG_ERROR, "Too small EXTRABITS\n");

                s->got_extra_bits = 0;

            }

        }

    if(s->stereo_in){

        if(avctx->sample_fmt == AV_SAMPLE_FMT_S16)

            samplecount = wv_unpack_stereo(s, &s->gb, samples, AV_SAMPLE_FMT_S16);

        else if(avctx->sample_fmt == AV_SAMPLE_FMT_S32)

            samplecount = wv_unpack_stereo(s, &s->gb, samples, AV_SAMPLE_FMT_S32);

        else

            samplecount = wv_unpack_stereo(s, &s->gb, samples, AV_SAMPLE_FMT_FLT);

        if (samplecount < 0)

            return -1;

        samplecount >>= 1;

    }else{

        const int channel_stride = avctx->channels;

        if(avctx->sample_fmt == AV_SAMPLE_FMT_S16)

            samplecount = wv_unpack_mono(s, &s->gb, samples, AV_SAMPLE_FMT_S16);

        else if(avctx->sample_fmt == AV_SAMPLE_FMT_S32)

            samplecount = wv_unpack_mono(s, &s->gb, samples, AV_SAMPLE_FMT_S32);

        else

            samplecount = wv_unpack_mono(s, &s->gb, samples, AV_SAMPLE_FMT_FLT);

        if (samplecount < 0)

            return -1;

        if(s->stereo && avctx->sample_fmt == AV_SAMPLE_FMT_S16){

            int16_t *dst = (int16_t*)samples + 1;

            int16_t *src = (int16_t*)samples;

            int cnt = samplecount;

            while(cnt--){

                *dst = *src;

                src += channel_stride;

                dst += channel_stride;

            }

        }else if(s->stereo && avctx->sample_fmt == AV_SAMPLE_FMT_S32){

            int32_t *dst = (int32_t*)samples + 1;

            int32_t *src = (int32_t*)samples;

            int cnt = samplecount;

            while(cnt--){

                *dst = *src;

                src += channel_stride;

                dst += channel_stride;

            }

        }else if(s->stereo){

            float *dst = (float*)samples + 1;

            float *src = (float*)samples;

            int cnt = samplecount;

            while(cnt--){

                *dst = *src;

                src += channel_stride;

                dst += channel_stride;

            }

        }

    }

    *got_frame_ptr = 1;

    return samplecount * bpp;

}


int ff_put_wav_header(AVFormatContext *s, AVIOContext *pb,

                      AVCodecParameters *par, int flags)

{

    int bps, blkalign, bytespersec, frame_size;

    int hdrsize;

    int64_t hdrstart = avio_tell(pb);

    int waveformatextensible;

    uint8_t temp[256];

    uint8_t *riff_extradata       = temp;

    uint8_t *riff_extradata_start = temp;

    if (!par->codec_tag || par->codec_tag > 0xffff)

        return -1;

    /* We use the known constant frame size for the codec if known, otherwise

     * fall back on using AVCodecContext.frame_size, which is not as reliable

     * for indicating packet duration. */

    frame_size = av_get_audio_frame_duration2(par, par->block_align);

    waveformatextensible = (par->channels > 2 && par->channel_layout) ||

                           par->sample_rate > 48000 ||

                           par->codec_id == AV_CODEC_ID_EAC3 ||

                           av_get_bits_per_sample(par->codec_id) > 16;

    if (waveformatextensible)

        avio_wl16(pb, 0xfffe);

    else

        avio_wl16(pb, par->codec_tag);

    avio_wl16(pb, par->channels);

    avio_wl32(pb, par->sample_rate);

    if (par->codec_id == AV_CODEC_ID_ATRAC3 ||

        par->codec_id == AV_CODEC_ID_G723_1 ||

        par->codec_id == AV_CODEC_ID_MP2    ||

        par->codec_id == AV_CODEC_ID_MP3    ||

        par->codec_id == AV_CODEC_ID_GSM_MS) {

        bps = 0;

    } else {

        if (!(bps = av_get_bits_per_sample(par->codec_id))) {

            if (par->bits_per_coded_sample)

                bps = par->bits_per_coded_sample;

            else

                bps = 16;  // default to 16

        }

    }

    if (bps != par->bits_per_coded_sample && par->bits_per_coded_sample) {

        av_log(s, AV_LOG_WARNING,

               "requested bits_per_coded_sample (%d) "

               "and actually stored (%d) differ\n",

               par->bits_per_coded_sample, bps);

    }

    if (par->codec_id == AV_CODEC_ID_MP2) {

        blkalign = (144 * par->bit_rate - 1)/par->sample_rate + 1;

    } else if (par->codec_id == AV_CODEC_ID_MP3) {

        blkalign = 576 * (par->sample_rate <= (24000 + 32000)/2 ? 1 : 2);

    } else if (par->codec_id == AV_CODEC_ID_AC3) {

        blkalign = 3840;                /* maximum bytes per frame */

    } else if (par->codec_id == AV_CODEC_ID_AAC) {

        blkalign = 768 * par->channels; /* maximum bytes per frame */

    } else if (par->codec_id == AV_CODEC_ID_G723_1) {

        blkalign = 24;

    } else if (par->block_align != 0) { /* specified by the codec */

        blkalign = par->block_align;

    } else

        blkalign = bps * par->channels / av_gcd(8, bps);

    if (par->codec_id == AV_CODEC_ID_PCM_U8 ||

        par->codec_id == AV_CODEC_ID_PCM_S24LE ||

        par->codec_id == AV_CODEC_ID_PCM_S32LE ||

        par->codec_id == AV_CODEC_ID_PCM_F32LE ||

        par->codec_id == AV_CODEC_ID_PCM_F64LE ||

        par->codec_id == AV_CODEC_ID_PCM_S16LE) {

        bytespersec = par->sample_rate * blkalign;

    } else if (par->codec_id == AV_CODEC_ID_G723_1) {

        bytespersec = 800;

    } else {

        bytespersec = par->bit_rate / 8;

    }

    avio_wl32(pb, bytespersec); /* bytes per second */

    avio_wl16(pb, blkalign);    /* block align */

    avio_wl16(pb, bps);         /* bits per sample */

    if (par->codec_id == AV_CODEC_ID_MP3) {

        bytestream_put_le16(&riff_extradata, 1);    /* wID */

        bytestream_put_le32(&riff_extradata, 2);    /* fdwFlags */

        bytestream_put_le16(&riff_extradata, 1152); /* nBlockSize */

        bytestream_put_le16(&riff_extradata, 1);    /* nFramesPerBlock */

        bytestream_put_le16(&riff_extradata, 1393); /* nCodecDelay */

    } else if (par->codec_id == AV_CODEC_ID_MP2) {

        /* fwHeadLayer */

        bytestream_put_le16(&riff_extradata, 2);

        /* dwHeadBitrate */

        bytestream_put_le32(&riff_extradata, par->bit_rate);

        /* fwHeadMode */

        bytestream_put_le16(&riff_extradata, par->channels == 2 ? 1 : 8);

        /* fwHeadModeExt */

        bytestream_put_le16(&riff_extradata, 0);

        /* wHeadEmphasis */

        bytestream_put_le16(&riff_extradata, 1);

        /* fwHeadFlags */

        bytestream_put_le16(&riff_extradata, 16);

        /* dwPTSLow */

        bytestream_put_le32(&riff_extradata, 0);

        /* dwPTSHigh */

        bytestream_put_le32(&riff_extradata, 0);

    } else if (par->codec_id == AV_CODEC_ID_G723_1) {

        bytestream_put_le32(&riff_extradata, 0x9ace0002); /* extradata needed for msacm g723.1 codec */

        bytestream_put_le32(&riff_extradata, 0xaea2f732);

        bytestream_put_le16(&riff_extradata, 0xacde);

    } else if (par->codec_id == AV_CODEC_ID_GSM_MS ||

               par->codec_id == AV_CODEC_ID_ADPCM_IMA_WAV) {

        /* wSamplesPerBlock */

        bytestream_put_le16(&riff_extradata, frame_size);

    } else if (par->extradata_size) {

        riff_extradata_start = par->extradata;

        riff_extradata       = par->extradata + par->extradata_size;

    }

    /* write WAVEFORMATEXTENSIBLE extensions */

    if (waveformatextensible) {

        int write_channel_mask = !(flags & FF_PUT_WAV_HEADER_SKIP_CHANNELMASK) &&

                                 (s->strict_std_compliance < FF_COMPLIANCE_NORMAL ||

                                  par->channel_layout < 0x40000);

        /* 22 is WAVEFORMATEXTENSIBLE size */

        avio_wl16(pb, riff_extradata - riff_extradata_start + 22);

        /* ValidBitsPerSample || SamplesPerBlock || Reserved */

        avio_wl16(pb, bps);

        /* dwChannelMask */

        avio_wl32(pb, write_channel_mask ? par->channel_layout : 0);

        /* GUID + next 3 */

        if (par->codec_id == AV_CODEC_ID_EAC3) {

            ff_put_guid(pb, ff_get_codec_guid(par->codec_id, ff_codec_wav_guids));

        } else {

        avio_wl32(pb, par->codec_tag);

        avio_wl32(pb, 0x00100000);

        avio_wl32(pb, 0xAA000080);

        avio_wl32(pb, 0x719B3800);

        }

    } else if ((flags & FF_PUT_WAV_HEADER_FORCE_WAVEFORMATEX) ||

               par->codec_tag != 0x0001 /* PCM */ ||

               riff_extradata - riff_extradata_start) {

        /* WAVEFORMATEX */

        avio_wl16(pb, riff_extradata - riff_extradata_start); /* cbSize */

    } /* else PCMWAVEFORMAT */

    avio_write(pb, riff_extradata_start, riff_extradata - riff_extradata_start);

    hdrsize = avio_tell(pb) - hdrstart;

    if (hdrsize & 1) {

        hdrsize++;

        avio_w8(pb, 0);

    }

    return hdrsize;

}


MigrationCapabilityStatusList *qmp_query_migrate_capabilities(Error **errp)

{

    MigrationCapabilityStatusList *head = NULL;

    MigrationCapabilityStatusList *caps;

    MigrationState *s = migrate_get_current();

    int i;

    caps = NULL; /* silence compiler warning */

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

#ifndef CONFIG_LIVE_BLOCK_MIGRATION

        if (i == MIGRATION_CAPABILITY_BLOCK) {

            continue;

        }

#endif

        if (i == MIGRATION_CAPABILITY_X_COLO && !colo_supported()) {

            continue;

        }

        if (head == NULL) {

            head = g_malloc0(sizeof(*caps));

            caps = head;

        } else {

            caps->next = g_malloc0(sizeof(*caps));

            caps = caps->next;

        }

        caps->value =

            g_malloc(sizeof(*caps->value));

        caps->value->capability = i;

        caps->value->state = s->enabled_capabilities[i];

    }

    return head;

}


static int read_f(BlockBackend *blk, int argc, char **argv)

{

    struct timeval t1, t2;

    int Cflag = 0, pflag = 0, qflag = 0, vflag = 0;

    int Pflag = 0, sflag = 0, lflag = 0, bflag = 0;

    int c, cnt;

    char *buf;

    int64_t offset;

    int count;

    /* Some compilers get confused and warn if this is not initialized.  */

    int total = 0;

    int pattern = 0, pattern_offset = 0, pattern_count = 0;

    while ((c = getopt(argc, argv, "bCl:pP:qs:v")) != EOF) {

        switch (c) {

        case 'b':

            bflag = 1;

            break;

        case 'C':

            Cflag = 1;

            break;

        case 'l':

            lflag = 1;

            pattern_count = cvtnum(optarg);

            if (pattern_count < 0) {

                printf("non-numeric length argument -- %s\n", optarg);

                return 0;

            }

            break;

        case 'p':

            pflag = 1;

            break;

        case 'P':

            Pflag = 1;

            pattern = parse_pattern(optarg);

            if (pattern < 0) {

                return 0;

            }

            break;

        case 'q':

            qflag = 1;

            break;

        case 's':

            sflag = 1;

            pattern_offset = cvtnum(optarg);

            if (pattern_offset < 0) {

                printf("non-numeric length argument -- %s\n", optarg);

                return 0;

            }

            break;

        case 'v':

            vflag = 1;

            break;

        default:

            return qemuio_command_usage(&read_cmd);

        }

    }

    if (optind != argc - 2) {

        return qemuio_command_usage(&read_cmd);

    }

    if (bflag && pflag) {

        printf("-b and -p cannot be specified at the same time\n");

        return 0;

    }

    offset = cvtnum(argv[optind]);

    if (offset < 0) {

        printf("non-numeric length argument -- %s\n", argv[optind]);

        return 0;

    }

    optind++;

    count = cvtnum(argv[optind]);

    if (count < 0) {

        printf("non-numeric length argument -- %s\n", argv[optind]);

        return 0;

    }

    if (!Pflag && (lflag || sflag)) {

        return qemuio_command_usage(&read_cmd);

    }

    if (!lflag) {

        pattern_count = count - pattern_offset;

    }

    if ((pattern_count < 0) || (pattern_count + pattern_offset > count))  {

        printf("pattern verification range exceeds end of read data\n");

        return 0;

    }

    if (!pflag) {

        if (offset & 0x1ff) {

            printf("offset %" PRId64 " is not sector aligned\n",

                   offset);

            return 0;

        }

        if (count & 0x1ff) {

            printf("count %d is not sector aligned\n",

                   count);

            return 0;

        }

    }

    buf = qemu_io_alloc(blk, count, 0xab);

    gettimeofday(&t1, NULL);

    if (pflag) {

        cnt = do_pread(blk, buf, offset, count, &total);

    } else if (bflag) {

        cnt = do_load_vmstate(blk, buf, offset, count, &total);

    } else {

        cnt = do_read(blk, buf, offset, count, &total);

    }

    gettimeofday(&t2, NULL);

    if (cnt < 0) {

        printf("read failed: %s\n", strerror(-cnt));

        goto out;

    }

    if (Pflag) {

        void *cmp_buf = g_malloc(pattern_count);

        memset(cmp_buf, pattern, pattern_count);

        if (memcmp(buf + pattern_offset, cmp_buf, pattern_count)) {

            printf("Pattern verification failed at offset %"

                   PRId64 ", %d bytes\n",

                   offset + pattern_offset, pattern_count);

        }

        g_free(cmp_buf);

    }

    if (qflag) {

        goto out;

    }

    if (vflag) {

        dump_buffer(buf, offset, count);

    }

    /* Finally, report back -- -C gives a parsable format */

    t2 = tsub(t2, t1);

    print_report("read", &t2, offset, count, total, cnt, Cflag);

out:

    qemu_io_free(buf);

    return 0;

}


static TRBCCode xhci_disable_ep(XHCIState *xhci, unsigned int slotid,

                               unsigned int epid)

{

    XHCISlot *slot;

    XHCIEPContext *epctx;

    int i;

    trace_usb_xhci_ep_disable(slotid, epid);

    assert(slotid >= 1 && slotid <= xhci->numslots);

    assert(epid >= 1 && epid <= 31);

    slot = &xhci->slots[slotid-1];

    if (!slot->eps[epid-1]) {

        DPRINTF("xhci: slot %d ep %d already disabled\n", slotid, epid);

        return CC_SUCCESS;

    }

    xhci_ep_nuke_xfers(xhci, slotid, epid, 0);

    epctx = slot->eps[epid-1];

    if (epctx->nr_pstreams) {

        xhci_free_streams(epctx);

    }

    for (i = 0; i < ARRAY_SIZE(epctx->transfers); i++) {

        usb_packet_cleanup(&epctx->transfers[i].packet);

    }

    /* only touch guest RAM if we're not resetting the HC */

    if (xhci->dcbaap_low || xhci->dcbaap_high) {

        xhci_set_ep_state(xhci, epctx, NULL, EP_DISABLED);

    }

    timer_free(epctx->kick_timer);

    g_free(epctx);

    slot->eps[epid-1] = NULL;

    return CC_SUCCESS;

}


static void monitor_find_completion(const char *cmdline)

{

    const char *cmdname;

    char *args[MAX_ARGS];

    int nb_args, i, len;

    const char *ptype, *str;

    const mon_cmd_t *cmd;

    const KeyDef *key;

    parse_cmdline(cmdline, &nb_args, args);

#ifdef DEBUG_COMPLETION

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

        monitor_printf(cur_mon, "arg%d = '%s'\n", i, (char *)args[i]);

    }

#endif

    /* if the line ends with a space, it means we want to complete the

       next arg */

    len = strlen(cmdline);

    if (len > 0 && qemu_isspace(cmdline[len - 1])) {

        if (nb_args >= MAX_ARGS) {

            goto cleanup;

        }

        args[nb_args++] = g_strdup("");

    }

    if (nb_args <= 1) {

        /* command completion */

        if (nb_args == 0)

            cmdname = "";

        else

            cmdname = args[0];

        readline_set_completion_index(cur_mon->rs, strlen(cmdname));

        for(cmd = mon_cmds; cmd->name != NULL; cmd++) {

            cmd_completion(cmdname, cmd->name);

        }

    } else {

        /* find the command */

        for (cmd = mon_cmds; cmd->name != NULL; cmd++) {

            if (compare_cmd(args[0], cmd->name)) {

                break;

            }

        }

        if (!cmd->name) {

            goto cleanup;

        }

        ptype = next_arg_type(cmd->args_type);

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

            if (*ptype != '\0') {

                ptype = next_arg_type(ptype);

                while (*ptype == '?')

                    ptype = next_arg_type(ptype);

            }

        }

        str = args[nb_args - 1];

        if (*ptype == '-' && ptype[1] != '\0') {

            ptype = next_arg_type(ptype);

        }

        switch(*ptype) {

        case 'F':

            /* file completion */

            readline_set_completion_index(cur_mon->rs, strlen(str));

            file_completion(str);

            break;

        case 'B':

            /* block device name completion */

            readline_set_completion_index(cur_mon->rs, strlen(str));

            bdrv_iterate(block_completion_it, (void *)str);

            break;

        case 's':

            /* XXX: more generic ? */

            if (!strcmp(cmd->name, "info")) {

                readline_set_completion_index(cur_mon->rs, strlen(str));

                for(cmd = info_cmds; cmd->name != NULL; cmd++) {

                    cmd_completion(str, cmd->name);

                }

            } else if (!strcmp(cmd->name, "sendkey")) {

                char *sep = strrchr(str, '-');

                if (sep)

                    str = sep + 1;

                readline_set_completion_index(cur_mon->rs, strlen(str));

                for(key = key_defs; key->name != NULL; key++) {

                    cmd_completion(str, key->name);

                }

            } else if (!strcmp(cmd->name, "help|?")) {

                readline_set_completion_index(cur_mon->rs, strlen(str));

                for (cmd = mon_cmds; cmd->name != NULL; cmd++) {

                    cmd_completion(str, cmd->name);

                }

            }

            break;

        default:

            break;

        }

    }

cleanup:

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

        g_free(args[i]);

    }

}


CPUSPARCState *cpu_sparc_init(const char *cpu_model)

{

    SPARCCPU *cpu;

    CPUSPARCState *env;

    cpu = SPARC_CPU(object_new(TYPE_SPARC_CPU));

    env = &cpu->env;

    gen_intermediate_code_init(env);

    if (cpu_sparc_register(env, cpu_model) < 0) {

        object_delete(OBJECT(cpu));

        return NULL;

    }

    qemu_init_vcpu(env);

    return env;

}


static abi_long unlock_iovec(struct iovec *vec, abi_ulong target_addr,

                             int count, int copy)

{

    struct target_iovec *target_vec;

    abi_ulong base;

    int i;

    target_vec = lock_user(VERIFY_READ, target_addr, count * sizeof(struct target_iovec), 1);

    if (!target_vec)

        return -TARGET_EFAULT;

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

        base = tswapl(target_vec[i].iov_base);

        unlock_user(vec[i].iov_base, base, copy ? vec[i].iov_len : 0);

    }

    unlock_user (target_vec, target_addr, 0);

    return 0;

}


static int v9fs_synth_chmod(FsContext *fs_ctx, V9fsPath *path, FsCred *credp)

{

    errno = EPERM;

    return -1;

}


static void mem_commit(MemoryListener *listener)

{

    AddressSpace *as = container_of(listener, AddressSpace, dispatch_listener);

    AddressSpaceDispatch *cur = as->dispatch;

    AddressSpaceDispatch *next = as->next_dispatch;

    next->nodes = next_map.nodes;

    next->sections = next_map.sections;

    phys_page_compact_all(next, next_map.nodes_nb);

    as->dispatch = next;

    g_free(cur);

}


static void do_audio_out(AVFormatContext *s, OutputStream *ost,

                         AVFrame *frame)

{

    AVCodecContext *enc = ost->st->codec;

    AVPacket pkt;

    int got_packet = 0;

    av_init_packet(&pkt);

    pkt.data = NULL;

    pkt.size = 0;

#if 0

    if (!check_recording_time(ost))

        return;

#endif

    if (frame->pts == AV_NOPTS_VALUE || audio_sync_method < 0)

        frame->pts = ost->sync_opts;

    ost->sync_opts = frame->pts + frame->nb_samples;

    av_assert0(pkt.size || !pkt.data);

    update_benchmark(NULL);

    if (avcodec_encode_audio2(enc, &pkt, frame, &got_packet) < 0) {

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

        exit_program(1);

    }

    update_benchmark("encode_audio %d.%d", ost->file_index, ost->index);

    if (got_packet) {

        if (pkt.pts != AV_NOPTS_VALUE)

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

        if (pkt.dts != AV_NOPTS_VALUE)

            pkt.dts      = av_rescale_q(pkt.dts,      enc->time_base, ost->st->time_base);

        if (pkt.duration > 0)

            pkt.duration = av_rescale_q(pkt.duration, enc->time_base, ost->st->time_base);

        if (debug_ts) {

            av_log(NULL, AV_LOG_INFO, "encoder -> type:audio "

                   "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",

                   av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ost->st->time_base),

                   av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ost->st->time_base));

        }

        write_frame(s, &pkt, ost);

        audio_size += pkt.size;

        av_free_packet(&pkt);

    }

}


static void qemu_rdma_init_one_block(void *host_addr,

    ram_addr_t block_offset, ram_addr_t length, void *opaque)

{

    rdma_add_block(opaque, host_addr, block_offset, length);

}


START_TEST(qdict_iterapi_test)

{

    int count;

    const QDictEntry *ent;

    fail_unless(qdict_first(tests_dict) == NULL);

    qdict_put(tests_dict, "key1", qint_from_int(1));

    qdict_put(tests_dict, "key2", qint_from_int(2));

    qdict_put(tests_dict, "key3", qint_from_int(3));

    count = 0;

    for (ent = qdict_first(tests_dict); ent; ent = qdict_next(tests_dict, ent)){

        fail_unless(qdict_haskey(tests_dict, qdict_entry_key(ent)) == 1);

        count++;

    }

    fail_unless(count == qdict_size(tests_dict));

    /* Do it again to test restarting */

    count = 0;

    for (ent = qdict_first(tests_dict); ent; ent = qdict_next(tests_dict, ent)){

        fail_unless(qdict_haskey(tests_dict, qdict_entry_key(ent)) == 1);

        count++;

    }

    fail_unless(count == qdict_size(tests_dict));

}