static void svq1_encode_plane(SVQ1Context *s, int plane, unsigned char *src_plane, unsigned char *ref_plane, unsigned char *decoded_plane,

    int width, int height, int src_stride, int stride)

{

    int x, y;

    int i;

    int block_width, block_height;

    int level;

    int threshold[6];

    const int lambda= (s->picture.quality*s->picture.quality) >> (2*FF_LAMBDA_SHIFT);

    /* figure out the acceptable level thresholds in advance */

    threshold[5] = QUALITY_THRESHOLD;

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

        threshold[level] = threshold[level + 1] * THRESHOLD_MULTIPLIER;

    block_width = (width + 15) / 16;

    block_height = (height + 15) / 16;

    if(s->picture.pict_type == P_TYPE){

        s->m.avctx= s->avctx;

        s->m.current_picture_ptr= &s->m.current_picture;

        s->m.last_picture_ptr   = &s->m.last_picture;

        s->m.last_picture.data[0]= ref_plane;

        s->m.linesize=

        s->m.last_picture.linesize[0]=

        s->m.new_picture.linesize[0]=

        s->m.current_picture.linesize[0]= stride;

        s->m.width= width;

        s->m.height= height;

        s->m.mb_width= block_width;

        s->m.mb_height= block_height;

        s->m.mb_stride= s->m.mb_width+1;

        s->m.b8_stride= 2*s->m.mb_width+1;

        s->m.f_code=1;

        s->m.pict_type= s->picture.pict_type;

        s->m.qscale= s->picture.quality/FF_QP2LAMBDA;

        s->m.me_method= s->avctx->me_method;

        if(!s->motion_val8[plane]){

            s->motion_val8 [plane]= av_mallocz((s->m.b8_stride*block_height*2 + 2)*2*sizeof(int16_t));

            s->motion_val16[plane]= av_mallocz((s->m.mb_stride*(block_height + 2) + 1)*2*sizeof(int16_t));

        }

        s->m.mb_type= s->mb_type;

        //dummies, to avoid segfaults

        s->m.current_picture.mb_mean=   (uint8_t *)s->dummy;

        s->m.current_picture.mb_var=    (uint16_t*)s->dummy;

        s->m.current_picture.mc_mb_var= (uint16_t*)s->dummy;

        s->m.current_picture.mb_type= s->dummy;

        s->m.current_picture.motion_val[0]= s->motion_val8[plane] + 2;

        s->m.p_mv_table= s->motion_val16[plane] + s->m.mb_stride + 1;

        s->m.dsp= s->dsp; //move

        ff_init_me(&s->m);

        s->m.me.dia_size= s->avctx->dia_size;

        s->m.first_slice_line=1;

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

            uint8_t src[stride*16];

            s->m.new_picture.data[0]= src - y*16*stride; //ugly

            s->m.mb_y= y;

            for(i=0; i<16 && i + 16*y<height; i++){

                memcpy(&src[i*stride], &src_plane[(i+16*y)*src_stride], width);

                for(x=width; x<16*block_width; x++)

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

            }

            for(; i<16 && i + 16*y<16*block_height; i++)

                memcpy(&src[i*stride], &src[(i-1)*stride], 16*block_width);

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

                s->m.mb_x= x;

                ff_init_block_index(&s->m);

                ff_update_block_index(&s->m);

                ff_estimate_p_frame_motion(&s->m, x, y);

            }

            s->m.first_slice_line=0;

        }

        ff_fix_long_p_mvs(&s->m);

        ff_fix_long_mvs(&s->m, NULL, 0, s->m.p_mv_table, s->m.f_code, CANDIDATE_MB_TYPE_INTER, 0);

    }

    s->m.first_slice_line=1;

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

        uint8_t src[stride*16];

        for(i=0; i<16 && i + 16*y<height; i++){

            memcpy(&src[i*stride], &src_plane[(i+16*y)*src_stride], width);

            for(x=width; x<16*block_width; x++)

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

        }

        for(; i<16 && i + 16*y<16*block_height; i++)

            memcpy(&src[i*stride], &src[(i-1)*stride], 16*block_width);

        s->m.mb_y= y;

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

            uint8_t reorder_buffer[3][6][7*32];

            int count[3][6];

            int offset = y * 16 * stride + x * 16;

            uint8_t *decoded= decoded_plane + offset;

            uint8_t *ref= ref_plane + offset;

            int score[4]={0,0,0,0}, best;

            uint8_t temp[16*stride];

            s->m.mb_x= x;

            ff_init_block_index(&s->m);

            ff_update_block_index(&s->m);

            if(s->picture.pict_type == I_TYPE || (s->m.mb_type[x + y*s->m.mb_stride]&CANDIDATE_MB_TYPE_INTRA)){

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

                    init_put_bits(&s->reorder_pb[i], reorder_buffer[0][i], 7*32);

                }

                if(s->picture.pict_type == P_TYPE){

                    const uint8_t *vlc= svq1_block_type_vlc[SVQ1_BLOCK_INTRA];

                    put_bits(&s->reorder_pb[5], vlc[1], vlc[0]);

                    score[0]= vlc[1]*lambda;

                }

                score[0]+= encode_block(s, src+16*x, NULL, temp, stride, 5, 64, lambda, 1);

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

                    count[0][i]= put_bits_count(&s->reorder_pb[i]);

                    flush_put_bits(&s->reorder_pb[i]);

                }

            }else

                score[0]= INT_MAX;

            best=0;

            if(s->picture.pict_type == P_TYPE){

                const uint8_t *vlc= svq1_block_type_vlc[SVQ1_BLOCK_INTER];

                int mx, my, pred_x, pred_y, dxy;

                int16_t *motion_ptr;

                motion_ptr= h263_pred_motion(&s->m, 0, 0, &pred_x, &pred_y);

                if(s->m.mb_type[x + y*s->m.mb_stride]&CANDIDATE_MB_TYPE_INTER){

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

                        init_put_bits(&s->reorder_pb[i], reorder_buffer[1][i], 7*32);

                    put_bits(&s->reorder_pb[5], vlc[1], vlc[0]);

                    s->m.pb= s->reorder_pb[5];

                    mx= motion_ptr[0];

                    my= motion_ptr[1];

                    assert(mx>=-32 && mx<=31);

                    assert(my>=-32 && my<=31);

                    assert(pred_x>=-32 && pred_x<=31);

                    assert(pred_y>=-32 && pred_y<=31);

                    ff_h263_encode_motion(&s->m, mx - pred_x, 1);

                    ff_h263_encode_motion(&s->m, my - pred_y, 1);

                    s->reorder_pb[5]= s->m.pb;

                    score[1] += lambda*put_bits_count(&s->reorder_pb[5]);

                    dxy= (mx&1) + 2*(my&1);

                    s->dsp.put_pixels_tab[0][dxy](temp+16, ref + (mx>>1) + stride*(my>>1), stride, 16);

                    score[1]+= encode_block(s, src+16*x, temp+16, decoded, stride, 5, 64, lambda, 0);

                    best= score[1] <= score[0];

                    vlc= svq1_block_type_vlc[SVQ1_BLOCK_SKIP];

                    score[2]= s->dsp.sse[0](NULL, src+16*x, ref, stride, 16);

                    score[2]+= vlc[1]*lambda;

                    if(score[2] < score[best] && mx==0 && my==0){

                        best=2;

                        s->dsp.put_pixels_tab[0][0](decoded, ref, stride, 16);

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

                            count[2][i]=0;

                        }

                        put_bits(&s->pb, vlc[1], vlc[0]);

                    }

                }

                if(best==1){

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

                        count[1][i]= put_bits_count(&s->reorder_pb[i]);

                        flush_put_bits(&s->reorder_pb[i]);

                    }

                }else{

                    motion_ptr[0                 ] = motion_ptr[1                 ]=

                    motion_ptr[2                 ] = motion_ptr[3                 ]=

                    motion_ptr[0+2*s->m.b8_stride] = motion_ptr[1+2*s->m.b8_stride]=

                    motion_ptr[2+2*s->m.b8_stride] = motion_ptr[3+2*s->m.b8_stride]=0;

                }

            }

            s->rd_total += score[best];

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

                ff_copy_bits(&s->pb, reorder_buffer[best][i], count[best][i]);

            }

            if(best==0){

                s->dsp.put_pixels_tab[0][0](decoded, temp, stride, 16);

            }

        }

        s->m.first_slice_line=0;

    }

}


