static int read_access_unit(AVCodecContext *avctx, void* data, int *data_size,

                            const uint8_t *buf, int buf_size)

{

    MLPDecodeContext *m = avctx->priv_data;

    GetBitContext gb;

    unsigned int length, substr;

    unsigned int substream_start;

    unsigned int header_size = 4;

    unsigned int substr_header_size = 0;

    uint8_t substream_parity_present[MAX_SUBSTREAMS];

    uint16_t substream_data_len[MAX_SUBSTREAMS];

    uint8_t parity_bits;

    if (buf_size < 4)

        return 0;

    length = (AV_RB16(buf) & 0xfff) * 2;

    if (length > buf_size)

        return -1;

    init_get_bits(&gb, (buf + 4), (length - 4) * 8);

    if (show_bits_long(&gb, 31) == (0xf8726fba >> 1)) {

        if (read_major_sync(m, &gb) < 0)

            goto error;

        header_size += 28;

    }

    if (!m->params_valid) {

        av_log(m->avctx, AV_LOG_WARNING,

               "Stream parameters not seen; skipping frame.\n");

        *data_size = 0;

        return length;

    }

    substream_start = 0;

    for (substr = 0; substr < m->num_substreams; substr++) {

        int extraword_present, checkdata_present, end;

        extraword_present = get_bits1(&gb);

        skip_bits1(&gb);

        checkdata_present = get_bits1(&gb);

        skip_bits1(&gb);

        end = get_bits(&gb, 12) * 2;

        substr_header_size += 2;

        if (extraword_present) {

            skip_bits(&gb, 16);

            substr_header_size += 2;

        }

        if (end + header_size + substr_header_size > length) {

            av_log(m->avctx, AV_LOG_ERROR,

                   "Indicated length of substream %d data goes off end of "

                   "packet.\n", substr);

            end = length - header_size - substr_header_size;

        }

        if (end < substream_start) {

            av_log(avctx, AV_LOG_ERROR,

                   "Indicated end offset of substream %d data "

                   "is smaller than calculated start offset.\n",

                   substr);

            goto error;

        }

        if (substr > m->max_decoded_substream)

            continue;

        substream_parity_present[substr] = checkdata_present;

        substream_data_len[substr] = end - substream_start;

        substream_start = end;

    }

    parity_bits  = ff_mlp_calculate_parity(buf, 4);

    parity_bits ^= ff_mlp_calculate_parity(buf + header_size, substr_header_size);

    if ((((parity_bits >> 4) ^ parity_bits) & 0xF) != 0xF) {

        av_log(avctx, AV_LOG_ERROR, "Parity check failed.\n");

        goto error;

    }

    buf += header_size + substr_header_size;

    for (substr = 0; substr <= m->max_decoded_substream; substr++) {

        SubStream *s = &m->substream[substr];

        init_get_bits(&gb, buf, substream_data_len[substr] * 8);

        s->blockpos = 0;

        do {

            if (get_bits1(&gb)) {

                if (get_bits1(&gb)) {

                    /* A restart header should be present. */

                    if (read_restart_header(m, &gb, buf, substr) < 0)

                        goto next_substr;

                    s->restart_seen = 1;

                }

                if (!s->restart_seen) {

                    goto next_substr;

                }

                if (read_decoding_params(m, &gb, substr) < 0)

                    goto next_substr;

            }

            if (!s->restart_seen) {

                goto next_substr;

            }

            if (read_block_data(m, &gb, substr) < 0)

                return -1;

            if (get_bits_count(&gb) >= substream_data_len[substr] * 8)

                goto substream_length_mismatch;

        } while (!get_bits1(&gb));

        skip_bits(&gb, (-get_bits_count(&gb)) & 15);

        if (substream_data_len[substr] * 8 - get_bits_count(&gb) >= 32) {

            int shorten_by;

            if (get_bits(&gb, 16) != 0xD234)

                return -1;

            shorten_by = get_bits(&gb, 16);

            if      (m->avctx->codec_id == CODEC_ID_TRUEHD && shorten_by  & 0x2000)

                s->blockpos -= FFMIN(shorten_by & 0x1FFF, s->blockpos);

            else if (m->avctx->codec_id == CODEC_ID_MLP    && shorten_by != 0xD234)

                return -1;

            if (substr == m->max_decoded_substream)

                av_log(m->avctx, AV_LOG_INFO, "End of stream indicated.\n");

        }

        if (substream_parity_present[substr]) {

            uint8_t parity, checksum;

            if (substream_data_len[substr] * 8 - get_bits_count(&gb) != 16)

                goto substream_length_mismatch;

            parity   = ff_mlp_calculate_parity(buf, substream_data_len[substr] - 2);

            checksum = ff_mlp_checksum8       (buf, substream_data_len[substr] - 2);

            if ((get_bits(&gb, 8) ^ parity) != 0xa9    )

                av_log(m->avctx, AV_LOG_ERROR, "Substream %d parity check failed.\n", substr);

            if ( get_bits(&gb, 8)           != checksum)

                av_log(m->avctx, AV_LOG_ERROR, "Substream %d checksum failed.\n"    , substr);

        }

        if (substream_data_len[substr] * 8 != get_bits_count(&gb)) {

            goto substream_length_mismatch;

        }

next_substr:

        if (!s->restart_seen) {

            av_log(m->avctx, AV_LOG_ERROR,

                   "No restart header present in substream %d.\n", substr);

        }

        buf += substream_data_len[substr];

    }

    rematrix_channels(m, m->max_decoded_substream);

    if (output_data(m, m->max_decoded_substream, data, data_size) < 0)

        return -1;

    return length;

substream_length_mismatch:

    av_log(m->avctx, AV_LOG_ERROR, "substream %d length mismatch\n", substr);

    return -1;

error:

    m->params_valid = 0;

    return -1;

}


int ff_get_buffer(AVCodecContext *avctx, AVFrame *frame, int flags)

{

    int ret;

    switch (avctx->codec_type) {

    case AVMEDIA_TYPE_VIDEO:

        if (!frame->width)

            frame->width               = avctx->width;

        if (!frame->height)

            frame->height              = avctx->height;

        if (frame->format < 0)

            frame->format              = avctx->pix_fmt;

        if (!frame->sample_aspect_ratio.num)

            frame->sample_aspect_ratio = avctx->sample_aspect_ratio;

        if ((ret = av_image_check_size(avctx->width, avctx->height, 0, avctx)) < 0)

            return ret;

        break;

    case AVMEDIA_TYPE_AUDIO:

        if (!frame->sample_rate)

            frame->sample_rate    = avctx->sample_rate;

        if (frame->format < 0)

            frame->format         = avctx->sample_fmt;

        if (!frame->channel_layout)

            frame->channel_layout = avctx->channel_layout;

        break;

    default: return AVERROR(EINVAL);

    }

    frame->pkt_pts = avctx->pkt ? avctx->pkt->pts : AV_NOPTS_VALUE;

    frame->reordered_opaque = avctx->reordered_opaque;

#if FF_API_GET_BUFFER

    /*

     * Wrap an old get_buffer()-allocated buffer in an bunch of AVBuffers.

     * We wrap each plane in its own AVBuffer. Each of those has a reference to

     * a dummy AVBuffer as its private data, unreffing it on free.

     * When all the planes are freed, the dummy buffer's free callback calls

     * release_buffer().

     */

    if (avctx->get_buffer) {

        CompatReleaseBufPriv *priv = NULL;

        AVBufferRef *dummy_buf = NULL;

        int planes, i, ret;

        if (flags & AV_GET_BUFFER_FLAG_REF)

            frame->reference    = 1;

        ret = avctx->get_buffer(avctx, frame);

        if (ret < 0)

            return ret;

        /* return if the buffers are already set up

         * this would happen e.g. when a custom get_buffer() calls

         * avcodec_default_get_buffer

         */

        if (frame->buf[0])

            return 0;

        priv = av_mallocz(sizeof(*priv));

        if (!priv) {

            ret = AVERROR(ENOMEM);

            goto fail;

        }

        priv->avctx = *avctx;

        priv->frame = *frame;

        dummy_buf = av_buffer_create(NULL, 0, compat_free_buffer, priv, 0);

        if (!dummy_buf) {

            ret = AVERROR(ENOMEM);

            goto fail;

        }

#define WRAP_PLANE(ref_out, data, data_size)                            \

do {                                                                    \

    AVBufferRef *dummy_ref = av_buffer_ref(dummy_buf);                  \

    if (!dummy_ref) {                                                   \

        ret = AVERROR(ENOMEM);                                          \

        goto fail;                                                      \

    }                                                                   \

    ref_out = av_buffer_create(data, data_size, compat_release_buffer,  \

                               dummy_ref, 0);                           \

    if (!ref_out) {                                                     \

        av_frame_unref(frame);                                          \

        ret = AVERROR(ENOMEM);                                          \

        goto fail;                                                      \

    }                                                                   \

} while (0)

        if (avctx->codec_type == AVMEDIA_TYPE_VIDEO) {

            const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(frame->format);

            if (!desc) {

                ret = AVERROR(EINVAL);

                goto fail;

            }

            planes = (desc->flags & PIX_FMT_PLANAR) ? desc->nb_components : 1;

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

                int h_shift    = (i == 1 || i == 2) ? desc->log2_chroma_h : 0;

                int plane_size = (frame->width >> h_shift) * frame->linesize[i];

                WRAP_PLANE(frame->buf[i], frame->data[i], plane_size);

            }

        } else {

            int planar = av_sample_fmt_is_planar(frame->format);

            planes = planar ? avctx->channels : 1;

            if (planes > FF_ARRAY_ELEMS(frame->buf)) {

                frame->nb_extended_buf = planes - FF_ARRAY_ELEMS(frame->buf);

                frame->extended_buf = av_malloc(sizeof(*frame->extended_buf) *

                                                frame->nb_extended_buf);

                if (!frame->extended_buf) {

                    ret = AVERROR(ENOMEM);

                    goto fail;

                }

            }

            for (i = 0; i < FFMIN(planes, FF_ARRAY_ELEMS(frame->buf)); i++)

                WRAP_PLANE(frame->buf[i], frame->extended_data[i], frame->linesize[0]);

            for (i = 0; i < planes - FF_ARRAY_ELEMS(frame->buf); i++)

                WRAP_PLANE(frame->extended_buf[i],

                           frame->extended_data[i + FF_ARRAY_ELEMS(frame->buf)],

                           frame->linesize[0]);

        }

        av_buffer_unref(&dummy_buf);

        return 0;

fail:

        avctx->release_buffer(avctx, frame);

        av_freep(&priv);

        av_buffer_unref(&dummy_buf);

        return ret;

    }

#endif

    return avctx->get_buffer2(avctx, frame, flags);

}


static av_cold void common_init(H264Context *h){

    MpegEncContext * const s = &h->s;

    s->width = s->avctx->width;

    s->height = s->avctx->height;

    s->codec_id= s->avctx->codec->id;

    ff_h264dsp_init(&h->h264dsp, 8, 1);

    ff_h264_pred_init(&h->hpc, s->codec_id, 8, 1);

    h->dequant_coeff_pps= -1;

    s->unrestricted_mv=1;

    s->decode=1; //FIXME

    dsputil_init(&s->dsp, s->avctx); // needed so that idct permutation is known early

    memset(h->pps.scaling_matrix4, 16, 6*16*sizeof(uint8_t));

    memset(h->pps.scaling_matrix8, 16, 2*64*sizeof(uint8_t));

}


static void RENAME(yuv2rgb555_2)(SwsContext *c, const uint16_t *buf0,

                                 const uint16_t *buf1, const uint16_t *ubuf0,

                                 const uint16_t *ubuf1, const uint16_t *vbuf0,

                                 const uint16_t *vbuf1, const uint16_t *abuf0,

                                 const uint16_t *abuf1, uint8_t *dest,

                                 int dstW, int yalpha, int uvalpha, int y)

{

    //Note 8280 == DSTW_OFFSET but the preprocessor can't handle that there :(

    __asm__ volatile(

        "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"

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

        "push %%"REG_BP"                        \n\t"

        YSCALEYUV2RGB(%%REGBP, %5)

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

        /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */

#ifdef DITHER1XBPP

        "paddusb "BLUE_DITHER"(%5), %%mm2      \n\t"

        "paddusb "GREEN_DITHER"(%5), %%mm4      \n\t"

        "paddusb "RED_DITHER"(%5), %%mm5      \n\t"

#endif

        WRITERGB15(%%REGb, 8280(%5), %%REGBP)

        "pop %%"REG_BP"                         \n\t"

        "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"

        :: "c" (buf0), "d" (buf1), "S" (ubuf0), "D" (ubuf1), "m" (dest),

           "a" (&c->redDither)

    );

}


static void device_finalize(Object *obj)

{

    DeviceState *dev = DEVICE(obj);

    BusState *bus;

    DeviceClass *dc = DEVICE_GET_CLASS(dev);

    if (dev->realized) {

        while (dev->num_child_bus) {

            bus = QLIST_FIRST(&dev->child_bus);

            qbus_free(bus);

        }

        if (qdev_get_vmsd(dev)) {

            vmstate_unregister(dev, qdev_get_vmsd(dev), dev);

        }

        if (dc->exit) {

            dc->exit(dev);

        }

        if (dev->opts) {

            qemu_opts_del(dev->opts);

        }

    }

}


