static int mov_get_h264_codec_tag(AVFormatContext *s, MOVTrack *track)

{

    int tag = track->par->codec_tag;

    int interlaced = track->par->field_order > AV_FIELD_PROGRESSIVE;

    AVStream *st = track->st;

    int rate = av_q2d(find_fps(s, st));

    if (!tag)

        tag = MKTAG('a', 'v', 'c', 'i'); //fallback tag

    if (track->par->format == AV_PIX_FMT_YUV420P10) {

        if (track->par->width == 960 && track->par->height == 720) {

            if (!interlaced) {

                if      (rate == 24) tag = MKTAG('a','i','5','p');

                else if (rate == 25) tag = MKTAG('a','i','5','q');

                else if (rate == 30) tag = MKTAG('a','i','5','p');

                else if (rate == 50) tag = MKTAG('a','i','5','q');

                else if (rate == 60) tag = MKTAG('a','i','5','p');

            }

        } else if (track->par->width == 1440 && track->par->height == 1080) {

            if (!interlaced) {

                if      (rate == 24) tag = MKTAG('a','i','5','3');

                else if (rate == 25) tag = MKTAG('a','i','5','2');

                else if (rate == 30) tag = MKTAG('a','i','5','3');

            } else {

                if      (rate == 50) tag = MKTAG('a','i','5','5');

                else if (rate == 60) tag = MKTAG('a','i','5','6');

            }

        }

    } else if (track->par->format == AV_PIX_FMT_YUV422P10) {

        if (track->par->width == 1280 && track->par->height == 720) {

            if (!interlaced) {

                if      (rate == 24) tag = MKTAG('a','i','1','p');

                else if (rate == 25) tag = MKTAG('a','i','1','q');

                else if (rate == 30) tag = MKTAG('a','i','1','p');

                else if (rate == 50) tag = MKTAG('a','i','1','q');

                else if (rate == 60) tag = MKTAG('a','i','1','p');

            }

        } else if (track->par->width == 1920 && track->par->height == 1080) {

            if (!interlaced) {

                if      (rate == 24) tag = MKTAG('a','i','1','3');

                else if (rate == 25) tag = MKTAG('a','i','1','2');

                else if (rate == 30) tag = MKTAG('a','i','1','3');

            } else {

                if      (rate == 25) tag = MKTAG('a','i','1','5');

                else if (rate == 50) tag = MKTAG('a','i','1','5');

                else if (rate == 60) tag = MKTAG('a','i','1','6');

            }

        } else if (   track->par->width == 4096 && track->par->height == 2160

                   || track->par->width == 3840 && track->par->height == 2160

                   || track->par->width == 2048 && track->par->height == 1080) {

            tag = MKTAG('a','i','v','x');

        }

    }

    return tag;

}


static int64_t get_dts(AVFormatContext *s, int64_t pos)

{

    AVIOContext *pb = s->pb;

    int64_t dts;

    ffm_seek1(s, pos);

    avio_skip(pb, 4);

    dts = avio_rb64(pb);

    av_dlog(s, "dts=%0.6f\n", dts / 1000000.0);

    return dts;

}


static void apply_channel_coupling(AC3EncodeContext *s)

{

    LOCAL_ALIGNED_16(CoefType, cpl_coords,      [AC3_MAX_BLOCKS], [AC3_MAX_CHANNELS][16]);

#if CONFIG_AC3ENC_FLOAT

    LOCAL_ALIGNED_16(int32_t, fixed_cpl_coords, [AC3_MAX_BLOCKS], [AC3_MAX_CHANNELS][16]);

#else

    int32_t (*fixed_cpl_coords)[AC3_MAX_CHANNELS][16] = cpl_coords;

#endif

    int av_uninit(blk), ch, bnd, i, j;

    CoefSumType energy[AC3_MAX_BLOCKS][AC3_MAX_CHANNELS][16] = {{{0}}};

    int cpl_start, num_cpl_coefs;

    memset(cpl_coords,       0, AC3_MAX_BLOCKS * sizeof(*cpl_coords));

#if CONFIG_AC3ENC_FLOAT

    memset(fixed_cpl_coords, 0, AC3_MAX_BLOCKS * sizeof(*cpl_coords));

#endif

    /* align start to 16-byte boundary. align length to multiple of 32.

        note: coupling start bin % 4 will always be 1 */

    cpl_start     = s->start_freq[CPL_CH] - 1;

    num_cpl_coefs = FFALIGN(s->num_cpl_subbands * 12 + 1, 32);

    cpl_start     = FFMIN(256, cpl_start + num_cpl_coefs) - num_cpl_coefs;

    /* calculate coupling channel from fbw channels */

    for (blk = 0; blk < s->num_blocks; blk++) {

        AC3Block *block = &s->blocks[blk];

        CoefType *cpl_coef = &block->mdct_coef[CPL_CH][cpl_start];

        if (!block->cpl_in_use)

            continue;

        memset(cpl_coef, 0, num_cpl_coefs * sizeof(*cpl_coef));

        for (ch = 1; ch <= s->fbw_channels; ch++) {

            CoefType *ch_coef = &block->mdct_coef[ch][cpl_start];

            if (!block->channel_in_cpl[ch])

                continue;

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

                cpl_coef[i] += ch_coef[i];

        }

        /* coefficients must be clipped in order to be encoded */

        clip_coefficients(&s->adsp, cpl_coef, num_cpl_coefs);

    }

    /* calculate energy in each band in coupling channel and each fbw channel */

    /* TODO: possibly use SIMD to speed up energy calculation */

    bnd = 0;

    i = s->start_freq[CPL_CH];

    while (i < s->cpl_end_freq) {

        int band_size = s->cpl_band_sizes[bnd];

        for (ch = CPL_CH; ch <= s->fbw_channels; ch++) {

            for (blk = 0; blk < s->num_blocks; blk++) {

                AC3Block *block = &s->blocks[blk];

                if (!block->cpl_in_use || (ch > CPL_CH && !block->channel_in_cpl[ch]))

                    continue;

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

                    CoefType v = block->mdct_coef[ch][i+j];

                    MAC_COEF(energy[blk][ch][bnd], v, v);

                }

            }

        }

        i += band_size;

        bnd++;

    }

    /* calculate coupling coordinates for all blocks for all channels */

    for (blk = 0; blk < s->num_blocks; blk++) {

        AC3Block *block  = &s->blocks[blk];

        if (!block->cpl_in_use)

            continue;

        for (ch = 1; ch <= s->fbw_channels; ch++) {

            if (!block->channel_in_cpl[ch])

                continue;

            for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {

                cpl_coords[blk][ch][bnd] = calc_cpl_coord(energy[blk][ch][bnd],

                                                          energy[blk][CPL_CH][bnd]);

            }

        }

    }

    /* determine which blocks to send new coupling coordinates for */

    for (blk = 0; blk < s->num_blocks; blk++) {

        AC3Block *block  = &s->blocks[blk];

        AC3Block *block0 = blk ? &s->blocks[blk-1] : NULL;

        memset(block->new_cpl_coords, 0, sizeof(block->new_cpl_coords));

        if (block->cpl_in_use) {

            /* send new coordinates if this is the first block, if previous

             * block did not use coupling but this block does, the channels

             * using coupling has changed from the previous block, or the

             * coordinate difference from the last block for any channel is

             * greater than a threshold value. */

            if (blk == 0 || !block0->cpl_in_use) {

                for (ch = 1; ch <= s->fbw_channels; ch++)

                    block->new_cpl_coords[ch] = 1;

            } else {

                for (ch = 1; ch <= s->fbw_channels; ch++) {

                    if (!block->channel_in_cpl[ch])

                        continue;

                    if (!block0->channel_in_cpl[ch]) {

                        block->new_cpl_coords[ch] = 1;

                    } else {

                        CoefSumType coord_diff = 0;

                        for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {

                            coord_diff += FFABS(cpl_coords[blk-1][ch][bnd] -

                                                cpl_coords[blk  ][ch][bnd]);

                        }

                        coord_diff /= s->num_cpl_bands;

                        if (coord_diff > NEW_CPL_COORD_THRESHOLD)

                            block->new_cpl_coords[ch] = 1;

                    }

                }

            }

        }

    }

    /* calculate final coupling coordinates, taking into account reusing of

       coordinates in successive blocks */

    for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {

        blk = 0;

        while (blk < s->num_blocks) {

            int av_uninit(blk1);

            AC3Block *block  = &s->blocks[blk];

            if (!block->cpl_in_use) {

                blk++;

                continue;

            }

            for (ch = 1; ch <= s->fbw_channels; ch++) {

                CoefSumType energy_ch, energy_cpl;

                if (!block->channel_in_cpl[ch])

                    continue;

                energy_cpl = energy[blk][CPL_CH][bnd];

                energy_ch = energy[blk][ch][bnd];

                blk1 = blk+1;

                while (!s->blocks[blk1].new_cpl_coords[ch] && blk1 < s->num_blocks) {

                    if (s->blocks[blk1].cpl_in_use) {

                        energy_cpl += energy[blk1][CPL_CH][bnd];

                        energy_ch += energy[blk1][ch][bnd];

                    }

                    blk1++;

                }

                cpl_coords[blk][ch][bnd] = calc_cpl_coord(energy_ch, energy_cpl);

            }

            blk = blk1;

        }

    }

    /* calculate exponents/mantissas for coupling coordinates */

    for (blk = 0; blk < s->num_blocks; blk++) {

        AC3Block *block = &s->blocks[blk];

        if (!block->cpl_in_use)

            continue;

#if CONFIG_AC3ENC_FLOAT

        s->ac3dsp.float_to_fixed24(fixed_cpl_coords[blk][1],

                                   cpl_coords[blk][1],

                                   s->fbw_channels * 16);

#endif

        s->ac3dsp.extract_exponents(block->cpl_coord_exp[1],

                                    fixed_cpl_coords[blk][1],

                                    s->fbw_channels * 16);

        for (ch = 1; ch <= s->fbw_channels; ch++) {

            int bnd, min_exp, max_exp, master_exp;

            if (!block->new_cpl_coords[ch])

                continue;

            /* determine master exponent */

            min_exp = max_exp = block->cpl_coord_exp[ch][0];

            for (bnd = 1; bnd < s->num_cpl_bands; bnd++) {

                int exp = block->cpl_coord_exp[ch][bnd];

                min_exp = FFMIN(exp, min_exp);

                max_exp = FFMAX(exp, max_exp);

            }

            master_exp = ((max_exp - 15) + 2) / 3;

            master_exp = FFMAX(master_exp, 0);

            while (min_exp < master_exp * 3)

                master_exp--;

            for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {

                block->cpl_coord_exp[ch][bnd] = av_clip(block->cpl_coord_exp[ch][bnd] -

                                                        master_exp * 3, 0, 15);

            }

            block->cpl_master_exp[ch] = master_exp;

            /* quantize mantissas */

            for (bnd = 0; bnd < s->num_cpl_bands; bnd++) {

                int cpl_exp  = block->cpl_coord_exp[ch][bnd];

                int cpl_mant = (fixed_cpl_coords[blk][ch][bnd] << (5 + cpl_exp + master_exp * 3)) >> 24;

                if (cpl_exp == 15)

                    cpl_mant >>= 1;

                else

                    cpl_mant -= 16;

                block->cpl_coord_mant[ch][bnd] = cpl_mant;

            }

        }

    }

    if (CONFIG_EAC3_ENCODER && s->eac3)

        ff_eac3_set_cpl_states(s);

}


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

{

    WVMuxContext *wc = s->priv_data;

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

    AVIOContext *pb = s->pb;

    uint64_t size;

    uint32_t flags;

    uint32_t left = pkt->size;

    uint8_t *ptr = pkt->data;

    int off = codec->channels > 2 ? 4 : 0;

    /* FIXME: Simplify decoder/demuxer so bellow code can support midstream

     *        change of stream parameters */

    wc->duration += pkt->duration;

    ffio_wfourcc(pb, "wvpk");

    if (off) {

        size = AV_RL32(pkt->data);

        if (size <= 12)

            return AVERROR_INVALIDDATA;

        size -= 12;

    } else {

        size = pkt->size;

    }

    if (size + off > left)

        return AVERROR_INVALIDDATA;

    avio_wl32(pb, size + 12);

    avio_wl16(pb, 0x410);

    avio_w8(pb, 0);

    avio_w8(pb, 0);

    avio_wl32(pb, -1);

    avio_wl32(pb, pkt->pts);

    ptr += off; left -= off;

    flags = AV_RL32(ptr + 4);

    avio_write(pb, ptr, size);

    ptr += size; left -= size;

    while (!(flags & WV_END_BLOCK) &&

            (left >= 4 + WV_EXTRA_SIZE)) {

        ffio_wfourcc(pb, "wvpk");

        size = AV_RL32(ptr);

        ptr += 4; left -= 4;

        if (size < 24 || size - 24 > left)

            return AVERROR_INVALIDDATA;

        avio_wl32(pb, size);

        avio_wl16(pb, 0x410);

        avio_w8(pb, 0);

        avio_w8(pb, 0);

        avio_wl32(pb, -1);

        avio_wl32(pb, pkt->pts);

        flags = AV_RL32(ptr + 4);

        avio_write(pb, ptr, WV_EXTRA_SIZE);

        ptr += WV_EXTRA_SIZE; left -= WV_EXTRA_SIZE;

        avio_write(pb, ptr, size - 24);

        ptr += size - 24; left -= size - 24;

    }

    return 0;

}


