static av_cold int initFilter(int16_t **outFilter, int32_t **filterPos,

                              int *outFilterSize, int xInc, int srcW,

                              int dstW, int filterAlign, int one,

                              int flags, int cpu_flags,

                              SwsVector *srcFilter, SwsVector *dstFilter,

                              double param[2], int srcPos, int dstPos)

{

    int i;

    int filterSize;

    int filter2Size;

    int minFilterSize;

    int64_t *filter    = NULL;

    int64_t *filter2   = NULL;

    const int64_t fone = 1LL << (54 - FFMIN(av_log2(srcW/dstW), 8));

    int ret            = -1;

    emms_c(); // FIXME should not be required but IS (even for non-MMX versions)

    // NOTE: the +3 is for the MMX(+1) / SSE(+3) scaler which reads over the end

    FF_ALLOC_ARRAY_OR_GOTO(NULL, *filterPos, (dstW + 3), sizeof(**filterPos), fail);

    if (FFABS(xInc - 0x10000) < 10 && srcPos == dstPos) { // unscaled

        int i;

        filterSize = 1;

        FF_ALLOCZ_ARRAY_OR_GOTO(NULL, filter,

                                dstW, sizeof(*filter) * filterSize, fail);

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

            filter[i * filterSize] = fone;

            (*filterPos)[i]        = i;

        }

    } else if (flags & SWS_POINT) { // lame looking point sampling mode

        int i;

        int64_t xDstInSrc;

        filterSize = 1;

        FF_ALLOC_ARRAY_OR_GOTO(NULL, filter,

                               dstW, sizeof(*filter) * filterSize, fail);

        xDstInSrc = ((dstPos*(int64_t)xInc)>>8) - ((srcPos*0x8000LL)>>7);

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

            int xx = (xDstInSrc - ((filterSize - 1) << 15) + (1 << 15)) >> 16;

            (*filterPos)[i] = xx;

            filter[i]       = fone;

            xDstInSrc      += xInc;

        }

    } else if ((xInc <= (1 << 16) && (flags & SWS_AREA)) ||

               (flags & SWS_FAST_BILINEAR)) { // bilinear upscale

        int i;

        int64_t xDstInSrc;

        filterSize = 2;

        FF_ALLOC_ARRAY_OR_GOTO(NULL, filter,

                               dstW, sizeof(*filter) * filterSize, fail);

        xDstInSrc = ((dstPos*(int64_t)xInc)>>8) - ((srcPos*0x8000LL)>>7);

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

            int xx = (xDstInSrc - ((filterSize - 1) << 15) + (1 << 15)) >> 16;

            int j;

            (*filterPos)[i] = xx;

            // bilinear upscale / linear interpolate / area averaging

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

                int64_t coeff= fone - FFABS(((int64_t)xx<<16) - xDstInSrc)*(fone>>16);

                if (coeff < 0)

                    coeff = 0;

                filter[i * filterSize + j] = coeff;

                xx++;

            }

            xDstInSrc += xInc;

        }

    } else {

        int64_t xDstInSrc;

        int sizeFactor = -1;

        for (i = 0; i < FF_ARRAY_ELEMS(scale_algorithms); i++) {

            if (flags & scale_algorithms[i].flag && scale_algorithms[i].size_factor > 0) {

                sizeFactor = scale_algorithms[i].size_factor;

                break;

            }

        }

        if (flags & SWS_LANCZOS)

            sizeFactor = param[0] != SWS_PARAM_DEFAULT ? ceil(2 * param[0]) : 6;

        av_assert0(sizeFactor > 0);

        if (xInc <= 1 << 16)

            filterSize = 1 + sizeFactor;    // upscale

        else

            filterSize = 1 + (sizeFactor * srcW + dstW - 1) / dstW;

        filterSize = FFMIN(filterSize, srcW - 2);

        filterSize = FFMAX(filterSize, 1);

        FF_ALLOC_ARRAY_OR_GOTO(NULL, filter,

                               dstW, sizeof(*filter) * filterSize, fail);

        xDstInSrc = ((dstPos*(int64_t)xInc)>>7) - ((srcPos*0x10000LL)>>7);

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

            int xx = (xDstInSrc - ((int64_t)(filterSize - 2) << 16)) / (1 << 17);

            int j;

            (*filterPos)[i] = xx;

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

                int64_t d = (FFABS(((int64_t)xx << 17) - xDstInSrc)) << 13;

                double floatd;

                int64_t coeff;

                if (xInc > 1 << 16)

                    d = d * dstW / srcW;

                floatd = d * (1.0 / (1 << 30));

                if (flags & SWS_BICUBIC) {

                    int64_t B = (param[0] != SWS_PARAM_DEFAULT ? param[0] :   0) * (1 << 24);

                    int64_t C = (param[1] != SWS_PARAM_DEFAULT ? param[1] : 0.6) * (1 << 24);

                    if (d >= 1LL << 31) {

                        coeff = 0.0;

                    } else {

                        int64_t dd  = (d  * d) >> 30;

                        int64_t ddd = (dd * d) >> 30;

                        if (d < 1LL << 30)

                            coeff =  (12 * (1 << 24) -  9 * B - 6 * C) * ddd +

                                    (-18 * (1 << 24) + 12 * B + 6 * C) *  dd +

                                      (6 * (1 << 24) -  2 * B)         * (1 << 30);

                        else

                            coeff =      (-B -  6 * C) * ddd +

                                      (6 * B + 30 * C) * dd  +

                                    (-12 * B - 48 * C) * d   +

                                      (8 * B + 24 * C) * (1 << 30);

                    }

                    coeff /= (1LL<<54)/fone;

                }

#if 0

                else if (flags & SWS_X) {

                    double p  = param ? param * 0.01 : 0.3;

                    coeff     = d ? sin(d * M_PI) / (d * M_PI) : 1.0;

                    coeff    *= pow(2.0, -p * d * d);

                }

#endif

                else if (flags & SWS_X) {

                    double A = param[0] != SWS_PARAM_DEFAULT ? param[0] : 1.0;

                    double c;

                    if (floatd < 1.0)

                        c = cos(floatd * M_PI);

                    else

                        c = -1.0;

                    if (c < 0.0)

                        c = -pow(-c, A);

                    else

                        c = pow(c, A);

                    coeff = (c * 0.5 + 0.5) * fone;

                } else if (flags & SWS_AREA) {

                    int64_t d2 = d - (1 << 29);

                    if (d2 * xInc < -(1LL << (29 + 16)))

                        coeff = 1.0 * (1LL << (30 + 16));

                    else if (d2 * xInc < (1LL << (29 + 16)))

                        coeff = -d2 * xInc + (1LL << (29 + 16));

                    else

                        coeff = 0.0;

                    coeff *= fone >> (30 + 16);

                } else if (flags & SWS_GAUSS) {

                    double p = param[0] != SWS_PARAM_DEFAULT ? param[0] : 3.0;

                    coeff = (pow(2.0, -p * floatd * floatd)) * fone;

                } else if (flags & SWS_SINC) {

                    coeff = (d ? sin(floatd * M_PI) / (floatd * M_PI) : 1.0) * fone;

                } else if (flags & SWS_LANCZOS) {

                    double p = param[0] != SWS_PARAM_DEFAULT ? param[0] : 3.0;

                    coeff = (d ? sin(floatd * M_PI) * sin(floatd * M_PI / p) /

                             (floatd * floatd * M_PI * M_PI / p) : 1.0) * fone;

                    if (floatd > p)

                        coeff = 0;

                } else if (flags & SWS_BILINEAR) {

                    coeff = (1 << 30) - d;

                    if (coeff < 0)

                        coeff = 0;

                    coeff *= fone >> 30;

                } else if (flags & SWS_SPLINE) {

                    double p = -2.196152422706632;

                    coeff = getSplineCoeff(1.0, 0.0, p, -p - 1.0, floatd) * fone;

                } else {

                    av_assert0(0);

                }

                filter[i * filterSize + j] = coeff;

                xx++;

            }

            xDstInSrc += 2 * xInc;

        }

    }

    /* apply src & dst Filter to filter -> filter2

     * av_free(filter);

     */

    av_assert0(filterSize > 0);

    filter2Size = filterSize;

    if (srcFilter)

        filter2Size += srcFilter->length - 1;

    if (dstFilter)

        filter2Size += dstFilter->length - 1;

    av_assert0(filter2Size > 0);

    FF_ALLOCZ_ARRAY_OR_GOTO(NULL, filter2, dstW, filter2Size * sizeof(*filter2), fail);

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

        int j, k;

        if (srcFilter) {

            for (k = 0; k < srcFilter->length; k++) {

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

                    filter2[i * filter2Size + k + j] +=

                        srcFilter->coeff[k] * filter[i * filterSize + j];

            }

        } else {

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

                filter2[i * filter2Size + j] = filter[i * filterSize + j];

        }

        // FIXME dstFilter

        (*filterPos)[i] += (filterSize - 1) / 2 - (filter2Size - 1) / 2;

    }

    av_freep(&filter);

    /* try to reduce the filter-size (step1 find size and shift left) */

    // Assume it is near normalized (*0.5 or *2.0 is OK but * 0.001 is not).

    minFilterSize = 0;

    for (i = dstW - 1; i >= 0; i--) {

        int min = filter2Size;

        int j;

        int64_t cutOff = 0.0;

        /* get rid of near zero elements on the left by shifting left */

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

            int k;

            cutOff += FFABS(filter2[i * filter2Size]);

            if (cutOff > SWS_MAX_REDUCE_CUTOFF * fone)

                break;

            /* preserve monotonicity because the core can't handle the

             * filter otherwise */

            if (i < dstW - 1 && (*filterPos)[i] >= (*filterPos)[i + 1])

                break;

            // move filter coefficients left

            for (k = 1; k < filter2Size; k++)

                filter2[i * filter2Size + k - 1] = filter2[i * filter2Size + k];

            filter2[i * filter2Size + k - 1] = 0;

            (*filterPos)[i]++;

        }

        cutOff = 0;

        /* count near zeros on the right */

        for (j = filter2Size - 1; j > 0; j--) {

            cutOff += FFABS(filter2[i * filter2Size + j]);

            if (cutOff > SWS_MAX_REDUCE_CUTOFF * fone)

                break;

            min--;

        }

        if (min > minFilterSize)

            minFilterSize = min;

    }

    if (PPC_ALTIVEC(cpu_flags)) {

        // we can handle the special case 4, so we don't want to go the full 8

        if (minFilterSize < 5)

            filterAlign = 4;

        /* We really don't want to waste our time doing useless computation, so

         * fall back on the scalar C code for very small filters.

         * Vectorizing is worth it only if you have a decent-sized vector. */

        if (minFilterSize < 3)

            filterAlign = 1;

    }

    if (HAVE_MMX && cpu_flags & AV_CPU_FLAG_MMX) {

        // special case for unscaled vertical filtering

        if (minFilterSize == 1 && filterAlign == 2)

            filterAlign = 1;

    }

    av_assert0(minFilterSize > 0);

    filterSize = (minFilterSize + (filterAlign - 1)) & (~(filterAlign - 1));

    av_assert0(filterSize > 0);

    filter = av_malloc_array(dstW, filterSize * sizeof(*filter));

    if (!filter)

        goto fail;

    if (filterSize >= MAX_FILTER_SIZE * 16 /

                      ((flags & SWS_ACCURATE_RND) ? APCK_SIZE : 16)) {

        ret = RETCODE_USE_CASCADE;

        goto fail;

    }

    *outFilterSize = filterSize;

    if (flags & SWS_PRINT_INFO)

        av_log(NULL, AV_LOG_VERBOSE,

               "SwScaler: reducing / aligning filtersize %d -> %d\n",

               filter2Size, filterSize);

    /* try to reduce the filter-size (step2 reduce it) */

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

        int j;

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

            if (j >= filter2Size)

                filter[i * filterSize + j] = 0;

            else

                filter[i * filterSize + j] = filter2[i * filter2Size + j];

            if ((flags & SWS_BITEXACT) && j >= minFilterSize)

                filter[i * filterSize + j] = 0;

        }

    }

    // FIXME try to align filterPos if possible

    // fix borders

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

        int j;

        if ((*filterPos)[i] < 0) {

            // move filter coefficients left to compensate for filterPos

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

                int left = FFMAX(j + (*filterPos)[i], 0);

                filter[i * filterSize + left] += filter[i * filterSize + j];

                filter[i * filterSize + j]     = 0;

            }

            (*filterPos)[i]= 0;

        }

        if ((*filterPos)[i] + filterSize > srcW) {

            int shift = (*filterPos)[i] + FFMIN(filterSize - srcW, 0);

            // move filter coefficients right to compensate for filterPos

            for (j = filterSize - 2; j >= 0; j--) {

                int right = FFMIN(j + shift, filterSize - 1);

                filter[i * filterSize + right] += filter[i * filterSize + j];

                filter[i * filterSize + j]      = 0;

            }

            (*filterPos)[i]-= shift;

        }

    }

    // Note the +1 is for the MMX scaler which reads over the end

    /* align at 16 for AltiVec (needed by hScale_altivec_real) */

    FF_ALLOCZ_ARRAY_OR_GOTO(NULL, *outFilter,

                            (dstW + 3), *outFilterSize * sizeof(int16_t), fail);

    /* normalize & store in outFilter */

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

        int j;

        int64_t error = 0;

        int64_t sum   = 0;

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

            sum += filter[i * filterSize + j];

        }

        sum = (sum + one / 2) / one;

        if (!sum) {

            av_log(NULL, AV_LOG_WARNING, "SwScaler: zero vector in scaling\n");

            sum = 1;

        }

        for (j = 0; j < *outFilterSize; j++) {

            int64_t v = filter[i * filterSize + j] + error;

            int intV  = ROUNDED_DIV(v, sum);

            (*outFilter)[i * (*outFilterSize) + j] = intV;

            error                                  = v - intV * sum;

        }

    }

    (*filterPos)[dstW + 0] =

    (*filterPos)[dstW + 1] =

    (*filterPos)[dstW + 2] = (*filterPos)[dstW - 1]; /* the MMX/SSE scaler will

                                                      * read over the end */

    for (i = 0; i < *outFilterSize; i++) {

        int k = (dstW - 1) * (*outFilterSize) + i;

        (*outFilter)[k + 1 * (*outFilterSize)] =

        (*outFilter)[k + 2 * (*outFilterSize)] =

        (*outFilter)[k + 3 * (*outFilterSize)] = (*outFilter)[k];

    }

    ret = 0;