static int pte_check_hash32(mmu_ctx_t *ctx, target_ulong pte0,

                            target_ulong pte1, int h, int rw, int type)

{

    target_ulong ptem, mmask;

    int access, ret, pteh, ptev, pp;

    ret = -1;

    /* Check validity and table match */

    ptev = pte_is_valid_hash32(pte0);

    pteh = (pte0 >> 6) & 1;

    if (ptev && h == pteh) {

        /* Check vsid & api */

        ptem = pte0 & PTE_PTEM_MASK;

        mmask = PTE_CHECK_MASK;

        pp = pte1 & 0x00000003;

        if (ptem == ctx->ptem) {

            if (ctx->raddr != (hwaddr)-1ULL) {

                /* all matches should have equal RPN, WIMG & PP */

                if ((ctx->raddr & mmask) != (pte1 & mmask)) {

                    qemu_log("Bad RPN/WIMG/PP\n");

                    return -3;

                }

            }

            /* Compute access rights */

            access = pp_check(ctx->key, pp, ctx->nx);

            /* Keep the matching PTE informations */

            ctx->raddr = pte1;

            ctx->prot = access;

            ret = check_prot(ctx->prot, rw, type);

            if (ret == 0) {

                /* Access granted */

                LOG_MMU("PTE access granted !\n");

            } else {

                /* Access right violation */

                LOG_MMU("PTE access rejected\n");

            }

        }

    }

    return ret;

}


static void gen_lea_modrm(DisasContext *s, int modrm, int *reg_ptr, int *offset_ptr)

{

    int havesib;

    int base, disp;

    int index;

    int scale;

    int opreg;

    int mod, rm, code, override, must_add_seg;

    /* XXX: add a generation time variable to tell if base == 0 in DS/ES/SS */

    override = -1;

    must_add_seg = s->addseg;

    if (s->prefix & (PREFIX_CS | PREFIX_SS | PREFIX_DS |

                     PREFIX_ES | PREFIX_FS | PREFIX_GS)) {

        if (s->prefix & PREFIX_ES)

            override = R_ES;

        else if (s->prefix & PREFIX_CS)

            override = R_CS;

        else if (s->prefix & PREFIX_SS)

            override = R_SS;

        else if (s->prefix & PREFIX_DS)

            override = R_DS;

        else if (s->prefix & PREFIX_FS)

            override = R_FS;

        else

            override = R_GS;

        must_add_seg = 1;

    }

    mod = (modrm >> 6) & 3;

    rm = modrm & 7;

    if (s->aflag) {

        havesib = 0;

        base = rm;

        index = 0;

        scale = 0;

        if (base == 4) {

            havesib = 1;

            code = ldub(s->pc++);

            scale = (code >> 6) & 3;

            index = (code >> 3) & 7;

            base = code & 7;

        }

        switch (mod) {

        case 0:

            if (base == 5) {

                base = -1;

                disp = ldl(s->pc);

                s->pc += 4;

            } else {

                disp = 0;

            }

            break;

        case 1:

            disp = (int8_t)ldub(s->pc++);

            break;

        default:

        case 2:

            disp = ldl(s->pc);

            s->pc += 4;

            break;

        }

        if (base >= 0) {

            gen_op_movl_A0_reg[base]();

            if (disp != 0)

                gen_op_addl_A0_im(disp);

        } else {

            gen_op_movl_A0_im(disp);

        }

        if (havesib && (index != 4 || scale != 0)) {

            gen_op_addl_A0_reg_sN[scale][index]();

        }

        if (must_add_seg) {

            if (override < 0) {

                if (base == R_EBP || base == R_ESP)

                    override = R_SS;

                else

                    override = R_DS;

            }

            gen_op_addl_A0_seg(offsetof(CPUX86State,seg_cache[override].base));

        }

    } else {

        switch (mod) {

        case 0:

            if (rm == 6) {

                disp = lduw(s->pc);

                s->pc += 2;

                gen_op_movl_A0_im(disp);

                rm = 0; /* avoid SS override */

                goto no_rm;

            } else {

                disp = 0;

            }

            break;

        case 1:

            disp = (int8_t)ldub(s->pc++);

            break;

        default:

        case 2:

            disp = lduw(s->pc);

            s->pc += 2;

            break;

        }

        switch(rm) {

        case 0:

            gen_op_movl_A0_reg[R_EBX]();

            gen_op_addl_A0_reg_sN[0][R_ESI]();

            break;

        case 1:

            gen_op_movl_A0_reg[R_EBX]();

            gen_op_addl_A0_reg_sN[0][R_EDI]();

            break;

        case 2:

            gen_op_movl_A0_reg[R_EBP]();

            gen_op_addl_A0_reg_sN[0][R_ESI]();

            break;

        case 3:

            gen_op_movl_A0_reg[R_EBP]();

            gen_op_addl_A0_reg_sN[0][R_EDI]();

            break;

        case 4:

            gen_op_movl_A0_reg[R_ESI]();

            break;

        case 5:

            gen_op_movl_A0_reg[R_EDI]();

            break;

        case 6:

            gen_op_movl_A0_reg[R_EBP]();

            break;

        default:

        case 7:

            gen_op_movl_A0_reg[R_EBX]();

            break;

        }

        if (disp != 0)

            gen_op_addl_A0_im(disp);

        gen_op_andl_A0_ffff();

    no_rm:

        if (must_add_seg) {

            if (override < 0) {

                if (rm == 2 || rm == 3 || rm == 6)

                    override = R_SS;

                else

                    override = R_DS;

            }

            gen_op_addl_A0_seg(offsetof(CPUX86State,seg_cache[override].base));

        }

    }

    opreg = OR_A0;

    disp = 0;

    *reg_ptr = opreg;

    *offset_ptr = disp;

}


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

{

    VideoPicture *vp;

#if CONFIG_AVFILTER

    AVPicture pict_src;

#else

    int dst_pix_fmt = AV_PIX_FMT_YUV420P;

#endif

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

    SDL_LockMutex(is->pictq_mutex);

    if (is->pictq_size >= VIDEO_PICTURE_QUEUE_SIZE && !is->refresh)

        is->skip_frames = FFMAX(1.0 - FRAME_SKIP_FACTOR, is->skip_frames * (1.0 - FRAME_SKIP_FACTOR));

    while (is->pictq_size >= VIDEO_PICTURE_QUEUE_SIZE &&

           !is->videoq.abort_request) {

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

    }

    SDL_UnlockMutex(is->pictq_mutex);

    if (is->videoq.abort_request)

        return -1;

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

    vp->sar = src_frame->sample_aspect_ratio;

    /* alloc or resize hardware picture buffer */

    if (!vp->bmp || vp->reallocate ||

#if CONFIG_AVFILTER

        vp->width  != is->out_video_filter->inputs[0]->w ||

        vp->height != is->out_video_filter->inputs[0]->h) {

#else

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

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

#endif

        SDL_Event event;

        vp->allocated  = 0;

        vp->reallocate = 0;

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

           locking problems */

        event.type = FF_ALLOC_EVENT;

        event.user.data1 = is;

        SDL_PushEvent(&event);

        /* wait until the picture is allocated */

        SDL_LockMutex(is->pictq_mutex);

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

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

        }

        SDL_UnlockMutex(is->pictq_mutex);

        if (is->videoq.abort_request)

            return -1;

    }

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

    if (vp->bmp) {

        AVPicture pict = { { 0 } };

        /* get a pointer on the bitmap */

        SDL_LockYUVOverlay (vp->bmp);

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

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

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

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

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

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

#if CONFIG_AVFILTER

        pict_src.data[0] = src_frame->data[0];

        pict_src.data[1] = src_frame->data[1];

        pict_src.data[2] = src_frame->data[2];

        pict_src.linesize[0] = src_frame->linesize[0];

        pict_src.linesize[1] = src_frame->linesize[1];

        pict_src.linesize[2] = src_frame->linesize[2];

        // FIXME use direct rendering

        av_picture_copy(&pict, &pict_src,

                        vp->pix_fmt, vp->width, vp->height);

#else

        av_opt_get_int(sws_opts, "sws_flags", 0, &sws_flags);

        is->img_convert_ctx = sws_getCachedContext(is->img_convert_ctx,

            vp->width, vp->height, vp->pix_fmt, vp->width, vp->height,

            dst_pix_fmt, sws_flags, NULL, NULL, NULL);

        if (is->img_convert_ctx == NULL) {

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

            exit(1);

        }

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

                  0, vp->height, pict.data, pict.linesize);

#endif

        /* update the bitmap content */

        SDL_UnlockYUVOverlay(vp->bmp);

        vp->pts = pts;

        vp->pos = pos;

        /* now we can update the picture count */

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

            is->pictq_windex = 0;

        SDL_LockMutex(is->pictq_mutex);

        vp->target_clock = compute_target_time(vp->pts, is);

        is->pictq_size++;

        SDL_UnlockMutex(is->pictq_mutex);

    }

    return 0;

}


float64 int64_to_float64( int64 a STATUS_PARAM )

{

    flag zSign;

    if ( a == 0 ) return 0;

    if ( a == (sbits64) LIT64( 0x8000000000000000 ) ) {

        return packFloat64( 1, 0x43E, 0 );

    }

    zSign = ( a < 0 );

    return normalizeRoundAndPackFloat64( zSign, 0x43C, zSign ? - a : a STATUS_VAR );

}


static void rtas_ibm_change_msi(sPAPREnvironment *spapr,

                                uint32_t token, uint32_t nargs,

                                target_ulong args, uint32_t nret,

                                target_ulong rets)

{

    uint32_t config_addr = rtas_ld(args, 0);

    uint64_t buid = ((uint64_t)rtas_ld(args, 1) << 32) | rtas_ld(args, 2);

    unsigned int func = rtas_ld(args, 3);

    unsigned int req_num = rtas_ld(args, 4); /* 0 == remove all */

    unsigned int seq_num = rtas_ld(args, 5);

    unsigned int ret_intr_type;

    int ndev, irq;

    sPAPRPHBState *phb = NULL;

    PCIDevice *pdev = NULL;

    switch (func) {

    case RTAS_CHANGE_MSI_FN:

    case RTAS_CHANGE_FN:

        ret_intr_type = RTAS_TYPE_MSI;

        break;

    case RTAS_CHANGE_MSIX_FN:

        ret_intr_type = RTAS_TYPE_MSIX;

        break;

    default:

        fprintf(stderr, "rtas_ibm_change_msi(%u) is not implemented\n", func);

        rtas_st(rets, 0, -3); /* Parameter error */

        return;

    }

    /* Fins sPAPRPHBState */

    phb = find_phb(spapr, buid);

    if (phb) {

        pdev = find_dev(spapr, buid, config_addr);

    }

    if (!phb || !pdev) {

        rtas_st(rets, 0, -3); /* Parameter error */

        return;

    }

    /* Releasing MSIs */

    if (!req_num) {

        ndev = spapr_msicfg_find(phb, config_addr, false);

        if (ndev < 0) {

            trace_spapr_pci_msi("MSI has not been enabled", -1, config_addr);

            rtas_st(rets, 0, -1); /* Hardware error */

            return;

        }

        trace_spapr_pci_msi("Released MSIs", ndev, config_addr);

        rtas_st(rets, 0, 0);

        rtas_st(rets, 1, 0);

        return;

    }

    /* Enabling MSI */

    /* Find a device number in the map to add or reuse the existing one */

    ndev = spapr_msicfg_find(phb, config_addr, true);

    if (ndev >= SPAPR_MSIX_MAX_DEVS || ndev < 0) {

        fprintf(stderr, "No free entry for a new MSI device\n");

        rtas_st(rets, 0, -1); /* Hardware error */

        return;

    }

    trace_spapr_pci_msi("Configuring MSI", ndev, config_addr);

    /* Check if there is an old config and MSI number has not changed */

    if (phb->msi_table[ndev].nvec && (req_num != phb->msi_table[ndev].nvec)) {

        /* Unexpected behaviour */

        fprintf(stderr, "Cannot reuse MSI config for device#%d", ndev);

        rtas_st(rets, 0, -1); /* Hardware error */

        return;

    }

    /* There is no cached config, allocate MSIs */

    if (!phb->msi_table[ndev].nvec) {

        irq = spapr_allocate_irq_block(req_num, false);

        if (irq < 0) {

            fprintf(stderr, "Cannot allocate MSIs for device#%d", ndev);

            rtas_st(rets, 0, -1); /* Hardware error */

            return;

        }

        phb->msi_table[ndev].irq = irq;

        phb->msi_table[ndev].nvec = req_num;

        phb->msi_table[ndev].config_addr = config_addr;

    }

    /* Setup MSI/MSIX vectors in the device (via cfgspace or MSIX BAR) */

    spapr_msi_setmsg(pdev, phb->msi_win_addr | (ndev << 16),

                     ret_intr_type == RTAS_TYPE_MSIX, req_num);

    rtas_st(rets, 0, 0);

    rtas_st(rets, 1, req_num);

    rtas_st(rets, 2, ++seq_num);

    rtas_st(rets, 3, ret_intr_type);

    trace_spapr_pci_rtas_ibm_change_msi(func, req_num);

}