static int smka_decode_frame(AVCodecContext *avctx, void *data,
                             int *got_frame_ptr, AVPacket *avpkt)
{
    SmackerAudioContext *s = avctx->priv_data;
    const uint8_t *buf = avpkt->data;
    int buf_size = avpkt->size;
    GetBitContext gb;
    HuffContext h[4] = { { 0 } };
    VLC vlc[4]       = { { 0 } };
    int16_t *samples;
    uint8_t *samples8;
    int val;
    int i, res, ret;
    int unp_size;
    int bits, stereo;
    int pred[2] = {0, 0};
    if (buf_size <= 4) {
        av_log(avctx, AV_LOG_ERROR, "packet is too small\n");
        return AVERROR(EINVAL);
    unp_size = AV_RL32(buf);
    init_get_bits(&gb, buf + 4, (buf_size - 4) * 8);
    if(!get_bits1(&gb)){
        av_log(avctx, AV_LOG_INFO, "Sound: no data\n");
        *got_frame_ptr = 0;
        return 1;
    stereo = get_bits1(&gb);
    bits = get_bits1(&gb);
    if (stereo ^ (avctx->channels != 1)) {
        av_log(avctx, AV_LOG_ERROR, "channels mismatch\n");
        return AVERROR(EINVAL);
    if (bits && avctx->sample_fmt == AV_SAMPLE_FMT_U8) {
        av_log(avctx, AV_LOG_ERROR, "sample format mismatch\n");
        return AVERROR(EINVAL);
    /* get output buffer */
    s->frame.nb_samples = unp_size / (avctx->channels * (bits + 1));
    if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0) {
        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");
        return ret;
    samples  = (int16_t *)s->frame.data[0];
    samples8 =            s->frame.data[0];
    // Initialize
    for(i = 0; i < (1 << (bits + stereo)); i++) {
        h[i].length = 256;
        h[i].maxlength = 0;
        h[i].current = 0;
        h[i].bits = av_mallocz(256 * 4);
        h[i].lengths = av_mallocz(256 * sizeof(int));
        h[i].values = av_mallocz(256 * sizeof(int));
        skip_bits1(&gb);
        smacker_decode_tree(&gb, &h[i], 0, 0);
        skip_bits1(&gb);
        if(h[i].current > 1) {
            res = init_vlc(&vlc[i], SMKTREE_BITS, h[i].length,
                    h[i].lengths, sizeof(int), sizeof(int),
                    h[i].bits, sizeof(uint32_t), sizeof(uint32_t), INIT_VLC_LE);
            if(res < 0) {
                av_log(avctx, AV_LOG_ERROR, "Cannot build VLC table\n");
    if(bits) { //decode 16-bit data
        for(i = stereo; i >= 0; i--)
            pred[i] = sign_extend(av_bswap16(get_bits(&gb, 16)), 16);
        for(i = 0; i <= stereo; i++)
            *samples++ = pred[i];
        for(; i < unp_size / 2; i++) {
            if(get_bits_left(&gb)<0)
            if(i & stereo) {
                if(vlc[2].table)
                    res = get_vlc2(&gb, vlc[2].table, SMKTREE_BITS, 3);
                else
                    res = 0;
                if (res < 0) {
                    av_log(avctx, AV_LOG_ERROR, "invalid vlc\n");
                val  = h[2].values[res];
                if(vlc[3].table)
                    res = get_vlc2(&gb, vlc[3].table, SMKTREE_BITS, 3);
                else
                    res = 0;
                if (res < 0) {
                    av_log(avctx, AV_LOG_ERROR, "invalid vlc\n");
                val |= h[3].values[res] << 8;
                pred[1] += sign_extend(val, 16);
                *samples++ = av_clip_int16(pred[1]);
            } else {
                if(vlc[0].table)
                    res = get_vlc2(&gb, vlc[0].table, SMKTREE_BITS, 3);
                else
                    res = 0;
                if (res < 0) {
                    av_log(avctx, AV_LOG_ERROR, "invalid vlc\n");
                val  = h[0].values[res];
                if(vlc[1].table)
                    res = get_vlc2(&gb, vlc[1].table, SMKTREE_BITS, 3);
                else
                    res = 0;
                if (res < 0) {
                    av_log(avctx, AV_LOG_ERROR, "invalid vlc\n");
                val |= h[1].values[res] << 8;
                pred[0] += sign_extend(val, 16);
                *samples++ = av_clip_int16(pred[0]);
    } else { //8-bit data
        for(i = stereo; i >= 0; i--)
            pred[i] = get_bits(&gb, 8);
        for(i = 0; i <= stereo; i++)
            *samples8++ = pred[i];
        for(; i < unp_size; i++) {
            if(get_bits_left(&gb)<0)
            if(i & stereo){
                if(vlc[1].table)
                    res = get_vlc2(&gb, vlc[1].table, SMKTREE_BITS, 3);
                else
                    res = 0;
                if (res < 0) {
                    av_log(avctx, AV_LOG_ERROR, "invalid vlc\n");
                pred[1] += sign_extend(h[1].values[res], 8);
                *samples8++ = av_clip_uint8(pred[1]);
            } else {
                if(vlc[0].table)
                    res = get_vlc2(&gb, vlc[0].table, SMKTREE_BITS, 3);
                else
                    res = 0;
                if (res < 0) {
                    av_log(avctx, AV_LOG_ERROR, "invalid vlc\n");
                pred[0] += sign_extend(h[0].values[res], 8);
                *samples8++ = av_clip_uint8(pred[0]);
    for(i = 0; i < 4; i++) {
        if(vlc[i].table)
            ff_free_vlc(&vlc[i]);
        av_free(h[i].bits);
        av_free(h[i].lengths);
        av_free(h[i].values);
    *got_frame_ptr   = 1;
    *(AVFrame *)data = s->frame;
    return buf_size;


static int decode_rle(AVCodecContext *avctx, AVSubtitle *sub,

                      const uint8_t *buf, unsigned int buf_size)

{

    const uint8_t *rle_bitmap_end;

    int pixel_count, line_count;

    rle_bitmap_end = buf + buf_size;

    sub->rects[0]->pict.data[0] = av_malloc(sub->rects[0]->w * sub->rects[0]->h);

    if (!sub->rects[0]->pict.data[0])

        return -1;

    pixel_count = 0;

    line_count  = 0;

    while (buf < rle_bitmap_end && line_count < sub->rects[0]->h) {

        uint8_t flags, color;

        int run;

        color = bytestream_get_byte(&buf);

        run   = 1;

        if (color == 0x00) {

            flags = bytestream_get_byte(&buf);

            run   = flags & 0x3f;

            if (flags & 0x40)

                run = (run << 8) + bytestream_get_byte(&buf);

            color = flags & 0x80 ? bytestream_get_byte(&buf) : 0;

        }

        if (run > 0 && pixel_count + run <= sub->rects[0]->w * sub->rects[0]->h) {

            memset(sub->rects[0]->pict.data[0] + pixel_count, color, run);

            pixel_count += run;

        } else if (!run) {

            /*

             * New Line. Check if correct pixels decoded, if not display warning

             * and adjust bitmap pointer to correct new line position.

             */

            if (pixel_count % sub->rects[0]->w > 0)

                av_log(avctx, AV_LOG_ERROR, "Decoded %d pixels, when line should be %d pixels\n",

                       pixel_count % sub->rects[0]->w, sub->rects[0]->w);

            line_count++;

        }

    }

    if (pixel_count < sub->rects[0]->w * sub->rects[0]->h) {

        av_log(avctx, AV_LOG_ERROR, "Insufficient RLE data for subtitle\n");

        return -1;

    }

    av_dlog(avctx, "Pixel Count = %d, Area = %d\n", pixel_count, sub->rects[0]->w * sub->rects[0]->h);

    return 0;

}


static int scsi_disk_initfn(SCSIDevice *dev)

{

    SCSIDriveKind kind;

    if (!dev->conf.bs) {

        kind = SCSI_HD;         /* will die in scsi_initfn() */

    } else {

        kind = bdrv_get_type_hint(dev->conf.bs) == BDRV_TYPE_CDROM

            ? SCSI_CD : SCSI_HD;

    }

    return scsi_initfn(dev, kind);

}


static int coroutine_fn bdrv_co_do_pwritev(BlockDriverState *bs,

    int64_t offset, unsigned int bytes, QEMUIOVector *qiov,

    BdrvRequestFlags flags)

{

    BdrvTrackedRequest req;

    /* TODO Lift BDRV_SECTOR_SIZE restriction in BlockDriver interface */

    uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment);

    uint8_t *head_buf = NULL;

    uint8_t *tail_buf = NULL;

    QEMUIOVector local_qiov;

    bool use_local_qiov = false;

    int ret;

    if (!bs->drv) {

        return -ENOMEDIUM;

    }

    if (bs->read_only) {

        return -EACCES;

    }

    ret = bdrv_check_byte_request(bs, offset, bytes);

    if (ret < 0) {

        return ret;

    }

    /* throttling disk I/O */

    if (bs->io_limits_enabled) {

        bdrv_io_limits_intercept(bs, bytes, true);

    }

    /*

     * Align write if necessary by performing a read-modify-write cycle.

     * Pad qiov with the read parts and be sure to have a tracked request not

     * only for bdrv_aligned_pwritev, but also for the reads of the RMW cycle.

     */

    tracked_request_begin(&req, bs, offset, bytes, true);

    if (offset & (align - 1)) {

        QEMUIOVector head_qiov;

        struct iovec head_iov;

        mark_request_serialising(&req, align);

        wait_serialising_requests(&req);

        head_buf = qemu_blockalign(bs, align);

        head_iov = (struct iovec) {

            .iov_base   = head_buf,

            .iov_len    = align,

        };

        qemu_iovec_init_external(&head_qiov, &head_iov, 1);

        BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_HEAD);

        ret = bdrv_aligned_preadv(bs, &req, offset & ~(align - 1), align,

                                  align, &head_qiov, 0);

        if (ret < 0) {

            goto fail;

        }

        BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD);

        qemu_iovec_init(&local_qiov, qiov->niov + 2);

        qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));

        qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);

        use_local_qiov = true;

        bytes += offset & (align - 1);

        offset = offset & ~(align - 1);

    }

    if ((offset + bytes) & (align - 1)) {

        QEMUIOVector tail_qiov;

        struct iovec tail_iov;

        size_t tail_bytes;

        bool waited;

        mark_request_serialising(&req, align);

        waited = wait_serialising_requests(&req);

        assert(!waited || !use_local_qiov);

        tail_buf = qemu_blockalign(bs, align);

        tail_iov = (struct iovec) {

            .iov_base   = tail_buf,

            .iov_len    = align,

        };

        qemu_iovec_init_external(&tail_qiov, &tail_iov, 1);

        BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_TAIL);

        ret = bdrv_aligned_preadv(bs, &req, (offset + bytes) & ~(align - 1), align,

                                  align, &tail_qiov, 0);

        if (ret < 0) {

            goto fail;

        }

        BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);

        if (!use_local_qiov) {

            qemu_iovec_init(&local_qiov, qiov->niov + 1);

            qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);

            use_local_qiov = true;

        }

        tail_bytes = (offset + bytes) & (align - 1);

        qemu_iovec_add(&local_qiov, tail_buf + tail_bytes, align - tail_bytes);

        bytes = ROUND_UP(bytes, align);

    }

    ret = bdrv_aligned_pwritev(bs, &req, offset, bytes,

                               use_local_qiov ? &local_qiov : qiov,

                               flags);

fail:

    tracked_request_end(&req);

    if (use_local_qiov) {

        qemu_iovec_destroy(&local_qiov);

    }

    qemu_vfree(head_buf);

    qemu_vfree(tail_buf);

    return ret;

}


static int cloop_read(BlockDriverState *bs, int64_t sector_num,

                    uint8_t *buf, int nb_sectors)

{

    BDRVCloopState *s = bs->opaque;

    int i;

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

        uint32_t sector_offset_in_block =

            ((sector_num + i) % s->sectors_per_block),

            block_num = (sector_num + i) / s->sectors_per_block;

        if (cloop_read_block(bs, block_num) != 0) {

            return -1;

        }

        memcpy(buf + i * 512,

            s->uncompressed_block + sector_offset_in_block * 512, 512);

    }

    return 0;

}


ram_addr_t ppc4xx_sdram_adjust(ram_addr_t ram_size, int nr_banks,

                               target_phys_addr_t ram_bases[],

                               target_phys_addr_t ram_sizes[],

                               const unsigned int sdram_bank_sizes[])

{

    ram_addr_t size_left = ram_size;

    int i;

    int j;

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

        for (j = 0; sdram_bank_sizes[j] != 0; j++) {

            unsigned int bank_size = sdram_bank_sizes[j];

            if (bank_size <= size_left) {

                char name[32];

                snprintf(name, sizeof(name), "ppc4xx.sdram%d", i);

                ram_bases[i] = qemu_ram_alloc(NULL, name, bank_size);

                ram_sizes[i] = bank_size;

                size_left -= bank_size;

                break;

            }

        }

        if (!size_left) {

            /* No need to use the remaining banks. */

            break;

        }

    }

    ram_size -= size_left;

    if (size_left)

        printf("Truncating memory to %d MiB to fit SDRAM controller limits.\n",

               (int)(ram_size >> 20));

    return ram_size;

}


static inline int check_fit(tcg_target_long val, unsigned int bits)

{

    return ((val << ((sizeof(tcg_target_long) * 8 - bits))

             >> (sizeof(tcg_target_long) * 8 - bits)) == val);

}


void *qemu_memalign(size_t alignment, size_t size)

{

    return VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE);

}


static void virtio_scsi_handle_ctrl_req(VirtIOSCSI *s, VirtIOSCSIReq *req)

{

    VirtIODevice *vdev = (VirtIODevice *)s;

    uint32_t type;

    int r = 0;

    if (iov_to_buf(req->elem.out_sg, req->elem.out_num, 0,

                &type, sizeof(type)) < sizeof(type)) {

        virtio_scsi_bad_req();

        return;

    }

    virtio_tswap32s(vdev, &type);

    if (type == VIRTIO_SCSI_T_TMF) {

        if (virtio_scsi_parse_req(req, sizeof(VirtIOSCSICtrlTMFReq),

                    sizeof(VirtIOSCSICtrlTMFResp)) < 0) {

            virtio_scsi_bad_req();

        } else {

            r = virtio_scsi_do_tmf(s, req);

        }

    } else if (type == VIRTIO_SCSI_T_AN_QUERY ||

               type == VIRTIO_SCSI_T_AN_SUBSCRIBE) {

        if (virtio_scsi_parse_req(req, sizeof(VirtIOSCSICtrlANReq),

                    sizeof(VirtIOSCSICtrlANResp)) < 0) {

            virtio_scsi_bad_req();

        } else {

            req->resp.an.event_actual = 0;

            req->resp.an.response = VIRTIO_SCSI_S_OK;

        }

    }

    if (r == 0) {

        virtio_scsi_complete_req(req);

    } else {

        assert(r == -EINPROGRESS);

    }

}


static inline uint32_t mipsdsp_sub32(int32_t a, int32_t b, CPUMIPSState *env)

{

    int32_t temp;

    temp = a - b;

    if (MIPSDSP_OVERFLOW(a, -b, temp, 0x80000000)) {

        set_DSPControl_overflow_flag(1, 20, env);

    }

    return temp;

}


static inline abi_long host_to_target_timespec(abi_ulong target_addr,

                                               struct timespec *host_ts)

{

    struct target_timespec *target_ts;

    if (!lock_user_struct(VERIFY_WRITE, target_ts, target_addr, 0))

        return -TARGET_EFAULT;

    target_ts->tv_sec = tswapal(host_ts->tv_sec);

    target_ts->tv_nsec = tswapal(host_ts->tv_nsec);

    unlock_user_struct(target_ts, target_addr, 1);

    return 0;

}


static int mpegvideo_probe(AVProbeData *p)

{

    uint32_t code= -1;

    int pic=0, seq=0, slice=0, pspack=0, vpes=0, apes=0, res=0;

    int i;

    for(i=0; i<p->buf_size; i++){

        code = (code<<8) + p->buf[i];

        if ((code & 0xffffff00) == 0x100) {

            switch(code){

            case     SEQ_START_CODE:   seq++; break;

            case PICTURE_START_CODE:   pic++; break;

            case    PACK_START_CODE: pspack++; break;

            case              0x1b6:

                                        res++; break;

            }

            if (code >= SLICE_START_CODE && code <= 0x1af) slice++;

            if     ((code & 0x1f0) == VIDEO_ID)   vpes++;

            else if((code & 0x1e0) == AUDIO_ID)   apes++;

        }

    }

    if(seq && seq*9<=pic*10 && pic*9<=slice*10 && !pspack && !apes && !res) {

        if(vpes) return AVPROBE_SCORE_MAX/8;

        else     return pic>1 ? AVPROBE_SCORE_MAX/2+1 : AVPROBE_SCORE_MAX/4; // +1 for .mpg

    }

    return 0;

}


av_cold void ff_yadif_init_x86(YADIFContext *yadif)

{

    int cpu_flags = av_get_cpu_flags();

    if (HAVE_MMX && cpu_flags & AV_CPU_FLAG_MMX)

        yadif->filter_line = yadif_filter_line_mmx;

    if (HAVE_SSE && cpu_flags & AV_CPU_FLAG_SSE2)

        yadif->filter_line = yadif_filter_line_sse2;

    if (HAVE_SSSE3 && cpu_flags & AV_CPU_FLAG_SSSE3)

        yadif->filter_line = yadif_filter_line_ssse3;

}


void av_frame_unref(AVFrame *frame)
{
    int i;
    wipe_side_data(frame);
    for (i = 0; i < FF_ARRAY_ELEMS(frame->buf); i++)
        av_buffer_unref(&frame->buf[i]);
    for (i = 0; i < frame->nb_extended_buf; i++)
        av_buffer_unref(&frame->extended_buf[i]);
    av_freep(&frame->extended_buf);
    av_dict_free(&frame->metadata);
    av_buffer_unref(&frame->qp_table_buf);
    get_frame_defaults(frame);
}


static bool load_asl(GArray *sdts, AcpiSdtTable *sdt)

{

    AcpiSdtTable *temp;

    GError *error = NULL;

    GString *command_line = g_string_new(iasl);

    gint fd;

    gchar *out, *out_err;

    gboolean ret;

    int i;

    fd = g_file_open_tmp("asl-XXXXXX.dsl", &sdt->asl_file, &error);

    g_assert_no_error(error);

    close(fd);

    /* build command line */

    g_string_append_printf(command_line, " -p %s ", sdt->asl_file);

    if (compare_signature(sdt, "DSDT") ||

        compare_signature(sdt, "SSDT")) {

        for (i = 0; i < sdts->len; ++i) {

            temp = &g_array_index(sdts, AcpiSdtTable, i);

            if (compare_signature(temp, "DSDT") ||

                compare_signature(temp, "SSDT")) {

                g_string_append_printf(command_line, "-e %s ", temp->aml_file);

            }

        }

    }

    g_string_append_printf(command_line, "-d %s", sdt->aml_file);

    /* pass 'out' and 'out_err' in order to be redirected */

    ret = g_spawn_command_line_sync(command_line->str, &out, &out_err, NULL, &error);

    g_assert_no_error(error);

    if (ret) {

        ret = g_file_get_contents(sdt->asl_file, (gchar **)&sdt->asl,

                                  &sdt->asl_len, &error);

        g_assert(ret);

        g_assert_no_error(error);

        g_assert(sdt->asl_len);

    }

    g_free(out);

    g_free(out_err);

    g_string_free(command_line, true);

    return !ret;

}


int ppc_hash64_handle_mmu_fault(PowerPCCPU *cpu, vaddr eaddr,

                                int rwx, int mmu_idx)

{

    CPUState *cs = CPU(cpu);

    CPUPPCState *env = &cpu->env;

    ppc_slb_t *slb;

    unsigned apshift;

    hwaddr pte_offset;

    ppc_hash_pte64_t pte;

    int pp_prot, amr_prot, prot;

    uint64_t new_pte1, dsisr;

    const int need_prot[] = {PAGE_READ, PAGE_WRITE, PAGE_EXEC};

    hwaddr raddr;

    assert((rwx == 0) || (rwx == 1) || (rwx == 2));

    /* 1. Handle real mode accesses */

    if (((rwx == 2) && (msr_ir == 0)) || ((rwx != 2) && (msr_dr == 0))) {

        /* Translation is off */

        /* In real mode the top 4 effective address bits are ignored */

        raddr = eaddr & 0x0FFFFFFFFFFFFFFFULL;

        tlb_set_page(cs, eaddr & TARGET_PAGE_MASK, raddr & TARGET_PAGE_MASK,

                     PAGE_READ | PAGE_WRITE | PAGE_EXEC, mmu_idx,

                     TARGET_PAGE_SIZE);

        return 0;

    }

    /* 2. Translation is on, so look up the SLB */

    slb = slb_lookup(cpu, eaddr);

    if (!slb) {

        if (rwx == 2) {

            cs->exception_index = POWERPC_EXCP_ISEG;

            env->error_code = 0;

        } else {

            cs->exception_index = POWERPC_EXCP_DSEG;

            env->error_code = 0;

            env->spr[SPR_DAR] = eaddr;

        }

        return 1;

    }

    /* 3. Check for segment level no-execute violation */

    if ((rwx == 2) && (slb->vsid & SLB_VSID_N)) {

        ppc_hash64_set_isi(cs, env, 0x10000000);

        return 1;

    }

    /* 4. Locate the PTE in the hash table */

    pte_offset = ppc_hash64_htab_lookup(cpu, slb, eaddr, &pte);

    if (pte_offset == -1) {

        dsisr = 0x40000000;

        if (rwx == 2) {

            ppc_hash64_set_isi(cs, env, dsisr);

        } else {

            if (rwx == 1) {

                dsisr |= 0x02000000;

            }

            ppc_hash64_set_dsi(cs, env, eaddr, dsisr);

        }

        return 1;

    }

    qemu_log_mask(CPU_LOG_MMU,

                "found PTE at offset %08" HWADDR_PRIx "\n", pte_offset);

    /* Validate page size encoding */

    apshift = hpte_page_shift(slb->sps, pte.pte0, pte.pte1);

    if (!apshift) {

        error_report("Bad page size encoding in HPTE 0x%"PRIx64" - 0x%"PRIx64

                     " @ 0x%"HWADDR_PRIx, pte.pte0, pte.pte1, pte_offset);

        /* Not entirely sure what the right action here, but machine

         * check seems reasonable */

        cs->exception_index = POWERPC_EXCP_MCHECK;

        env->error_code = 0;

        return 1;

    }

    /* 5. Check access permissions */

    pp_prot = ppc_hash64_pte_prot(cpu, slb, pte);

    amr_prot = ppc_hash64_amr_prot(cpu, pte);

    prot = pp_prot & amr_prot;

    if ((need_prot[rwx] & ~prot) != 0) {

        /* Access right violation */

        qemu_log_mask(CPU_LOG_MMU, "PTE access rejected\n");

        if (rwx == 2) {

            ppc_hash64_set_isi(cs, env, 0x08000000);

        } else {

            dsisr = 0;

            if (need_prot[rwx] & ~pp_prot) {

                dsisr |= 0x08000000;

            }

            if (rwx == 1) {

                dsisr |= 0x02000000;

            }

            if (need_prot[rwx] & ~amr_prot) {

                dsisr |= 0x00200000;

            }

            ppc_hash64_set_dsi(cs, env, eaddr, dsisr);

        }

        return 1;

    }

    qemu_log_mask(CPU_LOG_MMU, "PTE access granted !\n");

    /* 6. Update PTE referenced and changed bits if necessary */

    new_pte1 = pte.pte1 | HPTE64_R_R; /* set referenced bit */

    if (rwx == 1) {

        new_pte1 |= HPTE64_R_C; /* set changed (dirty) bit */

    } else {

        /* Treat the page as read-only for now, so that a later write

         * will pass through this function again to set the C bit */

        prot &= ~PAGE_WRITE;

    }

    if (new_pte1 != pte.pte1) {

        ppc_hash64_store_hpte(cpu, pte_offset / HASH_PTE_SIZE_64,

                              pte.pte0, new_pte1);

    }

    /* 7. Determine the real address from the PTE */

    raddr = deposit64(pte.pte1 & HPTE64_R_RPN, 0, apshift, eaddr);

    tlb_set_page(cs, eaddr & TARGET_PAGE_MASK, raddr & TARGET_PAGE_MASK,

                 prot, mmu_idx, 1ULL << apshift);

    return 0;

}


MemoryRegionSection memory_region_find(MemoryRegion *address_space,

                                       target_phys_addr_t addr, uint64_t size)

{

    AddressSpace *as = memory_region_to_address_space(address_space);

    AddrRange range = addrrange_make(int128_make64(addr),

                                     int128_make64(size));

    FlatRange *fr = address_space_lookup(as, range);

    MemoryRegionSection ret = { .mr = NULL, .size = 0 };

    if (!fr) {

        return ret;

    }

    while (fr > as->current_map.ranges

           && addrrange_intersects(fr[-1].addr, range)) {

        --fr;

    }

    ret.mr = fr->mr;

    range = addrrange_intersection(range, fr->addr);

    ret.offset_within_region = fr->offset_in_region;

    ret.offset_within_region += int128_get64(int128_sub(range.start,

                                                        fr->addr.start));

    ret.size = int128_get64(range.size);

    ret.offset_within_address_space = int128_get64(range.start);

    ret.readonly = fr->readonly;

    return ret;

}


static int decode_ics(AACContext *ac, SingleChannelElement *sce,

                      GetBitContext *gb, int common_window, int scale_flag)

{

    Pulse pulse;

    TemporalNoiseShaping    *tns = &sce->tns;

    IndividualChannelStream *ics = &sce->ics;

    INTFLOAT *out = sce->coeffs;

    int global_gain, eld_syntax, er_syntax, pulse_present = 0;

    int ret;

    eld_syntax = ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;

    er_syntax  = ac->oc[1].m4ac.object_type == AOT_ER_AAC_LC ||

                 ac->oc[1].m4ac.object_type == AOT_ER_AAC_LTP ||

                 ac->oc[1].m4ac.object_type == AOT_ER_AAC_LD ||

                 ac->oc[1].m4ac.object_type == AOT_ER_AAC_ELD;

    /* This assignment is to silence a GCC warning about the variable being used

     * uninitialized when in fact it always is.

     */

    pulse.num_pulse = 0;

    global_gain = get_bits(gb, 8);

    if (!common_window && !scale_flag) {

        if (decode_ics_info(ac, ics, gb) < 0)

            return AVERROR_INVALIDDATA;

    }

    if ((ret = decode_band_types(ac, sce->band_type,

                                 sce->band_type_run_end, gb, ics)) < 0)

        return ret;

    if ((ret = decode_scalefactors(ac, sce->sf, gb, global_gain, ics,

                                  sce->band_type, sce->band_type_run_end)) < 0)

        return ret;

    pulse_present = 0;

    if (!scale_flag) {

        if (!eld_syntax && (pulse_present = get_bits1(gb))) {

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

                av_log(ac->avctx, AV_LOG_ERROR,

                       "Pulse tool not allowed in eight short sequence.\n");

                return AVERROR_INVALIDDATA;

            }

            if (decode_pulses(&pulse, gb, ics->swb_offset, ics->num_swb)) {

                av_log(ac->avctx, AV_LOG_ERROR,

                       "Pulse data corrupt or invalid.\n");

                return AVERROR_INVALIDDATA;

            }

        }

        tns->present = get_bits1(gb);

        if (tns->present && !er_syntax)

            if (decode_tns(ac, tns, gb, ics) < 0)

                return AVERROR_INVALIDDATA;

        if (!eld_syntax && get_bits1(gb)) {

            avpriv_request_sample(ac->avctx, "SSR");

            return AVERROR_PATCHWELCOME;

        }

        // I see no textual basis in the spec for this occurring after SSR gain

        // control, but this is what both reference and real implmentations do

        if (tns->present && er_syntax)

            if (decode_tns(ac, tns, gb, ics) < 0)

                return AVERROR_INVALIDDATA;

    }

    if (decode_spectrum_and_dequant(ac, out, gb, sce->sf, pulse_present,

                                    &pulse, ics, sce->band_type) < 0)

        return AVERROR_INVALIDDATA;

    if (ac->oc[1].m4ac.object_type == AOT_AAC_MAIN && !common_window)

        apply_prediction(ac, sce);

    return 0;

}


static int decode_i_block(FourXContext *f, DCTELEM *block){
    int code, i, j, level, val;
    /* DC coef */
    val = get_vlc2(&f->pre_gb, f->pre_vlc.table, ACDC_VLC_BITS, 3);
    if (val>>4){
        av_log(f->avctx, AV_LOG_ERROR, "error dc run != 0\n");
    if(val)
        val = get_xbits(&f->gb, val);
    val = val * dequant_table[0] + f->last_dc;
    f->last_dc =
    block[0] = val;
    /* AC coefs */
    i = 1;
    for(;;) {
        code = get_vlc2(&f->pre_gb, f->pre_vlc.table, ACDC_VLC_BITS, 3);
        /* EOB */
        if (code == 0)
            break;
        if (code == 0xf0) {
            i += 16;
        } else {
            level = get_xbits(&f->gb, code & 0xf);
            i += code >> 4;
            if (i >= 64) {
                av_log(f->avctx, AV_LOG_ERROR, "run %d oveflow\n", i);
                return 0;
            j= ff_zigzag_direct[i];
            block[j] = level * dequant_table[j];
            i++;
            if (i >= 64)
                break;
    return 0;


uint64_t qpci_io_readq(QPCIDevice *dev, void *data)

{

    uintptr_t addr = (uintptr_t)data;

    if (addr < QPCI_PIO_LIMIT) {

        return dev->bus->pio_readq(dev->bus, addr);

    } else {

        uint64_t val;

        dev->bus->memread(dev->bus, addr, &val, sizeof(val));

        return le64_to_cpu(val);

    }

}


static int gxf_write_header(AVFormatContext *s)

{

    AVIOContext *pb = s->pb;

    GXFContext *gxf = s->priv_data;

    GXFStreamContext *vsc = NULL;

    uint8_t tracks[255] = {0};

    int i, media_info = 0;

    AVDictionaryEntry *tcr = av_dict_get(s->metadata, "timecode", NULL, 0);

    if (!pb->seekable) {

        av_log(s, AV_LOG_ERROR, "gxf muxer does not support streamed output, patch welcome\n");

        return -1;

    }

    gxf->flags |= 0x00080000; /* material is simple clip */

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

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

        GXFStreamContext *sc = av_mallocz(sizeof(*sc));

        if (!sc)

            return AVERROR(ENOMEM);

        st->priv_data = sc;

        sc->media_type = ff_codec_get_tag(gxf_media_types, st->codec->codec_id);

        if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {

            if (st->codec->codec_id != AV_CODEC_ID_PCM_S16LE) {

                av_log(s, AV_LOG_ERROR, "only 16 BIT PCM LE allowed for now\n");

                return -1;

            }

            if (st->codec->sample_rate != 48000) {

                av_log(s, AV_LOG_ERROR, "only 48000hz sampling rate is allowed\n");

                return -1;

            }

            if (st->codec->channels != 1) {

                av_log(s, AV_LOG_ERROR, "only mono tracks are allowed\n");

                return -1;

            }

            sc->track_type = 2;

            sc->sample_rate = st->codec->sample_rate;

            avpriv_set_pts_info(st, 64, 1, sc->sample_rate);

            sc->sample_size = 16;

            sc->frame_rate_index = -2;

            sc->lines_index = -2;

            sc->fields = -2;

            gxf->audio_tracks++;

            gxf->flags |= 0x04000000; /* audio is 16 bit pcm */

            media_info = 'A';

        } else if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {

            if (i != 0) {

                av_log(s, AV_LOG_ERROR, "video stream must be the first track\n");

                return -1;

            }

            /* FIXME check from time_base ? */

            if (st->codec->height == 480 || st->codec->height == 512) { /* NTSC or NTSC+VBI */

                sc->frame_rate_index = 5;

                sc->sample_rate = 60;

                gxf->flags |= 0x00000080;

                gxf->time_base = (AVRational){ 1001, 60000 };

            } else if (st->codec->height == 576 || st->codec->height == 608) { /* PAL or PAL+VBI */

                sc->frame_rate_index = 6;

                sc->media_type++;

                sc->sample_rate = 50;

                gxf->flags |= 0x00000040;

                gxf->time_base = (AVRational){ 1, 50 };

            } else {

                av_log(s, AV_LOG_ERROR, "unsupported video resolution, "

                       "gxf muxer only accepts PAL or NTSC resolutions currently\n");

                return -1;

            }

            if (!tcr)

                tcr = av_dict_get(st->metadata, "timecode", NULL, 0);

            avpriv_set_pts_info(st, 64, gxf->time_base.num, gxf->time_base.den);

            if (gxf_find_lines_index(st) < 0)

                sc->lines_index = -1;

            sc->sample_size = st->codec->bit_rate;

            sc->fields = 2; /* interlaced */

            vsc = sc;

            switch (st->codec->codec_id) {

            case AV_CODEC_ID_MJPEG:

                sc->track_type = 1;

                gxf->flags |= 0x00004000;

                media_info = 'J';

                break;

            case AV_CODEC_ID_MPEG1VIDEO:

                sc->track_type = 9;

                gxf->mpeg_tracks++;

                media_info = 'L';

                break;

            case AV_CODEC_ID_MPEG2VIDEO:

                sc->first_gop_closed = -1;

                sc->track_type = 4;

                gxf->mpeg_tracks++;

                gxf->flags |= 0x00008000;

                media_info = 'M';

                break;

            case AV_CODEC_ID_DVVIDEO:

                if (st->codec->pix_fmt == AV_PIX_FMT_YUV422P) {

                    sc->media_type += 2;

                    sc->track_type = 6;

                    gxf->flags |= 0x00002000;

                    media_info = 'E';

                } else {

                    sc->track_type = 5;

                    gxf->flags |= 0x00001000;

                    media_info = 'D';

                }

                break;

            default:

                av_log(s, AV_LOG_ERROR, "video codec not supported\n");

                return -1;

            }

        }

        /* FIXME first 10 audio tracks are 0 to 9 next 22 are A to V */

        sc->media_info = media_info<<8 | ('0'+tracks[media_info]++);

        sc->order = s->nb_streams - st->index;

    }

    if (ff_audio_interleave_init(s, GXF_samples_per_frame, (AVRational){ 1, 48000 }) < 0)

        return -1;

    if (tcr)

        gxf_init_timecode(s, &gxf->tc, tcr->value, vsc->fields);

    gxf_init_timecode_track(&gxf->timecode_track, vsc);

    gxf->flags |= 0x200000; // time code track is non-drop frame

    gxf_write_map_packet(s, 0);

    gxf_write_flt_packet(s);

    gxf_write_umf_packet(s);

    gxf->packet_count = 3;

    avio_flush(pb);

    return 0;

}


static int decode_nal_sei_prefix(GetBitContext *gb, HEVCSEIContext *s, const HEVCParamSets *ps,

                                 int type, int size, void *logctx)

{

    switch (type) {

    case 256:  // Mismatched value from HM 8.1

        return decode_nal_sei_decoded_picture_hash(&s->picture_hash, gb);

    case HEVC_SEI_TYPE_FRAME_PACKING:

        return decode_nal_sei_frame_packing_arrangement(&s->frame_packing, gb);

    case HEVC_SEI_TYPE_DISPLAY_ORIENTATION:

        return decode_nal_sei_display_orientation(&s->display_orientation, gb);

    case HEVC_SEI_TYPE_PICTURE_TIMING:

        {

            int ret = decode_pic_timing(s, gb, ps, logctx);

            av_log(logctx, AV_LOG_DEBUG, "Skipped PREFIX SEI %d\n", type);

            skip_bits(gb, 8 * size);

            return ret;

        }

    case HEVC_SEI_TYPE_MASTERING_DISPLAY_INFO:

        return decode_nal_sei_mastering_display_info(&s->mastering_display, gb);

    case HEVC_SEI_TYPE_CONTENT_LIGHT_LEVEL_INFO:

        return decode_nal_sei_content_light_info(&s->content_light, gb);

    case HEVC_SEI_TYPE_ACTIVE_PARAMETER_SETS:

        active_parameter_sets(s, gb, logctx);

        av_log(logctx, AV_LOG_DEBUG, "Skipped PREFIX SEI %d\n", type);

        return 0;

    case HEVC_SEI_TYPE_USER_DATA_REGISTERED_ITU_T_T35:

        return decode_nal_sei_user_data_registered_itu_t_t35(s, gb, size);

    default:

        av_log(logctx, AV_LOG_DEBUG, "Skipped PREFIX SEI %d\n", type);

        skip_bits_long(gb, 8 * size);

        return 0;

    }

}


static int get_segment (CPUState *env, mmu_ctx_t *ctx,

                        target_ulong eaddr, int rw, int type)

{

    target_phys_addr_t sdr, hash, mask, sdr_mask;

    target_ulong sr, vsid, vsid_mask, pgidx, page_mask;

#if defined(TARGET_PPC64)

    int attr;

#endif

    int ds, nx, vsid_sh, sdr_sh;

    int ret, ret2;

#if defined(TARGET_PPC64)

    if (env->mmu_model == POWERPC_MMU_64B ||

        env->mmu_model == POWERPC_MMU_64BRIDGE) {

        ret = slb_lookup(env, eaddr, &vsid, &page_mask, &attr);

        if (ret < 0)

            return ret;

        ctx->key = ((attr & 0x40) && msr_pr == 1) ||

            ((attr & 0x80) && msr_pr == 0) ? 1 : 0;

        ds = 0;

        nx = attr & 0x20 ? 1 : 0;

        vsid_mask = 0x00003FFFFFFFFF80ULL;

        vsid_sh = 7;

        sdr_sh = 18;

        sdr_mask = 0x3FF80;

    } else

#endif /* defined(TARGET_PPC64) */

    {

        sr = env->sr[eaddr >> 28];

        page_mask = 0x0FFFFFFF;

        ctx->key = (((sr & 0x20000000) && msr_pr == 1) ||

                    ((sr & 0x40000000) && msr_pr == 0)) ? 1 : 0;

        ds = sr & 0x80000000 ? 1 : 0;

        nx = sr & 0x10000000 ? 1 : 0;

        vsid = sr & 0x00FFFFFF;

        vsid_mask = 0x01FFFFC0;

        vsid_sh = 6;

        sdr_sh = 16;

        sdr_mask = 0xFFC0;

#if defined (DEBUG_MMU)

        if (loglevel != 0) {

            fprintf(logfile, "Check segment v=0x" ADDRX " %d 0x" ADDRX

                    " nip=0x" ADDRX " lr=0x" ADDRX

                    " ir=%d dr=%d pr=%d %d t=%d\n",

                    eaddr, (int)(eaddr >> 28), sr, env->nip,

                    env->lr, msr_ir, msr_dr, msr_pr, rw, type);

        }

        if (!ds && loglevel != 0) {

            fprintf(logfile, "pte segment: key=%d n=0x" ADDRX "\n",

                    ctx->key, sr & 0x10000000);

        }

#endif

    }

    ret = -1;

    if (!ds) {

        /* Check if instruction fetch is allowed, if needed */

        if (type != ACCESS_CODE || nx == 0) {

            /* Page address translation */

            pgidx = (eaddr & page_mask) >> TARGET_PAGE_BITS;

            hash = ((vsid ^ pgidx) << vsid_sh) & vsid_mask;

            /* Primary table address */

            sdr = env->sdr1;

            mask = ((sdr & 0x000001FF) << sdr_sh) | sdr_mask;

            ctx->pg_addr[0] = get_pgaddr(sdr, sdr_sh, hash, mask);

            /* Secondary table address */

            hash = (~hash) & vsid_mask;

            ctx->pg_addr[1] = get_pgaddr(sdr, sdr_sh, hash, mask);

#if defined(TARGET_PPC64)

            if (env->mmu_model == POWERPC_MMU_64B ||

                env->mmu_model == POWERPC_MMU_64BRIDGE) {

                /* Only 5 bits of the page index are used in the AVPN */

                ctx->ptem = (vsid << 12) | ((pgidx >> 4) & 0x0F80);

            } else

#endif

            {

                ctx->ptem = (vsid << 7) | (pgidx >> 10);

            }

            /* Initialize real address with an invalid value */

            ctx->raddr = (target_ulong)-1;

            if (unlikely(env->mmu_model == POWERPC_MMU_SOFT_6xx ||

                         env->mmu_model == POWERPC_MMU_SOFT_74xx)) {

                /* Software TLB search */

                ret = ppc6xx_tlb_check(env, ctx, eaddr, rw, type);

            } else {

#if defined (DEBUG_MMU)

                if (loglevel != 0) {

                    fprintf(logfile, "0 sdr1=0x" PADDRX " vsid=0x%06x "

                            "api=0x%04x hash=0x%07x pg_addr=0x" PADDRX "\n",

                            sdr, (uint32_t)vsid, (uint32_t)pgidx,

                            (uint32_t)hash, ctx->pg_addr[0]);

                }

#endif

                /* Primary table lookup */

                ret = find_pte(env, ctx, 0, rw);

                if (ret < 0) {

                    /* Secondary table lookup */

#if defined (DEBUG_MMU)

                    if (eaddr != 0xEFFFFFFF && loglevel != 0) {

                        fprintf(logfile,

                                "1 sdr1=0x" PADDRX " vsid=0x%06x api=0x%04x "

                                "hash=0x%05x pg_addr=0x" PADDRX "\n",

                                sdr, (uint32_t)vsid, (uint32_t)pgidx,

                                (uint32_t)hash, ctx->pg_addr[1]);

                    }

#endif

                    ret2 = find_pte(env, ctx, 1, rw);

                    if (ret2 != -1)

                        ret = ret2;

                }

            }

        } else {

#if defined (DEBUG_MMU)

            if (loglevel != 0)

                fprintf(logfile, "No access allowed\n");

#endif

            ret = -3;

        }

    } else {

#if defined (DEBUG_MMU)

        if (loglevel != 0)

            fprintf(logfile, "direct store...\n");

#endif

        /* Direct-store segment : absolutely *BUGGY* for now */

        switch (type) {

        case ACCESS_INT:

            /* Integer load/store : only access allowed */

            break;

        case ACCESS_CODE:

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

            return -4;

        case ACCESS_FLOAT:

            /* Floating point load/store */

            return -4;

        case ACCESS_RES:

            /* lwarx, ldarx or srwcx. */

            return -4;

        case ACCESS_CACHE:

            /* dcba, dcbt, dcbtst, dcbf, dcbi, dcbst, dcbz, or icbi */

            /* Should make the instruction do no-op.

             * As it already do no-op, it's quite easy :-)

             */

            ctx->raddr = eaddr;

            return 0;

        case ACCESS_EXT:

            /* eciwx or ecowx */

            return -4;

        default:

            if (logfile) {

                fprintf(logfile, "ERROR: instruction should not need "

                        "address translation\n");

            }

            return -4;

        }

        if ((rw == 1 || ctx->key != 1) && (rw == 0 || ctx->key != 0)) {

            ctx->raddr = eaddr;

            ret = 2;

        } else {

            ret = -2;

        }

    }

    return ret;

}


static void handle_satn_stop(ESPState *s)

{

    if (s->dma && !s->dma_enabled) {

        s->dma_cb = handle_satn_stop;

        return;

    }

    s->cmdlen = get_cmd(s, s->cmdbuf);

    if (s->cmdlen) {

        trace_esp_handle_satn_stop(s->cmdlen);

        s->do_cmd = 1;

        s->rregs[ESP_RSTAT] = STAT_TC | STAT_CD;

        s->rregs[ESP_RINTR] = INTR_BS | INTR_FC;

        s->rregs[ESP_RSEQ] = SEQ_CD;

        esp_raise_irq(s);

    }

}


static int xv_write_trailer(AVFormatContext *s)

{

    XVContext *xv = s->priv_data;

    XShmDetach(xv->display, &xv->yuv_shminfo);

    shmdt(xv->yuv_image->data);

    XFree(xv->yuv_image);

    XCloseDisplay(xv->display);

    return 0;

}


void ff_biweight_h264_pixels16_8_msa(uint8_t *dst, uint8_t *src,

                                     int stride, int height,

                                     int log2_denom, int weight_dst,

                                     int weight_src, int offset)

{

    avc_biwgt_16width_msa(src, stride,

                          dst, stride,

                          height, log2_denom,

                          weight_src, weight_dst, offset);

}


static void vt82c686b_write_config(PCIDevice * d, uint32_t address,

                                   uint32_t val, int len)

{

    VT82C686BState *vt686 = DO_UPCAST(VT82C686BState, dev, d);

    DPRINTF("vt82c686b_write_config  address 0x%x  val 0x%x len 0x%x \n",

           address, val, len);

    pci_default_write_config(d, address, val, len);

    if (address == 0x85) {  /* enable or disable super IO configure */

        if (val & 0x2) {

            /* floppy also uses 0x3f0 and 0x3f1.

             * But we do not emulate flopy,so just set it here. */

            isa_unassign_ioport(0x3f0, 2);

            register_ioport_read(0x3f0, 2, 1, superio_ioport_readb,

                                 &vt686->superio_conf);

            register_ioport_write(0x3f0, 2, 1, superio_ioport_writeb,

                                  &vt686->superio_conf);

        } else {

            isa_unassign_ioport(0x3f0, 2);

        }

    }

}


e1000_receive(VLANClientState *nc, const uint8_t *buf, size_t size)

{

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

    struct e1000_rx_desc desc;

    target_phys_addr_t base;

    unsigned int n, rdt;

    uint32_t rdh_start;

    uint16_t vlan_special = 0;

    uint8_t vlan_status = 0, vlan_offset = 0;

    if (!(s->mac_reg[RCTL] & E1000_RCTL_EN))

        return -1;

    if (size > s->rxbuf_size) {

        DBGOUT(RX, "packet too large for buffers (%lu > %d)\n",

               (unsigned long)size, s->rxbuf_size);

        return -1;

    }

    if (!receive_filter(s, buf, size))

        return size;

    if (vlan_enabled(s) && is_vlan_packet(s, buf)) {

        vlan_special = cpu_to_le16(be16_to_cpup((uint16_t *)(buf + 14)));

        memmove((uint8_t *)buf + 4, buf, 12);

        vlan_status = E1000_RXD_STAT_VP;

        vlan_offset = 4;

        size -= 4;

    }

    rdh_start = s->mac_reg[RDH];

    size += 4; // for the header

    do {

        if (s->mac_reg[RDH] == s->mac_reg[RDT] && s->check_rxov) {

            set_ics(s, 0, E1000_ICS_RXO);

            return -1;

        }

        base = ((uint64_t)s->mac_reg[RDBAH] << 32) + s->mac_reg[RDBAL] +

               sizeof(desc) * s->mac_reg[RDH];

        cpu_physical_memory_read(base, (void *)&desc, sizeof(desc));

        desc.special = vlan_special;

        desc.status |= (vlan_status | E1000_RXD_STAT_DD);

        if (desc.buffer_addr) {

            cpu_physical_memory_write(le64_to_cpu(desc.buffer_addr),

                                      (void *)(buf + vlan_offset), size);

            desc.length = cpu_to_le16(size);

            desc.status |= E1000_RXD_STAT_EOP|E1000_RXD_STAT_IXSM;

        } else // as per intel docs; skip descriptors with null buf addr

            DBGOUT(RX, "Null RX descriptor!!\n");

        cpu_physical_memory_write(base, (void *)&desc, sizeof(desc));

        if (++s->mac_reg[RDH] * sizeof(desc) >= s->mac_reg[RDLEN])

            s->mac_reg[RDH] = 0;

        s->check_rxov = 1;

        /* see comment in start_xmit; same here */

        if (s->mac_reg[RDH] == rdh_start) {

            DBGOUT(RXERR, "RDH wraparound @%x, RDT %x, RDLEN %x\n",

                   rdh_start, s->mac_reg[RDT], s->mac_reg[RDLEN]);

            set_ics(s, 0, E1000_ICS_RXO);

            return -1;

        }

    } while (desc.buffer_addr == 0);

    s->mac_reg[GPRC]++;

    s->mac_reg[TPR]++;

    n = s->mac_reg[TORL];

    if ((s->mac_reg[TORL] += size) < n)

        s->mac_reg[TORH]++;

    n = E1000_ICS_RXT0;

    if ((rdt = s->mac_reg[RDT]) < s->mac_reg[RDH])

        rdt += s->mac_reg[RDLEN] / sizeof(desc);

    if (((rdt - s->mac_reg[RDH]) * sizeof(desc)) <= s->mac_reg[RDLEN] >>

        s->rxbuf_min_shift)

        n |= E1000_ICS_RXDMT0;

    set_ics(s, 0, n);

    return size;

}


void stl_le_phys(target_phys_addr_t addr, uint32_t val)

{

    stl_phys_internal(addr, val, DEVICE_LITTLE_ENDIAN);

}


static void kvm_mce_broadcast_rest(CPUState *env)

{

    CPUState *cenv;

    int family, model, cpuver = env->cpuid_version;

    family = (cpuver >> 8) & 0xf;

    model = ((cpuver >> 12) & 0xf0) + ((cpuver >> 4) & 0xf);

    /* Broadcast MCA signal for processor version 06H_EH and above */

    if ((family == 6 && model >= 14) || family > 6) {

        for (cenv = first_cpu; cenv != NULL; cenv = cenv->next_cpu) {

            if (cenv == env) {

                continue;

            }

            kvm_inject_x86_mce(cenv, 1, MCI_STATUS_VAL | MCI_STATUS_UC,

                               MCG_STATUS_MCIP | MCG_STATUS_RIPV, 0, 0, 1);

        }

    }

}


void ff_put_dirac_pixels32_sse2(uint8_t *dst, const uint8_t *src[5], int stride, int h)

{

    if (h&3) {

        ff_put_dirac_pixels32_c(dst, src, stride, h);

    } else {

    ff_put_pixels16_sse2(dst   , src[0]   , stride, h);

    ff_put_pixels16_sse2(dst+16, src[0]+16, stride, h);

    }

}


void bdrv_guess_geometry(BlockDriverState *bs, int *pcyls, int *pheads, int *psecs)

{

    int translation, lba_detected = 0;

    int cylinders, heads, secs;

    uint64_t nb_sectors;

    /* if a geometry hint is available, use it */

    bdrv_get_geometry(bs, &nb_sectors);

    bdrv_get_geometry_hint(bs, &cylinders, &heads, &secs);

    translation = bdrv_get_translation_hint(bs);

    if (cylinders != 0) {

        *pcyls = cylinders;

        *pheads = heads;

        *psecs = secs;

    } else {

        if (guess_disk_lchs(bs, &cylinders, &heads, &secs) == 0) {

            if (heads > 16) {

                /* if heads > 16, it means that a BIOS LBA

                   translation was active, so the default

                   hardware geometry is OK */

                lba_detected = 1;

                goto default_geometry;

            } else {

                *pcyls = cylinders;

                *pheads = heads;

                *psecs = secs;

                /* disable any translation to be in sync with

                   the logical geometry */

                if (translation == BIOS_ATA_TRANSLATION_AUTO) {

                    bdrv_set_translation_hint(bs,

                                              BIOS_ATA_TRANSLATION_NONE);

                }

            }

        } else {

        default_geometry:

            /* if no geometry, use a standard physical disk geometry */

            cylinders = nb_sectors / (16 * 63);

            if (cylinders > 16383)

                cylinders = 16383;

            else if (cylinders < 2)

                cylinders = 2;

            *pcyls = cylinders;

            *pheads = 16;

            *psecs = 63;

            if ((lba_detected == 1) && (translation == BIOS_ATA_TRANSLATION_AUTO)) {

                if ((*pcyls * *pheads) <= 131072) {

                    bdrv_set_translation_hint(bs,

                                              BIOS_ATA_TRANSLATION_LARGE);

                } else {

                    bdrv_set_translation_hint(bs,

                                              BIOS_ATA_TRANSLATION_LBA);

                }

            }

        }

        bdrv_set_geometry_hint(bs, *pcyls, *pheads, *psecs);

    }

}


static void glib_pollfds_fill(uint32_t *cur_timeout)

{

    GMainContext *context = g_main_context_default();

    int timeout = 0;

    int n;

    g_main_context_prepare(context, &max_priority);

    glib_pollfds_idx = gpollfds->len;

    n = glib_n_poll_fds;

    do {

        GPollFD *pfds;

        glib_n_poll_fds = n;

        g_array_set_size(gpollfds, glib_pollfds_idx + glib_n_poll_fds);

        pfds = &g_array_index(gpollfds, GPollFD, glib_pollfds_idx);

        n = g_main_context_query(context, max_priority, &timeout, pfds,

                                 glib_n_poll_fds);

    } while (n != glib_n_poll_fds);

    if (timeout >= 0 && timeout < *cur_timeout) {

        *cur_timeout = timeout;

    }

}


long do_sigreturn(CPUMBState *env)

{

    struct target_signal_frame *frame;

    abi_ulong frame_addr;

    target_sigset_t target_set;

    sigset_t set;

    int i;

    frame_addr = env->regs[R_SP];

    /* Make sure the guest isn't playing games.  */

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

        goto badframe;

    /* Restore blocked signals */

    if (__get_user(target_set.sig[0], &frame->uc.tuc_mcontext.oldmask))

        goto badframe;

    for(i = 1; i < TARGET_NSIG_WORDS; i++) {

        if (__get_user(target_set.sig[i], &frame->extramask[i - 1]))

            goto badframe;

    }

    target_to_host_sigset_internal(&set, &target_set);

    sigprocmask(SIG_SETMASK, &set, NULL);

    restore_sigcontext(&frame->uc.tuc_mcontext, env);

    /* We got here through a sigreturn syscall, our path back is via an

       rtb insn so setup r14 for that.  */

    env->regs[14] = env->sregs[SR_PC];

    unlock_user_struct(frame, frame_addr, 0);

    return env->regs[10];

  badframe:

    unlock_user_struct(frame, frame_addr, 0);

    force_sig(TARGET_SIGSEGV);

}


static void vc1_put_signed_blocks_clamped(VC1Context *v)

{

    MpegEncContext *s = &v->s;

    int topleft_mb_pos, top_mb_pos;

    int stride_y, fieldtx;

    int v_dist;

    /* The put pixels loop is always one MB row behind the decoding loop,

     * because we can only put pixels when overlap filtering is done, and

     * for filtering of the bottom edge of a MB, we need the next MB row

     * present as well.

     * Within the row, the put pixels loop is also one MB col behind the

     * decoding loop. The reason for this is again, because for filtering

     * of the right MB edge, we need the next MB present. */

    if (!s->first_slice_line) {

        if (s->mb_x) {

            topleft_mb_pos = (s->mb_y - 1) * s->mb_stride + s->mb_x - 1;

            fieldtx        = v->fieldtx_plane[topleft_mb_pos];

            stride_y       = s->linesize << fieldtx;

            v_dist         = (16 - fieldtx) >> (fieldtx == 0);

            s->dsp.put_signed_pixels_clamped(v->block[v->topleft_blk_idx][0],

                                             s->dest[0] - 16 * s->linesize - 16,

                                             stride_y);

            s->dsp.put_signed_pixels_clamped(v->block[v->topleft_blk_idx][1],

                                             s->dest[0] - 16 * s->linesize - 8,

                                             stride_y);

            s->dsp.put_signed_pixels_clamped(v->block[v->topleft_blk_idx][2],

                                             s->dest[0] - v_dist * s->linesize - 16,

                                             stride_y);

            s->dsp.put_signed_pixels_clamped(v->block[v->topleft_blk_idx][3],

                                             s->dest[0] - v_dist * s->linesize - 8,

                                             stride_y);

            s->dsp.put_signed_pixels_clamped(v->block[v->topleft_blk_idx][4],

                                             s->dest[1] - 8 * s->uvlinesize - 8,

                                             s->uvlinesize);

            s->dsp.put_signed_pixels_clamped(v->block[v->topleft_blk_idx][5],

                                             s->dest[2] - 8 * s->uvlinesize - 8,

                                             s->uvlinesize);

        }

        if (s->mb_x == s->mb_width - 1) {

            top_mb_pos = (s->mb_y - 1) * s->mb_stride + s->mb_x;

            fieldtx    = v->fieldtx_plane[top_mb_pos];

            stride_y   = s->linesize << fieldtx;

            v_dist     = fieldtx ? 15 : 8;

            s->dsp.put_signed_pixels_clamped(v->block[v->top_blk_idx][0],

                                             s->dest[0] - 16 * s->linesize,

                                             stride_y);

            s->dsp.put_signed_pixels_clamped(v->block[v->top_blk_idx][1],

                                             s->dest[0] - 16 * s->linesize + 8,

                                             stride_y);

            s->dsp.put_signed_pixels_clamped(v->block[v->top_blk_idx][2],

                                             s->dest[0] - v_dist * s->linesize,

                                             stride_y);

            s->dsp.put_signed_pixels_clamped(v->block[v->top_blk_idx][3],

                                             s->dest[0] - v_dist * s->linesize + 8,

                                             stride_y);

            s->dsp.put_signed_pixels_clamped(v->block[v->top_blk_idx][4],

                                             s->dest[1] - 8 * s->uvlinesize,

                                             s->uvlinesize);

            s->dsp.put_signed_pixels_clamped(v->block[v->top_blk_idx][5],

                                             s->dest[2] - 8 * s->uvlinesize,

                                             s->uvlinesize);

        }

    }

#define inc_blk_idx(idx) do { \

        idx++; \

        if (idx >= v->n_allocated_blks) \

            idx = 0; \

    } while (0)

    inc_blk_idx(v->topleft_blk_idx);

    inc_blk_idx(v->top_blk_idx);

    inc_blk_idx(v->left_blk_idx);

    inc_blk_idx(v->cur_blk_idx);

}


static void scsi_device_destroy(SCSIDevice *s)

{

    SCSIDeviceClass *sc = SCSI_DEVICE_GET_CLASS(s);

    if (sc->destroy) {

        sc->destroy(s);

    }

}


int ff_h264_get_profile(SPS *sps)

{

    int profile = sps->profile_idc;

    switch (sps->profile_idc) {

    case FF_PROFILE_H264_BASELINE:

        // constraint_set1_flag set to 1

        profile |= (sps->constraint_set_flags & 1 << 1) ? FF_PROFILE_H264_CONSTRAINED : 0;

        break;

    case FF_PROFILE_H264_HIGH_10:

    case FF_PROFILE_H264_HIGH_422:

    case FF_PROFILE_H264_HIGH_444_PREDICTIVE:

        // constraint_set3_flag set to 1

        profile |= (sps->constraint_set_flags & 1 << 3) ? FF_PROFILE_H264_INTRA : 0;

        break;

    }

    return profile;

}


void net_tx_pkt_setup_vlan_header(struct NetTxPkt *pkt, uint16_t vlan)

{

    bool is_new;

    assert(pkt);

    eth_setup_vlan_headers(pkt->vec[NET_TX_PKT_L2HDR_FRAG].iov_base,

        vlan, &is_new);

    /* update l2hdrlen */

    if (is_new) {

        pkt->hdr_len += sizeof(struct vlan_header);

        pkt->vec[NET_TX_PKT_L2HDR_FRAG].iov_len +=

            sizeof(struct vlan_header);

    }

}


int pcnet_common_init(DeviceState *dev, PCNetState *s, NetClientInfo *info)

{

    int i;

    uint16_t checksum;

    s->poll_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, pcnet_poll_timer, s);

    qemu_macaddr_default_if_unset(&s->conf.macaddr);

    s->nic = qemu_new_nic(info, &s->conf, object_get_typename(OBJECT(dev)), dev->id, s);

    qemu_format_nic_info_str(qemu_get_queue(s->nic), s->conf.macaddr.a);

    /* Initialize the PROM */

    /*

      Datasheet: http://pdfdata.datasheetsite.com/web/24528/AM79C970A.pdf

      page 95

    */

    memcpy(s->prom, s->conf.macaddr.a, 6);

    /* Reserved Location: must be 00h */

    s->prom[6] = s->prom[7] = 0x00;

    /* Reserved Location: must be 00h */

    s->prom[8] = 0x00;

    /* Hardware ID: must be 11h if compatibility to AMD drivers is desired */

    s->prom[9] = 0x11;

    /* User programmable space, init with 0 */

    s->prom[10] = s->prom[11] = 0x00;

    /* LSByte of two-byte checksum, which is the sum of bytes 00h-0Bh

       and bytes 0Eh and 0Fh, must therefore be initialized with 0! */

    s->prom[12] = s->prom[13] = 0x00;

    /* Must be ASCII W (57h) if compatibility to AMD

       driver software is desired */

    s->prom[14] = s->prom[15] = 0x57;

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

        checksum += s->prom[i];

    }

    *(uint16_t *)&s->prom[12] = cpu_to_le16(checksum);

    s->lnkst = 0x40; /* initial link state: up */

    return 0;

}


static int query_memdev(Object *obj, void *opaque)

{

    MemdevList **list = opaque;

    Error *err = NULL;

    if (object_dynamic_cast(obj, TYPE_MEMORY_BACKEND)) {

        MemdevList *m = g_malloc0(sizeof(*m));

        m->value = g_malloc0(sizeof(*m->value));

        m->value->size = object_property_get_int(obj, "size",

                                                 &err);

        if (err) {

            goto error;

        }

        m->value->merge = object_property_get_bool(obj, "merge",

                                                   &err);

        if (err) {

            goto error;

        }

        m->value->dump = object_property_get_bool(obj, "dump",

                                                  &err);

        if (err) {

            goto error;

        }

        m->value->prealloc = object_property_get_bool(obj,

                                                      "prealloc", &err);

        if (err) {

            goto error;

        }

        m->value->policy = object_property_get_enum(obj,

                                                    "policy",

                                                    HostMemPolicy_lookup,

                                                    &err);

        if (err) {

            goto error;

        }

        object_property_get_uint16List(obj, "host-nodes",

                                       &m->value->host_nodes, &err);

        if (err) {

            goto error;

        }

        m->next = *list;

        *list = m;

    }

    return 0;

error:

    return -1;

}


static int decode_iccp_chunk(PNGDecContext *s, int length, AVFrame *f)

{

    int ret, cnt = 0;

    uint8_t *data, profile_name[82];

    AVBPrint bp;

    AVFrameSideData *sd;

    while ((profile_name[cnt++] = bytestream2_get_byte(&s->gb)) && cnt < 81);

    if (cnt > 80) {

        av_log(s->avctx, AV_LOG_ERROR, "iCCP with invalid name!\n");

        return AVERROR_INVALIDDATA;

    }

    length = FFMAX(length - cnt, 0);

    if (bytestream2_get_byte(&s->gb) != 0) {

        av_log(s->avctx, AV_LOG_ERROR, "iCCP with invalid compression!\n");

        return AVERROR_INVALIDDATA;

    }

    length = FFMAX(length - 1, 0);

    if ((ret = decode_zbuf(&bp, s->gb.buffer, s->gb.buffer + length)) < 0)

        return ret;

    av_bprint_finalize(&bp, (char **)&data);

    sd = av_frame_new_side_data(f, AV_FRAME_DATA_ICC_PROFILE, bp.len);

    if (!sd) {

        av_free(data);

    }

    av_dict_set(&sd->metadata, "name", profile_name, 0);

    memcpy(sd->data, data, bp.len);

    av_free(data);

    /* ICC compressed data and CRC */

    bytestream2_skip(&s->gb, length + 4);

    return 0;

}


uint64_t helper_fres(CPUPPCState *env, uint64_t arg)

{

    CPU_DoubleU farg;

    float32 f32;

    farg.ll = arg;

    if (unlikely(float64_is_signaling_nan(farg.d))) {

        /* sNaN reciprocal */

        fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXSNAN);

    }

    farg.d = float64_div(float64_one, farg.d, &env->fp_status);

    f32 = float64_to_float32(farg.d, &env->fp_status);

    farg.d = float32_to_float64(f32, &env->fp_status);

    return farg.ll;

}


void HELPER(wsr_lend)(uint32_t v)

{

    if (env->sregs[LEND] != v) {

        tb_invalidate_phys_page_range(

                env->sregs[LEND] - 1, env->sregs[LEND], 0);

        env->sregs[LEND] = v;

        tb_invalidate_phys_page_range(

                env->sregs[LEND] - 1, env->sregs[LEND], 0);

    }

}


static int aio_epoll(AioContext *ctx, GPollFD *pfds,

                     unsigned npfd, int64_t timeout)

{

    assert(false);

}


static int decode_buffering_period(H264Context *h)

{

    unsigned int sps_id;

    int sched_sel_idx;

    SPS *sps;

    sps_id = get_ue_golomb_31(&h->gb);

    if (sps_id > 31 || !h->sps_buffers[sps_id]) {

        av_log(h->avctx, AV_LOG_ERROR,

               "non-existing SPS %d referenced in buffering period\n", sps_id);

        return AVERROR_INVALIDDATA;

    }

    sps = h->sps_buffers[sps_id];

    // NOTE: This is really so duplicated in the standard... See H.264, D.1.1

    if (sps->nal_hrd_parameters_present_flag) {

        for (sched_sel_idx = 0; sched_sel_idx < sps->cpb_cnt; sched_sel_idx++) {

            h->initial_cpb_removal_delay[sched_sel_idx] =

                get_bits(&h->gb, sps->initial_cpb_removal_delay_length);

            // initial_cpb_removal_delay_offset

            skip_bits(&h->gb, sps->initial_cpb_removal_delay_length);

        }

    }

    if (sps->vcl_hrd_parameters_present_flag) {

        for (sched_sel_idx = 0; sched_sel_idx < sps->cpb_cnt; sched_sel_idx++) {

            h->initial_cpb_removal_delay[sched_sel_idx] =

                get_bits(&h->gb, sps->initial_cpb_removal_delay_length);

            // initial_cpb_removal_delay_offset

            skip_bits(&h->gb, sps->initial_cpb_removal_delay_length);

        }

    }

    h->sei_buffering_period_present = 1;

    return 0;

}


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

{

    SmoothStreamingContext *c = s->priv_data;

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

    OutputStream *os = &c->streams[pkt->stream_index];

    int64_t end_dts = (c->nb_fragments + 1) * c->min_frag_duration;

    int ret;

    if (st->first_dts == AV_NOPTS_VALUE)

        st->first_dts = pkt->dts;

    if ((!c->has_video || st->codec->codec_type == AVMEDIA_TYPE_VIDEO) &&

        av_compare_ts(pkt->dts - st->first_dts, st->time_base,

                      end_dts, AV_TIME_BASE_Q) >= 0 &&

        pkt->flags & AV_PKT_FLAG_KEY && os->packets_written) {

        if ((ret = ism_flush(s, 0)) < 0)

            return ret;

        c->nb_fragments++;

    }

    os->packets_written++;

    return ff_write_chained(os->ctx, 0, pkt, s);

}


static void avc_luma_midh_qrt_and_aver_dst_4w_msa(const uint8_t *src,

                                                  int32_t src_stride,

                                                  uint8_t *dst,

                                                  int32_t dst_stride,

                                                  int32_t height,

                                                  uint8_t horiz_offset)

{

    uint32_t row;

    v16i8 src0, src1, src2, src3, src4, src5, src6;

    v16u8 dst0, dst1, res;

    v8i16 vt_res0, vt_res1, vt_res2, vt_res3;

    v4i32 hz_res0, hz_res1;

    v8i16 res0, res1;

    v8i16 shf_vec0, shf_vec1, shf_vec2, shf_vec3, shf_vec4, shf_vec5;

    v8i16 mask0 = { 0, 5, 1, 6, 2, 7, 3, 8 };

    v8i16 mask1 = { 1, 4, 2, 5, 3, 6, 4, 7 };

    v8i16 mask2 = { 2, 3, 3, 4, 4, 5, 5, 6 };

    v8i16 minus5h = __msa_ldi_h(-5);

    v8i16 plus20h = __msa_ldi_h(20);

    v8i16 zeros = { 0 };

    LD_SB5(src, src_stride, src0, src1, src2, src3, src4);

    src += (5 * src_stride);

    XORI_B5_128_SB(src0, src1, src2, src3, src4);

    for (row = (height >> 1); row--;) {

        LD_SB2(src, src_stride, src5, src6);

        src += (2 * src_stride);

        XORI_B2_128_SB(src5, src6);

        LD_UB2(dst, dst_stride, dst0, dst1);

        dst0 = (v16u8) __msa_ilvr_w((v4i32) dst1, (v4i32) dst0);

        AVC_CALC_DPADD_B_6PIX_2COEFF_SH(src0, src1, src2, src3, src4, src5,

                                        vt_res0, vt_res1);

        AVC_CALC_DPADD_B_6PIX_2COEFF_SH(src1, src2, src3, src4, src5, src6,

                                        vt_res2, vt_res3);

        VSHF_H3_SH(vt_res0, vt_res1, vt_res0, vt_res1, vt_res0, vt_res1,

                   mask0, mask1, mask2, shf_vec0, shf_vec1, shf_vec2);

        VSHF_H3_SH(vt_res2, vt_res3, vt_res2, vt_res3, vt_res2, vt_res3,

                   mask0, mask1, mask2, shf_vec3, shf_vec4, shf_vec5);

        hz_res0 = __msa_hadd_s_w(shf_vec0, shf_vec0);

        DPADD_SH2_SW(shf_vec1, shf_vec2, minus5h, plus20h, hz_res0, hz_res0);

        hz_res1 = __msa_hadd_s_w(shf_vec3, shf_vec3);

        DPADD_SH2_SW(shf_vec4, shf_vec5, minus5h, plus20h, hz_res1, hz_res1);

        SRARI_W2_SW(hz_res0, hz_res1, 10);

        SAT_SW2_SW(hz_res0, hz_res1, 7);

        res0 = __msa_srari_h(shf_vec2, 5);

        res1 = __msa_srari_h(shf_vec5, 5);

        SAT_SH2_SH(res0, res1, 7);

        if (horiz_offset) {

            res0 = __msa_ilvod_h(zeros, res0);

            res1 = __msa_ilvod_h(zeros, res1);

        } else {

            ILVEV_H2_SH(res0, zeros, res1, zeros, res0, res1);

        }

        hz_res0 = __msa_aver_s_w(hz_res0, (v4i32) res0);

        hz_res1 = __msa_aver_s_w(hz_res1, (v4i32) res1);

        res0 = __msa_pckev_h((v8i16) hz_res1, (v8i16) hz_res0);

        res = PCKEV_XORI128_UB(res0, res0);

        dst0 = __msa_aver_u_b(res, dst0);

        ST4x2_UB(dst0, dst, dst_stride);

        dst += (2 * dst_stride);

        src0 = src2;

        src1 = src3;

        src2 = src4;

        src3 = src5;

        src4 = src6;

    }

}


static int onenand_initfn(SysBusDevice *sbd)

{

    DeviceState *dev = DEVICE(sbd);

    OneNANDState *s = ONE_NAND(dev);

    uint32_t size = 1 << (24 + ((s->id.dev >> 4) & 7));

    void *ram;

    s->base = (hwaddr)-1;

    s->rdy = NULL;

    s->blocks = size >> BLOCK_SHIFT;

    s->secs = size >> 9;

    s->blockwp = g_malloc(s->blocks);

    s->density_mask = (s->id.dev & 0x08)

        ? (1 << (6 + ((s->id.dev >> 4) & 7))) : 0;

    memory_region_init_io(&s->iomem, OBJECT(s), &onenand_ops, s, "onenand",

                          0x10000 << s->shift);

    if (!s->blk) {

        s->image = memset(g_malloc(size + (size >> 5)),

                          0xff, size + (size >> 5));

    } else {

        if (blk_is_read_only(s->blk)) {

            error_report("Can't use a read-only drive");

            return -1;

        }

        s->blk_cur = s->blk;

    }

    s->otp = memset(g_malloc((64 + 2) << PAGE_SHIFT),

                    0xff, (64 + 2) << PAGE_SHIFT);

    memory_region_init_ram(&s->ram, OBJECT(s), "onenand.ram",

                           0xc000 << s->shift, &error_abort);

    vmstate_register_ram_global(&s->ram);

    ram = memory_region_get_ram_ptr(&s->ram);

    s->boot[0] = ram + (0x0000 << s->shift);

    s->boot[1] = ram + (0x8000 << s->shift);

    s->data[0][0] = ram + ((0x0200 + (0 << (PAGE_SHIFT - 1))) << s->shift);

    s->data[0][1] = ram + ((0x8010 + (0 << (PAGE_SHIFT - 6))) << s->shift);

    s->data[1][0] = ram + ((0x0200 + (1 << (PAGE_SHIFT - 1))) << s->shift);

    s->data[1][1] = ram + ((0x8010 + (1 << (PAGE_SHIFT - 6))) << s->shift);

    onenand_mem_setup(s);

    sysbus_init_irq(sbd, &s->intr);

    sysbus_init_mmio(sbd, &s->container);

    vmstate_register(dev,

                     ((s->shift & 0x7f) << 24)

                     | ((s->id.man & 0xff) << 16)

                     | ((s->id.dev & 0xff) << 8)

                     | (s->id.ver & 0xff),

                     &vmstate_onenand, s);

    return 0;

}


static void sdl_resize(DisplayState *ds)

{

    int flags;

    //    printf("resizing to %d %d\n", w, h);

    flags = SDL_HWSURFACE|SDL_ASYNCBLIT|SDL_HWACCEL;

    if (gui_fullscreen)

        flags |= SDL_FULLSCREEN;

    if (gui_noframe)

        flags |= SDL_NOFRAME;

 again:

    real_screen = SDL_SetVideoMode(ds_get_width(ds), ds_get_height(ds), 0, flags);

    if (!real_screen) {

        fprintf(stderr, "Could not open SDL display\n");

        exit(1);

    }

    if (!real_screen->pixels && (flags & SDL_HWSURFACE) && (flags & SDL_FULLSCREEN)) {

        flags &= ~SDL_HWSURFACE;

        goto again;

    }

    if (!real_screen->pixels) {

        fprintf(stderr, "Could not open SDL display\n");

        exit(1);

    }

    sdl_setdata(ds);

}


static bool object_is_type(Object *obj, const char *typename)

{

    TypeImpl *target_type = type_get_by_name(typename);

    TypeImpl *type = obj->class->type;

    GSList *i;

    /* Check if typename is a direct ancestor of type */

    while (type) {

        if (type == target_type) {

            return true;

        }

        type = type_get_parent(type);

    }

    /* Check if obj has an interface of typename */

    for (i = obj->interfaces; i; i = i->next) {

        Interface *iface = i->data;

        if (object_is_type(OBJECT(iface), typename)) {

            return true;

        }

    }

    return false;

}


static int truespeech_decode_frame(AVCodecContext *avctx,

                void *data, int *data_size,

                uint8_t *buf, int buf_size)

{

    TSContext *c = avctx->priv_data;

    int i;

    short *samples = data;

    int consumed = 0;

    int16_t out_buf[240];

    if (!buf_size)

        return 0;

    while (consumed < buf_size) {

        truespeech_read_frame(c, buf + consumed);

        consumed += 32;

        truespeech_correlate_filter(c);

        truespeech_filters_merge(c);

        memset(out_buf, 0, 240 * 2);

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

            truespeech_apply_twopoint_filter(c, i);

            truespeech_place_pulses(c, out_buf + i * 60, i);

            truespeech_update_filters(c, out_buf + i * 60, i);

            truespeech_synth(c, out_buf + i * 60, i);

        }

        truespeech_save_prevvec(c);

        /* finally output decoded frame */

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

            *samples++ = out_buf[i];

    }

    *data_size = consumed * 15;

    return buf_size;

}


static uint64_t dchip_read(void *opaque, target_phys_addr_t addr, unsigned size)

{

    /* Skip this.  It's all related to DRAM timing and setup.  */

    return 0;

}


static void omap_prcm_write(void *opaque, target_phys_addr_t addr,

                            uint64_t value, unsigned size)

{

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

    if (size != 4) {

        return omap_badwidth_write32(opaque, addr, value);

    }

    switch (addr) {

    case 0x000:	/* PRCM_REVISION */

    case 0x054:	/* PRCM_VOLTST */

    case 0x084:	/* PRCM_CLKCFG_STATUS */

    case 0x1e4:	/* PM_PWSTST_MPU */

    case 0x220:	/* CM_IDLEST1_CORE */

    case 0x224:	/* CM_IDLEST2_CORE */

    case 0x22c:	/* CM_IDLEST4_CORE */

    case 0x2c8:	/* PM_WKDEP_CORE */

    case 0x2e4:	/* PM_PWSTST_CORE */

    case 0x320:	/* CM_IDLEST_GFX */

    case 0x3e4:	/* PM_PWSTST_GFX */

    case 0x420:	/* CM_IDLEST_WKUP */

    case 0x520:	/* CM_IDLEST_CKGEN */

    case 0x820:	/* CM_IDLEST_DSP */

    case 0x8e4:	/* PM_PWSTST_DSP */

        OMAP_RO_REG(addr);

        return;

    case 0x010:	/* PRCM_SYSCONFIG */

        s->sysconfig = value & 1;

        break;

    case 0x018:	/* PRCM_IRQSTATUS_MPU */

        s->irqst[0] &= ~value;

        omap_prcm_int_update(s, 0);

        break;

    case 0x01c:	/* PRCM_IRQENABLE_MPU */

        s->irqen[0] = value & 0x3f;

        omap_prcm_int_update(s, 0);

        break;

    case 0x050:	/* PRCM_VOLTCTRL */

        s->voltctrl = value & 0xf1c3;

        break;

    case 0x060:	/* PRCM_CLKSRC_CTRL */

        s->clksrc[0] = value & 0xdb;

        /* TODO update clocks */

        break;

    case 0x070:	/* PRCM_CLKOUT_CTRL */

        s->clkout[0] = value & 0xbbbb;

        /* TODO update clocks */

        break;

    case 0x078:	/* PRCM_CLKEMUL_CTRL */

        s->clkemul[0] = value & 1;

        /* TODO update clocks */

        break;

    case 0x080:	/* PRCM_CLKCFG_CTRL */

        break;

    case 0x090:	/* PRCM_VOLTSETUP */

        s->setuptime[0] = value & 0xffff;

        break;

    case 0x094:	/* PRCM_CLKSSETUP */

        s->setuptime[1] = value & 0xffff;

        break;

    case 0x098:	/* PRCM_POLCTRL */

        s->clkpol[0] = value & 0x701;

        break;

    case 0x0b0:	/* GENERAL_PURPOSE1 */

    case 0x0b4:	/* GENERAL_PURPOSE2 */

    case 0x0b8:	/* GENERAL_PURPOSE3 */

    case 0x0bc:	/* GENERAL_PURPOSE4 */

    case 0x0c0:	/* GENERAL_PURPOSE5 */

    case 0x0c4:	/* GENERAL_PURPOSE6 */

    case 0x0c8:	/* GENERAL_PURPOSE7 */

    case 0x0cc:	/* GENERAL_PURPOSE8 */

    case 0x0d0:	/* GENERAL_PURPOSE9 */

    case 0x0d4:	/* GENERAL_PURPOSE10 */

    case 0x0d8:	/* GENERAL_PURPOSE11 */

    case 0x0dc:	/* GENERAL_PURPOSE12 */

    case 0x0e0:	/* GENERAL_PURPOSE13 */

    case 0x0e4:	/* GENERAL_PURPOSE14 */

    case 0x0e8:	/* GENERAL_PURPOSE15 */

    case 0x0ec:	/* GENERAL_PURPOSE16 */

    case 0x0f0:	/* GENERAL_PURPOSE17 */

    case 0x0f4:	/* GENERAL_PURPOSE18 */

    case 0x0f8:	/* GENERAL_PURPOSE19 */

    case 0x0fc:	/* GENERAL_PURPOSE20 */

        s->scratch[(addr - 0xb0) >> 2] = value;

        break;

    case 0x140:	/* CM_CLKSEL_MPU */

        s->clksel[0] = value & 0x1f;

        /* TODO update clocks */

        break;

    case 0x148:	/* CM_CLKSTCTRL_MPU */

        s->clkctrl[0] = value & 0x1f;

        break;

    case 0x158:	/* RM_RSTST_MPU */

        s->rst[0] &= ~value;

        break;

    case 0x1c8:	/* PM_WKDEP_MPU */

        s->wkup[0] = value & 0x15;

        break;

    case 0x1d4:	/* PM_EVGENCTRL_MPU */

        s->ev = value & 0x1f;

        break;

    case 0x1d8:	/* PM_EVEGENONTIM_MPU */

        s->evtime[0] = value;

        break;

    case 0x1dc:	/* PM_EVEGENOFFTIM_MPU */

        s->evtime[1] = value;

        break;

    case 0x1e0:	/* PM_PWSTCTRL_MPU */

        s->power[0] = value & 0xc0f;

        break;

    case 0x200:	/* CM_FCLKEN1_CORE */

        s->clken[0] = value & 0xbfffffff;

        /* TODO update clocks */

        /* The EN_EAC bit only gets/puts func_96m_clk.  */

        break;

    case 0x204:	/* CM_FCLKEN2_CORE */

        s->clken[1] = value & 0x00000007;

        /* TODO update clocks */

        break;

    case 0x210:	/* CM_ICLKEN1_CORE */

        s->clken[2] = value & 0xfffffff9;

        /* TODO update clocks */

        /* The EN_EAC bit only gets/puts core_l4_iclk.  */

        break;

    case 0x214:	/* CM_ICLKEN2_CORE */

        s->clken[3] = value & 0x00000007;

        /* TODO update clocks */

        break;

    case 0x21c:	/* CM_ICLKEN4_CORE */

        s->clken[4] = value & 0x0000001f;

        /* TODO update clocks */

        break;

    case 0x230:	/* CM_AUTOIDLE1_CORE */

        s->clkidle[0] = value & 0xfffffff9;

        /* TODO update clocks */

        break;

    case 0x234:	/* CM_AUTOIDLE2_CORE */

        s->clkidle[1] = value & 0x00000007;

        /* TODO update clocks */

        break;

    case 0x238:	/* CM_AUTOIDLE3_CORE */

        s->clkidle[2] = value & 0x00000007;

        /* TODO update clocks */

        break;

    case 0x23c:	/* CM_AUTOIDLE4_CORE */

        s->clkidle[3] = value & 0x0000001f;

        /* TODO update clocks */

        break;

    case 0x240:	/* CM_CLKSEL1_CORE */

        s->clksel[1] = value & 0x0fffbf7f;

        /* TODO update clocks */

        break;

    case 0x244:	/* CM_CLKSEL2_CORE */

        s->clksel[2] = value & 0x00fffffc;

        /* TODO update clocks */

        break;

    case 0x248:	/* CM_CLKSTCTRL_CORE */

        s->clkctrl[1] = value & 0x7;

        break;

    case 0x2a0:	/* PM_WKEN1_CORE */

        s->wken[0] = value & 0x04667ff8;

        break;

    case 0x2a4:	/* PM_WKEN2_CORE */

        s->wken[1] = value & 0x00000005;

        break;

    case 0x2b0:	/* PM_WKST1_CORE */

        s->wkst[0] &= ~value;

        break;

    case 0x2b4:	/* PM_WKST2_CORE */

        s->wkst[1] &= ~value;

        break;

    case 0x2e0:	/* PM_PWSTCTRL_CORE */

        s->power[1] = (value & 0x00fc3f) | (1 << 2);

        break;

    case 0x300:	/* CM_FCLKEN_GFX */

        s->clken[5] = value & 6;

        /* TODO update clocks */

        break;

    case 0x310:	/* CM_ICLKEN_GFX */

        s->clken[6] = value & 1;

        /* TODO update clocks */

        break;

    case 0x340:	/* CM_CLKSEL_GFX */

        s->clksel[3] = value & 7;

        /* TODO update clocks */

        break;

    case 0x348:	/* CM_CLKSTCTRL_GFX */

        s->clkctrl[2] = value & 1;

        break;

    case 0x350:	/* RM_RSTCTRL_GFX */

        s->rstctrl[0] = value & 1;

        /* TODO: reset */

        break;

    case 0x358:	/* RM_RSTST_GFX */

        s->rst[1] &= ~value;

        break;

    case 0x3c8:	/* PM_WKDEP_GFX */

        s->wkup[1] = value & 0x13;

        break;

    case 0x3e0:	/* PM_PWSTCTRL_GFX */

        s->power[2] = (value & 0x00c0f) | (3 << 2);

        break;

    case 0x400:	/* CM_FCLKEN_WKUP */

        s->clken[7] = value & 0xd;

        /* TODO update clocks */

        break;

    case 0x410:	/* CM_ICLKEN_WKUP */

        s->clken[8] = value & 0x3f;

        /* TODO update clocks */

        break;

    case 0x430:	/* CM_AUTOIDLE_WKUP */

        s->clkidle[4] = value & 0x0000003f;

        /* TODO update clocks */

        break;

    case 0x440:	/* CM_CLKSEL_WKUP */

        s->clksel[4] = value & 3;

        /* TODO update clocks */

        break;

    case 0x450:	/* RM_RSTCTRL_WKUP */

        /* TODO: reset */

        if (value & 2)

            qemu_system_reset_request();

        break;

    case 0x454:	/* RM_RSTTIME_WKUP */

        s->rsttime_wkup = value & 0x1fff;

        break;

    case 0x458:	/* RM_RSTST_WKUP */

        s->rst[2] &= ~value;

        break;

    case 0x4a0:	/* PM_WKEN_WKUP */

        s->wken[2] = value & 0x00000005;

        break;

    case 0x4b0:	/* PM_WKST_WKUP */

        s->wkst[2] &= ~value;

        break;

    case 0x500:	/* CM_CLKEN_PLL */

        if (value & 0xffffff30)

            fprintf(stderr, "%s: write 0s in CM_CLKEN_PLL for "

                            "future compatibility\n", __FUNCTION__);

        if ((s->clken[9] ^ value) & 0xcc) {

            s->clken[9] &= ~0xcc;

            s->clken[9] |= value & 0xcc;

            omap_prcm_apll_update(s);

        }

        if ((s->clken[9] ^ value) & 3) {

            s->clken[9] &= ~3;

            s->clken[9] |= value & 3;

            omap_prcm_dpll_update(s);

        }

        break;

    case 0x530:	/* CM_AUTOIDLE_PLL */

        s->clkidle[5] = value & 0x000000cf;

        /* TODO update clocks */

        break;

    case 0x540:	/* CM_CLKSEL1_PLL */

        if (value & 0xfc4000d7)

            fprintf(stderr, "%s: write 0s in CM_CLKSEL1_PLL for "

                            "future compatibility\n", __FUNCTION__);

        if ((s->clksel[5] ^ value) & 0x003fff00) {

            s->clksel[5] = value & 0x03bfff28;

            omap_prcm_dpll_update(s);

        }

        /* TODO update the other clocks */

        s->clksel[5] = value & 0x03bfff28;

        break;

    case 0x544:	/* CM_CLKSEL2_PLL */

        if (value & ~3)

            fprintf(stderr, "%s: write 0s in CM_CLKSEL2_PLL[31:2] for "

                            "future compatibility\n", __FUNCTION__);

        if (s->clksel[6] != (value & 3)) {

            s->clksel[6] = value & 3;

            omap_prcm_dpll_update(s);

        }

        break;

    case 0x800:	/* CM_FCLKEN_DSP */

        s->clken[10] = value & 0x501;

        /* TODO update clocks */

        break;

    case 0x810:	/* CM_ICLKEN_DSP */

        s->clken[11] = value & 0x2;

        /* TODO update clocks */

        break;

    case 0x830:	/* CM_AUTOIDLE_DSP */

        s->clkidle[6] = value & 0x2;

        /* TODO update clocks */

        break;

    case 0x840:	/* CM_CLKSEL_DSP */

        s->clksel[7] = value & 0x3fff;

        /* TODO update clocks */

        break;

    case 0x848:	/* CM_CLKSTCTRL_DSP */

        s->clkctrl[3] = value & 0x101;

        break;

    case 0x850:	/* RM_RSTCTRL_DSP */

        /* TODO: reset */

        break;

    case 0x858:	/* RM_RSTST_DSP */

        s->rst[3] &= ~value;

        break;

    case 0x8c8:	/* PM_WKDEP_DSP */

        s->wkup[2] = value & 0x13;

        break;

    case 0x8e0:	/* PM_PWSTCTRL_DSP */

        s->power[3] = (value & 0x03017) | (3 << 2);

        break;

    case 0x8f0:	/* PRCM_IRQSTATUS_DSP */

        s->irqst[1] &= ~value;

        omap_prcm_int_update(s, 1);

        break;

    case 0x8f4:	/* PRCM_IRQENABLE_DSP */

        s->irqen[1] = value & 0x7;

        omap_prcm_int_update(s, 1);

        break;

    case 0x8f8:	/* PRCM_IRQSTATUS_IVA */

        s->irqst[2] &= ~value;

        omap_prcm_int_update(s, 2);

        break;

    case 0x8fc:	/* PRCM_IRQENABLE_IVA */

        s->irqen[2] = value & 0x7;

        omap_prcm_int_update(s, 2);

        break;

    default:

        OMAP_BAD_REG(addr);

        return;

    }

}


static void init_proc_755 (CPUPPCState *env)

{

    gen_spr_ne_601(env);

    gen_spr_7xx(env);

    gen_spr_G2_755(env);

    /* Time base */

    gen_tbl(env);

    /* L2 cache control */

    /* XXX : not implemented */

    spr_register(env, SPR_L2CR, "L2CR",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, NULL,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_L2PMCR, "L2PMCR",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* Thermal management */

    gen_spr_thrm(env);

    /* Hardware implementation registers */

    /* XXX : not implemented */

    spr_register(env, SPR_HID0, "HID0",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_HID1, "HID1",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* XXX : not implemented */

    spr_register(env, SPR_HID2, "HID2",

                 SPR_NOACCESS, SPR_NOACCESS,

                 &spr_read_generic, &spr_write_generic,

                 0x00000000);

    /* Memory management */

    gen_low_BATs(env);

    gen_high_BATs(env);

    gen_6xx_7xx_soft_tlb(env, 64, 2);

    init_excp_7x5(env);

    env->dcache_line_size = 32;

    env->icache_line_size = 32;

    /* Allocate hardware IRQ controller */

    ppc6xx_irq_init(env);

}


static int gxf_write_trailer(AVFormatContext *s)

{

    GXFContext *gxf = s->priv_data;

    AVIOContext *pb = s->pb;

    int64_t end;

    int i;

    ff_audio_interleave_close(s);

    gxf_write_eos_packet(pb);

    end = avio_tell(pb);

    avio_seek(pb, 0, SEEK_SET);

    /* overwrite map, flt and umf packets with new values */

    gxf_write_map_packet(s, 1);

    gxf_write_flt_packet(s);

    gxf_write_umf_packet(s);

    avio_flush(pb);

    /* update duration in all map packets */

    for (i = 1; i < gxf->map_offsets_nb; i++) {

        avio_seek(pb, gxf->map_offsets[i], SEEK_SET);

        gxf_write_map_packet(s, 1);

        avio_flush(pb);

    }

    avio_seek(pb, end, SEEK_SET);

    av_freep(&gxf->flt_entries);

    av_freep(&gxf->map_offsets);

    return 0;

}


static int bdrv_prwv_co(BdrvChild *child, int64_t offset,

                        QEMUIOVector *qiov, bool is_write,

                        BdrvRequestFlags flags)

{

    Coroutine *co;

    RwCo rwco = {

        .child = child,

        .offset = offset,

        .qiov = qiov,

        .is_write = is_write,

        .ret = NOT_DONE,

        .flags = flags,

    };

    if (qemu_in_coroutine()) {

        /* Fast-path if already in coroutine context */

        bdrv_rw_co_entry(&rwco);

    } else {

        AioContext *aio_context = bdrv_get_aio_context(child->bs);

        co = qemu_coroutine_create(bdrv_rw_co_entry, &rwco);

        qemu_coroutine_enter(co);

        while (rwco.ret == NOT_DONE) {

            aio_poll(aio_context, true);

        }

    }

    return rwco.ret;

}


static uint64_t virtio_pci_common_read(void *opaque, hwaddr addr,

                                       unsigned size)

{

    VirtIOPCIProxy *proxy = opaque;

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

    uint32_t val = 0;

    int i;

    switch (addr) {

    case VIRTIO_PCI_COMMON_DFSELECT:

        val = proxy->dfselect;

        break;

    case VIRTIO_PCI_COMMON_DF:

        if (proxy->dfselect <= 1) {

            val = vdev->host_features >> (32 * proxy->dfselect);

        }

        break;

    case VIRTIO_PCI_COMMON_GFSELECT:

        val = proxy->gfselect;

        break;

    case VIRTIO_PCI_COMMON_GF:

        if (proxy->gfselect < ARRAY_SIZE(proxy->guest_features)) {

            val = proxy->guest_features[proxy->gfselect];

        }

        break;

    case VIRTIO_PCI_COMMON_MSIX:

        val = vdev->config_vector;

        break;

    case VIRTIO_PCI_COMMON_NUMQ:

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

            if (virtio_queue_get_num(vdev, i)) {

                val = i + 1;

            }

        }

        break;

    case VIRTIO_PCI_COMMON_STATUS:

        val = vdev->status;

        break;

    case VIRTIO_PCI_COMMON_CFGGENERATION:

        val = vdev->generation;

        break;

    case VIRTIO_PCI_COMMON_Q_SELECT:

        val = vdev->queue_sel;

        break;

    case VIRTIO_PCI_COMMON_Q_SIZE:

        val = virtio_queue_get_num(vdev, vdev->queue_sel);

        break;

    case VIRTIO_PCI_COMMON_Q_MSIX:

        val = virtio_queue_vector(vdev, vdev->queue_sel);

        break;

    case VIRTIO_PCI_COMMON_Q_ENABLE:

        val = proxy->vqs[vdev->queue_sel].enabled;

        break;

    case VIRTIO_PCI_COMMON_Q_NOFF:

        /* Simply map queues in order */

        val = vdev->queue_sel;

        break;

    case VIRTIO_PCI_COMMON_Q_DESCLO:

        val = proxy->vqs[vdev->queue_sel].desc[0];

        break;

    case VIRTIO_PCI_COMMON_Q_DESCHI:

        val = proxy->vqs[vdev->queue_sel].desc[1];

        break;

    case VIRTIO_PCI_COMMON_Q_AVAILLO:

        val = proxy->vqs[vdev->queue_sel].avail[0];

        break;

    case VIRTIO_PCI_COMMON_Q_AVAILHI:

        val = proxy->vqs[vdev->queue_sel].avail[1];

        break;

    case VIRTIO_PCI_COMMON_Q_USEDLO:

        val = proxy->vqs[vdev->queue_sel].used[0];

        break;

    case VIRTIO_PCI_COMMON_Q_USEDHI:

        val = proxy->vqs[vdev->queue_sel].used[1];

        break;

    default:

        val = 0;

    }

    return val;

}


void in_asm_used_var_warning_killer()

{

 volatile int i= yCoeff+vrCoeff+ubCoeff+vgCoeff+ugCoeff+bF8+bFC+w400+w80+w10+

 bm00001111+bm00000111+bm11111000+b16Mask+g16Mask+r16Mask+b15Mask+g15Mask+r15Mask+asm_yalpha1+ asm_uvalpha1+

 M24A+M24B+M24C+w02 + b5Dither+g5Dither+r5Dither+g6Dither+dither4[0]+dither8[0];

 if(i) i=0;

}


static double setup_compress_thresh(double threshold)

{

    if ((threshold > DBL_EPSILON) && (threshold < (1.0 - DBL_EPSILON))) {

        double current_threshold = threshold;

        double step_size = 1.0;

        while (step_size > DBL_EPSILON) {

            while ((current_threshold + step_size > current_threshold) &&

                   (bound(current_threshold + step_size, 1.0) <= threshold)) {

                current_threshold += step_size;

            }

            step_size /= 2.0;

        }

        return current_threshold;

    } else {

        return threshold;

    }

}


static av_always_inline int get_decoded_frame(AVFormatContext *fmt_ctx,

                                              AVFrame *frame, int *got_frame,

                                              AVPacket *pkt)

{

    AVCodecContext *dec_ctx = fmt_ctx->streams[pkt->stream_index]->codec;

    int ret = 0;

    *got_frame = 0;

    if (dec_ctx->codec) {

    switch (dec_ctx->codec_type) {

    case AVMEDIA_TYPE_VIDEO:

        ret = avcodec_decode_video2(dec_ctx, frame, got_frame, pkt);

        break;

    case AVMEDIA_TYPE_AUDIO:

        ret = avcodec_decode_audio4(dec_ctx, frame, got_frame, pkt);

        break;

    return ret;


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

{

    XilinxAXIDMA *s = XILINX_AXI_DMA(dev);

    XilinxAXIDMAStreamSlave *ds = XILINX_AXI_DMA_DATA_STREAM(&s->rx_data_dev);

    XilinxAXIDMAStreamSlave *cs = XILINX_AXI_DMA_CONTROL_STREAM(

                                                            &s->rx_control_dev);

    Error *local_err = NULL;

    object_property_add_link(OBJECT(ds), "dma", TYPE_XILINX_AXI_DMA,

                             (Object **)&ds->dma,

                             object_property_allow_set_link,

                             OBJ_PROP_LINK_UNREF_ON_RELEASE,

                             &local_err);

    object_property_add_link(OBJECT(cs), "dma", TYPE_XILINX_AXI_DMA,

                             (Object **)&cs->dma,

                             object_property_allow_set_link,

                             OBJ_PROP_LINK_UNREF_ON_RELEASE,

                             &local_err);

    if (local_err) {

        goto xilinx_axidma_realize_fail;

    }

    object_property_set_link(OBJECT(ds), OBJECT(s), "dma", &local_err);

    object_property_set_link(OBJECT(cs), OBJECT(s), "dma", &local_err);

    if (local_err) {

        goto xilinx_axidma_realize_fail;

    }

    int i;

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

        struct Stream *st = &s->streams[i];

        st->nr = i;

        st->bh = qemu_bh_new(timer_hit, st);

        st->ptimer = ptimer_init(st->bh, PTIMER_POLICY_DEFAULT);

        ptimer_set_freq(st->ptimer, s->freqhz);

    }

    return;

xilinx_axidma_realize_fail:

    if (!*errp) {

        *errp = local_err;

    }

}


BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,

                             BlockDriverState *child_bs,

                             const char *child_name,

                             const BdrvChildRole *child_role,

                             Error **errp)

{

    BdrvChild *child = bdrv_root_attach_child(child_bs, child_name, child_role,

                                              parent_bs);

    QLIST_INSERT_HEAD(&parent_bs->children, child, next);

    return child;

}