fail:

    if(ret < 0)

        av_log(NULL, ret == RETCODE_USE_CASCADE ? AV_LOG_DEBUG : AV_LOG_ERROR, "sws: initFilter failed\n");

    av_free(filter);

    av_free(filter2);

    return ret;

}


static av_cold int vorbis_encode_init(AVCodecContext *avccontext)

{

    vorbis_enc_context *venc = avccontext->priv_data;

    if (avccontext->channels != 2) {

        av_log(avccontext, AV_LOG_ERROR, "Current Libav Vorbis encoder only supports 2 channels.\n");

        return -1;

    }

    create_vorbis_context(venc, avccontext);

    if (avccontext->flags & CODEC_FLAG_QSCALE)

        venc->quality = avccontext->global_quality / (float)FF_QP2LAMBDA / 10.;

    else

        venc->quality = 0.03;

    venc->quality *= venc->quality;

    avccontext->extradata_size = put_main_header(venc, (uint8_t**)&avccontext->extradata);

    avccontext->frame_size     = 1 << (venc->log2_blocksize[0] - 1);

    avccontext->coded_frame            = avcodec_alloc_frame();

    avccontext->coded_frame->key_frame = 1;

    return 0;

}


struct omap_gp_timer_s *omap_gp_timer_init(struct omap_target_agent_s *ta,

                qemu_irq irq, omap_clk fclk, omap_clk iclk)

{

    struct omap_gp_timer_s *s = (struct omap_gp_timer_s *)

            g_malloc0(sizeof(struct omap_gp_timer_s));

    s->ta = ta;

    s->irq = irq;

    s->clk = fclk;

    s->timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, omap_gp_timer_tick, s);

    s->match = timer_new_ns(QEMU_CLOCK_VIRTUAL, omap_gp_timer_match, s);

    s->in = qemu_allocate_irq(omap_gp_timer_input, s, 0);

    omap_gp_timer_reset(s);

    omap_gp_timer_clk_setup(s);

    memory_region_init_io(&s->iomem, NULL, &omap_gp_timer_ops, s, "omap.gptimer",

                          omap_l4_region_size(ta, 0));

    omap_l4_attach(ta, 0, &s->iomem);

    return s;

}


ISADevice *isa_try_create(ISABus *bus, const char *name)

{

    DeviceState *dev;

    if (!bus) {

        hw_error("Tried to create isa device %s with no isa bus present.",

                 name);

    }

    dev = qdev_try_create(BUS(bus), name);

    return ISA_DEVICE(dev);

}


static int spapr_tce_table_realize(DeviceState *dev)

{

    sPAPRTCETable *tcet = SPAPR_TCE_TABLE(dev);

    if (kvm_enabled()) {

        tcet->table = kvmppc_create_spapr_tce(tcet->liobn,

                                              tcet->nb_table <<

                                              tcet->page_shift,

                                              &tcet->fd,

                                              tcet->vfio_accel);

    }

    if (!tcet->table) {

        size_t table_size = tcet->nb_table * sizeof(uint64_t);

        tcet->table = g_malloc0(table_size);

    }

    trace_spapr_iommu_new_table(tcet->liobn, tcet, tcet->table, tcet->fd);

    memory_region_init_iommu(&tcet->iommu, OBJECT(dev), &spapr_iommu_ops,

                             "iommu-spapr",

                             (uint64_t)tcet->nb_table << tcet->page_shift);

    QLIST_INSERT_HEAD(&spapr_tce_tables, tcet, list);

    vmstate_register(DEVICE(tcet), tcet->liobn, &vmstate_spapr_tce_table,

                     tcet);

    return 0;

}


static bool get_phys_addr_pmsav7(CPUARMState *env, uint32_t address,

                                 MMUAccessType access_type, ARMMMUIdx mmu_idx,

                                 hwaddr *phys_ptr, int *prot,

                                 ARMMMUFaultInfo *fi)