static void gic_dist_writel(void *opaque, target_phys_addr_t offset,

                            uint32_t value)

{

    GICState *s = (GICState *)opaque;

    if (offset == 0xf00) {

        int cpu;

        int irq;

        int mask;

        cpu = gic_get_current_cpu(s);

        irq = value & 0x3ff;

        switch ((value >> 24) & 3) {

        case 0:

            mask = (value >> 16) & ALL_CPU_MASK;

            break;

        case 1:

            mask = ALL_CPU_MASK ^ (1 << cpu);

            break;

        case 2:

            mask = 1 << cpu;

            break;

        default:

            DPRINTF("Bad Soft Int target filter\n");

            mask = ALL_CPU_MASK;

            break;

        }

        GIC_SET_PENDING(irq, mask);

        gic_update(s);

        return;

    }

    gic_dist_writew(opaque, offset, value & 0xffff);

    gic_dist_writew(opaque, offset + 2, value >> 16);

}


void eth_setup_vlan_headers(struct eth_header *ehdr, uint16_t vlan_tag,

    bool *is_new)

{

    struct vlan_header *vhdr = PKT_GET_VLAN_HDR(ehdr);

    switch (be16_to_cpu(ehdr->h_proto)) {

    case ETH_P_VLAN:

    case ETH_P_DVLAN:

        /* vlan hdr exists */

        *is_new = false;

        break;

    default:

        /* No VLAN header, put a new one */

        vhdr->h_proto = ehdr->h_proto;

        ehdr->h_proto = cpu_to_be16(ETH_P_VLAN);

        *is_new = true;

        break;

    }

    vhdr->h_tci = cpu_to_be16(vlan_tag);

}


static void qemu_laio_completion_cb(void *opaque)

{

    struct qemu_laio_state *s = opaque;

    while (1) {

        struct io_event events[MAX_EVENTS];

        uint64_t val;

        ssize_t ret;

        struct timespec ts = { 0 };

        int nevents, i;

        do {

            ret = read(s->efd, &val, sizeof(val));

        } while (ret == 1 && errno == EINTR);

        if (ret == -1 && errno == EAGAIN)

            break;

        if (ret != 8)

            break;

        do {

            nevents = io_getevents(s->ctx, val, MAX_EVENTS, events, &ts);

        } while (nevents == -EINTR);

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

            struct iocb *iocb = events[i].obj;

            struct qemu_laiocb *laiocb =

                    container_of(iocb, struct qemu_laiocb, iocb);

            laiocb->ret = io_event_ret(&events[i]);

            qemu_laio_enqueue_completed(s, laiocb);

        }

    }

}


static void virtio_ccw_blk_realize(VirtioCcwDevice *ccw_dev, Error **errp)

{

    VirtIOBlkCcw *dev = VIRTIO_BLK_CCW(ccw_dev);

    DeviceState *vdev = DEVICE(&dev->vdev);

    Error *err = NULL;

    qdev_set_parent_bus(vdev, BUS(&ccw_dev->bus));

    object_property_set_bool(OBJECT(vdev), true, "realized", &err);

    if (err) {

        error_propagate(errp, err);

    }

}


S390PCIBusDevice *s390_pci_find_dev_by_idx(uint32_t idx)

{

    S390PCIBusDevice *pbdev;

    int i;

    int j = 0;

    S390pciState *s = S390_PCI_HOST_BRIDGE(

        object_resolve_path(TYPE_S390_PCI_HOST_BRIDGE, NULL));

    if (!s) {

        return NULL;

    }

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

        pbdev = &s->pbdev[i];

        if (pbdev->fh == 0) {

            continue;

        }

        if (j == idx) {

            return pbdev;

        }

        j++;

    }

    return NULL;

}


hadamard_func(mmxext)

hadamard_func(sse2)

hadamard_func(ssse3)

av_cold void ff_dsputilenc_init_mmx(DSPContext *c, AVCodecContext *avctx)

{

    int cpu_flags = av_get_cpu_flags();

#if HAVE_YASM

    int bit_depth = avctx->bits_per_raw_sample;

    if (EXTERNAL_MMX(cpu_flags)) {

        if (bit_depth <= 8)

            c->get_pixels = ff_get_pixels_mmx;

        c->diff_pixels = ff_diff_pixels_mmx;

        c->pix_sum = ff_pix_sum16_mmx;

        c->pix_norm1 = ff_pix_norm1_mmx;

    }

    if (EXTERNAL_SSE2(cpu_flags))

        if (bit_depth <= 8)

            c->get_pixels = ff_get_pixels_sse2;

#endif /* HAVE_YASM */

#if HAVE_INLINE_ASM

    if (cpu_flags & AV_CPU_FLAG_MMX) {

        const int dct_algo = avctx->dct_algo;

        if (avctx->bits_per_raw_sample <= 8 &&

            (dct_algo==FF_DCT_AUTO || dct_algo==FF_DCT_MMX)) {

            if (cpu_flags & AV_CPU_FLAG_SSE2) {

                c->fdct = ff_fdct_sse2;

            } else if (cpu_flags & AV_CPU_FLAG_MMXEXT) {

                c->fdct = ff_fdct_mmxext;

            }else{

                c->fdct = ff_fdct_mmx;

            }

        }

        c->diff_bytes= diff_bytes_mmx;

        c->sum_abs_dctelem= sum_abs_dctelem_mmx;

        c->sse[0] = sse16_mmx;

        c->sse[1] = sse8_mmx;

        c->vsad[4]= vsad_intra16_mmx;

        c->nsse[0] = nsse16_mmx;

        c->nsse[1] = nsse8_mmx;

        if(!(avctx->flags & CODEC_FLAG_BITEXACT)){

            c->vsad[0] = vsad16_mmx;

        }

        if(!(avctx->flags & CODEC_FLAG_BITEXACT)){

            c->try_8x8basis= try_8x8basis_mmx;

        }

        c->add_8x8basis= add_8x8basis_mmx;

        c->ssd_int8_vs_int16 = ssd_int8_vs_int16_mmx;

        if (cpu_flags & AV_CPU_FLAG_MMXEXT) {

            c->sum_abs_dctelem = sum_abs_dctelem_mmxext;

            c->vsad[4]         = vsad_intra16_mmxext;

            if(!(avctx->flags & CODEC_FLAG_BITEXACT)){

                c->vsad[0] = vsad16_mmxext;

            }

            c->sub_hfyu_median_prediction = sub_hfyu_median_prediction_mmxext;

        }

        if (cpu_flags & AV_CPU_FLAG_SSE2) {

            c->sum_abs_dctelem= sum_abs_dctelem_sse2;

        }

#if HAVE_SSSE3_INLINE

        if (cpu_flags & AV_CPU_FLAG_SSSE3) {

            if(!(avctx->flags & CODEC_FLAG_BITEXACT)){

                c->try_8x8basis= try_8x8basis_ssse3;

            }

            c->add_8x8basis= add_8x8basis_ssse3;

            c->sum_abs_dctelem= sum_abs_dctelem_ssse3;

        }

#endif

        if (cpu_flags & AV_CPU_FLAG_3DNOW) {

            if(!(avctx->flags & CODEC_FLAG_BITEXACT)){

                c->try_8x8basis= try_8x8basis_3dnow;

            }

            c->add_8x8basis= add_8x8basis_3dnow;

        }

    }

#endif /* HAVE_INLINE_ASM */

    if (EXTERNAL_MMX(cpu_flags)) {

        c->hadamard8_diff[0] = ff_hadamard8_diff16_mmx;

        c->hadamard8_diff[1] = ff_hadamard8_diff_mmx;

        if (EXTERNAL_MMXEXT(cpu_flags)) {

            c->hadamard8_diff[0] = ff_hadamard8_diff16_mmxext;

            c->hadamard8_diff[1] = ff_hadamard8_diff_mmxext;

        }

        if (EXTERNAL_SSE2(cpu_flags)) {

            c->sse[0] = ff_sse16_sse2;

#if HAVE_ALIGNED_STACK

            c->hadamard8_diff[0] = ff_hadamard8_diff16_sse2;

            c->hadamard8_diff[1] = ff_hadamard8_diff_sse2;

#endif

        }

        if (EXTERNAL_SSSE3(cpu_flags) && HAVE_ALIGNED_STACK) {

            c->hadamard8_diff[0] = ff_hadamard8_diff16_ssse3;

            c->hadamard8_diff[1] = ff_hadamard8_diff_ssse3;

        }

    }

    ff_dsputil_init_pix_mmx(c, avctx);

}


void aio_set_fd_poll(AioContext *ctx, int fd,

                     IOHandler *io_poll_begin,

                     IOHandler *io_poll_end)

{

    /* Not implemented */

}


static void raw_invalidate_cache(BlockDriverState *bs, Error **errp)

{

    BDRVRawState *s = bs->opaque;

    int ret;

    assert(!(bdrv_get_flags(bs) & BDRV_O_INACTIVE));

    ret = raw_handle_perm_lock(bs, RAW_PL_PREPARE, s->perm, s->shared_perm,

                               errp);

    if (ret) {

        return;

    }

    raw_handle_perm_lock(bs, RAW_PL_COMMIT, s->perm, s->shared_perm, NULL);

}


static uint64_t bw_conf1_read(void *opaque, target_phys_addr_t addr,

                              unsigned size)

{

    PCIBus *b = opaque;

    return pci_data_read(b, addr, size);

}


int bdrv_open(BlockDriverState *bs, const char *filename, QDict *options,

              int flags, BlockDriver *drv)

{

    int ret;

    /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */

    char tmp_filename[PATH_MAX + 1];

    BlockDriverState *file = NULL;

    /* NULL means an empty set of options */

    if (options == NULL) {

        options = qdict_new();

    }

    bs->options = options;

    options = qdict_clone_shallow(options);

    /* For snapshot=on, create a temporary qcow2 overlay */

    if (flags & BDRV_O_SNAPSHOT) {

        BlockDriverState *bs1;

        int64_t total_size;

        int is_protocol = 0;

        BlockDriver *bdrv_qcow2;

        QEMUOptionParameter *options;

        char backing_filename[PATH_MAX];

        /* if snapshot, we create a temporary backing file and open it

           instead of opening 'filename' directly */

        /* if there is a backing file, use it */

        bs1 = bdrv_new("");

        ret = bdrv_open(bs1, filename, NULL, 0, drv);

        if (ret < 0) {

            bdrv_delete(bs1);

            goto fail;

        }

        total_size = bdrv_getlength(bs1) & BDRV_SECTOR_MASK;

        if (bs1->drv && bs1->drv->protocol_name)

            is_protocol = 1;

        bdrv_delete(bs1);

        ret = get_tmp_filename(tmp_filename, sizeof(tmp_filename));

        if (ret < 0) {

            goto fail;

        }

        /* Real path is meaningless for protocols */

        if (is_protocol) {

            snprintf(backing_filename, sizeof(backing_filename),

                     "%s", filename);

        } else if (!realpath(filename, backing_filename)) {

            ret = -errno;

            goto fail;

        }

        bdrv_qcow2 = bdrv_find_format("qcow2");

        options = parse_option_parameters("", bdrv_qcow2->create_options, NULL);

        set_option_parameter_int(options, BLOCK_OPT_SIZE, total_size);

        set_option_parameter(options, BLOCK_OPT_BACKING_FILE, backing_filename);

        if (drv) {

            set_option_parameter(options, BLOCK_OPT_BACKING_FMT,

                drv->format_name);

        }

        ret = bdrv_create(bdrv_qcow2, tmp_filename, options);

        free_option_parameters(options);

        if (ret < 0) {

            goto fail;

        }

        filename = tmp_filename;

        drv = bdrv_qcow2;

        bs->is_temporary = 1;

    }

    /* Open image file without format layer */

    if (flags & BDRV_O_RDWR) {

        flags |= BDRV_O_ALLOW_RDWR;

    }

    ret = bdrv_file_open(&file, filename, bdrv_open_flags(bs, flags));

    if (ret < 0) {

        goto fail;

    }

    /* Find the right image format driver */

    if (!drv) {

        ret = find_image_format(file, filename, &drv);

    }

    if (!drv) {

        goto unlink_and_fail;

    }

    /* Open the image */

    ret = bdrv_open_common(bs, file, filename, options, flags, drv);

    if (ret < 0) {

        goto unlink_and_fail;

    }

    if (bs->file != file) {

        bdrv_delete(file);

        file = NULL;

    }

    /* If there is a backing file, use it */

    if ((flags & BDRV_O_NO_BACKING) == 0) {

        ret = bdrv_open_backing_file(bs);

        if (ret < 0) {

            goto close_and_fail;

        }

    }

    /* Check if any unknown options were used */

    if (qdict_size(options) != 0) {

        const QDictEntry *entry = qdict_first(options);

        qerror_report(ERROR_CLASS_GENERIC_ERROR, "Block format '%s' used by "

            "device '%s' doesn't support the option '%s'",

            drv->format_name, bs->device_name, entry->key);

        ret = -EINVAL;

        goto close_and_fail;

    }

    QDECREF(options);

    if (!bdrv_key_required(bs)) {

        bdrv_dev_change_media_cb(bs, true);

    }

    /* throttling disk I/O limits */

    if (bs->io_limits_enabled) {

        bdrv_io_limits_enable(bs);

    }

    return 0;

unlink_and_fail:

    if (file != NULL) {

        bdrv_delete(file);

    }

    if (bs->is_temporary) {

        unlink(filename);

    }

fail:

    QDECREF(bs->options);

    QDECREF(options);

    bs->options = NULL;

    return ret;

close_and_fail:

    bdrv_close(bs);

    QDECREF(options);

    return ret;

}