static void compute_antialias_integer(MPADecodeContext *s,

                              GranuleDef *g)

{

    int32_t *ptr, *csa;

    int n, i;

    /* we antialias only "long" bands */

    if (g->block_type == 2) {

        if (!g->switch_point)

            return;

        /* XXX: check this for 8000Hz case */

        n = 1;

    } else {

        n = SBLIMIT - 1;

    }

    ptr = g->sb_hybrid + 18;

    for(i = n;i > 0;i--) {

        int tmp0, tmp1, tmp2;

        csa = &csa_table[0][0];

#define INT_AA(j) \

            tmp0 = 4*(ptr[-1-j]);\

            tmp1 = 4*(ptr[   j]);\

            tmp2= MULH(tmp0 + tmp1, csa[0+4*j]);\

            ptr[-1-j] = tmp2 - MULH(tmp1, csa[2+4*j]);\

            ptr[   j] = tmp2 + MULH(tmp0, csa[3+4*j]);

        INT_AA(0)

        INT_AA(1)

        INT_AA(2)

        INT_AA(3)

        INT_AA(4)

        INT_AA(5)

        INT_AA(6)

        INT_AA(7)

        ptr += 18;

    }

}


static int receive_filter(VirtIONet *n, const uint8_t *buf, int size)

{

    static const uint8_t bcast[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff};

    static const uint8_t vlan[] = {0x81, 0x00};

    uint8_t *ptr = (uint8_t *)buf;

    int i;

    if (n->promisc)

        return 1;

    if (!memcmp(&ptr[12], vlan, sizeof(vlan))) {

        int vid = be16_to_cpup((uint16_t *)(ptr + 14)) & 0xfff;

        if (!(n->vlans[vid >> 5] & (1U << (vid & 0x1f))))

            return 0;

    }

    if (ptr[0] & 1) { // multicast

        if (!memcmp(ptr, bcast, sizeof(bcast))) {

            return 1;

        } else if (n->allmulti) {

            return 1;

        }

    } else { // unicast

        if (!memcmp(ptr, n->mac, ETH_ALEN)) {

            return 1;

        }

    }

    for (i = 0; i < n->mac_table.in_use; i++) {

        if (!memcmp(ptr, &n->mac_table.macs[i * ETH_ALEN], ETH_ALEN))

            return 1;

    }

    return 0;

}


static void expand_rle_row(unsigned char *optr, unsigned char *iptr,

        int chan_offset, int pixelstride)

{

    unsigned char pixel, count;

#ifndef WORDS_BIGENDIAN

    /* rgba -> bgra for rgba32 on little endian cpus */

    if (pixelstride == 4 && chan_offset != 3) {

       chan_offset = 2 - chan_offset;

    }

#endif

    optr += chan_offset;

    while (1) {

        pixel = *iptr++;

        if (!(count = (pixel & 0x7f))) {

            return;

        }

        if (pixel & 0x80) {

            while (count--) {

                *optr = *iptr;

                optr += pixelstride;

                iptr++;

            }

        } else {

            pixel = *iptr++;

            while (count--) {

                *optr = pixel;

                optr += pixelstride;

            }

        }

    }

}


static void rtsp_cmd_describe(HTTPContext *c, const char *url)

{

    FFStream *stream;

    char path1[1024];

    const char *path;

    uint8_t *content;

    int content_length, len;

    struct sockaddr_in my_addr;

    /* find which url is asked */

    url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url);

    path = path1;

    if (*path == '/')

        path++;

    for(stream = first_stream; stream != NULL; stream = stream->next) {

        if (!stream->is_feed && !strcmp(stream->fmt->name, "rtp") &&

            !strcmp(path, stream->filename)) {

            goto found;

        }

    }

    /* no stream found */

    rtsp_reply_error(c, RTSP_STATUS_SERVICE); /* XXX: right error ? */

    return;

 found:

    /* prepare the media description in sdp format */

    /* get the host IP */

    len = sizeof(my_addr);

    getsockname(c->fd, (struct sockaddr *)&my_addr, &len);

    content_length = prepare_sdp_description(stream, &content, my_addr.sin_addr);

    if (content_length < 0) {

        rtsp_reply_error(c, RTSP_STATUS_INTERNAL);

        return;

    }

    rtsp_reply_header(c, RTSP_STATUS_OK);

    url_fprintf(c->pb, "Content-Type: application/sdp\r\n");

    url_fprintf(c->pb, "Content-Length: %d\r\n", content_length);

    url_fprintf(c->pb, "\r\n");

    put_buffer(c->pb, content, content_length);

}


av_cold int ff_vp8_decode_free(AVCodecContext *avctx)
{
    VP8Context *s = avctx->priv_data;
    int i;
    vp8_decode_flush_impl(avctx, 1);
    for (i = 0; i < FF_ARRAY_ELEMS(s->frames); i++)
        av_frame_free(&s->frames[i].tf.f);
}


static void spapr_alloc_htab(sPAPRMachineState *spapr)

{

    long shift;

    int index;

    /* allocate hash page table.  For now we always make this 16mb,

     * later we should probably make it scale to the size of guest

     * RAM */

    shift = kvmppc_reset_htab(spapr->htab_shift);

    if (shift > 0) {

        /* Kernel handles htab, we don't need to allocate one */

        if (shift != spapr->htab_shift) {

            error_setg(&error_abort, "Failed to allocate HTAB of requested size, try with smaller maxmem");

        }

        spapr->htab_shift = shift;

        kvmppc_kern_htab = true;

    } else {

        /* Allocate htab */

        spapr->htab = qemu_memalign(HTAB_SIZE(spapr), HTAB_SIZE(spapr));

        /* And clear it */

        memset(spapr->htab, 0, HTAB_SIZE(spapr));

        for (index = 0; index < HTAB_SIZE(spapr) / HASH_PTE_SIZE_64; index++) {

            DIRTY_HPTE(HPTE(spapr->htab, index));

        }

    }

}


static int qemu_rdma_get_buffer(void *opaque, uint8_t *buf,

                                int64_t pos, int size)

{

    QEMUFileRDMA *r = opaque;

    RDMAContext *rdma = r->rdma;

    RDMAControlHeader head;

    int ret = 0;

    CHECK_ERROR_STATE();

    /*

     * First, we hold on to the last SEND message we

     * were given and dish out the bytes until we run

     * out of bytes.

     */

    r->len = qemu_rdma_fill(r->rdma, buf, size, 0);

    if (r->len) {

        return r->len;

    }

    /*

     * Once we run out, we block and wait for another

     * SEND message to arrive.

     */

    ret = qemu_rdma_exchange_recv(rdma, &head, RDMA_CONTROL_QEMU_FILE);

    if (ret < 0) {

        rdma->error_state = ret;

        return ret;

    }

    /*

     * SEND was received with new bytes, now try again.

     */

    return qemu_rdma_fill(r->rdma, buf, size, 0);

}


static int ebml_read_binary(AVIOContext *pb, int length, EbmlBin *bin)

{

    av_free(bin->data);

    if (!(bin->data = av_malloc(length)))

        return AVERROR(ENOMEM);

    bin->size = length;

    bin->pos  = avio_tell(pb);

    if (avio_read(pb, bin->data, length) != length) {

        av_freep(&bin->data);

        return AVERROR(EIO);

    }

    return 0;

}


void avcodec_init(void)

{

    static int inited = 0;

    if (inited != 0)

        return;

    inited = 1;

    dsputil_static_init();

}


void swri_get_dither(SwrContext *s, void *dst, int len, unsigned seed, enum AVSampleFormat noise_fmt) {

    double scale = s->dither.noise_scale;

#define TMP_EXTRA 2

    double *tmp = av_malloc_array(len + TMP_EXTRA, sizeof(double));

    int i;

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

        double v;

        seed = seed* 1664525 + 1013904223;

        switch(s->dither.method){

            case SWR_DITHER_RECTANGULAR: v= ((double)seed) / UINT_MAX - 0.5; break;

            default:

                av_assert0(s->dither.method < SWR_DITHER_NB);

                v = ((double)seed) / UINT_MAX;

                seed = seed*1664525 + 1013904223;

                v-= ((double)seed) / UINT_MAX;

                break;

        }

        tmp[i] = v;

    }

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

        double v;

        switch(s->dither.method){

            default:

                av_assert0(s->dither.method < SWR_DITHER_NB);

                v = tmp[i];

                break;

            case SWR_DITHER_TRIANGULAR_HIGHPASS :

                v = (- tmp[i] + 2*tmp[i+1] - tmp[i+2]) / sqrt(6);

                break;

        }

        v*= scale;

        switch(noise_fmt){

            case AV_SAMPLE_FMT_S16P: ((int16_t*)dst)[i] = v; break;

            case AV_SAMPLE_FMT_S32P: ((int32_t*)dst)[i] = v; break;

            case AV_SAMPLE_FMT_FLTP: ((float  *)dst)[i] = v; break;

            case AV_SAMPLE_FMT_DBLP: ((double *)dst)[i] = v; break;

            default: av_assert0(0);

        }

    }

    av_free(tmp);

}


static int hls_coding_quadtree(HEVCContext *s, int x0, int y0,

                               int log2_cb_size, int cb_depth)

{

    HEVCLocalContext *lc = s->HEVClc;

    const int cb_size    = 1 << log2_cb_size;

    int ret;

    lc->ct.depth = cb_depth;

    if (x0 + cb_size <= s->sps->width  &&

        y0 + cb_size <= s->sps->height &&

        log2_cb_size > s->sps->log2_min_cb_size) {

        SAMPLE(s->split_cu_flag, x0, y0) =

            ff_hevc_split_coding_unit_flag_decode(s, cb_depth, x0, y0);

    } else {

        SAMPLE(s->split_cu_flag, x0, y0) =

            (log2_cb_size > s->sps->log2_min_cb_size);

    }

    if (s->pps->cu_qp_delta_enabled_flag &&

        log2_cb_size >= s->sps->log2_ctb_size - s->pps->diff_cu_qp_delta_depth) {

        lc->tu.is_cu_qp_delta_coded = 0;

        lc->tu.cu_qp_delta          = 0;

    }

    if (SAMPLE(s->split_cu_flag, x0, y0)) {

        const int cb_size_split = cb_size >> 1;

        const int x1 = x0 + cb_size_split;

        const int y1 = y0 + cb_size_split;

        int more_data = 0;

        more_data = hls_coding_quadtree(s, x0, y0, log2_cb_size - 1, cb_depth + 1);

        if (more_data < 0)

            return more_data;

        if (more_data && x1 < s->sps->width)

            more_data = hls_coding_quadtree(s, x1, y0, log2_cb_size - 1, cb_depth + 1);

        if (more_data && y1 < s->sps->height)

            more_data = hls_coding_quadtree(s, x0, y1, log2_cb_size - 1, cb_depth + 1);

        if (more_data && x1 < s->sps->width &&

            y1 < s->sps->height) {

            return hls_coding_quadtree(s, x1, y1, log2_cb_size - 1, cb_depth + 1);

        }

        if (more_data)

            return ((x1 + cb_size_split) < s->sps->width ||

                    (y1 + cb_size_split) < s->sps->height);

        else

            return 0;

    } else {

        ret = hls_coding_unit(s, x0, y0, log2_cb_size);

        if (ret < 0)

            return ret;

        if ((!((x0 + cb_size) %

               (1 << (s->sps->log2_ctb_size))) ||

             (x0 + cb_size >= s->sps->width)) &&

            (!((y0 + cb_size) %

               (1 << (s->sps->log2_ctb_size))) ||

             (y0 + cb_size >= s->sps->height))) {

            int end_of_slice_flag = ff_hevc_end_of_slice_flag_decode(s);

            return !end_of_slice_flag;

        } else {

            return 1;

        }

    }

    return 0;

}


static void test_uuid_unparse_strdup(void)

{

    int i;

    for (i = 0; i < ARRAY_SIZE(uuid_test_data); i++) {

        char *out;

        if (!uuid_test_data[i].check_unparse) {

            continue;

        }

        out = qemu_uuid_unparse_strdup(&uuid_test_data[i].uuid);

        g_assert_cmpstr(uuid_test_data[i].uuidstr, ==, out);

    }

}


static int decode_frame(AVCodecContext *avctx, void *data, int *data_size, const uint8_t *buf, int buf_size)