{

    ARMCPU *cpu = arm_env_get_cpu(env);

    int n;

    bool is_user = regime_is_user(env, mmu_idx);

    *phys_ptr = address;

    *prot = 0;

    if (regime_translation_disabled(env, mmu_idx) ||

        m_is_ppb_region(env, address)) {

        /* MPU disabled or M profile PPB access: use default memory map.

         * The other case which uses the default memory map in the

         * v7M ARM ARM pseudocode is exception vector reads from the vector

         * table. In QEMU those accesses are done in arm_v7m_load_vector(),

         * which always does a direct read using address_space_ldl(), rather

         * than going via this function, so we don't need to check that here.

         */

        get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);

    } else { /* MPU enabled */

        for (n = (int)cpu->pmsav7_dregion - 1; n >= 0; n--) {

            /* region search */

            uint32_t base = env->pmsav7.drbar[n];

            uint32_t rsize = extract32(env->pmsav7.drsr[n], 1, 5);

            uint32_t rmask;

            bool srdis = false;

            if (!(env->pmsav7.drsr[n] & 0x1)) {

                continue;

            if (!rsize) {

                qemu_log_mask(LOG_GUEST_ERROR,

                              "DRSR[%d]: Rsize field cannot be 0\n", n);

                continue;

            rsize++;

            rmask = (1ull << rsize) - 1;

            if (base & rmask) {

                qemu_log_mask(LOG_GUEST_ERROR,

                              "DRBAR[%d]: 0x%" PRIx32 " misaligned "

                              "to DRSR region size, mask = 0x%" PRIx32 "\n",

                              n, base, rmask);

                continue;

            if (address < base || address > base + rmask) {

                continue;

            /* Region matched */

            if (rsize >= 8) { /* no subregions for regions < 256 bytes */

                int i, snd;

                uint32_t srdis_mask;

                rsize -= 3; /* sub region size (power of 2) */

                snd = ((address - base) >> rsize) & 0x7;

                srdis = extract32(env->pmsav7.drsr[n], snd + 8, 1);

                srdis_mask = srdis ? 0x3 : 0x0;

                for (i = 2; i <= 8 && rsize < TARGET_PAGE_BITS; i *= 2) {

                    /* This will check in groups of 2, 4 and then 8, whether

                     * the subregion bits are consistent. rsize is incremented

                     * back up to give the region size, considering consistent

                     * adjacent subregions as one region. Stop testing if rsize

                     * is already big enough for an entire QEMU page.

                     */

                    int snd_rounded = snd & ~(i - 1);

                    uint32_t srdis_multi = extract32(env->pmsav7.drsr[n],

                                                     snd_rounded + 8, i);

                    if (srdis_mask ^ srdis_multi) {

                    srdis_mask = (srdis_mask << i) | srdis_mask;

                    rsize++;

            if (rsize < TARGET_PAGE_BITS) {

                qemu_log_mask(LOG_UNIMP,

                              "DRSR[%d]: No support for MPU (sub)region "

                              "alignment of %" PRIu32 " bits. Minimum is %d\n",

                              n, rsize, TARGET_PAGE_BITS);

                continue;

            if (srdis) {

                continue;

        if (n == -1) { /* no hits */

            if (!pmsav7_use_background_region(cpu, mmu_idx, is_user)) {

                /* background fault */

                fi->type = ARMFault_Background;

                return true;

            get_phys_addr_pmsav7_default(env, mmu_idx, address, prot);

        } else { /* a MPU hit! */

            uint32_t ap = extract32(env->pmsav7.dracr[n], 8, 3);

            uint32_t xn = extract32(env->pmsav7.dracr[n], 12, 1);

            if (m_is_system_region(env, address)) {

                /* System space is always execute never */

                xn = 1;

            if (is_user) { /* User mode AP bit decoding */

                switch (ap) {

                case 0:

                case 1:

                case 5:

                    break; /* no access */

                case 3:

                    *prot |= PAGE_WRITE;

                case 2:

                case 6:

                default:

                    qemu_log_mask(LOG_GUEST_ERROR,

                                  "DRACR[%d]: Bad value for AP bits: 0x%"

                                  PRIx32 "\n", n, ap);

            } else { /* Priv. mode AP bits decoding */

                switch (ap) {

                case 0:

                    break; /* no access */

                case 1:

                case 2:

                case 3:

                    *prot |= PAGE_WRITE;

                case 5:

                case 6:

                default:

                    qemu_log_mask(LOG_GUEST_ERROR,

                                  "DRACR[%d]: Bad value for AP bits: 0x%"

                                  PRIx32 "\n", n, ap);

            /* execute never */

            if (xn) {

                *prot &= ~PAGE_EXEC;

    fi->type = ARMFault_Permission;

    fi->level = 1;

    return !(*prot & (1 << access_type));


bool address_space_access_valid(AddressSpace *as, hwaddr addr, int len, bool is_write)

{

    MemoryRegion *mr;

    hwaddr l, xlat;

    rcu_read_lock();

    while (len > 0) {

        l = len;

        mr = address_space_translate(as, addr, &xlat, &l, is_write);

        if (!memory_access_is_direct(mr, is_write)) {

            l = memory_access_size(mr, l, addr);

            if (!memory_region_access_valid(mr, xlat, l, is_write)) {

                return false;

            }

        }

        len -= l;

        addr += l;

    }

    return true;

}


static int restore_sigcontext(CPUAlphaState *env,

                              struct target_sigcontext *sc)

{

    uint64_t fpcr;

    int i, err = 0;

    __get_user(env->pc, &sc->sc_pc);

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

        __get_user(env->ir[i], &sc->sc_regs[i]);

    }

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

        __get_user(env->fir[i], &sc->sc_fpregs[i]);

    }

    __get_user(fpcr, &sc->sc_fpcr);

    cpu_alpha_store_fpcr(env, fpcr);

    return err;

}


static void qxl_realize_secondary(PCIDevice *dev, Error **errp)

{

    static int device_id = 1;

    PCIQXLDevice *qxl = PCI_QXL(dev);

    qxl->id = device_id++;

    qxl_init_ramsize(qxl);

    memory_region_init_ram(&qxl->vga.vram, OBJECT(dev), "qxl.vgavram",

                           qxl->vga.vram_size, &error_abort);

    vmstate_register_ram(&qxl->vga.vram, &qxl->pci.qdev);

    qxl->vga.vram_ptr = memory_region_get_ram_ptr(&qxl->vga.vram);

    qxl->vga.con = graphic_console_init(DEVICE(dev), 0, &qxl_ops, qxl);

    qxl_realize_common(qxl, errp);

}


static const unsigned char *seq_decode_op1(SeqVideoContext *seq, const unsigned char *src, unsigned char *dst)

{

    const unsigned char *color_table;

    int b, i, len, bits;

    GetBitContext gb;

    unsigned char block[8 * 8];

    len = *src++;

    if (len & 0x80) {

        switch (len & 3) {

        case 1:

            src = seq_unpack_rle_block(src, block, sizeof(block));

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

                memcpy(dst, &block[b * 8], 8);

                dst += seq->frame.linesize[0];

            }

            break;

        case 2:

            src = seq_unpack_rle_block(src, block, sizeof(block));

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

                for (b = 0; b < 8; b++)

                    dst[b * seq->frame.linesize[0]] = block[i * 8 + b];

                ++dst;

            }

            break;

        }

    } else {

        color_table = src;

        src += len;

        bits = ff_log2_tab[len - 1] + 1;

        init_get_bits(&gb, src, bits * 8 * 8); src += bits * 8;

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

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

                dst[i] = color_table[get_bits(&gb, bits)];

            dst += seq->frame.linesize[0];

        }

    }

    return src;

}


static void qed_commit_l2_update(void *opaque, int ret)

{

    QEDAIOCB *acb = opaque;

    BDRVQEDState *s = acb_to_s(acb);

    CachedL2Table *l2_table = acb->request.l2_table;

    qed_commit_l2_cache_entry(&s->l2_cache, l2_table);

    /* This is guaranteed to succeed because we just committed the entry to the

     * cache.

     */

    acb->request.l2_table = qed_find_l2_cache_entry(&s->l2_cache,

                                                    l2_table->offset);

    assert(acb->request.l2_table != NULL);

    qed_aio_next_io(opaque, ret);

}


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

{

    PCIDevice *pci_dev = PCI_DEVICE(dev);

    PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);

    pci_unregister_io_regions(pci_dev);

    pci_del_option_rom(pci_dev);

    if (pc->exit) {

        pc->exit(pci_dev);

    }

    do_pci_unregister_device(pci_dev);

}


static int start_frame(AVFilterLink *link, AVFilterBufferRef *picref)

{

    SliceContext *slice = link->dst->priv;

    if (slice->use_random_h) {

        slice->lcg_state = slice->lcg_state * 1664525 + 1013904223;

        slice->h = 8 + (uint64_t)slice->lcg_state * 25 / UINT32_MAX;

    }

    /* ensure that slices play nice with chroma subsampling, and enforce

     * a reasonable minimum size for the slices */

    slice->h = FFMAX(8, slice->h & (-1 << slice->vshift));

    av_log(link->dst, AV_LOG_DEBUG, "h:%d\n", slice->h);

    link->cur_buf = NULL;

    return ff_start_frame(link->dst->outputs[0], picref);

}


static void virtio_balloon_save(QEMUFile *f, void *opaque)

{

    VirtIOBalloon *s = opaque;

    virtio_save(&s->vdev, f);

    qemu_put_be32(f, s->num_pages);

    qemu_put_be32(f, s->actual);

    qemu_put_buffer(f, (uint8_t *)&s->stats_vq_elem, sizeof(VirtQueueElement));

    qemu_put_buffer(f, (uint8_t *)&s->stats_vq_offset, sizeof(size_t));

    qemu_put_buffer(f, (uint8_t *)&s->stats_callback, sizeof(MonitorCompletion));

    qemu_put_buffer(f, (uint8_t *)&s->stats_opaque_callback_data, sizeof(void));

}


static int inject_error(BlockDriverState *bs, BlkdebugRule *rule)

{

    BDRVBlkdebugState *s = bs->opaque;

    int error = rule->options.inject.error;

    bool immediately = rule->options.inject.immediately;

    if (rule->options.inject.once) {

        QSIMPLEQ_REMOVE(&s->active_rules, rule, BlkdebugRule, active_next);

        remove_rule(rule);

    }

    if (!immediately) {

        aio_bh_schedule_oneshot(bdrv_get_aio_context(bs), error_callback_bh,

                                qemu_coroutine_self());

        qemu_coroutine_yield();

    }

    return -error;

}


static void output_segment_list(OutputStream *os, AVIOContext *out, DASHContext *c,

                                int representation_id, int final)

{

    int i, start_index = 0, start_number = 1;

    if (c->window_size) {

        start_index  = FFMAX(os->nb_segments   - c->window_size, 0);

        start_number = FFMAX(os->segment_index - c->window_size, 1);

    }

    if (c->use_template) {

        int timescale = c->use_timeline ? os->ctx->streams[0]->time_base.den : AV_TIME_BASE;

        avio_printf(out, "\t\t\t\t<SegmentTemplate timescale=\"%d\" ", timescale);

        if (!c->use_timeline)

            avio_printf(out, "duration=\"%"PRId64"\" ", c->last_duration);

        avio_printf(out, "initialization=\"%s\" media=\"%s\" startNumber=\"%d\">\n", c->init_seg_name, c->media_seg_name, c->use_timeline ? start_number : 1);

        if (c->use_timeline) {

            int64_t cur_time = 0;

            avio_printf(out, "\t\t\t\t\t<SegmentTimeline>\n");

            for (i = start_index; i < os->nb_segments; ) {

                Segment *seg = os->segments[i];

                int repeat = 0;

                avio_printf(out, "\t\t\t\t\t\t<S ");

                if (i == start_index || seg->time != cur_time) {

                    cur_time = seg->time;

                    avio_printf(out, "t=\"%"PRId64"\" ", seg->time);

                }

                avio_printf(out, "d=\"%d\" ", seg->duration);

                while (i + repeat + 1 < os->nb_segments &&

                       os->segments[i + repeat + 1]->duration == seg->duration &&

                       os->segments[i + repeat + 1]->time == os->segments[i + repeat]->time + os->segments[i + repeat]->duration)

                    repeat++;

                if (repeat > 0)

                    avio_printf(out, "r=\"%d\" ", repeat);

                avio_printf(out, "/>\n");

                i += 1 + repeat;

                cur_time += (1 + repeat) * seg->duration;

            }

            avio_printf(out, "\t\t\t\t\t</SegmentTimeline>\n");

        }

        avio_printf(out, "\t\t\t\t</SegmentTemplate>\n");

    } else if (c->single_file) {

        avio_printf(out, "\t\t\t\t<BaseURL>%s</BaseURL>\n", os->initfile);

        avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);

        avio_printf(out, "\t\t\t\t\t<Initialization range=\"%"PRId64"-%"PRId64"\" />\n", os->init_start_pos, os->init_start_pos + os->init_range_length - 1);

        for (i = start_index; i < os->nb_segments; i++) {

            Segment *seg = os->segments[i];

            avio_printf(out, "\t\t\t\t\t<SegmentURL mediaRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->range_length - 1);

            if (seg->index_length)

                avio_printf(out, "indexRange=\"%"PRId64"-%"PRId64"\" ", seg->start_pos, seg->start_pos + seg->index_length - 1);

            avio_printf(out, "/>\n");

        }

        avio_printf(out, "\t\t\t\t</SegmentList>\n");

    } else {

        avio_printf(out, "\t\t\t\t<SegmentList timescale=\"%d\" duration=\"%"PRId64"\" startNumber=\"%d\">\n", AV_TIME_BASE, c->last_duration, start_number);

        avio_printf(out, "\t\t\t\t\t<Initialization sourceURL=\"%s\" />\n", os->initfile);

        for (i = start_index; i < os->nb_segments; i++) {

            Segment *seg = os->segments[i];

            avio_printf(out, "\t\t\t\t\t<SegmentURL media=\"%s\" />\n", seg->file);

        }

        avio_printf(out, "\t\t\t\t</SegmentList>\n");

    }

    if (c->hls_playlist && start_index < os->nb_segments)

    {

        int timescale = os->ctx->streams[0]->time_base.den;

        char temp_filename_hls[1024];

        char filename_hls[1024];

        AVIOContext *out_hls = NULL;

        AVDictionary *http_opts = NULL;

        int target_duration = 0;

        int ret = 0;

        const char *proto = avio_find_protocol_name(c->dirname);

        int use_rename = proto && !strcmp(proto, "file");

        get_hls_playlist_name(filename_hls, sizeof(filename_hls),

                              c->dirname, representation_id);

        snprintf(temp_filename_hls, sizeof(temp_filename_hls), use_rename ? "%s.tmp" : "%s", filename_hls);

        set_http_options(&http_opts, c);

        avio_open2(&out_hls, temp_filename_hls, AVIO_FLAG_WRITE, NULL, &http_opts);

        av_dict_free(&http_opts);

        for (i = start_index; i < os->nb_segments; i++) {

            Segment *seg = os->segments[i];

            double duration = (double) seg->duration / timescale;

            if (target_duration <= duration)

                target_duration = hls_get_int_from_double(duration);

        }

        ff_hls_write_playlist_header(out_hls, 6, -1, target_duration,

                                     start_number, PLAYLIST_TYPE_NONE);

        ff_hls_write_init_file(out_hls, os->initfile, c->single_file,

                               os->init_range_length, os->init_start_pos);

        for (i = start_index; i < os->nb_segments; i++) {

            Segment *seg = os->segments[i];

            ret = ff_hls_write_file_entry(out_hls, 0, c->single_file,

                                    (double) seg->duration / timescale, 0,

                                    seg->range_length, seg->start_pos, NULL,

                                    c->single_file ? os->initfile : seg->file,

                                    NULL);

            if (ret < 0) {

                av_log(os->ctx, AV_LOG_WARNING, "ff_hls_write_file_entry get error\n");

            }

        }

        if (final)

            ff_hls_write_end_list(out_hls);

        avio_close(out_hls);

        if (use_rename)

            avpriv_io_move(temp_filename_hls, filename_hls);

    }

}


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

                            AVPacket *avpkt) {

    const uint8_t *buf = avpkt->data;

    const uint8_t *buf_end = avpkt->data + avpkt->size;

    PTXContext * const s = avctx->priv_data;

    AVFrame *picture = data;

    AVFrame * const p = &s->picture;

    unsigned int offset, w, h, y, stride, bytes_per_pixel;

    uint8_t *ptr;

    if (buf_end - buf < 14)

        return AVERROR_INVALIDDATA;

    offset          = AV_RL16(buf);

    w               = AV_RL16(buf+8);

    h               = AV_RL16(buf+10);

    bytes_per_pixel = AV_RL16(buf+12) >> 3;

    if (bytes_per_pixel != 2) {

        av_log_ask_for_sample(avctx, "Image format is not RGB15.\n");

        return -1;

    }

    avctx->pix_fmt = PIX_FMT_RGB555;

    if (buf_end - buf < offset)

        return AVERROR_INVALIDDATA;

    if (offset != 0x2c)

        av_log_ask_for_sample(avctx, "offset != 0x2c\n");

    buf += offset;

    if (p->data[0])

        avctx->release_buffer(avctx, p);

    if (av_image_check_size(w, h, 0, avctx))

        return -1;

    if (w != avctx->width || h != avctx->height)

        avcodec_set_dimensions(avctx, w, h);

    if (avctx->get_buffer(avctx, p) < 0) {

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

        return -1;

    }

    p->pict_type = AV_PICTURE_TYPE_I;

    ptr    = p->data[0];

    stride = p->linesize[0];

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

        if (buf_end - buf < w * bytes_per_pixel)

            break;

#if HAVE_BIGENDIAN

        unsigned int x;

        for (x=0; x<w*bytes_per_pixel; x+=bytes_per_pixel)

            AV_WN16(ptr+x, AV_RL16(buf+x));

#else

        memcpy(ptr, buf, w*bytes_per_pixel);

#endif

        ptr += stride;

        buf += w*bytes_per_pixel;

    }

    *picture = s->picture;

    *data_size = sizeof(AVPicture);

    return offset + w*h*bytes_per_pixel;

}


static int alloc_sequence_buffers(DiracContext *s)

{

    int sbwidth  = DIVRNDUP(s->source.width,  4);

    int sbheight = DIVRNDUP(s->source.height, 4);

    int i, w, h, top_padding;

    /* todo: think more about this / use or set Plane here */

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

        int max_xblen = MAX_BLOCKSIZE >> (i ? s->chroma_x_shift : 0);

        int max_yblen = MAX_BLOCKSIZE >> (i ? s->chroma_y_shift : 0);

        w = s->source.width  >> (i ? s->chroma_x_shift : 0);

        h = s->source.height >> (i ? s->chroma_y_shift : 0);

        /* we allocate the max we support here since num decompositions can

         * change from frame to frame. Stride is aligned to 16 for SIMD, and

         * 1<<MAX_DWT_LEVELS top padding to avoid if(y>0) in arith decoding

         * MAX_BLOCKSIZE padding for MC: blocks can spill up to half of that

         * on each side */

        top_padding = FFMAX(1<<MAX_DWT_LEVELS, max_yblen/2);

        w = FFALIGN(CALC_PADDING(w, MAX_DWT_LEVELS), 8); /* FIXME: Should this be 16 for SSE??? */

        h = top_padding + CALC_PADDING(h, MAX_DWT_LEVELS) + max_yblen/2;

        s->plane[i].idwt_buf_base = av_mallocz_array((w+max_xblen), h * sizeof(IDWTELEM));

        s->plane[i].idwt_tmp      = av_malloc_array((w+16), sizeof(IDWTELEM));

        s->plane[i].idwt_buf      = s->plane[i].idwt_buf_base + top_padding*w;

        if (!s->plane[i].idwt_buf_base || !s->plane[i].idwt_tmp)

            return AVERROR(ENOMEM);

    }

    w = s->source.width;

    h = s->source.height;

    /* fixme: allocate using real stride here */

    s->sbsplit  = av_malloc_array(sbwidth, sbheight);

    s->blmotion = av_malloc_array(sbwidth, sbheight * 16 * sizeof(*s->blmotion));

    s->edge_emu_buffer_base = av_malloc_array((w+64), MAX_BLOCKSIZE);

    s->mctmp     = av_malloc_array((w+64+MAX_BLOCKSIZE), (h+MAX_BLOCKSIZE) * sizeof(*s->mctmp));

    s->mcscratch = av_malloc_array((w+64), MAX_BLOCKSIZE);

    if (!s->sbsplit || !s->blmotion || !s->mctmp || !s->mcscratch)

        return AVERROR(ENOMEM);

    return 0;

}


static av_cold int vpx_init(AVCodecContext *avctx,

                            const struct vpx_codec_iface *iface)

{

    VP8Context *ctx = avctx->priv_data;

    struct vpx_codec_enc_cfg enccfg = { 0 };

    int res;

    av_log(avctx, AV_LOG_INFO, "%s\n", vpx_codec_version_str());

    av_log(avctx, AV_LOG_VERBOSE, "%s\n", vpx_codec_build_config());

    if ((res = vpx_codec_enc_config_default(iface, &enccfg, 0)) != VPX_CODEC_OK) {

        av_log(avctx, AV_LOG_ERROR, "Failed to get config: %s\n",

               vpx_codec_err_to_string(res));

        return AVERROR(EINVAL);

    }

    dump_enc_cfg(avctx, &enccfg);

    enccfg.g_w            = avctx->width;

    enccfg.g_h            = avctx->height;

    enccfg.g_timebase.num = avctx->time_base.num;

    enccfg.g_timebase.den = avctx->time_base.den;

    enccfg.g_threads      = avctx->thread_count;

    if (ctx->lag_in_frames >= 0)

        enccfg.g_lag_in_frames = ctx->lag_in_frames;

    if (avctx->flags & CODEC_FLAG_PASS1)

        enccfg.g_pass = VPX_RC_FIRST_PASS;

    else if (avctx->flags & CODEC_FLAG_PASS2)

        enccfg.g_pass = VPX_RC_LAST_PASS;

    else

        enccfg.g_pass = VPX_RC_ONE_PASS;

    if (!avctx->bit_rate)

        avctx->bit_rate = enccfg.rc_target_bitrate * 1000;

    else

        enccfg.rc_target_bitrate = av_rescale_rnd(avctx->bit_rate, 1, 1000,

                                              AV_ROUND_NEAR_INF);

    if (ctx->crf)

        enccfg.rc_end_usage = VPX_CQ;

    else if (avctx->rc_min_rate == avctx->rc_max_rate &&

             avctx->rc_min_rate == avctx->bit_rate)

        enccfg.rc_end_usage = VPX_CBR;

    if (avctx->qmin > 0)

        enccfg.rc_min_quantizer = avctx->qmin;

    if (avctx->qmax > 0)

        enccfg.rc_max_quantizer = avctx->qmax;

    enccfg.rc_dropframe_thresh = avctx->frame_skip_threshold;

    //0-100 (0 => CBR, 100 => VBR)

    enccfg.rc_2pass_vbr_bias_pct           = round(avctx->qcompress * 100);

    enccfg.rc_2pass_vbr_minsection_pct     =

        avctx->rc_min_rate * 100LL / avctx->bit_rate;

    if (avctx->rc_max_rate)

        enccfg.rc_2pass_vbr_maxsection_pct =

            avctx->rc_max_rate * 100LL / avctx->bit_rate;

    if (avctx->rc_buffer_size)

        enccfg.rc_buf_sz         =

            avctx->rc_buffer_size * 1000LL / avctx->bit_rate;

    if (avctx->rc_initial_buffer_occupancy)

        enccfg.rc_buf_initial_sz =

            avctx->rc_initial_buffer_occupancy * 1000LL / avctx->bit_rate;

    enccfg.rc_buf_optimal_sz     = enccfg.rc_buf_sz * 5 / 6;

    //_enc_init() will balk if kf_min_dist differs from max w/VPX_KF_AUTO

    if (avctx->keyint_min >= 0 && avctx->keyint_min == avctx->gop_size)

        enccfg.kf_min_dist = avctx->keyint_min;

    if (avctx->gop_size >= 0)

        enccfg.kf_max_dist = avctx->gop_size;

    if (enccfg.g_pass == VPX_RC_FIRST_PASS)

        enccfg.g_lag_in_frames = 0;

    else if (enccfg.g_pass == VPX_RC_LAST_PASS) {

        int decode_size, ret;

        if (!avctx->stats_in) {

            av_log(avctx, AV_LOG_ERROR, "No stats file for second pass\n");

            return AVERROR_INVALIDDATA;

        }

        ctx->twopass_stats.sz  = strlen(avctx->stats_in) * 3 / 4;

        ret = av_reallocp(&ctx->twopass_stats.buf, ctx->twopass_stats.sz);

        if (ret < 0) {

            av_log(avctx, AV_LOG_ERROR,

                   "Stat buffer alloc (%zu bytes) failed\n",

                   ctx->twopass_stats.sz);

            return ret;

        }

        decode_size = av_base64_decode(ctx->twopass_stats.buf, avctx->stats_in,

                                       ctx->twopass_stats.sz);

        if (decode_size < 0) {

            av_log(avctx, AV_LOG_ERROR, "Stat buffer decode failed\n");

            return AVERROR_INVALIDDATA;

        }

        ctx->twopass_stats.sz      = decode_size;

        enccfg.rc_twopass_stats_in = ctx->twopass_stats;

    }

    /* 0-3: For non-zero values the encoder increasingly optimizes for reduced

       complexity playback on low powered devices at the expense of encode

       quality. */

    if (avctx->profile != FF_PROFILE_UNKNOWN)

        enccfg.g_profile = avctx->profile;

    else if (avctx->pix_fmt == AV_PIX_FMT_YUV420P)

        avctx->profile = enccfg.g_profile = FF_PROFILE_VP9_0;

    else

        avctx->profile = enccfg.g_profile = FF_PROFILE_VP9_1;

    enccfg.g_error_resilient = ctx->error_resilient;

    dump_enc_cfg(avctx, &enccfg);

    /* Construct Encoder Context */

    res = vpx_codec_enc_init(&ctx->encoder, iface, &enccfg, 0);

    if (res != VPX_CODEC_OK) {

        log_encoder_error(avctx, "Failed to initialize encoder");

        return AVERROR(EINVAL);

    }

    //codec control failures are currently treated only as warnings

    av_log(avctx, AV_LOG_DEBUG, "vpx_codec_control\n");

    if (ctx->cpu_used != INT_MIN)

        codecctl_int(avctx, VP8E_SET_CPUUSED,          ctx->cpu_used);

    if (ctx->auto_alt_ref >= 0)

        codecctl_int(avctx, VP8E_SET_ENABLEAUTOALTREF, ctx->auto_alt_ref);

    if (ctx->arnr_max_frames >= 0)

        codecctl_int(avctx, VP8E_SET_ARNR_MAXFRAMES,   ctx->arnr_max_frames);

    if (ctx->arnr_strength >= 0)

        codecctl_int(avctx, VP8E_SET_ARNR_STRENGTH,    ctx->arnr_strength);

    if (ctx->arnr_type >= 0)

        codecctl_int(avctx, VP8E_SET_ARNR_TYPE,        ctx->arnr_type);

    if (CONFIG_LIBVPX_VP8_ENCODER && iface == &vpx_codec_vp8_cx_algo) {

        codecctl_int(avctx, VP8E_SET_NOISE_SENSITIVITY, avctx->noise_reduction);

        codecctl_int(avctx, VP8E_SET_TOKEN_PARTITIONS,  av_log2(avctx->slices));

    }

#if FF_API_MPV_OPT

    FF_DISABLE_DEPRECATION_WARNINGS

    if (avctx->mb_threshold) {

        av_log(avctx, AV_LOG_WARNING, "The mb_threshold option is deprecated, "

               "use the static-thresh private option instead.\n");

        ctx->static_thresh = avctx->mb_threshold;

    }

    FF_ENABLE_DEPRECATION_WARNINGS

#endif

    codecctl_int(avctx, VP8E_SET_STATIC_THRESHOLD,  ctx->static_thresh);

    codecctl_int(avctx, VP8E_SET_CQ_LEVEL,          ctx->crf);

    //provide dummy value to initialize wrapper, values will be updated each _encode()

    vpx_img_wrap(&ctx->rawimg, ff_vpx_pixfmt_to_imgfmt(avctx->pix_fmt),

                 avctx->width, avctx->height, 1, (unsigned char *)1);

    avctx->coded_frame = av_frame_alloc();

    if (!avctx->coded_frame) {

        av_log(avctx, AV_LOG_ERROR, "Error allocating coded frame\n");

        vp8_free(avctx);

        return AVERROR(ENOMEM);

    }

    return 0;

}


static int virtio_pci_start_ioeventfd(VirtIOPCIProxy *proxy)

{

    int n, r;

    if (!(proxy->flags & VIRTIO_PCI_FLAG_USE_IOEVENTFD) ||

        proxy->ioeventfd_disabled ||

        proxy->ioeventfd_started) {

        return 0;

    }

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

        if (!virtio_queue_get_num(proxy->vdev, n)) {

            continue;

        }

        r = virtio_pci_set_host_notifier_internal(proxy, n, true);

        if (r < 0) {

            goto assign_error;

        }

        virtio_pci_set_host_notifier_fd_handler(proxy, n, true);

    }

    proxy->ioeventfd_started = true;

    return 0;

assign_error:

    while (--n >= 0) {

        if (!virtio_queue_get_num(proxy->vdev, n)) {

            continue;

        }

        virtio_pci_set_host_notifier_fd_handler(proxy, n, false);

        virtio_pci_set_host_notifier_internal(proxy, n, false);

    }

    proxy->ioeventfd_started = false;

    proxy->ioeventfd_disabled = true;

    return r;

}


static void block_set_params(const MigrationParams *params, void *opaque)

{

    block_mig_state.blk_enable = params->blk;

    block_mig_state.shared_base = params->shared;

    /* shared base means that blk_enable = 1 */

    block_mig_state.blk_enable |= params->shared;

}


static void show_packets(WriterContext *w, AVFormatContext *fmt_ctx)

{

    AVPacket pkt;

    AVFrame frame;

    int i = 0;

    av_init_packet(&pkt);

    while (!av_read_frame(fmt_ctx, &pkt)) {

        if (do_show_packets)

            show_packet(w, fmt_ctx, &pkt, i++);

        if (do_show_frames &&

            get_video_frame(fmt_ctx, &frame, &pkt)) {

            show_frame(w, &frame, fmt_ctx->streams[pkt.stream_index]);

            av_destruct_packet(&pkt);

        }

    }

    av_init_packet(&pkt);

    pkt.data = NULL;

    pkt.size = 0;

    //Flush remaining frames that are cached in the decoder

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

        pkt.stream_index = i;

        while (get_video_frame(fmt_ctx, &frame, &pkt))

            show_frame(w, &frame, fmt_ctx->streams[pkt.stream_index]);

    }

}


static void bios_supports_mode(const char *pmutils_bin, const char *pmutils_arg,

                               const char *sysfile_str, Error **err)

{

    pid_t pid;

    ssize_t ret;

    char *pmutils_path;

    int status, pipefds[2];

    if (pipe(pipefds) < 0) {

        error_set(err, QERR_UNDEFINED_ERROR);

        return;

    }

    pmutils_path = g_find_program_in_path(pmutils_bin);

    pid = fork();

    if (!pid) {

        struct sigaction act;

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

        act.sa_handler = SIG_DFL;

        sigaction(SIGCHLD, &act, NULL);

        setsid();

        close(pipefds[0]);

        reopen_fd_to_null(0);

        reopen_fd_to_null(1);

        reopen_fd_to_null(2);

        pid = fork();

        if (!pid) {

            int fd;

            char buf[32]; /* hopefully big enough */

            if (pmutils_path) {

                execle(pmutils_path, pmutils_bin, pmutils_arg, NULL, environ);

            }

            /*

             * If we get here either pm-utils is not installed or execle() has

             * failed. Let's try the manual method if the caller wants it.

             */

            if (!sysfile_str) {

                _exit(SUSPEND_NOT_SUPPORTED);

            }

            fd = open(LINUX_SYS_STATE_FILE, O_RDONLY);

            if (fd < 0) {

                _exit(SUSPEND_NOT_SUPPORTED);

            }

            ret = read(fd, buf, sizeof(buf)-1);

            if (ret <= 0) {

                _exit(SUSPEND_NOT_SUPPORTED);

            }

            buf[ret] = '\0';

            if (strstr(buf, sysfile_str)) {

                _exit(SUSPEND_SUPPORTED);

            }

            _exit(SUSPEND_NOT_SUPPORTED);

        }

        if (pid > 0) {

            wait(&status);

        } else {

            status = SUSPEND_NOT_SUPPORTED;

        }

        ret = write(pipefds[1], &status, sizeof(status));

        if (ret != sizeof(status)) {

            _exit(EXIT_FAILURE);

        }

        _exit(EXIT_SUCCESS);

    }

    close(pipefds[1]);

    g_free(pmutils_path);

    if (pid < 0) {

        error_set(err, QERR_UNDEFINED_ERROR);

        goto out;

    }

    ret = read(pipefds[0], &status, sizeof(status));

    if (ret == sizeof(status) && WIFEXITED(status) &&

        WEXITSTATUS(status) == SUSPEND_SUPPORTED) {

            goto out;

    }

    error_set(err, QERR_UNSUPPORTED);

out:

    close(pipefds[0]);

}


void tlb_reset_dirty_range(CPUTLBEntry *tlb_entry, uintptr_t start,

                           uintptr_t length)

{

    uintptr_t addr;

    if (tlb_is_dirty_ram(tlb_entry)) {

        addr = (tlb_entry->addr_write & TARGET_PAGE_MASK) + tlb_entry->addend;

        if ((addr - start) < length) {

            tlb_entry->addr_write |= TLB_NOTDIRTY;

        }

    }

}


static const char *scsi_command_name(uint8_t cmd)

{

    static const char *names[] = {

        [ TEST_UNIT_READY          ] = "TEST_UNIT_READY",

        [ REQUEST_SENSE            ] = "REQUEST_SENSE",

        [ FORMAT_UNIT              ] = "FORMAT_UNIT",

        [ READ_BLOCK_LIMITS        ] = "READ_BLOCK_LIMITS",

        [ REASSIGN_BLOCKS          ] = "REASSIGN_BLOCKS",

        [ READ_6                   ] = "READ_6",

        [ WRITE_6                  ] = "WRITE_6",

        [ SEEK_6                   ] = "SEEK_6",

        [ READ_REVERSE             ] = "READ_REVERSE",

        [ WRITE_FILEMARKS          ] = "WRITE_FILEMARKS",

        [ SPACE                    ] = "SPACE",

        [ INQUIRY                  ] = "INQUIRY",

        [ RECOVER_BUFFERED_DATA    ] = "RECOVER_BUFFERED_DATA",

        [ MAINTENANCE_IN           ] = "MAINTENANCE_IN",

        [ MAINTENANCE_OUT          ] = "MAINTENANCE_OUT",

        [ MODE_SELECT              ] = "MODE_SELECT",

        [ RESERVE                  ] = "RESERVE",

        [ RELEASE                  ] = "RELEASE",

        [ COPY                     ] = "COPY",

        [ ERASE                    ] = "ERASE",

        [ MODE_SENSE               ] = "MODE_SENSE",

        [ START_STOP               ] = "START_STOP",

        [ RECEIVE_DIAGNOSTIC       ] = "RECEIVE_DIAGNOSTIC",

        [ SEND_DIAGNOSTIC          ] = "SEND_DIAGNOSTIC",

        [ ALLOW_MEDIUM_REMOVAL     ] = "ALLOW_MEDIUM_REMOVAL",

        [ READ_CAPACITY            ] = "READ_CAPACITY",

        [ READ_10                  ] = "READ_10",

        [ WRITE_10                 ] = "WRITE_10",

        [ SEEK_10                  ] = "SEEK_10",

        [ WRITE_VERIFY             ] = "WRITE_VERIFY",

        [ VERIFY                   ] = "VERIFY",

        [ SEARCH_HIGH              ] = "SEARCH_HIGH",

        [ SEARCH_EQUAL             ] = "SEARCH_EQUAL",

        [ SEARCH_LOW               ] = "SEARCH_LOW",

        [ SET_LIMITS               ] = "SET_LIMITS",

        [ PRE_FETCH                ] = "PRE_FETCH",

        /* READ_POSITION and PRE_FETCH use the same operation code */

        [ SYNCHRONIZE_CACHE        ] = "SYNCHRONIZE_CACHE",

        [ LOCK_UNLOCK_CACHE        ] = "LOCK_UNLOCK_CACHE",

        [ READ_DEFECT_DATA         ] = "READ_DEFECT_DATA",

        [ MEDIUM_SCAN              ] = "MEDIUM_SCAN",

        [ COMPARE                  ] = "COMPARE",

        [ COPY_VERIFY              ] = "COPY_VERIFY",

        [ WRITE_BUFFER             ] = "WRITE_BUFFER",

        [ READ_BUFFER              ] = "READ_BUFFER",

        [ UPDATE_BLOCK             ] = "UPDATE_BLOCK",

        [ READ_LONG                ] = "READ_LONG",

        [ WRITE_LONG               ] = "WRITE_LONG",

        [ CHANGE_DEFINITION        ] = "CHANGE_DEFINITION",

        [ WRITE_SAME               ] = "WRITE_SAME",

        [ READ_TOC                 ] = "READ_TOC",

        [ LOG_SELECT               ] = "LOG_SELECT",

        [ LOG_SENSE                ] = "LOG_SENSE",

        [ MODE_SELECT_10           ] = "MODE_SELECT_10",

        [ RESERVE_10               ] = "RESERVE_10",

        [ RELEASE_10               ] = "RELEASE_10",

        [ MODE_SENSE_10            ] = "MODE_SENSE_10",

        [ PERSISTENT_RESERVE_IN    ] = "PERSISTENT_RESERVE_IN",

        [ PERSISTENT_RESERVE_OUT   ] = "PERSISTENT_RESERVE_OUT",

        [ MOVE_MEDIUM              ] = "MOVE_MEDIUM",

        [ READ_12                  ] = "READ_12",

        [ WRITE_12                 ] = "WRITE_12",

        [ WRITE_VERIFY_12          ] = "WRITE_VERIFY_12",

        [ SEARCH_HIGH_12           ] = "SEARCH_HIGH_12",

        [ SEARCH_EQUAL_12          ] = "SEARCH_EQUAL_12",

        [ SEARCH_LOW_12            ] = "SEARCH_LOW_12",

        [ READ_ELEMENT_STATUS      ] = "READ_ELEMENT_STATUS",

        [ SEND_VOLUME_TAG          ] = "SEND_VOLUME_TAG",

        [ WRITE_LONG_2             ] = "WRITE_LONG_2",

        [ REPORT_DENSITY_SUPPORT   ] = "REPORT_DENSITY_SUPPORT",

        [ GET_CONFIGURATION        ] = "GET_CONFIGURATION",

        [ READ_16                  ] = "READ_16",

        [ WRITE_16                 ] = "WRITE_16",

        [ WRITE_VERIFY_16          ] = "WRITE_VERIFY_16",

        [ SERVICE_ACTION_IN        ] = "SERVICE_ACTION_IN",

        [ REPORT_LUNS              ] = "REPORT_LUNS",

        [ LOAD_UNLOAD              ] = "LOAD_UNLOAD",

        [ SET_CD_SPEED             ] = "SET_CD_SPEED",

        [ BLANK                    ] = "BLANK",

    };

    if (cmd >= ARRAY_SIZE(names) || names[cmd] == NULL)

        return "*UNKNOWN*";

    return names[cmd];

}


X264_close(AVCodecContext *avctx)
{
    X264Context *x4 = avctx->priv_data;
    if(x4->enc)
        x264_encoder_close(x4->enc);
    return 0;
}


static void synthfilt_build_sb_samples (QDM2Context *q, GetBitContext *gb, int length, int sb_min, int sb_max)

{

    int sb, j, k, n, ch, run, channels;

    int joined_stereo, zero_encoding, chs;

    int type34_first;

    float type34_div = 0;

    float type34_predictor;

    float samples[10], sign_bits[16];

    if (length == 0) {

        // If no data use noise

        for (sb=sb_min; sb < sb_max; sb++)

            build_sb_samples_from_noise (q, sb);

        return;

    }

    for (sb = sb_min; sb < sb_max; sb++) {

        FIX_NOISE_IDX(q->noise_idx);

        channels = q->nb_channels;

        if (q->nb_channels <= 1 || sb < 12)

            joined_stereo = 0;

        else if (sb >= 24)

            joined_stereo = 1;

        else

            joined_stereo = (BITS_LEFT(length,gb) >= 1) ? get_bits1 (gb) : 0;

        if (joined_stereo) {

            if (BITS_LEFT(length,gb) >= 16)

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

                    sign_bits[j] = get_bits1 (gb);

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

                if (q->coding_method[1][sb][j] > q->coding_method[0][sb][j])

                    q->coding_method[0][sb][j] = q->coding_method[1][sb][j];

            fix_coding_method_array(sb, q->nb_channels, q->coding_method);

            channels = 1;

        }

        for (ch = 0; ch < channels; ch++) {

            zero_encoding = (BITS_LEFT(length,gb) >= 1) ? get_bits1(gb) : 0;

            type34_predictor = 0.0;

            type34_first = 1;

            for (j = 0; j < 128; ) {

                switch (q->coding_method[ch][sb][j / 2]) {

                    case 8:

                        if (BITS_LEFT(length,gb) >= 10) {

                            if (zero_encoding) {

                                for (k = 0; k < 5; k++) {

                                    if ((j + 2 * k) >= 128)

                                        break;

                                    samples[2 * k] = get_bits1(gb) ? dequant_1bit[joined_stereo][2 * get_bits1(gb)] : 0;

                                }

                            } else {

                                n = get_bits(gb, 8);

                                for (k = 0; k < 5; k++)

                                    samples[2 * k] = dequant_1bit[joined_stereo][random_dequant_index[n][k]];

                            }

                            for (k = 0; k < 5; k++)

                                samples[2 * k + 1] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        } else {

                            for (k = 0; k < 10; k++)

                                samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        }

                        run = 10;

                        break;

                    case 10:

                        if (BITS_LEFT(length,gb) >= 1) {

                            float f = 0.81;

                            if (get_bits1(gb))

                                f = -f;

                            f -= noise_samples[((sb + 1) * (j +5 * ch + 1)) & 127] * 9.0 / 40.0;

                            samples[0] = f;

                        } else {

                            samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        }

                        run = 1;

                        break;

                    case 16:

                        if (BITS_LEFT(length,gb) >= 10) {

                            if (zero_encoding) {

                                for (k = 0; k < 5; k++) {

                                    if ((j + k) >= 128)

                                        break;

                                    samples[k] = (get_bits1(gb) == 0) ? 0 : dequant_1bit[joined_stereo][2 * get_bits1(gb)];

                                }

                            } else {

                                n = get_bits (gb, 8);

                                for (k = 0; k < 5; k++)

                                    samples[k] = dequant_1bit[joined_stereo][random_dequant_index[n][k]];

                            }

                        } else {

                            for (k = 0; k < 5; k++)

                                samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        }

                        run = 5;

                        break;

                    case 24:

                        if (BITS_LEFT(length,gb) >= 7) {

                            n = get_bits(gb, 7);

                            for (k = 0; k < 3; k++)

                                samples[k] = (random_dequant_type24[n][k] - 2.0) * 0.5;

                        } else {

                            for (k = 0; k < 3; k++)

                                samples[k] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        }

                        run = 3;

                        break;

                    case 30:

                        if (BITS_LEFT(length,gb) >= 4)

                            samples[0] = type30_dequant[qdm2_get_vlc(gb, &vlc_tab_type30, 0, 1)];

                        else

                            samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        run = 1;

                        break;

                    case 34:

                        if (BITS_LEFT(length,gb) >= 7) {

                            if (type34_first) {

                                type34_div = (float)(1 << get_bits(gb, 2));

                                samples[0] = ((float)get_bits(gb, 5) - 16.0) / 15.0;

                                type34_predictor = samples[0];

                                type34_first = 0;

                            } else {

                                samples[0] = type34_delta[qdm2_get_vlc(gb, &vlc_tab_type34, 0, 1)] / type34_div + type34_predictor;

                                type34_predictor = samples[0];

                            }

                        } else {

                            samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        }

                        run = 1;

                        break;

                    default:

                        samples[0] = SB_DITHERING_NOISE(sb,q->noise_idx);

                        run = 1;

                        break;

                }

                if (joined_stereo) {

                    float tmp[10][MPA_MAX_CHANNELS];

                    for (k = 0; k < run; k++) {

                        tmp[k][0] = samples[k];

                        tmp[k][1] = (sign_bits[(j + k) / 8]) ? -samples[k] : samples[k];

                    }

                    for (chs = 0; chs < q->nb_channels; chs++)

                        for (k = 0; k < run; k++)

                            if ((j + k) < 128)

                                q->sb_samples[chs][j + k][sb] = q->tone_level[chs][sb][((j + k)/2)] * tmp[k][chs];

                } else {

                    for (k = 0; k < run; k++)

                        if ((j + k) < 128)

                            q->sb_samples[ch][j + k][sb] = q->tone_level[ch][sb][(j + k)/2] * samples[k];

                }

                j += run;

            } // j loop

        } // channel loop

    } // subband loop

}


static void opt_target(const char *arg)

{

    enum { PAL, NTSC, FILM, UNKNOWN } norm = UNKNOWN;

    static const char *const frame_rates[] = {"25", "30000/1001", "24000/1001"};

    if(!strncmp(arg, "pal-", 4)) {

        norm = PAL;

        arg += 4;

    } else if(!strncmp(arg, "ntsc-", 5)) {

        norm = NTSC;

        arg += 5;

    } else if(!strncmp(arg, "film-", 5)) {

        norm = FILM;

        arg += 5;

    } else {

        int fr;

        /* Calculate FR via float to avoid int overflow */

        fr = (int)(frame_rate.num * 1000.0 / frame_rate.den);

        if(fr == 25000) {

            norm = PAL;

        } else if((fr == 29970) || (fr == 23976)) {

            norm = NTSC;

        } else {

            /* Try to determine PAL/NTSC by peeking in the input files */

            if(nb_input_files) {

                int i, j;

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

                    for(i = 0; i < input_files[j]->nb_streams; i++) {

                        AVCodecContext *c = input_files[j]->streams[i]->codec;

                        if(c->codec_type != AVMEDIA_TYPE_VIDEO)

                            continue;

                        fr = c->time_base.den * 1000 / c->time_base.num;

                        if(fr == 25000) {

                            norm = PAL;

                            break;

                        } else if((fr == 29970) || (fr == 23976)) {

                            norm = NTSC;

                            break;

                        }

                    }

                    if(norm != UNKNOWN)

                        break;

                }

            }

        }

        if(verbose && norm != UNKNOWN)

            fprintf(stderr, "Assuming %s for target.\n", norm == PAL ? "PAL" : "NTSC");

    }

    if(norm == UNKNOWN) {

        fprintf(stderr, "Could not determine norm (PAL/NTSC/NTSC-Film) for target.\n");

        fprintf(stderr, "Please prefix target with \"pal-\", \"ntsc-\" or \"film-\",\n");

        fprintf(stderr, "or set a framerate with \"-r xxx\".\n");

        ffmpeg_exit(1);

    }

    if(!strcmp(arg, "vcd")) {

        opt_video_codec("mpeg1video");

        opt_audio_codec("mp2");

        opt_format("vcd");

        opt_frame_size(norm == PAL ? "352x288" : "352x240");

        opt_frame_rate(NULL, frame_rates[norm]);

        opt_default("g", norm == PAL ? "15" : "18");

        opt_default("b", "1150000");

        opt_default("maxrate", "1150000");

        opt_default("minrate", "1150000");

        opt_default("bufsize", "327680"); // 40*1024*8;

        opt_default("ab", "224000");

        audio_sample_rate = 44100;

        audio_channels = 2;

        opt_default("packetsize", "2324");

        opt_default("muxrate", "1411200"); // 2352 * 75 * 8;

        /* We have to offset the PTS, so that it is consistent with the SCR.

           SCR starts at 36000, but the first two packs contain only padding

           and the first pack from the other stream, respectively, may also have

           been written before.

           So the real data starts at SCR 36000+3*1200. */

        mux_preload= (36000+3*1200) / 90000.0; //0.44

    } else if(!strcmp(arg, "svcd")) {

        opt_video_codec("mpeg2video");

        opt_audio_codec("mp2");

        opt_format("svcd");

        opt_frame_size(norm == PAL ? "480x576" : "480x480");

        opt_frame_rate(NULL, frame_rates[norm]);

        opt_default("g", norm == PAL ? "15" : "18");

        opt_default("b", "2040000");

        opt_default("maxrate", "2516000");

        opt_default("minrate", "0"); //1145000;

        opt_default("bufsize", "1835008"); //224*1024*8;

        opt_default("flags", "+scan_offset");

        opt_default("ab", "224000");

        audio_sample_rate = 44100;

        opt_default("packetsize", "2324");

    } else if(!strcmp(arg, "dvd")) {

        opt_video_codec("mpeg2video");

        opt_audio_codec("ac3");

        opt_format("dvd");

        opt_frame_size(norm == PAL ? "720x576" : "720x480");

        opt_frame_rate(NULL, frame_rates[norm]);

        opt_default("g", norm == PAL ? "15" : "18");

        opt_default("b", "6000000");

        opt_default("maxrate", "9000000");

        opt_default("minrate", "0"); //1500000;

        opt_default("bufsize", "1835008"); //224*1024*8;

        opt_default("packetsize", "2048");  // from www.mpucoder.com: DVD sectors contain 2048 bytes of data, this is also the size of one pack.

        opt_default("muxrate", "10080000"); // from mplex project: data_rate = 1260000. mux_rate = data_rate * 8

        opt_default("ab", "448000");

        audio_sample_rate = 48000;

    } else if(!strncmp(arg, "dv", 2)) {

        opt_format("dv");

        opt_frame_size(norm == PAL ? "720x576" : "720x480");

        opt_frame_pix_fmt(!strncmp(arg, "dv50", 4) ? "yuv422p" :

                          (norm == PAL ? "yuv420p" : "yuv411p"));

        opt_frame_rate(NULL, frame_rates[norm]);

        audio_sample_rate = 48000;

        audio_channels = 2;

    } else {

        fprintf(stderr, "Unknown target: %s\n", arg);

        ffmpeg_exit(1);

    }

}


static int decode_init(AVCodecContext *avctx)

{

    LclContext * const c = (LclContext *)avctx->priv_data;

    int basesize = avctx->width * avctx->height;

    int zret; // Zlib return code

    c->avctx = avctx;

    avctx->has_b_frames = 0;

    c->pic.data[0] = NULL;

#ifdef CONFIG_ZLIB

    // Needed if zlib unused or init aborted before inflateInit

    memset(&(c->zstream), 0, sizeof(z_stream));

#endif

    if (avctx->extradata_size < 8) {

        av_log(avctx, AV_LOG_ERROR, "Extradata size too small.\n");

        return 1;

    }

    /* Check codec type */

    if (((avctx->codec_id == CODEC_ID_MSZH)  && (*((char *)avctx->extradata + 7) != CODEC_MSZH)) ||

        ((avctx->codec_id == CODEC_ID_ZLIB)  && (*((char *)avctx->extradata + 7) != CODEC_ZLIB))) {

        av_log(avctx, AV_LOG_ERROR, "Codec id and codec type mismatch. This should not happen.\n");

    }

    /* Detect image type */

    switch (c->imgtype = *((char *)avctx->extradata + 4)) {

        case IMGTYPE_YUV111:

            c->decomp_size = basesize * 3;

            av_log(avctx, AV_LOG_INFO, "Image type is YUV 1:1:1.\n");

            break;

        case IMGTYPE_YUV422:

            c->decomp_size = basesize * 2;

            av_log(avctx, AV_LOG_INFO, "Image type is YUV 4:2:2.\n");

            break;

        case IMGTYPE_RGB24:

            c->decomp_size = basesize * 3;

            av_log(avctx, AV_LOG_INFO, "Image type is RGB 24.\n");

            break;

        case IMGTYPE_YUV411:

            c->decomp_size = basesize / 2 * 3;

            av_log(avctx, AV_LOG_INFO, "Image type is YUV 4:1:1.\n");

            break;

        case IMGTYPE_YUV211:

            c->decomp_size = basesize * 2;

            av_log(avctx, AV_LOG_INFO, "Image type is YUV 2:1:1.\n");

            break;

        case IMGTYPE_YUV420:

            c->decomp_size = basesize / 2 * 3;

            av_log(avctx, AV_LOG_INFO, "Image type is YUV 4:2:0.\n");

            break;

        default:

            av_log(avctx, AV_LOG_ERROR, "Unsupported image format %d.\n", c->imgtype);

            return 1;

    }

    /* Detect compression method */

    c->compression = *((char *)avctx->extradata + 5);

    switch (avctx->codec_id) {

        case CODEC_ID_MSZH:

            switch (c->compression) {

                case COMP_MSZH:

                    av_log(avctx, AV_LOG_INFO, "Compression enabled.\n");

                    break;

                case COMP_MSZH_NOCOMP:

                    c->decomp_size = 0;

                    av_log(avctx, AV_LOG_INFO, "No compression.\n");

                    break;

                default:

                    av_log(avctx, AV_LOG_ERROR, "Unsupported compression format for MSZH (%d).\n", c->compression);

                    return 1;

            }

            break;

        case CODEC_ID_ZLIB:

#ifdef CONFIG_ZLIB

            switch (c->compression) {

                case COMP_ZLIB_HISPEED:

                    av_log(avctx, AV_LOG_INFO, "High speed compression.\n");

                    break;

                case COMP_ZLIB_HICOMP:

                    av_log(avctx, AV_LOG_INFO, "High compression.\n");

                    break;

                case COMP_ZLIB_NORMAL:

                    av_log(avctx, AV_LOG_INFO, "Normal compression.\n");

                    break;

                default:

                    if ((c->compression < Z_NO_COMPRESSION) || (c->compression > Z_BEST_COMPRESSION)) {

                	    av_log(avctx, AV_LOG_ERROR, "Unusupported compression level for ZLIB: (%d).\n", c->compression);

                        return 1;

                    }

                    av_log(avctx, AV_LOG_INFO, "Compression level for ZLIB: (%d).\n", c->compression);

            }

#else

            av_log(avctx, AV_LOG_ERROR, "Zlib support not compiled.\n");

            return 1;

#endif

            break;

        default:

            av_log(avctx, AV_LOG_ERROR, "BUG! Unknown codec in compression switch.\n");

            return 1;

    }

    /* Allocate decompression buffer */

    /* 4*8 max overflow space for mszh decomp algorithm */

    if (c->decomp_size) {

        if ((c->decomp_buf = av_malloc(c->decomp_size+4*8)) == NULL) {

            av_log(avctx, AV_LOG_ERROR, "Can't allocate decompression buffer.\n");

            return 1;

        }

    }

    /* Detect flags */

    c->flags = *((char *)avctx->extradata + 6);

    if (c->flags & FLAG_MULTITHREAD)

        av_log(avctx, AV_LOG_INFO, "Multithread encoder flag set.\n");

    if (c->flags & FLAG_NULLFRAME)

        av_log(avctx, AV_LOG_INFO, "Nullframe insertion flag set.\n");

    if ((avctx->codec_id == CODEC_ID_ZLIB) && (c->flags & FLAG_PNGFILTER))

        av_log(avctx, AV_LOG_INFO, "PNG filter flag set.\n");

    if (c->flags & FLAGMASK_UNUSED)

        av_log(avctx, AV_LOG_ERROR, "Unknown flag set (%d).\n", c->flags);

    /* If needed init zlib */

    if (avctx->codec_id == CODEC_ID_ZLIB) {

#ifdef CONFIG_ZLIB

        c->zstream.zalloc = Z_NULL;

        c->zstream.zfree = Z_NULL;

        c->zstream.opaque = Z_NULL;

        zret = inflateInit(&(c->zstream));

        if (zret != Z_OK) {

            av_log(avctx, AV_LOG_ERROR, "Inflate init error: %d\n", zret);

            return 1;

        }

#else

    av_log(avctx, AV_LOG_ERROR, "Zlib support not compiled.\n");

    return 1;

#endif

    }

    avctx->pix_fmt = PIX_FMT_BGR24;

    return 0;

}


static void lsi_do_command(LSIState *s)

{

    SCSIDevice *dev;

    uint8_t buf[16];

    uint32_t id;

    int n;

    DPRINTF("Send command len=%d\n", s->dbc);

    if (s->dbc > 16)

        s->dbc = 16;

    pci_dma_read(PCI_DEVICE(s), s->dnad, buf, s->dbc);

    s->sfbr = buf[0];

    s->command_complete = 0;

    id = (s->select_tag >> 8) & 0xf;

    dev = scsi_device_find(&s->bus, 0, id, s->current_lun);

    if (!dev) {

        lsi_bad_selection(s, id);

        return;

    }

    assert(s->current == NULL);

    s->current = g_malloc0(sizeof(lsi_request));

    s->current->tag = s->select_tag;

    s->current->req = scsi_req_new(dev, s->current->tag, s->current_lun, buf,

                                   s->current);

    n = scsi_req_enqueue(s->current->req);

    if (n) {

        if (n > 0) {

            lsi_set_phase(s, PHASE_DI);

        } else if (n < 0) {

            lsi_set_phase(s, PHASE_DO);

        }

        scsi_req_continue(s->current->req);

    }

    if (!s->command_complete) {

        if (n) {

            /* Command did not complete immediately so disconnect.  */

            lsi_add_msg_byte(s, 2); /* SAVE DATA POINTER */

            lsi_add_msg_byte(s, 4); /* DISCONNECT */

            /* wait data */

            lsi_set_phase(s, PHASE_MI);

            s->msg_action = 1;

            lsi_queue_command(s);

        } else {

            /* wait command complete */

            lsi_set_phase(s, PHASE_DI);

        }

    }

}


static void use_high_update_speed(WmallDecodeCtx *s, int ich)

{

    int ilms, recent, icoef;

    s->update_speed[ich] = 16;

    for (ilms = s->cdlms_ttl[ich]; ilms >= 0; ilms--) {

        recent = s->cdlms[ich][ilms].recent;

        if (s->bV3RTM) {

            for (icoef = 0; icoef < s->cdlms[ich][ilms].order; icoef++)

                s->cdlms[ich][ilms].lms_updates[icoef + recent] *= 2;

        } else {

            for (icoef = 0; icoef < s->cdlms[ich][ilms].order; icoef++)

                s->cdlms[ich][ilms].lms_updates[icoef] *= 2;

        }

    }

}


static void dump_json_image_check(ImageCheck *check, bool quiet)

{

    Error *local_err = NULL;

    QString *str;

    QmpOutputVisitor *ov = qmp_output_visitor_new();

    QObject *obj;

    visit_type_ImageCheck(qmp_output_get_visitor(ov), NULL, &check,

                          &local_err);

    obj = qmp_output_get_qobject(ov);

    str = qobject_to_json_pretty(obj);

    assert(str != NULL);

    qprintf(quiet, "%s\n", qstring_get_str(str));

    qobject_decref(obj);

    qmp_output_visitor_cleanup(ov);

    QDECREF(str);

}


static bool aux_bus_is_bridge(AUXBus *bus, DeviceState *dev)

{

    return (dev == DEVICE(bus->bridge));

}


void ff_estimate_b_frame_motion(MpegEncContext * s,

                             int mb_x, int mb_y)

{

    MotionEstContext * const c= &s->me;

    const int penalty_factor= c->mb_penalty_factor;

    int fmin, bmin, dmin, fbmin, bimin, fimin;

    int type=0;

    const int xy = mb_y*s->mb_stride + mb_x;

    init_ref(c, s->new_picture.f->data, s->last_picture.f->data,

             s->next_picture.f->data, 16 * mb_x, 16 * mb_y, 2);

    get_limits(s, 16*mb_x, 16*mb_y);

    c->skip=0;

    if (s->codec_id == AV_CODEC_ID_MPEG4 && s->next_picture.mbskip_table[xy]) {

        int score= direct_search(s, mb_x, mb_y); //FIXME just check 0,0

        score= ((unsigned)(score*score + 128*256))>>16;

        c->mc_mb_var_sum_temp += score;

        s->current_picture.mc_mb_var[mb_y*s->mb_stride + mb_x] = score; //FIXME use SSE

        s->mb_type[mb_y*s->mb_stride + mb_x]= CANDIDATE_MB_TYPE_DIRECT0;

        return;

    }

    if (s->codec_id == AV_CODEC_ID_MPEG4)

        dmin= direct_search(s, mb_x, mb_y);

    else

        dmin= INT_MAX;

//FIXME penalty stuff for non mpeg4

    c->skip=0;

    fmin = estimate_motion_b(s, mb_x, mb_y, s->b_forw_mv_table, 0, s->f_code) +

           3 * penalty_factor;

    c->skip=0;

    bmin = estimate_motion_b(s, mb_x, mb_y, s->b_back_mv_table, 2, s->b_code) +

           2 * penalty_factor;

    ff_dlog(s, " %d %d ", s->b_forw_mv_table[xy][0], s->b_forw_mv_table[xy][1]);

    c->skip=0;

    fbmin= bidir_refine(s, mb_x, mb_y) + penalty_factor;

    ff_dlog(s, "%d %d %d %d\n", dmin, fmin, bmin, fbmin);

    if (s->avctx->flags & AV_CODEC_FLAG_INTERLACED_ME) {

//FIXME mb type penalty

        c->skip=0;

        c->current_mv_penalty= c->mv_penalty[s->f_code] + MAX_MV;

        fimin= interlaced_search(s, 0,

                                 s->b_field_mv_table[0], s->b_field_select_table[0],

                                 s->b_forw_mv_table[xy][0], s->b_forw_mv_table[xy][1], 0);

        c->current_mv_penalty= c->mv_penalty[s->b_code] + MAX_MV;

        bimin= interlaced_search(s, 2,

                                 s->b_field_mv_table[1], s->b_field_select_table[1],

                                 s->b_back_mv_table[xy][0], s->b_back_mv_table[xy][1], 0);

    }else

        fimin= bimin= INT_MAX;

    {

        int score= fmin;

        type = CANDIDATE_MB_TYPE_FORWARD;

        if (dmin <= score){

            score = dmin;

            type = CANDIDATE_MB_TYPE_DIRECT;

        }

        if(bmin<score){

            score=bmin;

            type= CANDIDATE_MB_TYPE_BACKWARD;

        }

        if(fbmin<score){

            score=fbmin;

            type= CANDIDATE_MB_TYPE_BIDIR;

        }

        if(fimin<score){

            score=fimin;

            type= CANDIDATE_MB_TYPE_FORWARD_I;

        }

        if(bimin<score){

            score=bimin;

            type= CANDIDATE_MB_TYPE_BACKWARD_I;

        }

        score= ((unsigned)(score*score + 128*256))>>16;

        c->mc_mb_var_sum_temp += score;

        s->current_picture.mc_mb_var[mb_y*s->mb_stride + mb_x] = score; //FIXME use SSE

    }

    if(c->avctx->mb_decision > FF_MB_DECISION_SIMPLE){

        type= CANDIDATE_MB_TYPE_FORWARD | CANDIDATE_MB_TYPE_BACKWARD | CANDIDATE_MB_TYPE_BIDIR | CANDIDATE_MB_TYPE_DIRECT;

        if(fimin < INT_MAX)

            type |= CANDIDATE_MB_TYPE_FORWARD_I;

        if(bimin < INT_MAX)

            type |= CANDIDATE_MB_TYPE_BACKWARD_I;

        if(fimin < INT_MAX && bimin < INT_MAX){

            type |= CANDIDATE_MB_TYPE_BIDIR_I;

        }

         //FIXME something smarter

        if(dmin>256*256*16) type&= ~CANDIDATE_MB_TYPE_DIRECT; //do not try direct mode if it is invalid for this MB

        if (s->codec_id == AV_CODEC_ID_MPEG4 && type&CANDIDATE_MB_TYPE_DIRECT &&

            s->mpv_flags & FF_MPV_FLAG_MV0 && *(uint32_t*)s->b_direct_mv_table[xy])

            type |= CANDIDATE_MB_TYPE_DIRECT0;

    }

    s->mb_type[mb_y*s->mb_stride + mb_x]= type;

}


static inline int mpeg4_decode_dc(MpegEncContext * s, int n, int *dir_ptr)

{

    int level, pred, code;

    uint16_t *dc_val;

    if (n < 4)

        code = get_vlc2(&s->gb, dc_lum.table, DC_VLC_BITS, 1);

    else

        code = get_vlc2(&s->gb, dc_chrom.table, DC_VLC_BITS, 1);

    if (code < 0 || code > 9 /* && s->nbit<9 */){

        fprintf(stderr, "illegal dc vlc\n");

        return -1;

    }

    if (code == 0) {

        level = 0;

    } else {

        level = get_xbits(&s->gb, code);

        if (code > 8){

            if(get_bits1(&s->gb)==0){ /* marker */

                if(s->error_resilience>=2){

                    fprintf(stderr, "dc marker bit missing\n");

                    return -1;

                }

            }

        }

    }

    pred = ff_mpeg4_pred_dc(s, n, &dc_val, dir_ptr);

    level += pred;

    if (level < 0){

        if(s->error_resilience>=3){

            fprintf(stderr, "dc<0 at %dx%d\n", s->mb_x, s->mb_y);

            return -1;

        }

        level = 0;

    }

    if (n < 4) {

        *dc_val = level * s->y_dc_scale;

    } else {

        *dc_val = level * s->c_dc_scale;

    }

    if(s->error_resilience>=3){

        if(*dc_val > 2048 + s->y_dc_scale + s->c_dc_scale){

            fprintf(stderr, "dc overflow at %dx%d\n", s->mb_x, s->mb_y);

            return -1;

        }

    }

    return level;

}


static void check_pred8x8(H264PredContext *h, uint8_t *buf0, uint8_t *buf1,

                          int codec, int chroma_format, int bit_depth)

{

    int pred_mode;

    for (pred_mode = 0; pred_mode < 11; pred_mode++) {

        if (check_pred_func(h->pred8x8[pred_mode], (chroma_format == 2) ? "8x16" : "8x8",

                            pred8x8_modes[codec][pred_mode])) {

            randomize_buffers();

            call_ref(src0, (ptrdiff_t)24*SIZEOF_PIXEL);

            call_new(src1, (ptrdiff_t)24*SIZEOF_PIXEL);

            if (memcmp(buf0, buf1, BUF_SIZE))

                fail();

            bench_new(src1, (ptrdiff_t)24*SIZEOF_PIXEL);

        }

    }

}


int kvm_arch_remove_sw_breakpoint(CPUState *env, struct kvm_sw_breakpoint *bp)

{

    uint8_t int3;

    if (cpu_memory_rw_debug(env, bp->pc, &int3, 1, 0) || int3 != 0xcc ||

        cpu_memory_rw_debug(env, bp->pc, (uint8_t *)&bp->saved_insn, 1, 1))

        return -EINVAL;

    return 0;

}


static void rtas_nvram_fetch(sPAPREnvironment *spapr,

                             uint32_t token, uint32_t nargs,

                             target_ulong args,

                             uint32_t nret, target_ulong rets)

{

    sPAPRNVRAM *nvram = spapr->nvram;

    hwaddr offset, buffer, len;

    int alen;

    void *membuf;

    if ((nargs != 3) || (nret != 2)) {

        rtas_st(rets, 0, -3);

        return;

    }

    if (!nvram) {

        rtas_st(rets, 0, -1);

        rtas_st(rets, 1, 0);

        return;

    }

    offset = rtas_ld(args, 0);

    buffer = rtas_ld(args, 1);

    len = rtas_ld(args, 2);

    if (((offset + len) < offset)

        || ((offset + len) > nvram->size)) {

        rtas_st(rets, 0, -3);

        rtas_st(rets, 1, 0);

        return;

    }

    membuf = cpu_physical_memory_map(buffer, &len, 1);

    if (nvram->drive) {

        alen = bdrv_pread(nvram->drive, offset, membuf, len);

    } else {

        assert(nvram->buf);

        memcpy(membuf, nvram->buf + offset, len);

        alen = len;

    }

    cpu_physical_memory_unmap(membuf, len, 1, len);

    rtas_st(rets, 0, (alen < len) ? -1 : 0);

    rtas_st(rets, 1, (alen < 0) ? 0 : alen);

}


int socket_connect(SocketAddressLegacy *addr, NonBlockingConnectHandler *callback,

                   void *opaque, Error **errp)

{

    int fd;

    switch (addr->type) {

    case SOCKET_ADDRESS_LEGACY_KIND_INET:

        fd = inet_connect_saddr(addr->u.inet.data, callback, opaque, errp);

        break;

    case SOCKET_ADDRESS_LEGACY_KIND_UNIX:

        fd = unix_connect_saddr(addr->u.q_unix.data, callback, opaque, errp);

        break;

    case SOCKET_ADDRESS_LEGACY_KIND_FD:

        fd = monitor_get_fd(cur_mon, addr->u.fd.data->str, errp);

        if (fd >= 0 && callback) {

            qemu_set_nonblock(fd);

            callback(fd, NULL, opaque);

        }

        break;

    case SOCKET_ADDRESS_LEGACY_KIND_VSOCK:

        fd = vsock_connect_saddr(addr->u.vsock.data, callback, opaque, errp);

        break;

    default:

        abort();

    }

    return fd;

}


static void validate_numa_cpus(void)

{

    int i;

    unsigned long *seen_cpus = bitmap_new(max_cpus);

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

        if (bitmap_intersects(seen_cpus, numa_info[i].node_cpu, max_cpus)) {

            bitmap_and(seen_cpus, seen_cpus,

                       numa_info[i].node_cpu, max_cpus);

            error_report("CPU(s) present in multiple NUMA nodes: %s",

                         enumerate_cpus(seen_cpus, max_cpus));

            g_free(seen_cpus);

            exit(EXIT_FAILURE);

        }

        bitmap_or(seen_cpus, seen_cpus,

                  numa_info[i].node_cpu, max_cpus);

    }

    if (!bitmap_full(seen_cpus, max_cpus)) {

        char *msg;

        bitmap_complement(seen_cpus, seen_cpus, max_cpus);

        msg = enumerate_cpus(seen_cpus, max_cpus);

        error_report("warning: CPU(s) not present in any NUMA nodes: %s", msg);

        error_report("warning: All CPU(s) up to maxcpus should be described "

                     "in NUMA config");

        g_free(msg);

    }

    g_free(seen_cpus);

}


void hmp_nbd_server_start(Monitor *mon, const QDict *qdict)

{

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

    bool writable = qdict_get_try_bool(qdict, "writable", false);

    bool all = qdict_get_try_bool(qdict, "all", false);

    Error *local_err = NULL;

    BlockInfoList *block_list, *info;

    SocketAddressLegacy *addr;

    if (writable && !all) {

        error_setg(&local_err, "-w only valid together with -a");

        goto exit;

    }

    /* First check if the address is valid and start the server.  */

    addr = socket_parse(uri, &local_err);

    if (local_err != NULL) {

        goto exit;

    }

    qmp_nbd_server_start(addr, false, NULL, &local_err);

    qapi_free_SocketAddressLegacy(addr);

    if (local_err != NULL) {

        goto exit;

    }

    if (!all) {

        return;

    }

    /* Then try adding all block devices.  If one fails, close all and

     * exit.

     */

    block_list = qmp_query_block(NULL);

    for (info = block_list; info; info = info->next) {

        if (!info->value->has_inserted) {

            continue;

        }

        qmp_nbd_server_add(info->value->device, true, writable, &local_err);

        if (local_err != NULL) {

            qmp_nbd_server_stop(NULL);

            break;

        }

    }

    qapi_free_BlockInfoList(block_list);

exit:

    hmp_handle_error(mon, &local_err);

}


static void RENAME(yuv2bgr24_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"

        WRITEBGR24(%%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)

    );

}


void cpu_dump_statistics (CPUState *env, FILE*f,

                          int (*cpu_fprintf)(FILE *f, const char *fmt, ...),

                          int flags)

{

#if defined(DO_PPC_STATISTICS)

    opc_handler_t **t1, **t2, **t3, *handler;

    int op1, op2, op3;

    t1 = env->opcodes;

    for (op1 = 0; op1 < 64; op1++) {

        handler = t1[op1];

        if (is_indirect_opcode(handler)) {

            t2 = ind_table(handler);

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

                handler = t2[op2];

                if (is_indirect_opcode(handler)) {

                    t3 = ind_table(handler);

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

                        handler = t3[op3];

                        if (handler->count == 0)

                            continue;

                        cpu_fprintf(f, "%02x %02x %02x (%02x %04d) %16s: "

                                    "%016" PRIx64 " %" PRId64 "\n",

                                    op1, op2, op3, op1, (op3 << 5) | op2,

                                    handler->oname,

                                    handler->count, handler->count);

                    }

                } else {

                    if (handler->count == 0)

                        continue;

                    cpu_fprintf(f, "%02x %02x    (%02x %04d) %16s: "

                                "%016" PRIx64 " %" PRId64 "\n",

                                op1, op2, op1, op2, handler->oname,

                                handler->count, handler->count);

                }

            }

        } else {

            if (handler->count == 0)

                continue;

            cpu_fprintf(f, "%02x       (%02x     ) %16s: %016" PRIx64

                        " %" PRId64 "\n",

                        op1, op1, handler->oname,

                        handler->count, handler->count);

        }

    }

#endif

}


static Suite *qint_suite(void)

{

    Suite *s;

    TCase *qint_public_tcase;

    s = suite_create("QInt test-suite");

    qint_public_tcase = tcase_create("Public Interface");

    suite_add_tcase(s, qint_public_tcase);

    tcase_add_test(qint_public_tcase, qint_from_int_test);

    tcase_add_test(qint_public_tcase, qint_destroy_test);

    tcase_add_test(qint_public_tcase, qint_from_int64_test);

    tcase_add_test(qint_public_tcase, qint_get_int_test);

    tcase_add_test(qint_public_tcase, qobject_to_qint_test);

    return s;

}


static void qmp_input_type_int64(Visitor *v, const char *name, int64_t *obj,

                                 Error **errp)

{

    QmpInputVisitor *qiv = to_qiv(v);

    QObject *qobj = qmp_input_get_object(qiv, name, true, errp);

    QInt *qint;

    if (!qobj) {

        return;

    }

    qint = qobject_to_qint(qobj);

    if (!qint) {

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

                   "integer");

        return;

    }

    *obj = qint_get_int(qint);

}


static gint ppc_cpu_compare_class_pvr_mask(gconstpointer a, gconstpointer b)

{

    ObjectClass *oc = (ObjectClass *)a;

    uint32_t pvr = *(uint32_t *)b;

    PowerPCCPUClass *pcc = (PowerPCCPUClass *)a;

    gint ret;

    /* -cpu host does a PVR lookup during construction */

    if (unlikely(strcmp(object_class_get_name(oc),

                        TYPE_HOST_POWERPC_CPU) == 0)) {

        return -1;

    }

    if (!ppc_cpu_is_valid(pcc)) {

        return -1;

    }

    ret = (((pcc->pvr & pcc->pvr_mask) == (pvr & pcc->pvr_mask)) ? 0 : -1);

    return ret;

}


void cpu_resume_from_signal(CPUState *cpu, void *puc)

{

    /* XXX: restore cpu registers saved in host registers */

    cpu->exception_index = -1;

    siglongjmp(cpu->jmp_env, 1);

}


void bdrv_replace_in_backing_chain(BlockDriverState *old, BlockDriverState *new)

{

    assert(!bdrv_requests_pending(old));

    assert(!bdrv_requests_pending(new));

    bdrv_ref(old);

    change_parent_backing_link(old, new);

    bdrv_unref(old);

}


unsigned long virtio_load_direct(ulong rec_list1, ulong rec_list2,

				 ulong subchan_id, void *load_addr)

{

    u8 status;

    int sec = rec_list1;

    int sec_num = ((rec_list2 >> 32) & 0xffff) + 1;

    int sec_len = rec_list2 >> 48;

    ulong addr = (ulong)load_addr;

    if (sec_len != SECTOR_SIZE) {

        return -1;

    }

    sclp_print(".");

    status = virtio_read_many(sec, (void*)addr, sec_num);

    if (status) {

        virtio_panic("I/O Error");

    }

    addr += sec_num * SECTOR_SIZE;

    return addr;

}


void xen_init_display(int domid)

{

    struct XenDevice *xfb, *xin;

    struct XenFB *fb;

    struct XenInput *in;

    int i = 0;

wait_more:

    i++;

    main_loop_wait(true);

    xfb = xen_be_find_xendev("vfb", domid, 0);

    xin = xen_be_find_xendev("vkbd", domid, 0);

    if (!xfb || !xin) {

        if (i < 256) {

            usleep(10000);

            goto wait_more;

        }

        xen_be_printf(NULL, 1, "displaystate setup failed\n");

        return;

    }

    /* vfb */

    fb = container_of(xfb, struct XenFB, c.xendev);

    fb->c.con = graphic_console_init(xenfb_update,

                                     xenfb_invalidate,

                                     NULL,

                                     NULL,

                                     fb);

    fb->have_console = 1;

    /* vkbd */

    in = container_of(xin, struct XenInput, c.xendev);

    in->c.con = fb->c.con;

    /* retry ->init() */

    xen_be_check_state(xin);

    xen_be_check_state(xfb);

}


static int musicpal_lcd_init(SysBusDevice *dev)

{

    musicpal_lcd_state *s = FROM_SYSBUS(musicpal_lcd_state, dev);

    s->brightness = 7;

    memory_region_init_io(&s->iomem, &musicpal_lcd_ops, s,

                          "musicpal-lcd", MP_LCD_SIZE);

    sysbus_init_mmio(dev, &s->iomem);

    s->con = graphic_console_init(lcd_refresh, lcd_invalidate,

                                  NULL, NULL, s);

    qemu_console_resize(s->con, 128*3, 64*3);

    qdev_init_gpio_in(&dev->qdev, musicpal_lcd_gpio_brigthness_in, 3);

    return 0;

}


static int mov_write_gmhd_tag(AVIOContext *pb)

{

    avio_wb32(pb, 0x20);   /* size */

    ffio_wfourcc(pb, "gmhd");

    avio_wb32(pb, 0x18);   /* gmin size */

    ffio_wfourcc(pb, "gmin");/* generic media info */

    avio_wb32(pb, 0);      /* version & flags */

    avio_wb16(pb, 0x40);   /* graphics mode = */

    avio_wb16(pb, 0x8000); /* opColor (r?) */

    avio_wb16(pb, 0x8000); /* opColor (g?) */

    avio_wb16(pb, 0x8000); /* opColor (b?) */

    avio_wb16(pb, 0);      /* balance */

    avio_wb16(pb, 0);      /* reserved */

    return 0x20;

}


int float64_le( float64 a, float64 b STATUS_PARAM )

{

    flag aSign, bSign;

    if (    ( ( extractFloat64Exp( a ) == 0x7FF ) && extractFloat64Frac( a ) )

         || ( ( extractFloat64Exp( b ) == 0x7FF ) && extractFloat64Frac( b ) )

       ) {

        float_raise( float_flag_invalid STATUS_VAR);

        return 0;

    }

    aSign = extractFloat64Sign( a );

    bSign = extractFloat64Sign( b );

    if ( aSign != bSign ) return aSign || ( (bits64) ( ( a | b )<<1 ) == 0 );

    return ( a == b ) || ( aSign ^ ( a < b ) );

}


static int usb_qdev_init(DeviceState *qdev, DeviceInfo *base)

{

    USBDevice *dev = DO_UPCAST(USBDevice, qdev, qdev);

    USBDeviceInfo *info = DO_UPCAST(USBDeviceInfo, qdev, base);

    int rc;

    pstrcpy(dev->product_desc, sizeof(dev->product_desc), info->product_desc);

    dev->info = info;

    dev->auto_attach = 1;

    QLIST_INIT(&dev->strings);

    rc = dev->info->init(dev);

    if (rc == 0 && dev->auto_attach)

        rc = usb_device_attach(dev);

    return rc;

}


static int64_t coroutine_fn bdrv_co_get_block_status(BlockDriverState *bs,

                                                     int64_t sector_num,

                                                     int nb_sectors, int *pnum)

{

    int64_t length;

    int64_t n;

    int64_t ret, ret2;

    length = bdrv_getlength(bs);

    if (length < 0) {

        return length;

    }

    if (sector_num >= (length >> BDRV_SECTOR_BITS)) {

        *pnum = 0;

        return 0;

    }

    n = bs->total_sectors - sector_num;

    if (n < nb_sectors) {

        nb_sectors = n;

    }

    if (!bs->drv->bdrv_co_get_block_status) {

        *pnum = nb_sectors;

        ret = BDRV_BLOCK_DATA;

        if (bs->drv->protocol_name) {

            ret |= BDRV_BLOCK_OFFSET_VALID | (sector_num * BDRV_SECTOR_SIZE);

        }

        return ret;

    }

    ret = bs->drv->bdrv_co_get_block_status(bs, sector_num, nb_sectors, pnum);

    if (ret < 0) {

        *pnum = 0;

        return ret;

    }

    if (ret & BDRV_BLOCK_RAW) {

        assert(ret & BDRV_BLOCK_OFFSET_VALID);

        return bdrv_get_block_status(bs->file, ret >> BDRV_SECTOR_BITS,

                                     *pnum, pnum);

    }

    if (!(ret & BDRV_BLOCK_DATA)) {

        if (bdrv_has_zero_init(bs)) {

            ret |= BDRV_BLOCK_ZERO;

        } else if (bs->backing_hd) {

            BlockDriverState *bs2 = bs->backing_hd;

            int64_t length2 = bdrv_getlength(bs2);

            if (length2 >= 0 && sector_num >= (length2 >> BDRV_SECTOR_BITS)) {

                ret |= BDRV_BLOCK_ZERO;

            }

        }

    }

    if (bs->file &&

        (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) &&

        (ret & BDRV_BLOCK_OFFSET_VALID)) {

        ret2 = bdrv_co_get_block_status(bs->file, ret >> BDRV_SECTOR_BITS,

                                        *pnum, pnum);

        if (ret2 >= 0) {

            /* Ignore errors.  This is just providing extra information, it

             * is useful but not necessary.

             */

            ret |= (ret2 & BDRV_BLOCK_ZERO);

        }

    }

    return ret;

}


void *qemu_try_blockalign(BlockDriverState *bs, size_t size)

{

    size_t align = bdrv_opt_mem_align(bs);

    /* Ensure that NULL is never returned on success */

    assert(align > 0);

    if (size == 0) {

        size = align;

    }

    return qemu_try_memalign(align, size);

}


float32 helper_fxtos(CPUSPARCState *env, int64_t src)

{

    float32 ret;

    clear_float_exceptions(env);

    ret = int64_to_float32(src, &env->fp_status);

    check_ieee_exceptions(env);

    return ret;

}


VirtIOSCSIReq *virtio_scsi_pop_req_vring(VirtIOSCSI *s,

                                         VirtIOSCSIVring *vring)

{

    VirtIOSCSIReq *req = virtio_scsi_init_req(s, NULL);

    int r;

    req->vring = vring;

    r = vring_pop((VirtIODevice *)s, &vring->vring, &req->elem);

    if (r < 0) {

        virtio_scsi_free_req(req);

        req = NULL;

    }

    return req;

}


uint64_t helper_fctiwz (uint64_t arg)

{

    CPU_DoubleU farg;

    farg.ll = arg;

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

        /* sNaN conversion */

        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN | POWERPC_EXCP_FP_VXCVI);

    } else if (unlikely(float64_is_nan(farg.d) || float64_is_infinity(farg.d))) {

        /* qNan / infinity conversion */

        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXCVI);

    } else {

        farg.ll = float64_to_int32_round_to_zero(farg.d, &env->fp_status);

#if USE_PRECISE_EMULATION

        /* XXX: higher bits are not supposed to be significant.

         *     to make tests easier, return the same as a real PowerPC 750

         */

        farg.ll |= 0xFFF80000ULL << 32;

#endif

    }

    return farg.ll;

}


void list_cpus(FILE *f, int (*cpu_fprintf)(FILE *f, const char *fmt, ...),

               const char *optarg)

{

    /* XXX: implement xxx_cpu_list for targets that still miss it */

#if defined(cpu_list_id)

    cpu_list_id(f, cpu_fprintf, optarg);

#elif defined(cpu_list)

    cpu_list(f, cpu_fprintf); /* deprecated */

#endif

}