static uint32_t omap_sysctl_read(void *opaque, target_phys_addr_t addr)

{

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

    switch (addr) {

    case 0x000:	/* CONTROL_REVISION */

        return 0x20;

    case 0x010:	/* CONTROL_SYSCONFIG */

        return s->sysconfig;

    case 0x030 ... 0x140:	/* CONTROL_PADCONF - only used in the POP */

        return s->padconf[(addr - 0x30) >> 2];

    case 0x270:	/* CONTROL_DEBOBS */

        return s->obs;

    case 0x274:	/* CONTROL_DEVCONF */

        return s->devconfig;

    case 0x28c:	/* CONTROL_EMU_SUPPORT */

        return 0;

    case 0x290:	/* CONTROL_MSUSPENDMUX_0 */

        return s->msuspendmux[0];

    case 0x294:	/* CONTROL_MSUSPENDMUX_1 */

        return s->msuspendmux[1];

    case 0x298:	/* CONTROL_MSUSPENDMUX_2 */

        return s->msuspendmux[2];

    case 0x29c:	/* CONTROL_MSUSPENDMUX_3 */

        return s->msuspendmux[3];

    case 0x2a0:	/* CONTROL_MSUSPENDMUX_4 */

        return s->msuspendmux[4];

    case 0x2a4:	/* CONTROL_MSUSPENDMUX_5 */

        return 0;

    case 0x2b8:	/* CONTROL_PSA_CTRL */

        return s->psaconfig;

    case 0x2bc:	/* CONTROL_PSA_CMD */

    case 0x2c0:	/* CONTROL_PSA_VALUE */

        return 0;

    case 0x2b0:	/* CONTROL_SEC_CTRL */

        return 0x800000f1;

    case 0x2d0:	/* CONTROL_SEC_EMU */

        return 0x80000015;

    case 0x2d4:	/* CONTROL_SEC_TAP */

        return 0x8000007f;

    case 0x2b4:	/* CONTROL_SEC_TEST */

    case 0x2f0:	/* CONTROL_SEC_STATUS */

    case 0x2f4:	/* CONTROL_SEC_ERR_STATUS */

        /* Secure mode is not present on general-pusrpose device.  Outside

         * secure mode these values cannot be read or written.  */

        return 0;

    case 0x2d8:	/* CONTROL_OCM_RAM_PERM */

        return 0xff;

    case 0x2dc:	/* CONTROL_OCM_PUB_RAM_ADD */

    case 0x2e0:	/* CONTROL_EXT_SEC_RAM_START_ADD */

    case 0x2e4:	/* CONTROL_EXT_SEC_RAM_STOP_ADD */

        /* No secure mode so no Extended Secure RAM present.  */

        return 0;

    case 0x2f8:	/* CONTROL_STATUS */

        /* Device Type => General-purpose */

        return 0x0300;

    case 0x2fc:	/* CONTROL_GENERAL_PURPOSE_STATUS */

    case 0x300:	/* CONTROL_RPUB_KEY_H_0 */

    case 0x304:	/* CONTROL_RPUB_KEY_H_1 */

    case 0x308:	/* CONTROL_RPUB_KEY_H_2 */

    case 0x30c:	/* CONTROL_RPUB_KEY_H_3 */

        return 0xdecafbad;

    case 0x310:	/* CONTROL_RAND_KEY_0 */

    case 0x314:	/* CONTROL_RAND_KEY_1 */

    case 0x318:	/* CONTROL_RAND_KEY_2 */

    case 0x31c:	/* CONTROL_RAND_KEY_3 */

    case 0x320:	/* CONTROL_CUST_KEY_0 */

    case 0x324:	/* CONTROL_CUST_KEY_1 */

    case 0x330:	/* CONTROL_TEST_KEY_0 */

    case 0x334:	/* CONTROL_TEST_KEY_1 */

    case 0x338:	/* CONTROL_TEST_KEY_2 */

    case 0x33c:	/* CONTROL_TEST_KEY_3 */

    case 0x340:	/* CONTROL_TEST_KEY_4 */

    case 0x344:	/* CONTROL_TEST_KEY_5 */

    case 0x348:	/* CONTROL_TEST_KEY_6 */

    case 0x34c:	/* CONTROL_TEST_KEY_7 */

    case 0x350:	/* CONTROL_TEST_KEY_8 */

    case 0x354:	/* CONTROL_TEST_KEY_9 */

        /* Can only be accessed in secure mode and when C_FieldAccEnable

         * bit is set in CONTROL_SEC_CTRL.

         * TODO: otherwise an interconnect access error is generated.  */

        return 0;

    }

    OMAP_BAD_REG(addr);

    return 0;

}


static void gen_dmtc0 (DisasContext *ctx, int reg, int sel)

{

    const char *rn = "invalid";

    switch (reg) {

    case 0:

        switch (sel) {

        case 0:

            gen_op_mtc0_index();

            rn = "Index";

            break;

        case 1:

//         gen_op_dmtc0_mvpcontrol(); /* MT ASE */

            rn = "MVPControl";

//         break;

        case 2:

//         gen_op_dmtc0_mvpconf0(); /* MT ASE */

            rn = "MVPConf0";

//         break;

        case 3:

//         gen_op_dmtc0_mvpconf1(); /* MT ASE */

            rn = "MVPConf1";

//         break;

        default:

            goto die;

        }

        break;

    case 1:

        switch (sel) {

        case 0:

           /* ignored */

            rn = "Random";

           break;

        case 1:

//         gen_op_dmtc0_vpecontrol(); /* MT ASE */

            rn = "VPEControl";

//         break;

        case 2:

//         gen_op_dmtc0_vpeconf0(); /* MT ASE */

            rn = "VPEConf0";

//         break;

        case 3:

//         gen_op_dmtc0_vpeconf1(); /* MT ASE */

            rn = "VPEConf1";

//         break;

        case 4:

//         gen_op_dmtc0_YQMask(); /* MT ASE */

            rn = "YQMask";

//         break;

        case 5:

//         gen_op_dmtc0_vpeschedule(); /* MT ASE */

            rn = "VPESchedule";

//         break;

        case 6:

//         gen_op_dmtc0_vpeschefback(); /* MT ASE */

            rn = "VPEScheFBack";

//         break;

        case 7:

//         gen_op_dmtc0_vpeopt(); /* MT ASE */

            rn = "VPEOpt";

//         break;

        default:

            goto die;

        }

        break;

    case 2:

        switch (sel) {

        case 0:

           gen_op_dmtc0_entrylo0();

           rn = "EntryLo0";

           break;

        case 1:

//         gen_op_dmtc0_tcstatus(); /* MT ASE */

           rn = "TCStatus";

//         break;

        case 2:

//         gen_op_dmtc0_tcbind(); /* MT ASE */

           rn = "TCBind";

//         break;

        case 3:

//         gen_op_dmtc0_tcrestart(); /* MT ASE */

           rn = "TCRestart";

//         break;

        case 4:

//         gen_op_dmtc0_tchalt(); /* MT ASE */

           rn = "TCHalt";

//         break;

        case 5:

//         gen_op_dmtc0_tccontext(); /* MT ASE */

           rn = "TCContext";

//         break;

        case 6:

//         gen_op_dmtc0_tcschedule(); /* MT ASE */

           rn = "TCSchedule";

//         break;

        case 7:

//         gen_op_dmtc0_tcschefback(); /* MT ASE */

           rn = "TCScheFBack";

//         break;

        default:

            goto die;

        }

        break;

    case 3:

        switch (sel) {

        case 0:

           gen_op_dmtc0_entrylo1();

           rn = "EntryLo1";

           break;

        default:

            goto die;

       }

        break;

    case 4:

        switch (sel) {

        case 0:

           gen_op_dmtc0_context();

           rn = "Context";

           break;

        case 1:

//         gen_op_dmtc0_contextconfig(); /* SmartMIPS ASE */

           rn = "ContextConfig";

//         break;

        default:

            goto die;

       }

        break;

    case 5:

        switch (sel) {

        case 0:

           gen_op_mtc0_pagemask();

           rn = "PageMask";

           break;

        case 1:

           gen_op_mtc0_pagegrain();

           rn = "PageGrain";

           break;

        default:

            goto die;

       }

        break;

    case 6:

        switch (sel) {

        case 0:

           gen_op_mtc0_wired();

           rn = "Wired";

           break;

        case 1:

//         gen_op_dmtc0_srsconf0(); /* shadow registers */

           rn = "SRSConf0";

//         break;

        case 2:

//         gen_op_dmtc0_srsconf1(); /* shadow registers */

           rn = "SRSConf1";

//         break;

        case 3:

//         gen_op_dmtc0_srsconf2(); /* shadow registers */

           rn = "SRSConf2";

//         break;

        case 4:

//         gen_op_dmtc0_srsconf3(); /* shadow registers */

           rn = "SRSConf3";

//         break;

        case 5:

//         gen_op_dmtc0_srsconf4(); /* shadow registers */

           rn = "SRSConf4";

//         break;

        default:

            goto die;

       }

        break;

    case 7:

        switch (sel) {

        case 0:

           gen_op_mtc0_hwrena();

           rn = "HWREna";

           break;

        default:

            goto die;

       }

        break;

    case 8:

        /* ignored */

        rn = "BadVaddr";

        break;

    case 9:

        switch (sel) {

        case 0:

           gen_op_mtc0_count();

           rn = "Count";

           break;

       /* 6,7 are implementation dependent */

        default:

            goto die;

       }

       /* Stop translation as we may have switched the execution mode */

       ctx->bstate = BS_STOP;

        break;

    case 10:

        switch (sel) {

        case 0:

           gen_op_mtc0_entryhi();

           rn = "EntryHi";

           break;

        default:

            goto die;

       }

        break;

    case 11:

        switch (sel) {

        case 0:

           gen_op_mtc0_compare();

           rn = "Compare";

           break;

       /* 6,7 are implementation dependent */

        default:

            goto die;

       }

       /* Stop translation as we may have switched the execution mode */

       ctx->bstate = BS_STOP;

        break;

    case 12:

        switch (sel) {

        case 0:

           gen_op_mtc0_status();

           rn = "Status";

           break;

        case 1:

           gen_op_mtc0_intctl();

           rn = "IntCtl";

           break;

        case 2:

           gen_op_mtc0_srsctl();

           rn = "SRSCtl";

           break;

        case 3:

         gen_op_mtc0_srsmap(); /* shadow registers */

           rn = "SRSMap";

         break;

        default:

            goto die;

       }

       /* Stop translation as we may have switched the execution mode */

       ctx->bstate = BS_STOP;

        break;

    case 13:

        switch (sel) {

        case 0:

           gen_op_mtc0_cause();

           rn = "Cause";

           break;

        default:

            goto die;

       }

       /* Stop translation as we may have switched the execution mode */

       ctx->bstate = BS_STOP;

        break;

    case 14:

        switch (sel) {

        case 0:

           gen_op_dmtc0_epc();

           rn = "EPC";

           break;

        default:

            goto die;

       }

        break;

    case 15:

        switch (sel) {

        case 0:

           /* ignored */

           rn = "PRid";

           break;

        case 1:

           gen_op_dmtc0_ebase();

           rn = "EBase";

           break;

        default:

            goto die;

       }

        break;

    case 16:

        switch (sel) {

        case 0:

            gen_op_mtc0_config0();

            rn = "Config";

            break;

        case 1:

           /* ignored */

            rn = "Config1";

            break;

        case 2:

            gen_op_mtc0_config2();

            rn = "Config2";

            break;

        case 3:

           /* ignored */

            rn = "Config3";

            break;

        /* 6,7 are implementation dependent */

        default:

            rn = "Invalid config selector";

            goto die;

        }

        /* Stop translation as we may have switched the execution mode */

        ctx->bstate = BS_STOP;

        break;

    case 17:

        switch (sel) {

        case 0:

           /* ignored */

           rn = "LLAddr";

           break;

        default:

            goto die;

        }

        break;

    case 18:

        switch (sel) {

        case 0:

           gen_op_dmtc0_watchlo0();

           rn = "WatchLo";

           break;

        case 1:

//         gen_op_dmtc0_watchlo1();

           rn = "WatchLo1";

//         break;

        case 2:

//         gen_op_dmtc0_watchlo2();

           rn = "WatchLo2";

//         break;

        case 3:

//         gen_op_dmtc0_watchlo3();

           rn = "WatchLo3";

//         break;

        case 4:

//         gen_op_dmtc0_watchlo4();

           rn = "WatchLo4";

//         break;

        case 5:

//         gen_op_dmtc0_watchlo5();

           rn = "WatchLo5";

//         break;

        case 6:

//         gen_op_dmtc0_watchlo6();

           rn = "WatchLo6";

//         break;

        case 7:

//         gen_op_dmtc0_watchlo7();

           rn = "WatchLo7";

//         break;

        default:

            goto die;

        }

        break;

    case 19:

        switch (sel) {

        case 0:

           gen_op_mtc0_watchhi0();

           rn = "WatchHi";

           break;

        case 1:

//         gen_op_dmtc0_watchhi1();

           rn = "WatchHi1";

//         break;

        case 2:

//         gen_op_dmtc0_watchhi2();

           rn = "WatchHi2";

//         break;

        case 3:

//         gen_op_dmtc0_watchhi3();

           rn = "WatchHi3";

//         break;

        case 4:

//         gen_op_dmtc0_watchhi4();

           rn = "WatchHi4";

//         break;

        case 5:

//         gen_op_dmtc0_watchhi5();

           rn = "WatchHi5";

//         break;

        case 6:

//         gen_op_dmtc0_watchhi6();

           rn = "WatchHi6";

//         break;

        case 7:

//         gen_op_dmtc0_watchhi7();

           rn = "WatchHi7";

//         break;

        default:

            goto die;

        }

        break;

    case 20:

        switch (sel) {

        case 0:

           /* 64 bit MMU only */

           gen_op_dmtc0_xcontext();

           rn = "XContext";

           break;

        default:

            goto die;

        }

        break;

    case 21:

       /* Officially reserved, but sel 0 is used for R1x000 framemask */

        switch (sel) {

        case 0:

           gen_op_mtc0_framemask();

           rn = "Framemask";

           break;

        default:

            goto die;

        }

        break;

    case 22:

        /* ignored */

        rn = "Diagnostic"; /* implementation dependent */

       break;

    case 23:

        switch (sel) {

        case 0:

           gen_op_mtc0_debug(); /* EJTAG support */

           rn = "Debug";

           break;

        case 1:

//         gen_op_dmtc0_tracecontrol(); /* PDtrace support */

           rn = "TraceControl";

//         break;

        case 2:

//         gen_op_dmtc0_tracecontrol2(); /* PDtrace support */

           rn = "TraceControl2";

//         break;

        case 3:

//         gen_op_dmtc0_usertracedata(); /* PDtrace support */

           rn = "UserTraceData";

//         break;

        case 4:

//         gen_op_dmtc0_debug(); /* PDtrace support */

           rn = "TraceBPC";

//         break;

        default:

            goto die;

        }

       /* Stop translation as we may have switched the execution mode */

       ctx->bstate = BS_STOP;

        break;

    case 24:

        switch (sel) {

        case 0:

           gen_op_dmtc0_depc(); /* EJTAG support */

           rn = "DEPC";

           break;

        default:

            goto die;

        }

        break;

    case 25:

        switch (sel) {

        case 0:

           gen_op_mtc0_performance0();

           rn = "Performance0";

           break;

        case 1:

//         gen_op_dmtc0_performance1();

           rn = "Performance1";

//         break;

        case 2:

//         gen_op_dmtc0_performance2();

           rn = "Performance2";

//         break;

        case 3:

//         gen_op_dmtc0_performance3();

           rn = "Performance3";

//         break;

        case 4:

//         gen_op_dmtc0_performance4();

           rn = "Performance4";

//         break;

        case 5:

//         gen_op_dmtc0_performance5();

           rn = "Performance5";

//         break;

        case 6:

//         gen_op_dmtc0_performance6();

           rn = "Performance6";

//         break;

        case 7:

//         gen_op_dmtc0_performance7();

           rn = "Performance7";

//         break;

        default:

            goto die;

        }

       break;

    case 26:

       /* ignored */

        rn = "ECC";

       break;

    case 27:

        switch (sel) {

        case 0 ... 3:

           /* ignored */

           rn = "CacheErr";

           break;

        default:

            goto die;

        }

       break;

    case 28:

        switch (sel) {

        case 0:

        case 2:

        case 4:

        case 6:

            gen_op_mtc0_taglo();

            rn = "TagLo";

            break;

        case 1:

        case 3:

        case 5:

        case 7:

           gen_op_mtc0_datalo();

            rn = "DataLo";

            break;

        default:

            goto die;

        }

        break;

    case 29:

        switch (sel) {

        case 0:

        case 2:

        case 4:

        case 6:

            gen_op_mtc0_taghi();

            rn = "TagHi";

            break;

        case 1:

        case 3:

        case 5:

        case 7:

           gen_op_mtc0_datahi();

            rn = "DataHi";

            break;

        default:

            rn = "invalid sel";

            goto die;

        }

       break;

    case 30:

        switch (sel) {

        case 0:

           gen_op_dmtc0_errorepc();

           rn = "ErrorEPC";

           break;

        default:

            goto die;

        }

        break;

    case 31:

        switch (sel) {

        case 0:

           gen_op_mtc0_desave(); /* EJTAG support */

           rn = "DESAVE";

           break;

        default:

            goto die;

        }

       /* Stop translation as we may have switched the execution mode */

       ctx->bstate = BS_STOP;

        break;

    default:

       goto die;

    }

#if defined MIPS_DEBUG_DISAS

    if (loglevel & CPU_LOG_TB_IN_ASM) {

        fprintf(logfile, "dmtc0 %s (reg %d sel %d)\n",

                rn, reg, sel);

    }

#endif

    return;

die:

#if defined MIPS_DEBUG_DISAS

    if (loglevel & CPU_LOG_TB_IN_ASM) {

        fprintf(logfile, "dmtc0 %s (reg %d sel %d)\n",

                rn, reg, sel);

    }

#endif

    generate_exception(ctx, EXCP_RI);

}