{

    SmackVContext * const smk = avctx->priv_data;

    uint8_t *out;

    uint32_t *pal;

    GetBitContext gb;

    int blocks, blk, bw, bh;

    int i;

    int stride;

    if(buf_size == 769)

        return 0;

    if(smk->pic.data[0])

            avctx->release_buffer(avctx, &smk->pic);

    smk->pic.reference = 1;

    smk->pic.buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE | FF_BUFFER_HINTS_REUSABLE;

    if(avctx->reget_buffer(avctx, &smk->pic) < 0){

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

        return -1;

    }

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

    pal = (uint32_t*)smk->pic.data[1];

    smk->pic.palette_has_changed = buf[0] & 1;

    smk->pic.key_frame = !!(buf[0] & 2);

    if(smk->pic.key_frame)

        smk->pic.pict_type = FF_I_TYPE;

    else

        smk->pic.pict_type = FF_P_TYPE;

    buf++;

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

        *pal++ = bytestream_get_be24(&buf);

    buf_size -= 769;

    last_reset(smk->mmap_tbl, smk->mmap_last);

    last_reset(smk->mclr_tbl, smk->mclr_last);

    last_reset(smk->full_tbl, smk->full_last);

    last_reset(smk->type_tbl, smk->type_last);

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

    blk = 0;

    bw = avctx->width >> 2;

    bh = avctx->height >> 2;

    blocks = bw * bh;

    out = smk->pic.data[0];

    stride = smk->pic.linesize[0];

    while(blk < blocks) {

        int type, run, mode;

        uint16_t pix;

        type = smk_get_code(&gb, smk->type_tbl, smk->type_last);

        run = block_runs[(type >> 2) & 0x3F];

        switch(type & 3){

        case SMK_BLK_MONO:

            while(run-- && blk < blocks){

                int clr, map;

                int hi, lo;

                clr = smk_get_code(&gb, smk->mclr_tbl, smk->mclr_last);

                map = smk_get_code(&gb, smk->mmap_tbl, smk->mmap_last);

                out = smk->pic.data[0] + (blk / bw) * (stride * 4) + (blk % bw) * 4;

                hi = clr >> 8;

                lo = clr & 0xFF;

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

                    if(map & 1) out[0] = hi; else out[0] = lo;

                    if(map & 2) out[1] = hi; else out[1] = lo;

                    if(map & 4) out[2] = hi; else out[2] = lo;

                    if(map & 8) out[3] = hi; else out[3] = lo;

                    map >>= 4;

                    out += stride;

                }

                blk++;

            }

            break;

        case SMK_BLK_FULL:

            mode = 0;

            if(avctx->codec_tag == MKTAG('S', 'M', 'K', '4')) { // In case of Smacker v4 we have three modes

                if(get_bits1(&gb)) mode = 1;

                else if(get_bits1(&gb)) mode = 2;

            }

            while(run-- && blk < blocks){

                out = smk->pic.data[0] + (blk / bw) * (stride * 4) + (blk % bw) * 4;

                switch(mode){

                case 0:

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

                        pix = smk_get_code(&gb, smk->full_tbl, smk->full_last);

                        AV_WL16(out+2,pix);

                        pix = smk_get_code(&gb, smk->full_tbl, smk->full_last);

                        AV_WL16(out,pix);

                        out += stride;

                    }

                    break;

                case 1:

                    pix = smk_get_code(&gb, smk->full_tbl, smk->full_last);

                    out[0] = out[1] = pix & 0xFF;

                    out[2] = out[3] = pix >> 8;

                    out += stride;

                    out[0] = out[1] = pix & 0xFF;

                    out[2] = out[3] = pix >> 8;

                    out += stride;

                    pix = smk_get_code(&gb, smk->full_tbl, smk->full_last);

                    out[0] = out[1] = pix & 0xFF;

                    out[2] = out[3] = pix >> 8;

                    out += stride;

                    out[0] = out[1] = pix & 0xFF;

                    out[2] = out[3] = pix >> 8;

                    out += stride;

                    break;

                case 2:

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

                        uint16_t pix1, pix2;

                        pix1 = smk_get_code(&gb, smk->full_tbl, smk->full_last);

                        pix2 = smk_get_code(&gb, smk->full_tbl, smk->full_last);

                        AV_WL16(out,pix1);

                        AV_WL16(out+2,pix2);

                        out += stride;

                        AV_WL16(out,pix1);

                        AV_WL16(out+2,pix2);

                        out += stride;

                    }

                    break;

                }

                blk++;

            }

            break;

        case SMK_BLK_SKIP:

            while(run-- && blk < blocks)

                blk++;

            break;

        case SMK_BLK_FILL:

            mode = type >> 8;

            while(run-- && blk < blocks){

                uint32_t col;

                out = smk->pic.data[0] + (blk / bw) * (stride * 4) + (blk % bw) * 4;

                col = mode * 0x01010101;

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

                    *((uint32_t*)out) = col;

                    out += stride;

                }

                blk++;

            }

            break;

        }

    }

    *data_size = sizeof(AVFrame);

    *(AVFrame*)data = smk->pic;

    /* always report that the buffer was completely consumed */

    return buf_size;

}


static void core_region_del(MemoryListener *listener,

                            MemoryRegionSection *section)

{

    cpu_register_physical_memory_log(section, false);

}


void do_store_msr (CPUPPCState *env, target_ulong value)

{

    int enter_pm;

    value &= env->msr_mask;

    if (((value >> MSR_IR) & 1) != msr_ir ||

        ((value >> MSR_DR) & 1) != msr_dr) {

        /* Flush all tlb when changing translation mode */

        tlb_flush(env, 1);

        env->interrupt_request |= CPU_INTERRUPT_EXITTB;

    }

#if 0

    if (loglevel != 0) {

        fprintf(logfile, "%s: T0 %08lx\n", __func__, value);

    }

#endif

    switch (PPC_EXCP(env)) {

    case PPC_FLAGS_EXCP_602:

    case PPC_FLAGS_EXCP_603:

        if (((value >> MSR_TGPR) & 1) != msr_tgpr) {

            /* Swap temporary saved registers with GPRs */

            swap_gpr_tgpr(env);

        }

        break;

    default:

        break;

    }

#if defined (TARGET_PPC64)

    msr_sf   = (value >> MSR_SF)   & 1;

    msr_isf  = (value >> MSR_ISF)  & 1;

    msr_hv   = (value >> MSR_HV)   & 1;

#endif

    msr_ucle = (value >> MSR_UCLE) & 1;

    msr_vr   = (value >> MSR_VR)   & 1; /* VR / SPE */

    msr_ap   = (value >> MSR_AP)   & 1;

    msr_sa   = (value >> MSR_SA)   & 1;

    msr_key  = (value >> MSR_KEY)  & 1;

    msr_pow  = (value >> MSR_POW)  & 1; /* POW / WE */

    msr_tlb  = (value >> MSR_TLB)  & 1; /* TLB / TGPR / CE */

    msr_ile  = (value >> MSR_ILE)  & 1;

    msr_ee   = (value >> MSR_EE)   & 1;

    msr_pr   = (value >> MSR_PR)   & 1;

    msr_fp   = (value >> MSR_FP)   & 1;

    msr_me   = (value >> MSR_ME)   & 1;

    msr_fe0  = (value >> MSR_FE0)  & 1;

    msr_se   = (value >> MSR_SE)   & 1; /* SE / DWE / UBLE */

    msr_be   = (value >> MSR_BE)   & 1; /* BE / DE */

    msr_fe1  = (value >> MSR_FE1)  & 1;

    msr_al   = (value >> MSR_AL)   & 1;

    msr_ip   = (value >> MSR_IP)   & 1;

    msr_ir   = (value >> MSR_IR)   & 1; /* IR / IS */

    msr_dr   = (value >> MSR_DR)   & 1; /* DR / DS */

    msr_pe   = (value >> MSR_PE)   & 1; /* PE / EP */

    msr_px   = (value >> MSR_PX)   & 1; /* PX / PMM */

    msr_ri   = (value >> MSR_RI)   & 1;

    msr_le   = (value >> MSR_LE)   & 1;

    do_compute_hflags(env);

    enter_pm = 0;

    switch (PPC_EXCP(env)) {

    case PPC_FLAGS_EXCP_603:

        /* Don't handle SLEEP mode: we should disable all clocks...

         * No dynamic power-management.

         */

        if (msr_pow == 1 && (env->spr[SPR_HID0] & 0x00C00000) != 0)

            enter_pm = 1;

        break;

    case PPC_FLAGS_EXCP_604:

        if (msr_pow == 1)

            enter_pm = 1;

        break;

    case PPC_FLAGS_EXCP_7x0:

        if (msr_pow == 1 && (env->spr[SPR_HID0] & 0x00E00000) != 0)

            enter_pm = 1;

        break;

    default:

        break;

    }

    if (enter_pm) {

        /* power save: exit cpu loop */

        env->halted = 1;

        env->exception_index = EXCP_HLT;

        cpu_loop_exit();

    }

}