static void xilinx_spips_write(void *opaque, hwaddr addr,

                                        uint64_t value, unsigned size)

{

    int mask = ~0;

    int man_start_com = 0;

    XilinxSPIPS *s = opaque;

    DB_PRINT("addr=" TARGET_FMT_plx " = %x\n", addr, (unsigned)value);

    addr >>= 2;

    switch (addr) {

    case R_CONFIG:

        mask = 0x0002FFFF;

        if (value & MAN_START_COM) {

            man_start_com = 1;

        }

        break;

    case R_INTR_STATUS:

        mask = IXR_ALL;

        s->regs[R_INTR_STATUS] &= ~(mask & value);

        goto no_reg_update;

    case R_INTR_DIS:

        mask = IXR_ALL;

        s->regs[R_INTR_MASK] &= ~(mask & value);

        goto no_reg_update;

    case R_INTR_EN:

        mask = IXR_ALL;

        s->regs[R_INTR_MASK] |= mask & value;

        goto no_reg_update;

    case R_EN:

        mask = 0x1;

        break;

    case R_SLAVE_IDLE_COUNT:

        mask = 0xFF;

        break;

    case R_RX_DATA:

    case R_INTR_MASK:

    case R_MOD_ID:

        mask = 0;

        break;

    case R_TX_DATA:

        tx_data_bytes(s, (uint32_t)value, s->num_txrx_bytes);

        goto no_reg_update;

    case R_TXD1:

        tx_data_bytes(s, (uint32_t)value, 1);

        goto no_reg_update;

    case R_TXD2:

        tx_data_bytes(s, (uint32_t)value, 2);

        goto no_reg_update;

    case R_TXD3:

        tx_data_bytes(s, (uint32_t)value, 3);

        goto no_reg_update;

    }

    s->regs[addr] = (s->regs[addr] & ~mask) | (value & mask);

no_reg_update:

    xilinx_spips_update_cs_lines(s);

    if ((man_start_com && s->regs[R_CONFIG] & MAN_START_EN) ||

            (fifo8_is_empty(&s->tx_fifo) && s->regs[R_CONFIG] & MAN_START_EN)) {

        xilinx_spips_flush_txfifo(s);

    }

    xilinx_spips_update_cs_lines(s);

    xilinx_spips_update_ixr(s);

}


int nbd_init(int fd, QIOChannelSocket *ioc, uint32_t flags, off_t size)

{

    return -ENOTSUP;

}


static int dca_find_frame_end(DCAParseContext *pc1, const uint8_t *buf,

                              int buf_size)

{

    int start_found, i;

    uint32_t state;

    ParseContext *pc = &pc1->pc;

    start_found = pc->frame_start_found;

    state       = pc->state;

    i = 0;

    if (!start_found) {

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

            state = (state << 8) | buf[i];

            if (IS_MARKER(state, i, buf, buf_size)) {

                if (!pc1->lastmarker || state == pc1->lastmarker || pc1->lastmarker == DCA_SYNCWORD_SUBSTREAM) {

                    start_found     = 1;

                    pc1->lastmarker = state;

                    i++;

                    break;

                }

            }

        }

    }

    if (start_found) {

        for (; i < buf_size; i++) {

            pc1->size++;

            state = (state << 8) | buf[i];

            if (state == DCA_SYNCWORD_SUBSTREAM && !pc1->hd_pos)

                pc1->hd_pos = pc1->size;

            if (IS_MARKER(state, i, buf, buf_size) && (state == pc1->lastmarker || pc1->lastmarker == DCA_SYNCWORD_SUBSTREAM)) {

                if (pc1->framesize > pc1->size)

                    continue;

                pc->frame_start_found = 0;

                pc->state             = -1;

                pc1->size             = 0;

                return i - 3;

            }

        }

    }

    pc->frame_start_found = start_found;

    pc->state             = state;

    return END_NOT_FOUND;

}


static int connect_to_sdog(BDRVSheepdogState *s, Error **errp)

{

    int fd;

    fd = socket_connect(s->addr, NULL, NULL, errp);

    if (s->addr->type == SOCKET_ADDRESS_KIND_INET && fd >= 0) {

        int ret = socket_set_nodelay(fd);

        if (ret < 0) {

            error_report("%s", strerror(errno));

        }

    }

    if (fd >= 0) {

        qemu_set_nonblock(fd);

    } else {

        fd = -EIO;

    }

    return fd;

}


static void do_info_block(int argc, const char **argv)

{

    bdrv_info();

}


static void buffered_flush(QEMUFileBuffered *s)

{

    size_t offset = 0;

    int error;

    error = qemu_file_get_error(s->file);

    if (error != 0) {

        DPRINTF("flush when error, bailing: %s\n", strerror(-error));

        return;

    }

    DPRINTF("flushing %zu byte(s) of data\n", s->buffer_size);

    while (s->bytes_xfer < s->xfer_limit && offset < s->buffer_size) {

        ssize_t ret;

        ret = migrate_fd_put_buffer(s->migration_state, s->buffer + offset,

                                    s->buffer_size - offset);

        if (ret == -EAGAIN) {

            DPRINTF("backend not ready, freezing\n");

            s->freeze_output = 1;

            break;

        }

        if (ret <= 0) {

            DPRINTF("error flushing data, %zd\n", ret);

            qemu_file_set_error(s->file, ret);

            break;

        } else {

            DPRINTF("flushed %zd byte(s)\n", ret);

            offset += ret;

            s->bytes_xfer += ret;

        }

    }

    DPRINTF("flushed %zu of %zu byte(s)\n", offset, s->buffer_size);

    memmove(s->buffer, s->buffer + offset, s->buffer_size - offset);

    s->buffer_size -= offset;

}


static int vt82c686b_mc97_initfn(PCIDevice *dev)

{

    VT686MC97State *s = DO_UPCAST(VT686MC97State, dev, dev);

    uint8_t *pci_conf = s->dev.config;

    pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_VIA);

    pci_config_set_device_id(pci_conf, PCI_DEVICE_ID_VIA_MC97);

    pci_config_set_class(pci_conf, PCI_CLASS_COMMUNICATION_OTHER);

    pci_config_set_revision(pci_conf, 0x30);

    pci_set_word(pci_conf + PCI_COMMAND, PCI_COMMAND_INVALIDATE |

                 PCI_COMMAND_VGA_PALETTE);

    pci_set_word(pci_conf + PCI_STATUS, PCI_STATUS_DEVSEL_MEDIUM);

    pci_set_long(pci_conf + PCI_INTERRUPT_PIN, 0x03);

    return 0;

}


PCIBus *pci_gt64120_init(qemu_irq *pic)

{

    GT64120State *s;

    PCIDevice *d;

    (void)&pci_host_data_writeb; /* avoid warning */

    (void)&pci_host_data_writew; /* avoid warning */

    (void)&pci_host_data_writel; /* avoid warning */

    (void)&pci_host_data_readb; /* avoid warning */

    (void)&pci_host_data_readw; /* avoid warning */

    (void)&pci_host_data_readl; /* avoid warning */

    s = qemu_mallocz(sizeof(GT64120State));

    s->pci = qemu_mallocz(sizeof(GT64120PCIState));

    s->pci->bus = pci_register_bus(NULL, "pci",

                                   pci_gt64120_set_irq, pci_gt64120_map_irq,

                                   pic, 144, 4);

    s->ISD_handle = cpu_register_io_memory(gt64120_read, gt64120_write, s);

    d = pci_register_device(s->pci->bus, "GT64120 PCI Bus", sizeof(PCIDevice),

                            0, gt64120_read_config, gt64120_write_config);

    /* FIXME: Malta specific hw assumptions ahead */

    pci_config_set_vendor_id(d->config, PCI_VENDOR_ID_MARVELL);

    pci_config_set_device_id(d->config, PCI_DEVICE_ID_MARVELL_GT6412X);

    d->config[0x04] = 0x00;

    d->config[0x05] = 0x00;

    d->config[0x06] = 0x80;

    d->config[0x07] = 0x02;

    d->config[0x08] = 0x10;

    d->config[0x09] = 0x00;

    pci_config_set_class(d->config, PCI_CLASS_BRIDGE_HOST);

    d->config[0x10] = 0x08;

    d->config[0x14] = 0x08;

    d->config[0x17] = 0x01;

    d->config[0x1B] = 0x1c;

    d->config[0x1F] = 0x1f;

    d->config[0x23] = 0x14;

    d->config[0x24] = 0x01;

    d->config[0x27] = 0x14;

    d->config[0x3D] = 0x01;

    gt64120_reset(s);

    register_savevm("GT64120 PCI Bus", 0, 1, gt64120_save, gt64120_load, d);

    return s->pci->bus;

}


static void enter_pgmcheck(S390CPU *cpu, uint16_t code)

{

    kvm_s390_interrupt(cpu, KVM_S390_PROGRAM_INT, code);

}


static void add_xblock(DWTELEM *dst, uint8_t *src, uint8_t *obmc, int s_x, int s_y, int b_w, int b_h, int mv_x, int mv_y, int w, int h, int dst_stride, int src_stride, int obmc_stride, int mb_type, int add){

    uint8_t tmp[src_stride*(b_h+5)]; //FIXME move to context to gurantee alignment

    int x,y;

    if(s_x<0){

        obmc -= s_x;

        b_w += s_x;

        s_x=0;

    }else if(s_x + b_w > w){

        b_w = w - s_x;

    }

    if(s_y<0){

        obmc -= s_y*obmc_stride;

        b_h += s_y;

        s_y=0;

    }else if(s_y + b_h> h){

        b_h = h - s_y;

    }

    if(b_w<=0 || b_h<=0) return;

    dst += s_x + s_y*dst_stride;

    if(mb_type==1){

        src += s_x + s_y*src_stride;

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

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

                if(add) dst[x + y*dst_stride] += obmc[x + y*obmc_stride] * 128 * (256/OBMC_MAX);

                else    dst[x + y*dst_stride] -= obmc[x + y*obmc_stride] * 128 * (256/OBMC_MAX);

            }

        }

    }else{

        int dx= mv_x&15;

        int dy= mv_y&15;

//        int dxy= (mv_x&1) + 2*(mv_y&1);

        s_x += (mv_x>>4) - 2;

        s_y += (mv_y>>4) - 2;

        src += s_x + s_y*src_stride;

        //use dsputil

        if(   (unsigned)s_x >= w - b_w - 4

           || (unsigned)s_y >= h - b_h - 4){

            ff_emulated_edge_mc(tmp + 32, src, src_stride, b_w+5, b_h+5, s_x, s_y, w, h);

            src= tmp + 32;

        }

        if(mb_type==0){

            mc_block(tmp, src, tmp + 64+8, src_stride, b_w, b_h, dx, dy);

        }else{

            int sum=0;

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

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

                    sum += src[x+  y*src_stride];

                }

            }

            sum= (sum + b_h*b_w/2) / (b_h*b_w);

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

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

                    tmp[x + y*src_stride]= sum;

                }

            }

        }

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

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

                if(add) dst[x + y*dst_stride] += obmc[x + y*obmc_stride] * tmp[x + y*src_stride] * (256/OBMC_MAX);

                else    dst[x + y*dst_stride] -= obmc[x + y*obmc_stride] * tmp[x + y*src_stride] * (256/OBMC_MAX);

            }

        }

    }

}


int av_buffersrc_add_ref(AVFilterContext *buffer_filter,

                         AVFilterBufferRef *picref, int flags)

{

    BufferSourceContext *c = buffer_filter->priv;

    AVFilterLink *outlink = buffer_filter->outputs[0];

    AVFilterBufferRef *buf;

    int ret;

    if (!picref) {

        c->eof = 1;

        return 0;

    } else if (c->eof)

        return AVERROR(EINVAL);

    if (!av_fifo_space(c->fifo) &&

        (ret = av_fifo_realloc2(c->fifo, av_fifo_size(c->fifo) +

                                         sizeof(buf))) < 0)

        return ret;

    if (!(flags & AV_BUFFERSRC_FLAG_NO_CHECK_FORMAT)) {

        /* TODO reindent */

    if (picref->video->w != c->w || picref->video->h != c->h || picref->format != c->pix_fmt) {

        AVFilterContext *scale = buffer_filter->outputs[0]->dst;

        AVFilterLink *link;

        char scale_param[1024];

        av_log(buffer_filter, AV_LOG_INFO,

               "Buffer video input changed from size:%dx%d fmt:%s to size:%dx%d fmt:%s\n",

               c->w, c->h, av_pix_fmt_descriptors[c->pix_fmt].name,

               picref->video->w, picref->video->h, av_pix_fmt_descriptors[picref->format].name);

        if (!scale || strcmp(scale->filter->name, "scale")) {

            AVFilter *f = avfilter_get_by_name("scale");

            av_log(buffer_filter, AV_LOG_INFO, "Inserting scaler filter\n");

            if ((ret = avfilter_open(&scale, f, "Input equalizer")) < 0)

                return ret;

            c->scale = scale;

            snprintf(scale_param, sizeof(scale_param)-1, "%d:%d:%s", c->w, c->h, c->sws_param);

            if ((ret = avfilter_init_filter(scale, scale_param, NULL)) < 0) {

                return ret;

            }

            if ((ret = avfilter_insert_filter(buffer_filter->outputs[0], scale, 0, 0)) < 0) {

                return ret;

            }

            scale->outputs[0]->time_base = scale->inputs[0]->time_base;

            scale->outputs[0]->format= c->pix_fmt;

        } else if (!strcmp(scale->filter->name, "scale")) {

            snprintf(scale_param, sizeof(scale_param)-1, "%d:%d:%s",

                     scale->outputs[0]->w, scale->outputs[0]->h, c->sws_param);

            scale->filter->init(scale, scale_param, NULL);

        }

        c->pix_fmt = scale->inputs[0]->format = picref->format;

        c->w       = scale->inputs[0]->w      = picref->video->w;

        c->h       = scale->inputs[0]->h      = picref->video->h;

        link = scale->outputs[0];

        if ((ret =  link->srcpad->config_props(link)) < 0)

            return ret;

    }

    }

    if (flags & AV_BUFFERSRC_FLAG_NO_COPY) {

        buf = picref;

    } else {

    buf = avfilter_get_video_buffer(outlink, AV_PERM_WRITE,

                                    picref->video->w, picref->video->h);

    av_image_copy(buf->data, buf->linesize,

                  (void*)picref->data, picref->linesize,

                  picref->format, picref->video->w, picref->video->h);

    avfilter_copy_buffer_ref_props(buf, picref);

    }

    if ((ret = av_fifo_generic_write(c->fifo, &buf, sizeof(buf), NULL)) < 0) {

        if (buf != picref)

            avfilter_unref_buffer(buf);

        return ret;

    }

    c->nb_failed_requests = 0;

    return 0;

}


int avformat_write_header(AVFormatContext *s, AVDictionary **options)

{

    int ret = 0, i;

    AVStream *st;

    AVDictionary *tmp = NULL;

    if (options)

        av_dict_copy(&tmp, *options, 0);

    if ((ret = av_opt_set_dict(s, &tmp)) < 0)

        goto fail;

    if (s->priv_data && s->oformat->priv_class && *(const AVClass**)s->priv_data==s->oformat->priv_class &&

        (ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)

        goto fail;

    // some sanity checks

    if (s->nb_streams == 0 && !(s->oformat->flags & AVFMT_NOSTREAMS)) {

        av_log(s, AV_LOG_ERROR, "no streams\n");

        ret = AVERROR(EINVAL);

        goto fail;

    }

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

        st = s->streams[i];

        switch (st->codec->codec_type) {

        case AVMEDIA_TYPE_AUDIO:

            if(st->codec->sample_rate<=0){

                av_log(s, AV_LOG_ERROR, "sample rate not set\n");

                ret = AVERROR(EINVAL);

                goto fail;

            }

            if(!st->codec->block_align)

                st->codec->block_align = st->codec->channels *

                    av_get_bits_per_sample(st->codec->codec_id) >> 3;

            break;

        case AVMEDIA_TYPE_VIDEO:

            if(st->codec->time_base.num<=0 || st->codec->time_base.den<=0){ //FIXME audio too?

                av_log(s, AV_LOG_ERROR, "time base not set\n");

                ret = AVERROR(EINVAL);

                goto fail;

            }

            if((st->codec->width<=0 || st->codec->height<=0) && !(s->oformat->flags & AVFMT_NODIMENSIONS)){

                av_log(s, AV_LOG_ERROR, "dimensions not set\n");

                ret = AVERROR(EINVAL);

                goto fail;

            }

            if(av_cmp_q(st->sample_aspect_ratio, st->codec->sample_aspect_ratio)

               && FFABS(av_q2d(st->sample_aspect_ratio) - av_q2d(st->codec->sample_aspect_ratio)) > 0.004*av_q2d(st->sample_aspect_ratio)

            ){

                av_log(s, AV_LOG_ERROR, "Aspect ratio mismatch between muxer "

                       "(%d/%d) and encoder layer (%d/%d)\n",

                       st->sample_aspect_ratio.num, st->sample_aspect_ratio.den,

                       st->codec->sample_aspect_ratio.num,

                       st->codec->sample_aspect_ratio.den);

                ret = AVERROR(EINVAL);

                goto fail;

            }

            break;

        }

        if(s->oformat->codec_tag){

            if(st->codec->codec_tag && st->codec->codec_id == CODEC_ID_RAWVIDEO && av_codec_get_tag(s->oformat->codec_tag, st->codec->codec_id) == 0 && !validate_codec_tag(s, st)){

                //the current rawvideo encoding system ends up setting the wrong codec_tag for avi, we override it here

                st->codec->codec_tag= 0;

            }

            if(st->codec->codec_tag){

                if (!validate_codec_tag(s, st)) {

                    char tagbuf[32], cortag[32];

                    av_get_codec_tag_string(tagbuf, sizeof(tagbuf), st->codec->codec_tag);

                    av_get_codec_tag_string(cortag, sizeof(cortag), av_codec_get_tag(s->oformat->codec_tag, st->codec->codec_id));

                    av_log(s, AV_LOG_ERROR,

                           "Tag %s/0x%08x incompatible with output codec id '%d' (%s)\n",

                           tagbuf, st->codec->codec_tag, st->codec->codec_id, cortag);

                    ret = AVERROR_INVALIDDATA;

                    goto fail;

                }

            }else

                st->codec->codec_tag= av_codec_get_tag(s->oformat->codec_tag, st->codec->codec_id);

        }

        if(s->oformat->flags & AVFMT_GLOBALHEADER &&

            !(st->codec->flags & CODEC_FLAG_GLOBAL_HEADER))

          av_log(s, AV_LOG_WARNING, "Codec for stream %d does not use global headers but container format requires global headers\n", i);

    }

    if (!s->priv_data && s->oformat->priv_data_size > 0) {

        s->priv_data = av_mallocz(s->oformat->priv_data_size);

        if (!s->priv_data) {

            ret = AVERROR(ENOMEM);

            goto fail;

        }

        if (s->oformat->priv_class) {

            *(const AVClass**)s->priv_data= s->oformat->priv_class;

            av_opt_set_defaults(s->priv_data);

            if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)

                goto fail;

        }

    }

    /* set muxer identification string */

    if (s->nb_streams && !(s->streams[0]->codec->flags & CODEC_FLAG_BITEXACT)) {

        av_dict_set(&s->metadata, "encoder", LIBAVFORMAT_IDENT, 0);

    }

    if(s->oformat->write_header){

        ret = s->oformat->write_header(s);

        if (ret < 0)

            goto fail;

    }

    /* init PTS generation */

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

        int64_t den = AV_NOPTS_VALUE;

        st = s->streams[i];

        switch (st->codec->codec_type) {

        case AVMEDIA_TYPE_AUDIO:

            den = (int64_t)st->time_base.num * st->codec->sample_rate;

            break;

        case AVMEDIA_TYPE_VIDEO:

            den = (int64_t)st->time_base.num * st->codec->time_base.den;

            break;

        default:

            break;

        }

        if (den != AV_NOPTS_VALUE) {

            if (den <= 0) {

                ret = AVERROR_INVALIDDATA;

                goto fail;

            }

            frac_init(&st->pts, 0, 0, den);

        }

    }

    if (options) {

        av_dict_free(options);

        *options = tmp;

    }

    return 0;