static int dv_extract_audio_info(DVDemuxContext* c, uint8_t* frame)
{
    const uint8_t* as_pack;
    int freq, stype, smpls, quant, i, ach;
    as_pack = dv_extract_pack(frame, dv_audio_source);
    if (!as_pack || !c->sys) {    /* No audio ? */
        c->ach = 0;
    smpls =  as_pack[1] & 0x3f;       /* samples in this frame - min. samples */
    freq  = (as_pack[4] >> 3) & 0x07; /* 0 - 48kHz, 1 - 44,1kHz, 2 - 32kHz */
    stype = (as_pack[3] & 0x1f);      /* 0 - 2CH, 2 - 4CH, 3 - 8CH */
    quant =  as_pack[4] & 0x07;       /* 0 - 16bit linear, 1 - 12bit nonlinear */
    if (stype > 3) {
        av_log(c->fctx, AV_LOG_ERROR, "stype %d is invalid\n", stype);
        c->ach = 0;
    /* note: ach counts PAIRS of channels (i.e. stereo channels) */
    ach = ((int[4]){  1,  0,  2,  4})[stype];
    if (ach == 1 && quant && freq == 2)
        ach = 2;
    /* Dynamic handling of the audio streams in DV */
    for (i = 0; i < ach; i++) {
       if (!c->ast[i]) {
           c->ast[i] = avformat_new_stream(c->fctx, NULL);
           if (!c->ast[i])
               break;
           avpriv_set_pts_info(c->ast[i], 64, 1, 30000);
           c->ast[i]->codec->codec_type = AVMEDIA_TYPE_AUDIO;
           c->ast[i]->codec->codec_id   = CODEC_ID_PCM_S16LE;
           av_init_packet(&c->audio_pkt[i]);
           c->audio_pkt[i].size         = 0;
           c->audio_pkt[i].data         = c->audio_buf[i];
           c->audio_pkt[i].stream_index = c->ast[i]->index;
           c->audio_pkt[i].flags       |= AV_PKT_FLAG_KEY;
       c->ast[i]->codec->sample_rate = dv_audio_frequency[freq];
       c->ast[i]->codec->channels    = 2;
       c->ast[i]->codec->bit_rate    = 2 * dv_audio_frequency[freq] * 16;
       c->ast[i]->start_time         = 0;
    c->ach = i;
    return (c->sys->audio_min_samples[freq] + smpls) * 4; /* 2ch, 2bytes */;


QEMUFile *qemu_fopen_socket(int fd, const char *mode)

{

    QEMUFileSocket *s;

    if (qemu_file_mode_is_not_valid(mode)) {

        return NULL;

    }

    s = g_malloc0(sizeof(QEMUFileSocket));

    s->fd = fd;

    if (mode[0] == 'w') {

        qemu_set_block(s->fd);

        s->file = qemu_fopen_ops(s, &socket_write_ops);

    } else {

        s->file = qemu_fopen_ops(s, &socket_read_ops);

    }

    return s->file;

}


static void aio_rfifolock_cb(void *opaque)

{

    /* Kick owner thread in case they are blocked in aio_poll() */

    aio_notify(opaque);

}


int nbd_receive_negotiate(QIOChannel *ioc, const char *name,
                          QCryptoTLSCreds *tlscreds, const char *hostname,
                          QIOChannel **outioc, NBDExportInfo *info,
                          Error **errp)
{
    char buf[256];
    uint64_t magic;
    int rc;
    bool zeroes = true;
    bool structured_reply = info->structured_reply;
    trace_nbd_receive_negotiate(tlscreds, hostname ? hostname : "<null>");
    info->structured_reply = false;
    rc = -EINVAL;
    if (outioc) {
        *outioc = NULL;
    if (tlscreds && !outioc) {
        error_setg(errp, "Output I/O channel required for TLS");
    if (nbd_read(ioc, buf, 8, errp) < 0) {
        error_prepend(errp, "Failed to read data");
    buf[8] = '\0';
    if (strlen(buf) == 0) {
        error_setg(errp, "Server connection closed unexpectedly");
    magic = ldq_be_p(buf);
    trace_nbd_receive_negotiate_magic(magic);
    if (memcmp(buf, "NBDMAGIC", 8) != 0) {
        error_setg(errp, "Invalid magic received");
    if (nbd_read(ioc, &magic, sizeof(magic), errp) < 0) {
        error_prepend(errp, "Failed to read magic");
    magic = be64_to_cpu(magic);
    trace_nbd_receive_negotiate_magic(magic);
    if (magic == NBD_OPTS_MAGIC) {
        uint32_t clientflags = 0;
        uint16_t globalflags;
        bool fixedNewStyle = false;
        if (nbd_read(ioc, &globalflags, sizeof(globalflags), errp) < 0) {
            error_prepend(errp, "Failed to read server flags");
        globalflags = be16_to_cpu(globalflags);
        trace_nbd_receive_negotiate_server_flags(globalflags);
        if (globalflags & NBD_FLAG_FIXED_NEWSTYLE) {
            fixedNewStyle = true;
            clientflags |= NBD_FLAG_C_FIXED_NEWSTYLE;
        if (globalflags & NBD_FLAG_NO_ZEROES) {
            zeroes = false;
            clientflags |= NBD_FLAG_C_NO_ZEROES;
        /* client requested flags */
        clientflags = cpu_to_be32(clientflags);
        if (nbd_write(ioc, &clientflags, sizeof(clientflags), errp) < 0) {
            error_prepend(errp, "Failed to send clientflags field");
        if (tlscreds) {
            if (fixedNewStyle) {
                *outioc = nbd_receive_starttls(ioc, tlscreds, hostname, errp);
                if (!*outioc) {
                ioc = *outioc;
            } else {
                error_setg(errp, "Server does not support STARTTLS");
        if (!name) {
            trace_nbd_receive_negotiate_default_name();
            name = "";
        if (fixedNewStyle) {
            int result;
            /* Try NBD_OPT_GO first - if it works, we are done (it
             * also gives us a good message if the server requires
             * TLS).  If it is not available, fall back to
             * NBD_OPT_LIST for nicer error messages about a missing
             * export, then use NBD_OPT_EXPORT_NAME.  */
            result = nbd_opt_go(ioc, name, info, errp);
            if (result > 0) {
                return 0;
            /* Check our desired export is present in the
             * server export list. Since NBD_OPT_EXPORT_NAME
             * cannot return an error message, running this
             * query gives us better error reporting if the
             * export name is not available.
             */
            if (nbd_receive_query_exports(ioc, name, errp) < 0) {
        /* write the export name request */
        if (nbd_send_option_request(ioc, NBD_OPT_EXPORT_NAME, -1, name,
                                    errp) < 0) {
        /* Read the response */
        if (nbd_read(ioc, &info->size, sizeof(info->size), errp) < 0) {
            error_prepend(errp, "Failed to read export length");
        be64_to_cpus(&info->size);
        if (nbd_read(ioc, &info->flags, sizeof(info->flags), errp) < 0) {
            error_prepend(errp, "Failed to read export flags");
        be16_to_cpus(&info->flags);
    } else if (magic == NBD_CLIENT_MAGIC) {
        uint32_t oldflags;
        if (name) {
            error_setg(errp, "Server does not support export names");
        if (tlscreds) {
            error_setg(errp, "Server does not support STARTTLS");
        if (nbd_read(ioc, &info->size, sizeof(info->size), errp) < 0) {
            error_prepend(errp, "Failed to read export length");
        be64_to_cpus(&info->size);
        if (nbd_read(ioc, &oldflags, sizeof(oldflags), errp) < 0) {
            error_prepend(errp, "Failed to read export flags");
        be32_to_cpus(&oldflags);
        if (oldflags & ~0xffff) {
            error_setg(errp, "Unexpected export flags %0x" PRIx32, oldflags);
        info->flags = oldflags;
    } else {
        error_setg(errp, "Bad magic received");
    trace_nbd_receive_negotiate_size_flags(info->size, info->flags);
    if (zeroes && nbd_drop(ioc, 124, errp) < 0) {
        error_prepend(errp, "Failed to read reserved block");
    rc = 0;
fail:
    return rc;


static int get_codec_data(AVIOContext *pb, AVStream *vst,

                          AVStream *ast, int myth)

{

    nuv_frametype frametype;

    if (!vst && !myth)

        return 1; // no codec data needed

    while (!pb->eof_reached) {

        int size, subtype;

        frametype = avio_r8(pb);

        switch (frametype) {

        case NUV_EXTRADATA:

            subtype = avio_r8(pb);

            avio_skip(pb, 6);

            size = PKTSIZE(avio_rl32(pb));

            if (vst && subtype == 'R') {

                vst->codec->extradata_size = size;

                vst->codec->extradata      = av_malloc(size);

                avio_read(pb, vst->codec->extradata, size);

                size = 0;

                if (!myth)

                    return 1;

            }

            break;

        case NUV_MYTHEXT:

            avio_skip(pb, 7);

            size = PKTSIZE(avio_rl32(pb));

            if (size != 128 * 4)

                break;

            avio_rl32(pb); // version

            if (vst) {

                vst->codec->codec_tag = avio_rl32(pb);

                vst->codec->codec_id =

                    ff_codec_get_id(ff_codec_bmp_tags, vst->codec->codec_tag);

                if (vst->codec->codec_tag == MKTAG('R', 'J', 'P', 'G'))

                    vst->codec->codec_id = AV_CODEC_ID_NUV;

            } else

                avio_skip(pb, 4);

            if (ast) {

                int id;

                ast->codec->codec_tag             = avio_rl32(pb);

                ast->codec->sample_rate           = avio_rl32(pb);

                ast->codec->bits_per_coded_sample = avio_rl32(pb);

                ast->codec->channels              = avio_rl32(pb);

                ast->codec->channel_layout        = 0;

                id = ff_wav_codec_get_id(ast->codec->codec_tag,

                                         ast->codec->bits_per_coded_sample);

                if (id == AV_CODEC_ID_NONE) {

                    id = ff_codec_get_id(nuv_audio_tags, ast->codec->codec_tag);

                    if (id == AV_CODEC_ID_PCM_S16LE)

                        id = ff_get_pcm_codec_id(ast->codec->bits_per_coded_sample,

                                                 0, 0, ~1);

                }

                ast->codec->codec_id = id;

                ast->need_parsing = AVSTREAM_PARSE_FULL;

            } else

                avio_skip(pb, 4 * 4);

            size -= 6 * 4;

            avio_skip(pb, size);

            return 1;

        case NUV_SEEKP:

            size = 11;

            break;

        default:

            avio_skip(pb, 7);

            size = PKTSIZE(avio_rl32(pb));

            break;

        }

        avio_skip(pb, size);

    }

    return 0;

}


void qmp_guest_set_time(bool has_time, int64_t time_ns, Error **errp)
{
    int ret;
    int status;
    pid_t pid;
    Error *local_err = NULL;
    struct timeval tv;
    /* If user has passed a time, validate and set it. */
    if (has_time) {
        /* year-2038 will overflow in case time_t is 32bit */
        if (time_ns / 1000000000 != (time_t)(time_ns / 1000000000)) {
            error_setg(errp, "Time %" PRId64 " is too large", time_ns);
            return;
        }
        tv.tv_sec = time_ns / 1000000000;
        tv.tv_usec = (time_ns % 1000000000) / 1000;
        g_date_set_time_t(&date, tv.tv_sec);
        if (date.year < 1970 || date.year >= 2070) {
            error_setg_errno(errp, errno, "Invalid time");
            return;
        }
        ret = settimeofday(&tv, NULL);
        if (ret < 0) {
            error_setg_errno(errp, errno, "Failed to set time to guest");
            return;
        }
    }
    /* Now, if user has passed a time to set and the system time is set, we
     * just need to synchronize the hardware clock. However, if no time was
     * passed, user is requesting the opposite: set the system time from the
     * hardware clock (RTC). */
    pid = fork();
    if (pid == 0) {
        setsid();
        reopen_fd_to_null(0);
        reopen_fd_to_null(1);
        reopen_fd_to_null(2);
        /* Use '/sbin/hwclock -w' to set RTC from the system time,
         * or '/sbin/hwclock -s' to set the system time from RTC. */
        execle("/sbin/hwclock", "hwclock", has_time ? "-w" : "-s",
               NULL, environ);
        _exit(EXIT_FAILURE);
    } else if (pid < 0) {
        error_setg_errno(errp, errno, "failed to create child process");
        return;
    }
    ga_wait_child(pid, &status, &local_err);
    if (local_err) {
        error_propagate(errp, local_err);
        return;
    }
    if (!WIFEXITED(status)) {
        error_setg(errp, "child process has terminated abnormally");
        return;
    }
    if (WEXITSTATUS(status)) {
        error_setg(errp, "hwclock failed to set hardware clock to system time");
        return;
    }
}


static int posix_aio_init(void)

{

    sigset_t mask;

    PosixAioState *s;

    if (posix_aio_state)

        return 0;

    s = qemu_malloc(sizeof(PosixAioState));

    if (s == NULL)

        return -ENOMEM;

    /* Make sure to block AIO signal */

    sigemptyset(&mask);

    sigaddset(&mask, SIGUSR2);

    sigprocmask(SIG_BLOCK, &mask, NULL);

    s->first_aio = NULL;

    s->fd = qemu_signalfd(&mask);

    if (s->fd == -1) {

        fprintf(stderr, "failed to create signalfd\n");

        return -errno;

    }

    fcntl(s->fd, F_SETFL, O_NONBLOCK);

    qemu_aio_set_fd_handler(s->fd, posix_aio_read, NULL, posix_aio_flush, s);

#if defined(__linux__)

    {

        struct aioinit ai;

        memset(&ai, 0, sizeof(ai));

#if defined(__GLIBC_PREREQ) && __GLIBC_PREREQ(2, 4)

        ai.aio_threads = 64;

        ai.aio_num = 64;

#else

        /* XXX: aio thread exit seems to hang on RedHat 9 and this init

           seems to fix the problem. */

        ai.aio_threads = 1;

        ai.aio_num = 1;

        ai.aio_idle_time = 365 * 100000;

#endif

        aio_init(&ai);

    }

#endif

    posix_aio_state = s;

    return 0;

}


static void vp8_idct_dc_add4y_c(uint8_t *dst, int16_t block[4][16],

                                ptrdiff_t stride)

{

    vp8_idct_dc_add_c(dst +  0, block[0], stride);

    vp8_idct_dc_add_c(dst +  4, block[1], stride);

    vp8_idct_dc_add_c(dst +  8, block[2], stride);

    vp8_idct_dc_add_c(dst + 12, block[3], stride);

}


void ff_frame_thread_encoder_free(AVCodecContext *avctx){

    int i;

    ThreadContext *c= avctx->internal->frame_thread_encoder;

    pthread_mutex_lock(&c->task_fifo_mutex);

    c->exit = 1;

    pthread_cond_broadcast(&c->task_fifo_cond);

    pthread_mutex_unlock(&c->task_fifo_mutex);

    for (i=0; i<avctx->thread_count; i++) {

         pthread_join(c->worker[i], NULL);

    }

    pthread_mutex_destroy(&c->task_fifo_mutex);

    pthread_mutex_destroy(&c->finished_task_mutex);

    pthread_mutex_destroy(&c->buffer_mutex);

    pthread_cond_destroy(&c->task_fifo_cond);

    pthread_cond_destroy(&c->finished_task_cond);

    av_fifo_freep(&c->task_fifo);

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

}


static void build_fs_mount_list_from_mtab(FsMountList *mounts, Error **errp)

{

    struct mntent *ment;

    FsMount *mount;

    char const *mtab = "/proc/self/mounts";

    FILE *fp;

    unsigned int devmajor, devminor;

    fp = setmntent(mtab, "r");

    if (!fp) {

        error_setg(errp, "failed to open mtab file: '%s'", mtab);

        return;

    }

    while ((ment = getmntent(fp))) {

        /*

         * An entry which device name doesn't start with a '/' is

         * either a dummy file system or a network file system.

         * Add special handling for smbfs and cifs as is done by

         * coreutils as well.

         */

        if ((ment->mnt_fsname[0] != '/') ||

            (strcmp(ment->mnt_type, "smbfs") == 0) ||

            (strcmp(ment->mnt_type, "cifs") == 0)) {

            continue;

        }

        if (dev_major_minor(ment->mnt_fsname, &devmajor, &devminor) == -2) {

            /* Skip bind mounts */

            continue;

        }

        mount = g_malloc0(sizeof(FsMount));

        mount->dirname = g_strdup(ment->mnt_dir);

        mount->devtype = g_strdup(ment->mnt_type);

        mount->devmajor = devmajor;

        mount->devminor = devminor;

        QTAILQ_INSERT_TAIL(mounts, mount, next);

    }

    endmntent(fp);

}


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

{

    AVStream *st;

    MOVStreamContext *sc;

    int version;

    char language[4] = {0};

    unsigned lang;

    int64_t creation_time;

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

        return 0;

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

    sc = st->priv_data;

    if (sc->time_scale) {

        av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n");

        return AVERROR_INVALIDDATA;

    }

    version = avio_r8(pb);

    if (version > 1) {

        avpriv_request_sample(c->fc, "Version %d", version);

        return AVERROR_PATCHWELCOME;

    }

    avio_rb24(pb); /* flags */

    if (version == 1) {

        creation_time = avio_rb64(pb);

        avio_rb64(pb);

    } else {

        creation_time = avio_rb32(pb);

        avio_rb32(pb); /* modification time */

    }

    mov_metadata_creation_time(&st->metadata, creation_time);

    sc->time_scale = avio_rb32(pb);

    if (sc->time_scale <= 0) {

        av_log(c->fc, AV_LOG_ERROR, "Invalid mdhd time scale %d\n", sc->time_scale);

        return AVERROR_INVALIDDATA;

    }

    st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */

    lang = avio_rb16(pb); /* language */

    if (ff_mov_lang_to_iso639(lang, language))

        av_dict_set(&st->metadata, "language", language, 0);

    avio_rb16(pb); /* quality */

    return 0;

}


void visit_type_enum(Visitor *v, const char *name, int *obj,

                     const char *const strings[], Error **errp)

{

    assert(obj && strings);

    if (v->type == VISITOR_INPUT) {

        input_type_enum(v, name, obj, strings, errp);

    } else if (v->type == VISITOR_OUTPUT) {

        output_type_enum(v, name, obj, strings, errp);

    }

}


av_cold int ff_rdft_init(RDFTContext *s, int nbits, enum RDFTransformType trans)

{

    int n = 1 << nbits;

    int i;

    const double theta = (trans == RDFT || trans == IRIDFT ? -1 : 1)*2*M_PI/n;

    s->nbits           = nbits;

    s->inverse         = trans == IRDFT || trans == IRIDFT;

    s->sign_convention = trans == RIDFT || trans == IRIDFT ? 1 : -1;

    if (nbits < 4 || nbits > 16)

        return -1;

    if (ff_fft_init(&s->fft, nbits-1, trans == IRDFT || trans == RIDFT) < 0)

        return -1;

    s->tcos = ff_cos_tabs[nbits-4];

    s->tsin = ff_sin_tabs[nbits-4]+(trans == RDFT || trans == IRIDFT)*(n>>2);

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

        s->tcos[i] = cos(i*theta);

        s->tsin[i] = sin(i*theta);

    }

    return 0;

}


static int qio_channel_buffer_close(QIOChannel *ioc,

                                    Error **errp)

{

    QIOChannelBuffer *bioc = QIO_CHANNEL_BUFFER(ioc);

    g_free(bioc->data);

    bioc->capacity = bioc->usage = bioc->offset = 0;

    return 0;

}


static void cpu_4xx_wdt_cb (void *opaque)

{

    PowerPCCPU *cpu;

    CPUPPCState *env;

    ppc_tb_t *tb_env;

    ppc40x_timer_t *ppc40x_timer;

    uint64_t now, next;

    env = opaque;

    cpu = ppc_env_get_cpu(env);

    tb_env = env->tb_env;

    ppc40x_timer = tb_env->opaque;

    now = qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL);

    switch ((env->spr[SPR_40x_TCR] >> 30) & 0x3) {

    case 0:

        next = 1 << 17;

        break;

    case 1:

        next = 1 << 21;

        break;

    case 2:

        next = 1 << 25;

        break;

    case 3:

        next = 1 << 29;

        break;

    default:

        /* Cannot occur, but makes gcc happy */

        return;

    }

    next = now + muldiv64(next, get_ticks_per_sec(), tb_env->decr_freq);

    if (next == now)

        next++;

    LOG_TB("%s: TCR " TARGET_FMT_lx " TSR " TARGET_FMT_lx "\n", __func__,

           env->spr[SPR_40x_TCR], env->spr[SPR_40x_TSR]);

    switch ((env->spr[SPR_40x_TSR] >> 30) & 0x3) {

    case 0x0:

    case 0x1:

        timer_mod(ppc40x_timer->wdt_timer, next);

        ppc40x_timer->wdt_next = next;

        env->spr[SPR_40x_TSR] |= 1 << 31;

        break;

    case 0x2:

        timer_mod(ppc40x_timer->wdt_timer, next);

        ppc40x_timer->wdt_next = next;

        env->spr[SPR_40x_TSR] |= 1 << 30;

        if ((env->spr[SPR_40x_TCR] >> 27) & 0x1) {

            ppc_set_irq(cpu, PPC_INTERRUPT_WDT, 1);

        }

        break;

    case 0x3:

        env->spr[SPR_40x_TSR] &= ~0x30000000;

        env->spr[SPR_40x_TSR] |= env->spr[SPR_40x_TCR] & 0x30000000;

        switch ((env->spr[SPR_40x_TCR] >> 28) & 0x3) {

        case 0x0:

            /* No reset */

            break;

        case 0x1: /* Core reset */

            ppc40x_core_reset(cpu);

            break;

        case 0x2: /* Chip reset */

            ppc40x_chip_reset(cpu);

            break;

        case 0x3: /* System reset */

            ppc40x_system_reset(cpu);

            break;

        }

    }

}


int unix_connect_opts(QemuOpts *opts)

{

    struct sockaddr_un un;

    const char *path = qemu_opt_get(opts, "path");

    int sock;

    if (NULL == path) {

        fprintf(stderr, "unix connect: no path specified\n");

        return -1;

    }

    sock = qemu_socket(PF_UNIX, SOCK_STREAM, 0);

    if (sock < 0) {

        perror("socket(unix)");

        return -1;

    }

    memset(&un, 0, sizeof(un));

    un.sun_family = AF_UNIX;

    snprintf(un.sun_path, sizeof(un.sun_path), "%s", path);

    if (connect(sock, (struct sockaddr*) &un, sizeof(un)) < 0) {

        fprintf(stderr, "connect(unix:%s): %s\n", path, strerror(errno));

	return -1;

    }

    if (sockets_debug)

        fprintf(stderr, "connect(unix:%s): OK\n", path);

    return sock;

}


static int vhost_net_start_one(struct vhost_net *net,

                               VirtIODevice *dev)

{

    struct vhost_vring_file file = { };

    int r;

    net->dev.nvqs = 2;

    net->dev.vqs = net->vqs;

    r = vhost_dev_enable_notifiers(&net->dev, dev);

    if (r < 0) {

        goto fail_notifiers;

    }

    r = vhost_dev_start(&net->dev, dev);

    if (r < 0) {

        goto fail_start;

    }

    if (net->nc->info->poll) {

        net->nc->info->poll(net->nc, false);

    }

    if (net->nc->info->type == NET_CLIENT_DRIVER_TAP) {

        qemu_set_fd_handler(net->backend, NULL, NULL, NULL);

        file.fd = net->backend;

        for (file.index = 0; file.index < net->dev.nvqs; ++file.index) {

            const VhostOps *vhost_ops = net->dev.vhost_ops;

            r = vhost_ops->vhost_net_set_backend(&net->dev, &file);

            if (r < 0) {

                r = -errno;

                goto fail;

            }

        }

    }

    return 0;

fail:

    file.fd = -1;

    if (net->nc->info->type == NET_CLIENT_DRIVER_TAP) {

        while (file.index-- > 0) {

            const VhostOps *vhost_ops = net->dev.vhost_ops;

            int r = vhost_ops->vhost_net_set_backend(&net->dev, &file);

            assert(r >= 0);

        }

    }

    if (net->nc->info->poll) {

        net->nc->info->poll(net->nc, true);

    }

    vhost_dev_stop(&net->dev, dev);

fail_start:

    vhost_dev_disable_notifiers(&net->dev, dev);

fail_notifiers:

    return r;

}


int qcow2_pre_write_overlap_check(BlockDriverState *bs, int chk, int64_t offset,

                                  int64_t size)

{

    int ret = qcow2_check_metadata_overlap(bs, chk, offset, size);

    if (ret < 0) {

        return ret;

    } else if (ret > 0) {

        int metadata_ol_bitnr = ffs(ret) - 1;

        char *message;

        QObject *data;

        assert(metadata_ol_bitnr < QCOW2_OL_MAX_BITNR);

        fprintf(stderr, "qcow2: Preventing invalid write on metadata (overlaps "

                "with %s); image marked as corrupt.\n",

                metadata_ol_names[metadata_ol_bitnr]);

        message = g_strdup_printf("Prevented %s overwrite",

                metadata_ol_names[metadata_ol_bitnr]);

        data = qobject_from_jsonf("{ 'device': %s, 'msg': %s, 'offset': %"

                PRId64 ", 'size': %" PRId64 " }", bs->device_name, message,

                offset, size);

        monitor_protocol_event(QEVENT_BLOCK_IMAGE_CORRUPTED, data);

        g_free(message);

        qobject_decref(data);

        qcow2_mark_corrupt(bs);

        bs->drv = NULL; /* make BDS unusable */

        return -EIO;

    }

    return 0;

}


static OutputStream *new_audio_stream(OptionsContext *o, AVFormatContext *oc, int source_index)

{

    int n;

    AVStream *st;

    OutputStream *ost;

    AVCodecContext *audio_enc;

    ost = new_output_stream(o, oc, AVMEDIA_TYPE_AUDIO, source_index);

    st  = ost->st;

    audio_enc = st->codec;

    audio_enc->codec_type = AVMEDIA_TYPE_AUDIO;

    MATCH_PER_STREAM_OPT(filter_scripts, str, ost->filters_script, oc, st);

    MATCH_PER_STREAM_OPT(filters,        str, ost->filters,        oc, st);

    if (!ost->stream_copy) {

        char *sample_fmt = NULL;

        MATCH_PER_STREAM_OPT(audio_channels, i, audio_enc->channels, oc, st);

        MATCH_PER_STREAM_OPT(sample_fmts, str, sample_fmt, oc, st);

        if (sample_fmt &&

            (audio_enc->sample_fmt = av_get_sample_fmt(sample_fmt)) == AV_SAMPLE_FMT_NONE) {

            av_log(NULL, AV_LOG_FATAL, "Invalid sample format '%s'\n", sample_fmt);

            exit_program(1);

        }

        MATCH_PER_STREAM_OPT(audio_sample_rate, i, audio_enc->sample_rate, oc, st);

        MATCH_PER_STREAM_OPT(apad, str, ost->apad, oc, st);

        ost->apad = av_strdup(ost->apad);

        ost->avfilter = get_ost_filters(o, oc, ost);

        if (!ost->avfilter)

            exit_program(1);

        /* check for channel mapping for this audio stream */

        for (n = 0; n < o->nb_audio_channel_maps; n++) {

            AudioChannelMap *map = &o->audio_channel_maps[n];

            InputStream *ist = input_streams[ost->source_index];

            if ((map->channel_idx == -1 || (ist->file_index == map->file_idx && ist->st->index == map->stream_idx)) &&

                (map->ofile_idx   == -1 || ost->file_index == map->ofile_idx) &&

                (map->ostream_idx == -1 || ost->st->index  == map->ostream_idx)) {

                if (ost->audio_channels_mapped < FF_ARRAY_ELEMS(ost->audio_channels_map))

                    ost->audio_channels_map[ost->audio_channels_mapped++] = map->channel_idx;

                else

                    av_log(NULL, AV_LOG_FATAL, "Max channel mapping for output %d.%d reached\n",

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

            }

        }

    }

    if (ost->stream_copy)

        check_streamcopy_filters(o, oc, ost, AVMEDIA_TYPE_AUDIO);

    return ost;

}


static void end_frame(AVFilterLink *link)

{

    DeshakeContext *deshake = link->dst->priv;

    AVFilterBufferRef *in  = link->cur_buf;

    AVFilterBufferRef *out = link->dst->outputs[0]->out_buf;

    Transform t;

    float matrix[9];

    float alpha = 2.0 / deshake->refcount;

    char tmp[256];

    Transform orig;

    if (deshake->cx < 0 || deshake->cy < 0 || deshake->cw < 0 || deshake->ch < 0) {

        // Find the most likely global motion for the current frame

        find_motion(deshake, (deshake->ref == NULL) ? in->data[0] : deshake->ref->data[0], in->data[0], link->w, link->h, in->linesize[0], &t);

    } else {

        uint8_t *src1 = (deshake->ref == NULL) ? in->data[0] : deshake->ref->data[0];

        uint8_t *src2 = in->data[0];

        deshake->cx = FFMIN(deshake->cx, link->w);

        deshake->cy = FFMIN(deshake->cy, link->h);

        if ((unsigned)deshake->cx + (unsigned)deshake->cw > link->w) deshake->cw = link->w - deshake->cx;

        if ((unsigned)deshake->cy + (unsigned)deshake->ch > link->h) deshake->ch = link->h - deshake->cy;

        // Quadword align right margin

        deshake->cw &= ~15;

        src1 += deshake->cy * in->linesize[0] + deshake->cx;

        src2 += deshake->cy * in->linesize[0] + deshake->cx;

        find_motion(deshake, src1, src2, deshake->cw, deshake->ch, in->linesize[0], &t);

    }

    // Copy transform so we can output it later to compare to the smoothed value

    orig.vector.x = t.vector.x;

    orig.vector.y = t.vector.y;

    orig.angle = t.angle;

    orig.zoom = t.zoom;

    // Generate a one-sided moving exponential average

    deshake->avg.vector.x = alpha * t.vector.x + (1.0 - alpha) * deshake->avg.vector.x;

    deshake->avg.vector.y = alpha * t.vector.y + (1.0 - alpha) * deshake->avg.vector.y;

    deshake->avg.angle = alpha * t.angle + (1.0 - alpha) * deshake->avg.angle;

    deshake->avg.zoom = alpha * t.zoom + (1.0 - alpha) * deshake->avg.zoom;

    // Remove the average from the current motion to detect the motion that

    // is not on purpose, just as jitter from bumping the camera

    t.vector.x -= deshake->avg.vector.x;

    t.vector.y -= deshake->avg.vector.y;

    t.angle -= deshake->avg.angle;

    t.zoom -= deshake->avg.zoom;

    // Invert the motion to undo it

    t.vector.x *= -1;

    t.vector.y *= -1;

    t.angle *= -1;

    // Write statistics to file

    if (deshake->fp) {

        snprintf(tmp, 256, "%f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f, %f\n", orig.vector.x, deshake->avg.vector.x, t.vector.x, orig.vector.y, deshake->avg.vector.y, t.vector.y, orig.angle, deshake->avg.angle, t.angle, orig.zoom, deshake->avg.zoom, t.zoom);

        fwrite(tmp, sizeof(char), strlen(tmp), deshake->fp);

    }

    // Turn relative current frame motion into absolute by adding it to the

    // last absolute motion

    t.vector.x += deshake->last.vector.x;

    t.vector.y += deshake->last.vector.y;

    t.angle += deshake->last.angle;

    t.zoom += deshake->last.zoom;

    // Shrink motion by 10% to keep things centered in the camera frame

    t.vector.x *= 0.9;

    t.vector.y *= 0.9;

    t.angle *= 0.9;

    // Store the last absolute motion information

    deshake->last.vector.x = t.vector.x;

    deshake->last.vector.y = t.vector.y;

    deshake->last.angle = t.angle;

    deshake->last.zoom = t.zoom;

    // Generate a luma transformation matrix

    avfilter_get_matrix(t.vector.x, t.vector.y, t.angle, 1.0 + t.zoom / 100.0, matrix);

    // Transform the luma plane

    avfilter_transform(in->data[0], out->data[0], in->linesize[0], out->linesize[0], link->w, link->h, matrix, INTERPOLATE_BILINEAR, deshake->edge);

    // Generate a chroma transformation matrix

    avfilter_get_matrix(t.vector.x / (link->w / CHROMA_WIDTH(link)), t.vector.y / (link->h / CHROMA_HEIGHT(link)), t.angle, 1.0 + t.zoom / 100.0, matrix);

    // Transform the chroma planes

    avfilter_transform(in->data[1], out->data[1], in->linesize[1], out->linesize[1], CHROMA_WIDTH(link), CHROMA_HEIGHT(link), matrix, INTERPOLATE_BILINEAR, deshake->edge);

    avfilter_transform(in->data[2], out->data[2], in->linesize[2], out->linesize[2], CHROMA_WIDTH(link), CHROMA_HEIGHT(link), matrix, INTERPOLATE_BILINEAR, deshake->edge);

    // Store the current frame as the reference frame for calculating the

    // motion of the next frame

    if (deshake->ref != NULL)

        avfilter_unref_buffer(deshake->ref);

    // Cleanup the old reference frame

    deshake->ref = in;

    // Draw the transformed frame information

    avfilter_draw_slice(link->dst->outputs[0], 0, link->h, 1);

    avfilter_end_frame(link->dst->outputs[0]);

    avfilter_unref_buffer(out);

}


static av_cold int dsp_init(AVCodecContext *avctx, AACEncContext *s)

{

    int ret = 0;

    s->fdsp = avpriv_float_dsp_alloc(avctx->flags & CODEC_FLAG_BITEXACT);

    if (!s->fdsp)

        return AVERROR(ENOMEM);

    // window init

    ff_kbd_window_init(ff_aac_kbd_long_1024, 4.0, 1024);

    ff_kbd_window_init(ff_aac_kbd_short_128, 6.0, 128);

    ff_init_ff_sine_windows(10);

    ff_init_ff_sine_windows(7);

    if (ret = ff_mdct_init(&s->mdct1024, 11, 0, 32768.0))

        return ret;

    if (ret = ff_mdct_init(&s->mdct128,   8, 0, 32768.0))

        return ret;

    return 0;

}


static void sbr_dequant(SpectralBandReplication *sbr, int id_aac)

{

    int k, e;

    int ch;

    if (id_aac == TYPE_CPE && sbr->bs_coupling) {

        int alpha      = sbr->data[0].bs_amp_res ?  2 :  1;

        int pan_offset = sbr->data[0].bs_amp_res ? 12 : 24;

        for (e = 1; e <= sbr->data[0].bs_num_env; e++) {

            for (k = 0; k < sbr->n[sbr->data[0].bs_freq_res[e]]; k++) {

                SoftFloat temp1, temp2, fac;

                temp1.exp = sbr->data[0].env_facs[e][k].mant * alpha + 14;

                if (temp1.exp & 1)

                  temp1.mant = 759250125;

                else

                  temp1.mant = 0x20000000;

                temp1.exp = (temp1.exp >> 1) + 1;

                if (temp1.exp > 66) { // temp1 > 1E20

                    av_log(NULL, AV_LOG_ERROR, "envelope scalefactor overflow in dequant\n");

                    temp1 = FLOAT_1;

                }

                temp2.exp = (pan_offset - sbr->data[1].env_facs[e][k].mant) * alpha;

                if (temp2.exp & 1)

                  temp2.mant = 759250125;

                else

                  temp2.mant = 0x20000000;

                temp2.exp = (temp2.exp >> 1) + 1;

                fac   = av_div_sf(temp1, av_add_sf(FLOAT_1, temp2));

                sbr->data[0].env_facs[e][k] = fac;

                sbr->data[1].env_facs[e][k] = av_mul_sf(fac, temp2);

            }

        }

        for (e = 1; e <= sbr->data[0].bs_num_noise; e++) {

            for (k = 0; k < sbr->n_q; k++) {

                SoftFloat temp1, temp2, fac;

                temp1.exp = NOISE_FLOOR_OFFSET - \

                    sbr->data[0].noise_facs[e][k].mant + 2;

                temp1.mant = 0x20000000;

                if (temp1.exp > 66) { // temp1 > 1E20

                    av_log(NULL, AV_LOG_ERROR, "envelope scalefactor overflow in dequant\n");

                    temp1 = FLOAT_1;

                }

                temp2.exp = 12 - sbr->data[1].noise_facs[e][k].mant + 1;

                temp2.mant = 0x20000000;

                fac   = av_div_sf(temp1, av_add_sf(FLOAT_1, temp2));

                sbr->data[0].noise_facs[e][k] = fac;

                sbr->data[1].noise_facs[e][k] = av_mul_sf(fac, temp2);

            }

        }

    } else { // SCE or one non-coupled CPE

        for (ch = 0; ch < (id_aac == TYPE_CPE) + 1; ch++) {

            int alpha = sbr->data[ch].bs_amp_res ? 2 : 1;

            for (e = 1; e <= sbr->data[ch].bs_num_env; e++)

                for (k = 0; k < sbr->n[sbr->data[ch].bs_freq_res[e]]; k++){

                    SoftFloat temp1;

                    temp1.exp = alpha * sbr->data[ch].env_facs[e][k].mant + 12;

                    if (temp1.exp & 1)

                        temp1.mant = 759250125;

                    else

                        temp1.mant = 0x20000000;

                    temp1.exp = (temp1.exp >> 1) + 1;

                    if (temp1.exp > 66) { // temp1 > 1E20

                        av_log(NULL, AV_LOG_ERROR, "envelope scalefactor overflow in dequant\n");

                        temp1 = FLOAT_1;

                    }

                    sbr->data[ch].env_facs[e][k] = temp1;

                }

            for (e = 1; e <= sbr->data[ch].bs_num_noise; e++)

                for (k = 0; k < sbr->n_q; k++){

                    sbr->data[ch].noise_facs[e][k].exp = NOISE_FLOOR_OFFSET - \

                        sbr->data[ch].noise_facs[e][k].mant + 1;

                    sbr->data[ch].noise_facs[e][k].mant = 0x20000000;

                }

        }

    }

}


static int decode_value(SCPRContext *s, unsigned *cnt, unsigned maxc, unsigned step, unsigned *rval)

{

    GetByteContext *gb = &s->gb;

    RangeCoder *rc = &s->rc;

    unsigned totfr = cnt[maxc];

    unsigned value;

    unsigned c = 0, cumfr = 0, cnt_c = 0;

    int i, ret;

    if ((ret = s->get_freq(rc, totfr, &value)) < 0)

        return ret;

    while (c < maxc) {

        cnt_c = cnt[c];

        if (value >= cumfr + cnt_c)

            cumfr += cnt_c;

        else

            break;

        c++;

    }

    s->decode(gb, rc, cumfr, cnt_c, totfr);

    cnt[c] = cnt_c + step;

    totfr += step;

    if (totfr > BOT) {

        totfr = 0;

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

            unsigned nc = (cnt[i] >> 1) + 1;

            cnt[i] = nc;

            totfr += nc;

        }

    }

    cnt[maxc] = totfr;

    *rval = c;

    return 0;

}


char *socket_address_to_string(struct SocketAddressLegacy *addr, Error **errp)

{

    char *buf;

    InetSocketAddress *inet;

    switch (addr->type) {

    case SOCKET_ADDRESS_LEGACY_KIND_INET:

        inet = addr->u.inet.data;

        if (strchr(inet->host, ':') == NULL) {

            buf = g_strdup_printf("%s:%s", inet->host, inet->port);

        } else {

            buf = g_strdup_printf("[%s]:%s", inet->host, inet->port);

        }

        break;

    case SOCKET_ADDRESS_LEGACY_KIND_UNIX:

        buf = g_strdup(addr->u.q_unix.data->path);

        break;

    case SOCKET_ADDRESS_LEGACY_KIND_FD:

        buf = g_strdup(addr->u.fd.data->str);

        break;

    case SOCKET_ADDRESS_LEGACY_KIND_VSOCK:

        buf = g_strdup_printf("%s:%s",

                              addr->u.vsock.data->cid,

                              addr->u.vsock.data->port);

        break;

    default:

        abort();

    }

    return buf;

}


START_TEST(unterminated_escape)

{

    QObject *obj = qobject_from_json("\"abc\\\"");

    fail_unless(obj == NULL);

}


BlockBackend *blk_new(uint64_t perm, uint64_t shared_perm)

{

    BlockBackend *blk;

    blk = g_new0(BlockBackend, 1);

    blk->refcnt = 1;

    blk->perm = perm;

    blk->shared_perm = shared_perm;

    blk_set_enable_write_cache(blk, true);

    qemu_co_mutex_init(&blk->public.throttle_group_member.throttled_reqs_lock);

    qemu_co_queue_init(&blk->public.throttle_group_member.throttled_reqs[0]);

    qemu_co_queue_init(&blk->public.throttle_group_member.throttled_reqs[1]);

    block_acct_init(&blk->stats);

    notifier_list_init(&blk->remove_bs_notifiers);

    notifier_list_init(&blk->insert_bs_notifiers);

    QTAILQ_INSERT_TAIL(&block_backends, blk, link);

    return blk;

}


static inline int put_dwords(uint32_t addr, uint32_t *buf, int num)

{

    int i;

    for(i = 0; i < num; i++, buf++, addr += sizeof(*buf)) {

        uint32_t tmp = cpu_to_le32(*buf);

        cpu_physical_memory_rw(addr,(uint8_t *)&tmp, sizeof(tmp), 1);

    }

    return 1;

}


static int vc1_decode_p_block(VC1Context *v, DCTELEM block[64], int n, int mquant, int ttmb, int first_block,

                              uint8_t *dst, int linesize, int skip_block)

{

    MpegEncContext *s = &v->s;

    GetBitContext *gb = &s->gb;

    int i, j;

    int subblkpat = 0;

    int scale, off, idx, last, skip, value;

    int ttblk = ttmb & 7;

    if(ttmb == -1) {

        ttblk = ff_vc1_ttblk_to_tt[v->tt_index][get_vlc2(gb, ff_vc1_ttblk_vlc[v->tt_index].table, VC1_TTBLK_VLC_BITS, 1)];

    }

    if(ttblk == TT_4X4) {

        subblkpat = ~(get_vlc2(gb, ff_vc1_subblkpat_vlc[v->tt_index].table, VC1_SUBBLKPAT_VLC_BITS, 1) + 1);

    }

    if((ttblk != TT_8X8 && ttblk != TT_4X4) && (v->ttmbf || (ttmb != -1 && (ttmb & 8) && !first_block))) {

        subblkpat = decode012(gb);

        if(subblkpat) subblkpat ^= 3; //swap decoded pattern bits

        if(ttblk == TT_8X4_TOP || ttblk == TT_8X4_BOTTOM) ttblk = TT_8X4;

        if(ttblk == TT_4X8_RIGHT || ttblk == TT_4X8_LEFT) ttblk = TT_4X8;

    }

    scale = 2 * mquant + ((v->pq == mquant) ? v->halfpq : 0);

    // convert transforms like 8X4_TOP to generic TT and SUBBLKPAT

    if(ttblk == TT_8X4_TOP || ttblk == TT_8X4_BOTTOM) {

        subblkpat = 2 - (ttblk == TT_8X4_TOP);

        ttblk = TT_8X4;

    }

    if(ttblk == TT_4X8_RIGHT || ttblk == TT_4X8_LEFT) {

        subblkpat = 2 - (ttblk == TT_4X8_LEFT);

        ttblk = TT_4X8;

    }

    switch(ttblk) {

    case TT_8X8:

        i = 0;

        last = 0;

        while (!last) {

            vc1_decode_ac_coeff(v, &last, &skip, &value, v->codingset2);

            i += skip;

            if(i > 63)

                break;

            idx = wmv1_scantable[0][i++];

            block[idx] = value * scale;

            if(!v->pquantizer)

                block[idx] += (block[idx] < 0) ? -mquant : mquant;

        }

        if(!skip_block){

            s->dsp.vc1_inv_trans_8x8(block);

            s->dsp.add_pixels_clamped(block, dst, linesize);

        }

        break;

    case TT_4X4:

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

            last = subblkpat & (1 << (3 - j));

            i = 0;

            off = (j & 1) * 4 + (j & 2) * 16;

            while (!last) {

                vc1_decode_ac_coeff(v, &last, &skip, &value, v->codingset2);

                i += skip;

                if(i > 15)

                    break;

                idx = ff_vc1_simple_progressive_4x4_zz[i++];

                block[idx + off] = value * scale;

                if(!v->pquantizer)

                    block[idx + off] += (block[idx + off] < 0) ? -mquant : mquant;

            }

            if(!(subblkpat & (1 << (3 - j))) && !skip_block)

                s->dsp.vc1_inv_trans_4x4(dst + (j&1)*4 + (j&2)*2*linesize, linesize, block + off);

        }

        break;

    case TT_8X4:

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

            last = subblkpat & (1 << (1 - j));

            i = 0;

            off = j * 32;

            while (!last) {

                vc1_decode_ac_coeff(v, &last, &skip, &value, v->codingset2);

                i += skip;

                if(i > 31)

                    break;

                idx = v->zz_8x4[i++]+off;

                block[idx] = value * scale;

                if(!v->pquantizer)

                    block[idx] += (block[idx] < 0) ? -mquant : mquant;

            }

            if(!(subblkpat & (1 << (1 - j))) && !skip_block)

                s->dsp.vc1_inv_trans_8x4(dst + j*4*linesize, linesize, block + off);

        }

        break;

    case TT_4X8:

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

            last = subblkpat & (1 << (1 - j));

            i = 0;

            off = j * 4;

            while (!last) {

                vc1_decode_ac_coeff(v, &last, &skip, &value, v->codingset2);

                i += skip;

                if(i > 31)

                    break;

                idx = v->zz_4x8[i++]+off;

                block[idx] = value * scale;

                if(!v->pquantizer)

                    block[idx] += (block[idx] < 0) ? -mquant : mquant;

            }

            if(!(subblkpat & (1 << (1 - j))) && !skip_block)

                s->dsp.vc1_inv_trans_4x8(dst + j*4, linesize, block + off);

        }

        break;

    }

    return 0;

}


static void dma_bdrv_unmap(DMAAIOCB *dbs)

{

    int i;

    for (i = 0; i < dbs->iov.niov; ++i) {

        dma_memory_unmap(dbs->sg->as, dbs->iov.iov[i].iov_base,

                         dbs->iov.iov[i].iov_len, dbs->dir,

                         dbs->iov.iov[i].iov_len);

    }

    qemu_iovec_reset(&dbs->iov);

}


static inline abi_long do_msgsnd(int msqid, abi_long msgp,

                                 unsigned int msgsz, int msgflg)

{

    struct target_msgbuf *target_mb;

    struct msgbuf *host_mb;

    abi_long ret = 0;

    if (!lock_user_struct(VERIFY_READ, target_mb, msgp, 0))

        return -TARGET_EFAULT;

    host_mb = malloc(msgsz+sizeof(long));

    host_mb->mtype = (abi_long) tswapal(target_mb->mtype);

    memcpy(host_mb->mtext, target_mb->mtext, msgsz);

    ret = get_errno(msgsnd(msqid, host_mb, msgsz, msgflg));

    free(host_mb);

    unlock_user_struct(target_mb, msgp, 0);

    return ret;

}


void qemu_service_io(void)

{

    qemu_notify_event();

}


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

{

    errno = EPERM;

    return -1;

}


static void invalidate_tlb (int idx, int use_extra)

{

    tlb_t *tlb;

    target_ulong addr;

    uint8_t ASID;

    ASID = env->CP0_EntryHi & 0xFF;

    tlb = &env->tlb[idx];

    /* The qemu TLB is flushed then the ASID changes, so no need to

       flush these entries again.  */

    if (tlb->G == 0 && tlb->ASID != ASID) {

        return;

    }

    if (use_extra && env->tlb_in_use < MIPS_TLB_MAX) {

        /* For tlbwr, we can shadow the discarded entry into

	   a new (fake) TLB entry, as long as the guest can not

	   tell that it's there.  */

        env->tlb[env->tlb_in_use] = *tlb;

        env->tlb_in_use++;

        return;

    }

    if (tlb->V0) {

        tb_invalidate_page_range(tlb->PFN[0], tlb->end - tlb->VPN);

        addr = tlb->VPN;

        while (addr < tlb->end) {

            tlb_flush_page (env, addr);

            addr += TARGET_PAGE_SIZE;

        }

    }

    if (tlb->V1) {

        tb_invalidate_page_range(tlb->PFN[1], tlb->end2 - tlb->end);

        addr = tlb->end;

        while (addr < tlb->end2) {

            tlb_flush_page (env, addr);

            addr += TARGET_PAGE_SIZE;

        }

    }

}


static int parse_uri(const char *filename, QDict *options, Error **errp)

{

    URI *uri = NULL;

    QueryParams *qp = NULL;

    int i;

    uri = uri_parse(filename);

    if (!uri) {

        return -EINVAL;

    }

    if (strcmp(uri->scheme, "ssh") != 0) {

        error_setg(errp, "URI scheme must be 'ssh'");

        goto err;

    }

    if (!uri->server || strcmp(uri->server, "") == 0) {

        error_setg(errp, "missing hostname in URI");

        goto err;

    }

    if (!uri->path || strcmp(uri->path, "") == 0) {

        error_setg(errp, "missing remote path in URI");

        goto err;

    }

    qp = query_params_parse(uri->query);

    if (!qp) {

        error_setg(errp, "could not parse query parameters");

        goto err;

    }

    if(uri->user && strcmp(uri->user, "") != 0) {

        qdict_put(options, "user", qstring_from_str(uri->user));

    }

    qdict_put(options, "host", qstring_from_str(uri->server));

    if (uri->port) {

        qdict_put(options, "port", qint_from_int(uri->port));

    }

    qdict_put(options, "path", qstring_from_str(uri->path));

    /* Pick out any query parameters that we understand, and ignore

     * the rest.

     */

    for (i = 0; i < qp->n; ++i) {

        if (strcmp(qp->p[i].name, "host_key_check") == 0) {

            qdict_put(options, "host_key_check",

                      qstring_from_str(qp->p[i].value));

        }

    }

    query_params_free(qp);

    uri_free(uri);

    return 0;

 err:

    if (qp) {

      query_params_free(qp);

    }

    if (uri) {

      uri_free(uri);

    }

    return -EINVAL;

}


static void qmp_chardev_open_udp(Chardev *chr,

                                 ChardevBackend *backend,

                                 bool *be_opened,

                                 Error **errp)

{

    ChardevUdp *udp = backend->u.udp.data;

    QIOChannelSocket *sioc = qio_channel_socket_new();

    char *name;

    UdpChardev *s = UDP_CHARDEV(chr);

    if (qio_channel_socket_dgram_sync(sioc,

                                      udp->local, udp->remote,

                                      errp) < 0) {

        object_unref(OBJECT(sioc));

        return;

    }

    name = g_strdup_printf("chardev-udp-%s", chr->label);

    qio_channel_set_name(QIO_CHANNEL(sioc), name);

    g_free(name);

    s->ioc = QIO_CHANNEL(sioc);

    /* be isn't opened until we get a connection */

    *be_opened = false;

}


void qbus_create_inplace(BusState *bus, const char *typename,

                         DeviceState *parent, const char *name)

{

    object_initialize(bus, typename);

    qbus_realize(bus, parent, name);

}


static int qemu_rdma_drain_cq(QEMUFile *f, RDMAContext *rdma)

{

    int ret;

    if (qemu_rdma_write_flush(f, rdma) < 0) {

        return -EIO;

    }

    while (rdma->nb_sent) {

        ret = qemu_rdma_block_for_wrid(rdma, RDMA_WRID_RDMA_WRITE);

        if (ret < 0) {

            fprintf(stderr, "rdma migration: complete polling error!\n");

            return -EIO;

        }

    }

    qemu_rdma_unregister_waiting(rdma);

    return 0;

}


SwsVector *sws_cloneVec(SwsVector *a)

{

    int i;

    SwsVector *vec = sws_allocVec(a->length);

    if (!vec)

        return NULL;

    for (i = 0; i < a->length; i++)

        vec->coeff[i] = a->coeff[i];

    return vec;

}


static void expr_error(const char *fmt)

{

    term_printf(fmt);

    term_printf("\n");

    longjmp(expr_env, 1);

}


static void dec_wcsr(DisasContext *dc)

{

    int no;

    LOG_DIS("wcsr r%d, %d\n", dc->r1, dc->csr);

    switch (dc->csr) {

    case CSR_IE:

        tcg_gen_mov_tl(cpu_ie, cpu_R[dc->r1]);

        tcg_gen_movi_tl(cpu_pc, dc->pc + 4);

        dc->is_jmp = DISAS_UPDATE;

        break;

    case CSR_IM:

        /* mark as an io operation because it could cause an interrupt */

        if (use_icount) {

            gen_io_start();

        }

        gen_helper_wcsr_im(cpu_env, cpu_R[dc->r1]);

        tcg_gen_movi_tl(cpu_pc, dc->pc + 4);

        if (use_icount) {

            gen_io_end();

        }

        dc->is_jmp = DISAS_UPDATE;

        break;

    case CSR_IP:

        /* mark as an io operation because it could cause an interrupt */

        if (use_icount) {

            gen_io_start();

        }

        gen_helper_wcsr_ip(cpu_env, cpu_R[dc->r1]);

        tcg_gen_movi_tl(cpu_pc, dc->pc + 4);

        if (use_icount) {

            gen_io_end();

        }

        dc->is_jmp = DISAS_UPDATE;

        break;

    case CSR_ICC:

        /* TODO */

        break;

    case CSR_DCC:

        /* TODO */

        break;

    case CSR_EBA:

        tcg_gen_mov_tl(cpu_eba, cpu_R[dc->r1]);

        break;

    case CSR_DEBA:

        tcg_gen_mov_tl(cpu_deba, cpu_R[dc->r1]);

        break;

    case CSR_JTX:

        gen_helper_wcsr_jtx(cpu_env, cpu_R[dc->r1]);

        break;

    case CSR_JRX:

        gen_helper_wcsr_jrx(cpu_env, cpu_R[dc->r1]);

        break;

    case CSR_DC:

        gen_helper_wcsr_dc(cpu_env, cpu_R[dc->r1]);

        break;

    case CSR_BP0:

    case CSR_BP1:

    case CSR_BP2:

    case CSR_BP3:

        no = dc->csr - CSR_BP0;

        if (dc->num_breakpoints <= no) {

            qemu_log_mask(LOG_GUEST_ERROR,

                          "breakpoint #%i is not available\n", no);

            t_gen_illegal_insn(dc);

            break;

        }

        gen_helper_wcsr_bp(cpu_env, cpu_R[dc->r1], tcg_const_i32(no));

        break;

    case CSR_WP0:

    case CSR_WP1:

    case CSR_WP2:

    case CSR_WP3:

        no = dc->csr - CSR_WP0;

        if (dc->num_watchpoints <= no) {

            qemu_log_mask(LOG_GUEST_ERROR,

                          "watchpoint #%i is not available\n", no);

            t_gen_illegal_insn(dc);

            break;

        }

        gen_helper_wcsr_wp(cpu_env, cpu_R[dc->r1], tcg_const_i32(no));

        break;

    case CSR_CC:

    case CSR_CFG:

        qemu_log_mask(LOG_GUEST_ERROR, "invalid write access csr=%x\n",

                      dc->csr);

        break;

    default:

        qemu_log_mask(LOG_GUEST_ERROR, "write_csr: unknown csr=%x\n",

                      dc->csr);

        break;

    }

}


static void coroutine_enter_cb(void *opaque, int ret)

{

    Coroutine *co = opaque;

    qemu_coroutine_enter(co, NULL);

}


int cpu_ppc_handle_mmu_fault (CPUState *env, target_ulong address, int rw,

                              int mmu_idx, int is_softmmu)

{

    mmu_ctx_t ctx;

    int access_type;

    int ret = 0;

    if (rw == 2) {

        /* code access */

        rw = 0;

        access_type = ACCESS_CODE;

    } else {

        /* data access */

        access_type = env->access_type;

    }

    ret = get_physical_address(env, &ctx, address, rw, access_type);

    if (ret == 0) {

        ret = tlb_set_page_exec(env, address & TARGET_PAGE_MASK,

                                ctx.raddr & TARGET_PAGE_MASK, ctx.prot,

                                mmu_idx, is_softmmu);

    } else if (ret < 0) {

        LOG_MMU_STATE(env);

        if (access_type == ACCESS_CODE) {

            switch (ret) {

            case -1:

                /* No matches in page tables or TLB */

                switch (env->mmu_model) {

                case POWERPC_MMU_SOFT_6xx:

                    env->exception_index = POWERPC_EXCP_IFTLB;

                    env->error_code = 1 << 18;

                    env->spr[SPR_IMISS] = address;

                    env->spr[SPR_ICMP] = 0x80000000 | ctx.ptem;

                    goto tlb_miss;

                case POWERPC_MMU_SOFT_74xx:

                    env->exception_index = POWERPC_EXCP_IFTLB;

                    goto tlb_miss_74xx;

                case POWERPC_MMU_SOFT_4xx:

                case POWERPC_MMU_SOFT_4xx_Z:

                    env->exception_index = POWERPC_EXCP_ITLB;

                    env->error_code = 0;

                    env->spr[SPR_40x_DEAR] = address;

                    env->spr[SPR_40x_ESR] = 0x00000000;

                    break;

                case POWERPC_MMU_32B:

                case POWERPC_MMU_601:

#if defined(TARGET_PPC64)

                case POWERPC_MMU_620:

                case POWERPC_MMU_64B:

#endif

                    env->exception_index = POWERPC_EXCP_ISI;

                    env->error_code = 0x40000000;

                    break;

                case POWERPC_MMU_BOOKE:

                    /* XXX: TODO */

                    cpu_abort(env, "BookE MMU model is not implemented\n");

                    return -1;

                case POWERPC_MMU_BOOKE_FSL:

                    /* XXX: TODO */

                    cpu_abort(env, "BookE FSL MMU model is not implemented\n");

                    return -1;

                case POWERPC_MMU_MPC8xx:

                    /* XXX: TODO */

                    cpu_abort(env, "MPC8xx MMU model is not implemented\n");

                    break;

                case POWERPC_MMU_REAL:

                    cpu_abort(env, "PowerPC in real mode should never raise "

                              "any MMU exceptions\n");

                    return -1;

                default:

                    cpu_abort(env, "Unknown or invalid MMU model\n");

                    return -1;

                }

                break;

            case -2:

                /* Access rights violation */

                env->exception_index = POWERPC_EXCP_ISI;

                env->error_code = 0x08000000;

                break;

            case -3:

                /* No execute protection violation */

                env->exception_index = POWERPC_EXCP_ISI;

                env->error_code = 0x10000000;

                break;

            case -4:

                /* Direct store exception */

                /* No code fetch is allowed in direct-store areas */

                env->exception_index = POWERPC_EXCP_ISI;

                env->error_code = 0x10000000;

                break;

#if defined(TARGET_PPC64)

            case -5:

                /* No match in segment table */

                if (env->mmu_model == POWERPC_MMU_620) {

                    env->exception_index = POWERPC_EXCP_ISI;

                    /* XXX: this might be incorrect */

                    env->error_code = 0x40000000;

                } else {

                    env->exception_index = POWERPC_EXCP_ISEG;

                    env->error_code = 0;

                }

                break;

#endif

            }

        } else {

            switch (ret) {

            case -1:

                /* No matches in page tables or TLB */

                switch (env->mmu_model) {

                case POWERPC_MMU_SOFT_6xx:

                    if (rw == 1) {

                        env->exception_index = POWERPC_EXCP_DSTLB;

                        env->error_code = 1 << 16;

                    } else {

                        env->exception_index = POWERPC_EXCP_DLTLB;

                        env->error_code = 0;

                    }

                    env->spr[SPR_DMISS] = address;

                    env->spr[SPR_DCMP] = 0x80000000 | ctx.ptem;

                tlb_miss:

                    env->error_code |= ctx.key << 19;

                    env->spr[SPR_HASH1] = ctx.pg_addr[0];

                    env->spr[SPR_HASH2] = ctx.pg_addr[1];

                    break;

                case POWERPC_MMU_SOFT_74xx:

                    if (rw == 1) {

                        env->exception_index = POWERPC_EXCP_DSTLB;

                    } else {

                        env->exception_index = POWERPC_EXCP_DLTLB;

                    }

                tlb_miss_74xx:

                    /* Implement LRU algorithm */

                    env->error_code = ctx.key << 19;

                    env->spr[SPR_TLBMISS] = (address & ~((target_ulong)0x3)) |

                        ((env->last_way + 1) & (env->nb_ways - 1));

                    env->spr[SPR_PTEHI] = 0x80000000 | ctx.ptem;

                    break;

                case POWERPC_MMU_SOFT_4xx:

                case POWERPC_MMU_SOFT_4xx_Z:

                    env->exception_index = POWERPC_EXCP_DTLB;

                    env->error_code = 0;

                    env->spr[SPR_40x_DEAR] = address;

                    if (rw)

                        env->spr[SPR_40x_ESR] = 0x00800000;

                    else

                        env->spr[SPR_40x_ESR] = 0x00000000;

                    break;

                case POWERPC_MMU_32B:

                case POWERPC_MMU_601:

#if defined(TARGET_PPC64)

                case POWERPC_MMU_620:

                case POWERPC_MMU_64B:

#endif

                    env->exception_index = POWERPC_EXCP_DSI;

                    env->error_code = 0;

                    env->spr[SPR_DAR] = address;

                    if (rw == 1)

                        env->spr[SPR_DSISR] = 0x42000000;

                    else

                        env->spr[SPR_DSISR] = 0x40000000;

                    break;

                case POWERPC_MMU_MPC8xx:

                    /* XXX: TODO */

                    cpu_abort(env, "MPC8xx MMU model is not implemented\n");

                    break;

                case POWERPC_MMU_BOOKE:

                    /* XXX: TODO */

                    cpu_abort(env, "BookE MMU model is not implemented\n");

                    return -1;

                case POWERPC_MMU_BOOKE_FSL:

                    /* XXX: TODO */

                    cpu_abort(env, "BookE FSL MMU model is not implemented\n");

                    return -1;

                case POWERPC_MMU_REAL:

                    cpu_abort(env, "PowerPC in real mode should never raise "

                              "any MMU exceptions\n");

                    return -1;

                default:

                    cpu_abort(env, "Unknown or invalid MMU model\n");

                    return -1;

                }

                break;

            case -2:

                /* Access rights violation */

                env->exception_index = POWERPC_EXCP_DSI;

                env->error_code = 0;

                env->spr[SPR_DAR] = address;

                if (rw == 1)

                    env->spr[SPR_DSISR] = 0x0A000000;

                else

                    env->spr[SPR_DSISR] = 0x08000000;

                break;

            case -4:

                /* Direct store exception */

                switch (access_type) {

                case ACCESS_FLOAT:

                    /* Floating point load/store */

                    env->exception_index = POWERPC_EXCP_ALIGN;

                    env->error_code = POWERPC_EXCP_ALIGN_FP;

                    env->spr[SPR_DAR] = address;

                    break;

                case ACCESS_RES:

                    /* lwarx, ldarx or stwcx. */

                    env->exception_index = POWERPC_EXCP_DSI;

                    env->error_code = 0;

                    env->spr[SPR_DAR] = address;

                    if (rw == 1)

                        env->spr[SPR_DSISR] = 0x06000000;

                    else

                        env->spr[SPR_DSISR] = 0x04000000;

                    break;

                case ACCESS_EXT:

                    /* eciwx or ecowx */

                    env->exception_index = POWERPC_EXCP_DSI;

                    env->error_code = 0;

                    env->spr[SPR_DAR] = address;

                    if (rw == 1)

                        env->spr[SPR_DSISR] = 0x06100000;

                    else

                        env->spr[SPR_DSISR] = 0x04100000;

                    break;

                default:

                    printf("DSI: invalid exception (%d)\n", ret);

                    env->exception_index = POWERPC_EXCP_PROGRAM;

                    env->error_code =

                        POWERPC_EXCP_INVAL | POWERPC_EXCP_INVAL_INVAL;

                    env->spr[SPR_DAR] = address;

                    break;

                }

                break;

#if defined(TARGET_PPC64)

            case -5:

                /* No match in segment table */

                if (env->mmu_model == POWERPC_MMU_620) {

                    env->exception_index = POWERPC_EXCP_DSI;

                    env->error_code = 0;

                    env->spr[SPR_DAR] = address;

                    /* XXX: this might be incorrect */

                    if (rw == 1)

                        env->spr[SPR_DSISR] = 0x42000000;

                    else

                        env->spr[SPR_DSISR] = 0x40000000;

                } else {

                    env->exception_index = POWERPC_EXCP_DSEG;

                    env->error_code = 0;

                    env->spr[SPR_DAR] = address;

                }

                break;

#endif

            }

        }

#if 0

        printf("%s: set exception to %d %02x\n", __func__,

               env->exception, env->error_code);

#endif

        ret = 1;

    }

    return ret;

}


static int sd_create(const char *filename, QEMUOptionParameter *options,

                     Error **errp)

{

    int ret = 0;

    uint32_t vid = 0;

    char *backing_file = NULL;

    BDRVSheepdogState *s;

    char tag[SD_MAX_VDI_TAG_LEN];

    uint32_t snapid;

    bool prealloc = false;

    Error *local_err = NULL;

    s = g_malloc0(sizeof(BDRVSheepdogState));

    memset(tag, 0, sizeof(tag));

    if (strstr(filename, "://")) {

        ret = sd_parse_uri(s, filename, s->name, &snapid, tag);

    } else {

        ret = parse_vdiname(s, filename, s->name, &snapid, tag);

    }

    if (ret < 0) {

        goto out;

    }

    while (options && options->name) {

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

            s->inode.vdi_size = options->value.n;

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

            backing_file = options->value.s;

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

            if (!options->value.s || !strcmp(options->value.s, "off")) {

                prealloc = false;

            } else if (!strcmp(options->value.s, "full")) {

                prealloc = true;

            } else {

                error_report("Invalid preallocation mode: '%s'",

                             options->value.s);

                ret = -EINVAL;

                goto out;

            }

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

            ret = parse_redundancy(s, options->value.s);

            if (ret < 0) {

                goto out;

            }

        }

        options++;

    }

    if (s->inode.vdi_size > SD_MAX_VDI_SIZE) {

        error_report("too big image size");

        ret = -EINVAL;

        goto out;

    }

    if (backing_file) {

        BlockDriverState *bs;

        BDRVSheepdogState *s;

        BlockDriver *drv;

        /* Currently, only Sheepdog backing image is supported. */

        drv = bdrv_find_protocol(backing_file, true);

        if (!drv || strcmp(drv->protocol_name, "sheepdog") != 0) {

            error_report("backing_file must be a sheepdog image");

            ret = -EINVAL;

            goto out;

        }

        ret = bdrv_file_open(&bs, backing_file, NULL, 0, &local_err);

        if (ret < 0) {

            qerror_report_err(local_err);

            error_free(local_err);

            goto out;

        }

        s = bs->opaque;

        if (!is_snapshot(&s->inode)) {

            error_report("cannot clone from a non snapshot vdi");

            bdrv_unref(bs);

            ret = -EINVAL;

            goto out;

        }

        bdrv_unref(bs);

    }

    ret = do_sd_create(s, &vid, 0);

    if (!prealloc || ret) {

        goto out;

    }

    ret = sd_prealloc(filename);

out:

    g_free(s);

    return ret;

}


opts_type_uint64(Visitor *v, uint64_t *obj, const char *name, Error **errp)

{

    OptsVisitor *ov = DO_UPCAST(OptsVisitor, visitor, v);

    const QemuOpt *opt;

    const char *str;

    unsigned long long val;

    char *endptr;

    if (ov->list_mode == LM_UNSIGNED_INTERVAL) {

        *obj = ov->range_next.u;

        return;

    }

    opt = lookup_scalar(ov, name, errp);

    if (!opt) {

        return;

    }

    str = opt->str;

    /* we've gotten past lookup_scalar() */

    assert(ov->list_mode == LM_NONE || ov->list_mode == LM_IN_PROGRESS);

    if (parse_uint(str, &val, &endptr, 0) == 0 && val <= UINT64_MAX) {

        if (*endptr == '\0') {

            *obj = val;

            processed(ov, name);

            return;

        }

        if (*endptr == '-' && ov->list_mode == LM_IN_PROGRESS) {

            unsigned long long val2;

            str = endptr + 1;

            if (parse_uint_full(str, &val2, 0) == 0 &&

                val2 <= UINT64_MAX && val <= val2) {

                ov->range_next.u = val;

                ov->range_limit.u = val2;

                ov->list_mode = LM_UNSIGNED_INTERVAL;

                /* as if entering on the top */

                *obj = ov->range_next.u;

                return;

            }

        }

    }

    error_set(errp, QERR_INVALID_PARAMETER_VALUE, opt->name,

              (ov->list_mode == LM_NONE) ? "a uint64 value" :

                                           "a uint64 value or range");

}


static void pci_basic_config(void)

{

    QVirtIO9P *v9p;

    void *addr;

    size_t tag_len;

    char *tag;

    int i;

    qvirtio_9p_start();

    v9p = qvirtio_9p_pci_init();

    addr = ((QVirtioPCIDevice *) v9p->dev)->addr + VIRTIO_PCI_CONFIG_OFF(false);

    tag_len = qvirtio_config_readw(v9p->dev,

                                   (uint64_t)(uintptr_t)addr);

    g_assert_cmpint(tag_len, ==, strlen(mount_tag));

    addr += sizeof(uint16_t);

    tag = g_malloc(tag_len);

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

        tag[i] = qvirtio_config_readb(v9p->dev, (uint64_t)(uintptr_t)addr + i);

    }

    g_assert_cmpmem(tag, tag_len, mount_tag, tag_len);

    g_free(tag);

    qvirtio_9p_pci_free(v9p);

    qvirtio_9p_stop();

}