fail:

    av_dict_free(&tmp);

    return ret;

}


static int decode_slice_header(H264Context *h){

    MpegEncContext * const s = &h->s;

    int first_mb_in_slice, pps_id;

    int num_ref_idx_active_override_flag;

    static const uint8_t slice_type_map[5]= {P_TYPE, B_TYPE, I_TYPE, SP_TYPE, SI_TYPE};

    int slice_type;

    int default_ref_list_done = 0;

    s->current_picture.reference= h->nal_ref_idc != 0;

    s->dropable= h->nal_ref_idc == 0;

    first_mb_in_slice= get_ue_golomb(&s->gb);

    slice_type= get_ue_golomb(&s->gb);

    if(slice_type > 9){

        av_log(h->s.avctx, AV_LOG_ERROR, "slice type too large (%d) at %d %d\n", h->slice_type, s->mb_x, s->mb_y);

        return -1;

    }

    if(slice_type > 4){

        slice_type -= 5;

        h->slice_type_fixed=1;

    }else

        h->slice_type_fixed=0;

    slice_type= slice_type_map[ slice_type ];

    if (slice_type == I_TYPE

        || (h->slice_num != 0 && slice_type == h->slice_type) ) {

        default_ref_list_done = 1;

    }

    h->slice_type= slice_type;

    s->pict_type= h->slice_type; // to make a few old func happy, it's wrong though

    pps_id= get_ue_golomb(&s->gb);

    if(pps_id>255){

        av_log(h->s.avctx, AV_LOG_ERROR, "pps_id out of range\n");

        return -1;

    }

    h->pps= h->pps_buffer[pps_id];

    if(h->pps.slice_group_count == 0){

        av_log(h->s.avctx, AV_LOG_ERROR, "non existing PPS referenced\n");

        return -1;

    }

    h->sps= h->sps_buffer[ h->pps.sps_id ];

    if(h->sps.log2_max_frame_num == 0){

        av_log(h->s.avctx, AV_LOG_ERROR, "non existing SPS referenced\n");

        return -1;

    }

    if(h->dequant_coeff_pps != pps_id){

        h->dequant_coeff_pps = pps_id;

        init_dequant_tables(h);

    }

    s->mb_width= h->sps.mb_width;

    s->mb_height= h->sps.mb_height * (2 - h->sps.frame_mbs_only_flag);

    h->b_stride=  s->mb_width*4 + 1;

    h->b8_stride= s->mb_width*2 + 1;

    s->width = 16*s->mb_width - 2*(h->sps.crop_left + h->sps.crop_right );

    if(h->sps.frame_mbs_only_flag)

        s->height= 16*s->mb_height - 2*(h->sps.crop_top  + h->sps.crop_bottom);

    else

        s->height= 16*s->mb_height - 4*(h->sps.crop_top  + h->sps.crop_bottom); //FIXME recheck

    if (s->context_initialized

        && (   s->width != s->avctx->width || s->height != s->avctx->height)) {

        free_tables(h);

        MPV_common_end(s);

    }

    if (!s->context_initialized) {

        if (MPV_common_init(s) < 0)

            return -1;

        if(s->dsp.h264_idct_add == ff_h264_idct_add_c){ //FIXME little ugly

            memcpy(h->zigzag_scan, zigzag_scan, 16*sizeof(uint8_t));

            memcpy(h-> field_scan,  field_scan, 16*sizeof(uint8_t));

        }else{

            int i;

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

#define T(x) (x>>2) | ((x<<2) & 0xF)

                h->zigzag_scan[i] = T(zigzag_scan[i]);

                h-> field_scan[i] = T( field_scan[i]);

            }

        }

        if(h->sps.transform_bypass){ //FIXME same ugly

            h->zigzag_scan_q0 = zigzag_scan;

            h->field_scan_q0 = field_scan;

        }else{

            h->zigzag_scan_q0 = h->zigzag_scan;

            h->field_scan_q0 = h->field_scan;

        }

        alloc_tables(h);

        s->avctx->width = s->width;

        s->avctx->height = s->height;

        s->avctx->sample_aspect_ratio= h->sps.sar;

        if(!s->avctx->sample_aspect_ratio.den)

            s->avctx->sample_aspect_ratio.den = 1;

        if(h->sps.timing_info_present_flag){

            s->avctx->time_base= (AVRational){h->sps.num_units_in_tick, h->sps.time_scale};

        }

    }

    if(h->slice_num == 0){

        frame_start(h);

    }

    s->current_picture_ptr->frame_num= //FIXME frame_num cleanup

    h->frame_num= get_bits(&s->gb, h->sps.log2_max_frame_num);

    h->mb_aff_frame = 0;

    if(h->sps.frame_mbs_only_flag){

        s->picture_structure= PICT_FRAME;

    }else{

        if(get_bits1(&s->gb)) { //field_pic_flag

            s->picture_structure= PICT_TOP_FIELD + get_bits1(&s->gb); //bottom_field_flag

        } else {

            s->picture_structure= PICT_FRAME;

            first_mb_in_slice <<= h->sps.mb_aff;

            h->mb_aff_frame = h->sps.mb_aff;

        }

    }

    s->resync_mb_x = s->mb_x = first_mb_in_slice % s->mb_width;

    s->resync_mb_y = s->mb_y = first_mb_in_slice / s->mb_width;

    if(s->mb_y >= s->mb_height){

        return -1;

    }

    if(s->picture_structure==PICT_FRAME){

        h->curr_pic_num=   h->frame_num;

        h->max_pic_num= 1<< h->sps.log2_max_frame_num;

    }else{

        h->curr_pic_num= 2*h->frame_num;

        h->max_pic_num= 1<<(h->sps.log2_max_frame_num + 1);

    }

    if(h->nal_unit_type == NAL_IDR_SLICE){

        get_ue_golomb(&s->gb); /* idr_pic_id */

    }

    if(h->sps.poc_type==0){

        h->poc_lsb= get_bits(&s->gb, h->sps.log2_max_poc_lsb);

        if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME){

            h->delta_poc_bottom= get_se_golomb(&s->gb);

        }

    }

    if(h->sps.poc_type==1 && !h->sps.delta_pic_order_always_zero_flag){

        h->delta_poc[0]= get_se_golomb(&s->gb);

        if(h->pps.pic_order_present==1 && s->picture_structure==PICT_FRAME)

            h->delta_poc[1]= get_se_golomb(&s->gb);

    }

    init_poc(h);

    if(h->pps.redundant_pic_cnt_present){

        h->redundant_pic_count= get_ue_golomb(&s->gb);

    }

    //set defaults, might be overriden a few line later

    h->ref_count[0]= h->pps.ref_count[0];

    h->ref_count[1]= h->pps.ref_count[1];

    if(h->slice_type == P_TYPE || h->slice_type == SP_TYPE || h->slice_type == B_TYPE){

        if(h->slice_type == B_TYPE){

            h->direct_spatial_mv_pred= get_bits1(&s->gb);

        }

        num_ref_idx_active_override_flag= get_bits1(&s->gb);

        if(num_ref_idx_active_override_flag){

            h->ref_count[0]= get_ue_golomb(&s->gb) + 1;

            if(h->slice_type==B_TYPE)

                h->ref_count[1]= get_ue_golomb(&s->gb) + 1;

            if(h->ref_count[0] > 32 || h->ref_count[1] > 32){

                av_log(h->s.avctx, AV_LOG_ERROR, "reference overflow\n");

                return -1;

            }

        }

    }

    if(!default_ref_list_done){

        fill_default_ref_list(h);

    }

    if(decode_ref_pic_list_reordering(h) < 0)

        return -1;

    if(   (h->pps.weighted_pred          && (h->slice_type == P_TYPE || h->slice_type == SP_TYPE ))

       || (h->pps.weighted_bipred_idc==1 && h->slice_type==B_TYPE ) )

        pred_weight_table(h);

    else if(h->pps.weighted_bipred_idc==2 && h->slice_type==B_TYPE)

        implicit_weight_table(h);

    else

        h->use_weight = 0;

    if(s->current_picture.reference)

        decode_ref_pic_marking(h);

    if( h->slice_type != I_TYPE && h->slice_type != SI_TYPE && h->pps.cabac )

        h->cabac_init_idc = get_ue_golomb(&s->gb);

    h->last_qscale_diff = 0;

    s->qscale = h->pps.init_qp + get_se_golomb(&s->gb);

    if(s->qscale<0 || s->qscale>51){

        av_log(s->avctx, AV_LOG_ERROR, "QP %d out of range\n", s->qscale);

        return -1;

    }

    h->chroma_qp = get_chroma_qp(h->pps.chroma_qp_index_offset, s->qscale);

    //FIXME qscale / qp ... stuff

    if(h->slice_type == SP_TYPE){

        get_bits1(&s->gb); /* sp_for_switch_flag */

    }

    if(h->slice_type==SP_TYPE || h->slice_type == SI_TYPE){

        get_se_golomb(&s->gb); /* slice_qs_delta */

    }

    h->deblocking_filter = 1;

    h->slice_alpha_c0_offset = 0;

    h->slice_beta_offset = 0;

    if( h->pps.deblocking_filter_parameters_present ) {

        h->deblocking_filter= get_ue_golomb(&s->gb);

        if(h->deblocking_filter < 2)

            h->deblocking_filter^= 1; // 1<->0

        if( h->deblocking_filter ) {

            h->slice_alpha_c0_offset = get_se_golomb(&s->gb) << 1;

            h->slice_beta_offset = get_se_golomb(&s->gb) << 1;

        }

    }

    if(   s->avctx->skip_loop_filter >= AVDISCARD_ALL

       ||(s->avctx->skip_loop_filter >= AVDISCARD_NONKEY && h->slice_type != I_TYPE)

       ||(s->avctx->skip_loop_filter >= AVDISCARD_BIDIR  && h->slice_type == B_TYPE)

       ||(s->avctx->skip_loop_filter >= AVDISCARD_NONREF && h->nal_ref_idc == 0))

        h->deblocking_filter= 0;

#if 0 //FMO

    if( h->pps.num_slice_groups > 1  && h->pps.mb_slice_group_map_type >= 3 && h->pps.mb_slice_group_map_type <= 5)

        slice_group_change_cycle= get_bits(&s->gb, ?);

#endif

    h->slice_num++;

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

        av_log(h->s.avctx, AV_LOG_DEBUG, "slice:%d %s mb:%d %c pps:%d frame:%d poc:%d/%d ref:%d/%d qp:%d loop:%d:%d:%d weight:%d%s\n",

               h->slice_num,

               (s->picture_structure==PICT_FRAME ? "F" : s->picture_structure==PICT_TOP_FIELD ? "T" : "B"),

               first_mb_in_slice,

               av_get_pict_type_char(h->slice_type),

               pps_id, h->frame_num,

               s->current_picture_ptr->field_poc[0], s->current_picture_ptr->field_poc[1],

               h->ref_count[0], h->ref_count[1],

               s->qscale,

               h->deblocking_filter, h->slice_alpha_c0_offset/2, h->slice_beta_offset/2,

               h->use_weight,

               h->use_weight==1 && h->use_weight_chroma ? "c" : ""

               );

    }

    return 0;

}


void ff_put_h264_qpel8_mc12_msa(uint8_t *dst, const uint8_t *src,

                                ptrdiff_t stride)

{

    avc_luma_midh_qrt_8w_msa(src - (2 * stride) - 2, stride, dst, stride, 8, 0);

}


static void become_daemon(const char *pidfile)

{

#ifndef _WIN32

    pid_t pid, sid;

    pid = fork();

    if (pid < 0) {

        exit(EXIT_FAILURE);

    }

    if (pid > 0) {

        exit(EXIT_SUCCESS);

    }

    if (pidfile) {

        if (!ga_open_pidfile(pidfile)) {

            g_critical("failed to create pidfile");

            exit(EXIT_FAILURE);

        }

    }

    umask(0);

    sid = setsid();

    if (sid < 0) {

        goto fail;

    }

    if ((chdir("/")) < 0) {

        goto fail;

    }

    close(STDIN_FILENO);

    close(STDOUT_FILENO);

    close(STDERR_FILENO);

    return;

fail:

    unlink(pidfile);

    g_critical("failed to daemonize");

    exit(EXIT_FAILURE);

#endif

}


static int msvideo1_decode_frame(AVCodecContext *avctx,
                                void *data, int *got_frame,
                                AVPacket *avpkt)
{
    const uint8_t *buf = avpkt->data;
    int buf_size = avpkt->size;
    Msvideo1Context *s = avctx->priv_data;
    int ret;
    s->buf = buf;
    s->size = buf_size;
    if ((ret = ff_reget_buffer(avctx, s->frame)) < 0)
        return ret;
    if (s->mode_8bit) {
        int size;
        const uint8_t *pal = av_packet_get_side_data(avpkt, AV_PKT_DATA_PALETTE, &size);
        if (pal && size == AVPALETTE_SIZE) {
            memcpy(s->pal, pal, AVPALETTE_SIZE);
            s->frame->palette_has_changed = 1;
        } else if (pal) {
            av_log(avctx, AV_LOG_ERROR, "Palette size %d is wrong\n", size);
    if (s->mode_8bit)
        msvideo1_decode_8bit(s);
    else
        msvideo1_decode_16bit(s);
    if ((ret = av_frame_ref(data, s->frame)) < 0)
        return ret;
    *got_frame      = 1;
    /* report that the buffer was completely consumed */
    return buf_size;


void rgb16tobgr24(const uint8_t *src, uint8_t *dst, long src_size)

{

	const uint16_t *end;

	uint8_t *d = (uint8_t *)dst;

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

	end = s + src_size/2;

	while(s < end)

	{

		register uint16_t bgr;

		bgr = *s++;

		*d++ = (bgr&0xF800)>>8;

		*d++ = (bgr&0x7E0)>>3;

		*d++ = (bgr&0x1F)<<3;

	}

}


static void serial_receive_byte(SerialState *s, int ch)

{

    s->rbr = ch;

    s->lsr |= UART_LSR_DR;

    serial_update_irq(s);

}


ram_addr_t migration_bitmap_find_and_reset_dirty(RAMBlock *rb,

                                                 ram_addr_t start)

{

    unsigned long base = rb->offset >> TARGET_PAGE_BITS;

    unsigned long nr = base + (start >> TARGET_PAGE_BITS);

    uint64_t rb_size = rb->used_length;

    unsigned long size = base + (rb_size >> TARGET_PAGE_BITS);

    unsigned long *bitmap;

    unsigned long next;

    bitmap = atomic_rcu_read(&migration_bitmap);

    if (ram_bulk_stage && nr > base) {

        next = nr + 1;

    } else {

        next = find_next_bit(bitmap, size, nr);

    }

    if (next < size) {

        clear_bit(next, bitmap);

        migration_dirty_pages--;

    }

    return (next - base) << TARGET_PAGE_BITS;

}


static int svq1_motion_inter_block(DSPContext *dsp, GetBitContext *bitbuf,

                                   uint8_t *current, uint8_t *previous,

                                   int pitch, svq1_pmv *motion, int x, int y)

{

    uint8_t *src;

    uint8_t *dst;

    svq1_pmv mv;

    svq1_pmv *pmv[3];

    int result;

    /* predict and decode motion vector */

    pmv[0] = &motion[0];

    if (y == 0) {

        pmv[1] =

        pmv[2] = pmv[0];

    } else {

        pmv[1] = &motion[x / 8 + 2];

        pmv[2] = &motion[x / 8 + 4];

    }

    result = svq1_decode_motion_vector(bitbuf, &mv, pmv);

    if (result != 0)

        return result;

    motion[0].x         =

    motion[x / 8 + 2].x =

    motion[x / 8 + 3].x = mv.x;

    motion[0].y         =

    motion[x / 8 + 2].y =

    motion[x / 8 + 3].y = mv.y;

    if (y + (mv.y >> 1) < 0)

        mv.y = 0;

    if (x + (mv.x >> 1) < 0)

        mv.x = 0;

    src = &previous[(x + (mv.x >> 1)) + (y + (mv.y >> 1)) * pitch];

    dst = current;

    dsp->put_pixels_tab[0][(mv.y & 1) << 1 | (mv.x & 1)](dst, src, pitch, 16);

    return 0;

}


static inline TCGv gen_ld8u(TCGv addr, int index)

{

    TCGv tmp = new_tmp();

    tcg_gen_qemu_ld8u(tmp, addr, index);

    return tmp;

}


void replay_account_executed_instructions(void)
{
    if (replay_mode == REPLAY_MODE_PLAY) {
        replay_mutex_lock();
        if (replay_state.instructions_count > 0) {
            int count = (int)(replay_get_current_step()
                              - replay_state.current_step);
            replay_state.instructions_count -= count;
            replay_state.current_step += count;
            if (replay_state.instructions_count == 0) {
                assert(replay_state.data_kind == EVENT_INSTRUCTION);
                replay_finish_event();
                /* Wake up iothread. This is required because
                   timers will not expire until clock counters
                   will be read from the log. */
                qemu_notify_event();
            }
        }
        replay_mutex_unlock();
    }
}


static int decode_tile(J2kDecoderContext *s, J2kTile *tile)

{

    int compno, reslevelno, bandno;

    int x, y, *src[4];

    uint8_t *line;

    J2kT1Context t1;

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

        J2kComponent *comp = tile->comp + compno;

        J2kCodingStyle *codsty = tile->codsty + compno;

        for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++){

            J2kResLevel *rlevel = comp->reslevel + reslevelno;

            for (bandno = 0; bandno < rlevel->nbands; bandno++){

                J2kBand *band = rlevel->band + bandno;

                int cblkx, cblky, cblkno=0, xx0, x0, xx1, y0, yy0, yy1, bandpos;

                bandpos = bandno + (reslevelno > 0);

                yy0 = bandno == 0 ? 0 : comp->reslevel[reslevelno-1].coord[1][1] - comp->reslevel[reslevelno-1].coord[1][0];

                y0 = yy0;

                yy1 = FFMIN(ff_j2k_ceildiv(band->coord[1][0] + 1, band->codeblock_height) * band->codeblock_height,

                            band->coord[1][1]) - band->coord[1][0] + yy0;

                if (band->coord[0][0] == band->coord[0][1] || band->coord[1][0] == band->coord[1][1])

                    continue;

                for (cblky = 0; cblky < band->cblkny; cblky++){

                    if (reslevelno == 0 || bandno == 1)

                        xx0 = 0;

                    else

                        xx0 = comp->reslevel[reslevelno-1].coord[0][1] - comp->reslevel[reslevelno-1].coord[0][0];

                    x0 = xx0;

                    xx1 = FFMIN(ff_j2k_ceildiv(band->coord[0][0] + 1, band->codeblock_width) * band->codeblock_width,

                                band->coord[0][1]) - band->coord[0][0] + xx0;

                    for (cblkx = 0; cblkx < band->cblknx; cblkx++, cblkno++){

                        int y, x;

                        decode_cblk(s, codsty, &t1, band->cblk + cblkno, xx1 - xx0, yy1 - yy0, bandpos);

                        if (codsty->transform == FF_DWT53){

                            for (y = yy0; y < yy1; y+=s->cdy[compno]){

                                int *ptr = t1.data[y-yy0];

                                for (x = xx0; x < xx1; x+=s->cdx[compno]){

                                    comp->data[(comp->coord[0][1] - comp->coord[0][0]) * y + x] = *ptr++ >> 1;

                                }

                            }

                        } else{

                            for (y = yy0; y < yy1; y+=s->cdy[compno]){

                                int *ptr = t1.data[y-yy0];

                                for (x = xx0; x < xx1; x+=s->cdx[compno]){

                                    int tmp = ((int64_t)*ptr++) * ((int64_t)band->stepsize) >> 13, tmp2;

                                    tmp2 = FFABS(tmp>>1) + FFABS(tmp&1);

                                    comp->data[(comp->coord[0][1] - comp->coord[0][0]) * y + x] = tmp < 0 ? -tmp2 : tmp2;

                                }

                            }

                        }

                        xx0 = xx1;

                        xx1 = FFMIN(xx1 + band->codeblock_width, band->coord[0][1] - band->coord[0][0] + x0);

                    }

                    yy0 = yy1;

                    yy1 = FFMIN(yy1 + band->codeblock_height, band->coord[1][1] - band->coord[1][0] + y0);

                }

            }

        }

        ff_j2k_dwt_decode(&comp->dwt, comp->data);

        src[compno] = comp->data;

    }

    if (tile->codsty[0].mct)

        mct_decode(s, tile);

    if (s->avctx->pix_fmt == PIX_FMT_BGRA) // RGBA -> BGRA

        FFSWAP(int *, src[0], src[2]);

    if (s->precision <= 8) {

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

            y = tile->comp[compno].coord[1][0] - s->image_offset_y;

            line = s->picture.data[0] + y * s->picture.linesize[0];

            for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]){

                uint8_t *dst;

                x = tile->comp[compno].coord[0][0] - s->image_offset_x;

                dst = line + x * s->ncomponents + compno;

                for (; x < tile->comp[compno].coord[0][1] - s->image_offset_x; x += s->cdx[compno]) {

                    *src[compno] += 1 << (s->cbps[compno]-1);

                    if (*src[compno] < 0)

                        *src[compno] = 0;

                    else if (*src[compno] >= (1 << s->cbps[compno]))

                        *src[compno] = (1 << s->cbps[compno]) - 1;

                    *dst = *src[compno]++;

                    dst += s->ncomponents;

                }

                line += s->picture.linesize[0];

            }

        }

    } else {

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

            y = tile->comp[compno].coord[1][0] - s->image_offset_y;

            line = s->picture.data[0] + y * s->picture.linesize[0];

            for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {

                uint16_t *dst;

                x = tile->comp[compno].coord[0][0] - s->image_offset_x;

                dst = line + (x * s->ncomponents + compno) * 2;

                for (; x < tile->comp[compno].coord[0][1] - s->image_offset_x; x += s-> cdx[compno]) {

                    int32_t val;

                    val = *src[compno]++ << (16 - s->cbps[compno]);

                    val += 1 << 15;

                    val = av_clip(val, 0, (1 << 16) - 1);

                    *dst = val;

                    dst += s->ncomponents;

                }

                line += s->picture.linesize[0];

            }

        }

    }

    return 0;

}


void boot_sector_test(void)

{

    uint8_t signature_low;

    uint8_t signature_high;

    uint16_t signature;

    int i;

    /* Wait at most 90 seconds */

#define TEST_DELAY (1 * G_USEC_PER_SEC / 10)

#define TEST_CYCLES MAX((90 * G_USEC_PER_SEC / TEST_DELAY), 1)

    /* Poll until code has run and modified memory.  Once it has we know BIOS

     * initialization is done.  TODO: check that IP reached the halt

     * instruction.

     */

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

        signature_low = readb(BOOT_SECTOR_ADDRESS + SIGNATURE_OFFSET);

        signature_high = readb(BOOT_SECTOR_ADDRESS + SIGNATURE_OFFSET + 1);

        signature = (signature_high << 8) | signature_low;

        if (signature == SIGNATURE) {

            break;

        }

        g_usleep(TEST_DELAY);

    }

    g_assert_cmphex(signature, ==, SIGNATURE);

}


int scsi_req_parse_cdb(SCSIDevice *dev, SCSICommand *cmd, uint8_t *buf)

{

    int rc;

    cmd->lba = -1;

    cmd->len = scsi_cdb_length(buf);

    switch (dev->type) {

    case TYPE_TAPE:

        rc = scsi_req_stream_xfer(cmd, dev, buf);

        break;

    case TYPE_MEDIUM_CHANGER:

        rc = scsi_req_medium_changer_xfer(cmd, dev, buf);

        break;

    default:

        rc = scsi_req_xfer(cmd, dev, buf);

        break;

    }

    if (rc != 0)

        return rc;

    memcpy(cmd->buf, buf, cmd->len);

    scsi_cmd_xfer_mode(cmd);

    cmd->lba = scsi_cmd_lba(cmd);

    return 0;

}


static int graph_config_formats(AVFilterGraph *graph, AVClass *log_ctx)

{

    int ret;

    /* find supported formats from sub-filters, and merge along links */

    if ((ret = query_formats(graph, log_ctx)) < 0)

        return ret;

    /* Once everything is merged, it's possible that we'll still have

     * multiple valid media format choices. We try to minimize the amount

     * of format conversion inside filters */

    reduce_formats(graph);

    /* for audio filters, ensure the best format, sample rate and channel layout

     * is selected */

    swap_sample_fmts(graph);

    swap_samplerates(graph);

    swap_channel_layouts(graph);

    if ((ret = pick_formats(graph)) < 0)

        return ret;

    return 0;

}


void watchdog_perform_action(void)

{

    switch (watchdog_action) {

    case WDT_RESET:             /* same as 'system_reset' in monitor */

        qapi_event_send_watchdog(WATCHDOG_EXPIRATION_ACTION_RESET, &error_abort);

        qemu_system_reset_request();

        break;

    case WDT_SHUTDOWN:          /* same as 'system_powerdown' in monitor */

        qapi_event_send_watchdog(WATCHDOG_EXPIRATION_ACTION_SHUTDOWN, &error_abort);

        qemu_system_powerdown_request();

        break;

    case WDT_POWEROFF:          /* same as 'quit' command in monitor */

        qapi_event_send_watchdog(WATCHDOG_EXPIRATION_ACTION_POWEROFF, &error_abort);

        exit(0);

    case WDT_PAUSE:             /* same as 'stop' command in monitor */

        qapi_event_send_watchdog(WATCHDOG_EXPIRATION_ACTION_PAUSE, &error_abort);

        vm_stop(RUN_STATE_WATCHDOG);

        break;

    case WDT_DEBUG:

        qapi_event_send_watchdog(WATCHDOG_EXPIRATION_ACTION_DEBUG, &error_abort);

        fprintf(stderr, "watchdog: timer fired\n");

        break;

    case WDT_NONE:

        qapi_event_send_watchdog(WATCHDOG_EXPIRATION_ACTION_NONE, &error_abort);

        break;

    }

}