int cpu_load(QEMUFile *f, void *opaque, int version_id)

{

	CPUCRISState *env = opaque;

    int i;

    int s;

    int mmu;

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

        env->regs[i] = qemu_get_be32(f);

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

        env->pregs[i] = qemu_get_be32(f);

    env->pc = qemu_get_be32(f);

    env->ksp = qemu_get_be32(f);

    env->dslot = qemu_get_be32(f);

    env->btaken = qemu_get_be32(f);

    env->btarget = qemu_get_be32(f);

    env->cc_op = qemu_get_be32(f);

    env->cc_mask = qemu_get_be32(f);

    env->cc_dest = qemu_get_be32(f);

    env->cc_src = qemu_get_be32(f);

    env->cc_result = qemu_get_be32(f);

    env->cc_size = qemu_get_be32(f);

    env->cc_x = qemu_get_be32(f);

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

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

            env->sregs[s][i] = qemu_get_be32(f);

    }

    env->mmu_rand_lfsr = qemu_get_be32(f);

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

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

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

                env->tlbsets[mmu][s][i].lo = qemu_get_be32(f);

                env->tlbsets[mmu][s][i].hi = qemu_get_be32(f);

            }

        }

    }

    return 0;

}


static int xvid_strip_vol_header(AVCodecContext *avctx,

                  AVPacket *pkt,

                  unsigned int header_len,

                  unsigned int frame_len) {

    int vo_len = 0, i;

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

        if( pkt->data[i] == 0x00 &&

            pkt->data[i+1] == 0x00 &&

            pkt->data[i+2] == 0x01 &&

            pkt->data[i+3] == 0xB6 ) {

            vo_len = i;

            break;

        }

    }

    if( vo_len > 0 ) {

        /* We need to store the header, so extract it */

        if( avctx->extradata == NULL ) {

            avctx->extradata = av_malloc(vo_len);

            memcpy(avctx->extradata, pkt->data, vo_len);

            avctx->extradata_size = vo_len;

        }

        /* Less dangerous now, memmove properly copies the two

           chunks of overlapping data */

        memmove(pkt->data, &pkt->data[vo_len], frame_len - vo_len);

        pkt->size = frame_len - vo_len;

    }

    return 0;

}


static int vfio_setup_pcie_cap(VFIOPCIDevice *vdev, int pos, uint8_t size,

                               Error **errp)

{

    uint16_t flags;

    uint8_t type;

    flags = pci_get_word(vdev->pdev.config + pos + PCI_CAP_FLAGS);

    type = (flags & PCI_EXP_FLAGS_TYPE) >> 4;

    if (type != PCI_EXP_TYPE_ENDPOINT &&

        type != PCI_EXP_TYPE_LEG_END &&

        type != PCI_EXP_TYPE_RC_END) {

        error_setg(errp, "assignment of PCIe type 0x%x "

                   "devices is not currently supported", type);

        return -EINVAL;

    }

    if (!pci_bus_is_express(vdev->pdev.bus)) {

        PCIBus *bus = vdev->pdev.bus;

        PCIDevice *bridge;

        /*

         * Traditionally PCI device assignment exposes the PCIe capability

         * as-is on non-express buses.  The reason being that some drivers

         * simply assume that it's there, for example tg3.  However when

         * we're running on a native PCIe machine type, like Q35, we need

         * to hide the PCIe capability.  The reason for this is twofold;

         * first Windows guests get a Code 10 error when the PCIe capability

         * is exposed in this configuration.  Therefore express devices won't

         * work at all unless they're attached to express buses in the VM.

         * Second, a native PCIe machine introduces the possibility of fine

         * granularity IOMMUs supporting both translation and isolation.

         * Guest code to discover the IOMMU visibility of a device, such as

         * IOMMU grouping code on Linux, is very aware of device types and

         * valid transitions between bus types.  An express device on a non-

         * express bus is not a valid combination on bare metal systems.

         *

         * Drivers that require a PCIe capability to make the device

         * functional are simply going to need to have their devices placed

         * on a PCIe bus in the VM.

         */

        while (!pci_bus_is_root(bus)) {

            bridge = pci_bridge_get_device(bus);

            bus = bridge->bus;

        }

        if (pci_bus_is_express(bus)) {

            return 0;

        }

    } else if (pci_bus_is_root(vdev->pdev.bus)) {

        /*

         * On a Root Complex bus Endpoints become Root Complex Integrated

         * Endpoints, which changes the type and clears the LNK & LNK2 fields.

         */

        if (type == PCI_EXP_TYPE_ENDPOINT) {

            vfio_add_emulated_word(vdev, pos + PCI_CAP_FLAGS,

                                   PCI_EXP_TYPE_RC_END << 4,

                                   PCI_EXP_FLAGS_TYPE);

            /* Link Capabilities, Status, and Control goes away */

            if (size > PCI_EXP_LNKCTL) {

                vfio_add_emulated_long(vdev, pos + PCI_EXP_LNKCAP, 0, ~0);

                vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKCTL, 0, ~0);

                vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKSTA, 0, ~0);

#ifndef PCI_EXP_LNKCAP2

#define PCI_EXP_LNKCAP2 44

#endif

#ifndef PCI_EXP_LNKSTA2

#define PCI_EXP_LNKSTA2 50

#endif

                /* Link 2 Capabilities, Status, and Control goes away */

                if (size > PCI_EXP_LNKCAP2) {

                    vfio_add_emulated_long(vdev, pos + PCI_EXP_LNKCAP2, 0, ~0);

                    vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKCTL2, 0, ~0);

                    vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKSTA2, 0, ~0);

                }

            }

        } else if (type == PCI_EXP_TYPE_LEG_END) {

            /*

             * Legacy endpoints don't belong on the root complex.  Windows

             * seems to be happier with devices if we skip the capability.

             */

            return 0;

        }

    } else {

        /*

         * Convert Root Complex Integrated Endpoints to regular endpoints.

         * These devices don't support LNK/LNK2 capabilities, so make them up.

         */

        if (type == PCI_EXP_TYPE_RC_END) {

            vfio_add_emulated_word(vdev, pos + PCI_CAP_FLAGS,

                                   PCI_EXP_TYPE_ENDPOINT << 4,

                                   PCI_EXP_FLAGS_TYPE);

            vfio_add_emulated_long(vdev, pos + PCI_EXP_LNKCAP,

                                   PCI_EXP_LNK_MLW_1 | PCI_EXP_LNK_LS_25, ~0);

            vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKCTL, 0, ~0);

        }

        /* Mark the Link Status bits as emulated to allow virtual negotiation */

        vfio_add_emulated_word(vdev, pos + PCI_EXP_LNKSTA,

                               pci_get_word(vdev->pdev.config + pos +

                                            PCI_EXP_LNKSTA),

                               PCI_EXP_LNKCAP_MLW | PCI_EXP_LNKCAP_SLS);

    }

    /*

     * Intel 82599 SR-IOV VFs report an invalid PCIe capability version 0

     * (Niantic errate #35) causing Windows to error with a Code 10 for the

     * device on Q35.  Fixup any such devices to report version 1.  If we

     * were to remove the capability entirely the guest would lose extended

     * config space.

     */

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

        vfio_add_emulated_word(vdev, pos + PCI_CAP_FLAGS,

                               1, PCI_EXP_FLAGS_VERS);

    }

    pos = pci_add_capability(&vdev->pdev, PCI_CAP_ID_EXP, pos, size,

                             errp);

    if (pos < 0) {

        return pos;

    }

    vdev->pdev.exp.exp_cap = pos;

    return pos;

}


static void IRQ_local_pipe (openpic_t *opp, int n_CPU, int n_IRQ)

{

    IRQ_dst_t *dst;

    IRQ_src_t *src;

    int priority;

    dst = &opp->dst[n_CPU];

    src = &opp->src[n_IRQ];

    priority = IPVP_PRIORITY(src->ipvp);

    if (priority <= dst->pctp) {

        /* Too low priority */

        DPRINTF("%s: IRQ %d has too low priority on CPU %d\n",

                __func__, n_IRQ, n_CPU);

        return;

    }

    if (IRQ_testbit(&dst->raised, n_IRQ)) {

        /* Interrupt miss */

        DPRINTF("%s: IRQ %d was missed on CPU %d\n",

                __func__, n_IRQ, n_CPU);

        return;

    }

    set_bit(&src->ipvp, IPVP_ACTIVITY);

    IRQ_setbit(&dst->raised, n_IRQ);

    if (priority < dst->raised.priority) {

        /* An higher priority IRQ is already raised */

        DPRINTF("%s: IRQ %d is hidden by raised IRQ %d on CPU %d\n",

                __func__, n_IRQ, dst->raised.next, n_CPU);

        return;

    }

    IRQ_get_next(opp, &dst->raised);

    if (IRQ_get_next(opp, &dst->servicing) != -1 &&

        priority <= dst->servicing.priority) {

        DPRINTF("%s: IRQ %d is hidden by servicing IRQ %d on CPU %d\n",

                __func__, n_IRQ, dst->servicing.next, n_CPU);

        /* Already servicing a higher priority IRQ */

        return;

    }

    DPRINTF("Raise OpenPIC INT output cpu %d irq %d\n", n_CPU, n_IRQ);

    opp->irq_raise(opp, n_CPU, src);

}


void armv7m_nvic_complete_irq(void *opaque, int irq)

{

    nvic_state *s = (nvic_state *)opaque;

    if (irq >= 16)

        irq += 16;

    gic_complete_irq(&s->gic, 0, irq);

}


static void amdvi_iommu_notify_flag_changed(MemoryRegion *iommu,

                                            IOMMUNotifierFlag old,

                                            IOMMUNotifierFlag new)

{

    AMDVIAddressSpace *as = container_of(iommu, AMDVIAddressSpace, iommu);

    hw_error("device %02x.%02x.%x requires iommu notifier which is not "

             "currently supported", as->bus_num, PCI_SLOT(as->devfn),

             PCI_FUNC(as->devfn));

}


static int kvm_put_tscdeadline_msr(X86CPU *cpu)

{

    CPUX86State *env = &cpu->env;

    struct {

        struct kvm_msrs info;

        struct kvm_msr_entry entries[1];

    } msr_data;

    struct kvm_msr_entry *msrs = msr_data.entries;

    if (!has_msr_tsc_deadline) {

        return 0;

    }

    kvm_msr_entry_set(&msrs[0], MSR_IA32_TSCDEADLINE, env->tsc_deadline);

    msr_data.info.nmsrs = 1;

    return kvm_vcpu_ioctl(CPU(cpu), KVM_SET_MSRS, &msr_data);

}


static void m5208_sys_write(void *opaque, target_phys_addr_t addr,

                            uint64_t value, unsigned size)

{

    hw_error("m5208_sys_write: Bad offset 0x%x\n", (int)addr);

}


static int get_physical_address_data(CPUState *env,

                                     target_phys_addr_t *physical, int *prot,

                                     target_ulong address, int rw, int is_user)

{

    unsigned int i;

    uint64_t context;

    int is_nucleus;

    if ((env->lsu & DMMU_E) == 0) { /* DMMU disabled */

        *physical = ultrasparc_truncate_physical(address);

        *prot = PAGE_READ | PAGE_WRITE;

        return 0;

    }

    context = env->dmmu.mmu_primary_context & 0x1fff;

    is_nucleus = env->tl > 0;

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

        // ctx match, vaddr match, valid?

        if (ultrasparc_tag_match(&env->dtlb[i],

                                 address, context, physical,

                                 is_nucleus)) {

            // access ok?

            if (((env->dtlb[i].tte & 0x4) && is_user) ||

                (!(env->dtlb[i].tte & 0x2) && (rw == 1))) {

                uint8_t fault_type = 0;

                if ((env->dtlb[i].tte & 0x4) && is_user) {

                    fault_type |= 1; /* privilege violation */

                }

                if (env->dmmu.sfsr & 1) /* Fault status register */

                    env->dmmu.sfsr = 2; /* overflow (not read before

                                             another fault) */

                env->dmmu.sfsr |= (is_user << 3) | ((rw == 1) << 2) | 1;

                env->dmmu.sfsr |= (fault_type << 7);

                env->dmmu.sfar = address; /* Fault address register */

                env->exception_index = TT_DFAULT;

#ifdef DEBUG_MMU

                printf("DFAULT at 0x%" PRIx64 "\n", address);

#endif

                return 1;

            }

            *prot = PAGE_READ;

            if (env->dtlb[i].tte & 0x2)

                *prot |= PAGE_WRITE;

            TTE_SET_USED(env->dtlb[i].tte);

            return 0;

        }

    }

#ifdef DEBUG_MMU

    printf("DMISS at 0x%" PRIx64 "\n", address);

#endif

    env->dmmu.tag_access = (address & ~0x1fffULL) | context;

    env->exception_index = TT_DMISS;

    return 1;

}


static void sd_response_r1_make(SDState *sd, uint8_t *response)

{

    uint32_t status = sd->card_status;

    /* Clear the "clear on read" status bits (except APP_CMD) */

    sd->card_status &= ~CARD_STATUS_C | APP_CMD;

    response[0] = (status >> 24) & 0xff;

    response[1] = (status >> 16) & 0xff;

    response[2] = (status >> 8) & 0xff;

    response[3] = (status >> 0) & 0xff;

}


void FUNC(ff_simple_idct_add)(uint8_t *dest_, int line_size, DCTELEM *block)

{

    pixel *dest = (pixel *)dest_;

    int i;

    line_size /= sizeof(pixel);

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

        FUNC(idctRowCondDC)(block + i*8);

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

        FUNC(idctSparseColAdd)(dest + i, line_size, block + i);

}


static void pci_set_irq(void *opaque, int irq_num, int level)

{

    PCIDevice *pci_dev = opaque;

    PCIBus *bus;

    int change;

    change = level - pci_dev->irq_state[irq_num];

    if (!change)

        return;

    pci_dev->irq_state[irq_num] = level;

    for (;;) {

        bus = pci_dev->bus;

        irq_num = bus->map_irq(pci_dev, irq_num);

        if (bus->set_irq)

            break;

        pci_dev = bus->parent_dev;

    }

    bus->irq_count[irq_num] += change;

    bus->set_irq(bus->irq_opaque, irq_num, bus->irq_count[irq_num] != 0);

}


static int setup_partitions(VP8Context *s, const uint8_t *buf, int buf_size)

{

    const uint8_t *sizes = buf;

    int i;

    s->num_coeff_partitions = 1 << vp8_rac_get_uint(&s->c, 2);

    buf      += 3 * (s->num_coeff_partitions - 1);

    buf_size -= 3 * (s->num_coeff_partitions - 1);

    if (buf_size < 0)

        return -1;

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

        int size = AV_RL24(sizes + 3 * i);

        if (buf_size - size < 0)

            return -1;

        ff_vp56_init_range_decoder(&s->coeff_partition[i], buf, size);

        buf      += size;

        buf_size -= size;

    }

    ff_vp56_init_range_decoder(&s->coeff_partition[i], buf, buf_size);

    return 0;

}


static int load_data(AVFilterContext *ctx, int azim, int elev, float radius)

{

    struct SOFAlizerContext *s = ctx->priv;

    const int n_samples = s->sofa.n_samples;

    int n_conv = s->n_conv; /* no. channels to convolve */

    int n_fft = s->n_fft;

    int delay_l[16]; /* broadband delay for each IR */

    int delay_r[16];

    int nb_input_channels = ctx->inputs[0]->channels; /* no. input channels */

    float gain_lin = expf((s->gain - 3 * nb_input_channels) / 20 * M_LN10); /* gain - 3dB/channel */

    FFTComplex *data_hrtf_l = NULL;

    FFTComplex *data_hrtf_r = NULL;

    FFTComplex *fft_in_l = NULL;

    FFTComplex *fft_in_r = NULL;

    float *data_ir_l = NULL;

    float *data_ir_r = NULL;

    int offset = 0; /* used for faster pointer arithmetics in for-loop */

    int m[16]; /* measurement index m of IR closest to required source positions */

    int i, j, azim_orig = azim, elev_orig = elev;

    if (!s->sofa.ncid) { /* if an invalid SOFA file has been selected */

        av_log(ctx, AV_LOG_ERROR, "Selected SOFA file is invalid. Please select valid SOFA file.\n");

        return AVERROR_INVALIDDATA;

    }

    if (s->type == TIME_DOMAIN) {

        s->temp_src[0] = av_calloc(FFALIGN(n_samples, 16), sizeof(float));

        s->temp_src[1] = av_calloc(FFALIGN(n_samples, 16), sizeof(float));

        /* get temporary IR for L and R channel */

        data_ir_l = av_malloc_array(n_conv * n_samples, sizeof(*data_ir_l));

        data_ir_r = av_malloc_array(n_conv * n_samples, sizeof(*data_ir_r));

        if (!data_ir_r || !data_ir_l || !s->temp_src[0] || !s->temp_src[1]) {

            av_free(data_ir_l);

            av_free(data_ir_r);

            return AVERROR(ENOMEM);

        }

    } else {

        /* get temporary HRTF memory for L and R channel */

        data_hrtf_l = av_malloc_array(n_fft, sizeof(*data_hrtf_l) * n_conv);

        data_hrtf_r = av_malloc_array(n_fft, sizeof(*data_hrtf_r) * n_conv);

        if (!data_hrtf_r || !data_hrtf_l) {

            av_free(data_hrtf_l);

            av_free(data_hrtf_r);

            return AVERROR(ENOMEM);

        }

    }

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

        /* load and store IRs and corresponding delays */

        azim = (int)(s->speaker_azim[i] + azim_orig) % 360;

        elev = (int)(s->speaker_elev[i] + elev_orig) % 90;

        /* get id of IR closest to desired position */

        m[i] = find_m(s, azim, elev, radius);

        /* load the delays associated with the current IRs */

        delay_l[i] = *(s->sofa.data_delay + 2 * m[i]);

        delay_r[i] = *(s->sofa.data_delay + 2 * m[i] + 1);

        if (s->type == TIME_DOMAIN) {

            offset = i * n_samples; /* no. samples already written */

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

                /* load reversed IRs of the specified source position

                 * sample-by-sample for left and right ear; and apply gain */

                *(data_ir_l + offset + j) = /* left channel */

                *(s->sofa.data_ir + 2 * m[i] * n_samples + n_samples - 1 - j) * gain_lin;

                *(data_ir_r + offset + j) = /* right channel */

                *(s->sofa.data_ir + 2 * m[i] * n_samples + n_samples - 1 - j  + n_samples) * gain_lin;

            }

        } else {

            fft_in_l = av_calloc(n_fft, sizeof(*fft_in_l));

            fft_in_r = av_calloc(n_fft, sizeof(*fft_in_r));

            if (!fft_in_l || !fft_in_r) {

                av_free(data_hrtf_l);

                av_free(data_hrtf_r);

                av_free(fft_in_l);

                av_free(fft_in_r);

                return AVERROR(ENOMEM);

            }

            offset = i * n_fft; /* no. samples already written */

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

                /* load non-reversed IRs of the specified source position

                 * sample-by-sample and apply gain,

                 * L channel is loaded to real part, R channel to imag part,

                 * IRs ared shifted by L and R delay */

                fft_in_l[delay_l[i] + j].re = /* left channel */

                *(s->sofa.data_ir + 2 * m[i] * n_samples + j) * gain_lin;

                fft_in_r[delay_r[i] + j].re = /* right channel */

                *(s->sofa.data_ir + (2 * m[i] + 1) * n_samples + j) * gain_lin;

            }

            /* actually transform to frequency domain (IRs -> HRTFs) */

            av_fft_permute(s->fft[0], fft_in_l);

            av_fft_calc(s->fft[0], fft_in_l);

            memcpy(data_hrtf_l + offset, fft_in_l, n_fft * sizeof(*fft_in_l));

            av_fft_permute(s->fft[0], fft_in_r);

            av_fft_calc(s->fft[0], fft_in_r);

            memcpy(data_hrtf_r + offset, fft_in_r, n_fft * sizeof(*fft_in_r));

        }

        av_log(ctx, AV_LOG_DEBUG, "Index: %d, Azimuth: %f, Elevation: %f, Radius: %f of SOFA file.\n",

               m[i], *(s->sofa.sp_a + m[i]), *(s->sofa.sp_e + m[i]), *(s->sofa.sp_r + m[i]));

    }

    if (s->type == TIME_DOMAIN) {

        /* copy IRs and delays to allocated memory in the SOFAlizerContext struct: */

        memcpy(s->data_ir[0], data_ir_l, sizeof(float) * n_conv * n_samples);

        memcpy(s->data_ir[1], data_ir_r, sizeof(float) * n_conv * n_samples);

        av_freep(&data_ir_l); /* free temporary IR memory */

        av_freep(&data_ir_r);

    } else {

        s->data_hrtf[0] = av_malloc_array(n_fft * s->n_conv, sizeof(FFTComplex));

        s->data_hrtf[1] = av_malloc_array(n_fft * s->n_conv, sizeof(FFTComplex));

        if (!s->data_hrtf[0] || !s->data_hrtf[1]) {

            av_freep(&data_hrtf_l);

            av_freep(&data_hrtf_r);

            av_freep(&fft_in_l);

            av_freep(&fft_in_r);

            return AVERROR(ENOMEM); /* memory allocation failed */

        }

        memcpy(s->data_hrtf[0], data_hrtf_l, /* copy HRTF data to */

            sizeof(FFTComplex) * n_conv * n_fft); /* filter struct */

        memcpy(s->data_hrtf[1], data_hrtf_r,

            sizeof(FFTComplex) * n_conv * n_fft);

        av_freep(&data_hrtf_l); /* free temporary HRTF memory */

        av_freep(&data_hrtf_r);

        av_freep(&fft_in_l); /* free temporary FFT memory */

        av_freep(&fft_in_r);

    }

    memcpy(s->delay[0], &delay_l[0], sizeof(int) * s->n_conv);

    memcpy(s->delay[1], &delay_r[0], sizeof(int) * s->n_conv);

    return 0;

}


static int decode_555(GetByteContext *gB, uint16_t *dst, int stride,

                      int keyframe, int w, int h)

{

    int last_symbol = 0, repeat = 0, prev_avail = 0;

    if (!keyframe) {

        int x, y, endx, endy, t;

#define READ_PAIR(a, b)                 \

    a  = bytestream2_get_byte(gB) << 4; \

    t  = bytestream2_get_byte(gB);      \

    a |= t >> 4;                        \

    b  = (t & 0xF) << 8;                \

    b |= bytestream2_get_byte(gB);      \

        READ_PAIR(x, endx)

        READ_PAIR(y, endy)

        if (endx >= w || endy >= h || x > endx || y > endy)

            return AVERROR_INVALIDDATA;

        dst += x + stride * y;

        w    = endx - x + 1;

        h    = endy - y + 1;

        if (y)

            prev_avail = 1;

    }

    do {

        uint16_t *p = dst;

        do {

            if (repeat-- < 1) {

                int b = bytestream2_get_byte(gB);

                if (b < 128)

                    last_symbol = b << 8 | bytestream2_get_byte(gB);

                else if (b > 129) {

                    repeat = 0;

                    while (b-- > 130)

                        repeat = (repeat << 8) + bytestream2_get_byte(gB) + 1;

                    if (last_symbol == -2) {

                        int skip = FFMIN((unsigned)repeat, dst + w - p);

                        repeat -= skip;

                        p      += skip;

                    }

                } else

                    last_symbol = 127 - b;

            }

            if (last_symbol >= 0)

                *p = last_symbol;

            else if (last_symbol == -1 && prev_avail)

                *p = *(p - stride);

        } while (++p < dst + w);

        dst       += stride;

        prev_avail = 1;

    } while (--h);

    return 0;

}


static int get_rice_un(GetBitContext *gb, int k)

{

    unsigned int v = get_unary(gb, 1, 128);

    return (v << k) | get_bits_long(gb, k);

}


static void qmf_32_subbands(DCAContext * s, int chans,

                            float samples_in[32][8], float *samples_out,

                            float scale)

{

    const float *prCoeff;

    int i;

    int sb_act = s->subband_activity[chans];

    int subindex;

    scale *= sqrt(1/8.0);

    /* Select filter */

    if (!s->multirate_inter)    /* Non-perfect reconstruction */

        prCoeff = fir_32bands_nonperfect;

    else                        /* Perfect reconstruction */

        prCoeff = fir_32bands_perfect;

    /* Reconstructed channel sample index */

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

        /* Load in one sample from each subband and clear inactive subbands */

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

            uint32_t v = AV_RN32A(&samples_in[i][subindex]) ^ ((i-1)&2)<<30;

            AV_WN32A(&s->raXin[i], v);

        }

        for (; i < 32; i++)

            s->raXin[i] = 0.0;

        s->synth.synth_filter_float(&s->imdct,

                              s->subband_fir_hist[chans], &s->hist_index[chans],

                              s->subband_fir_noidea[chans], prCoeff,

                              samples_out, s->raXin, scale);

        samples_out+= 32;

    }

}


static int vnc_display_connect(VncDisplay *vd,

                               SocketAddressLegacy **saddr,

                               size_t nsaddr,

                               SocketAddressLegacy **wsaddr,

                               size_t nwsaddr,

                               Error **errp)

{

    /* connect to viewer */

    QIOChannelSocket *sioc = NULL;

    if (nwsaddr != 0) {

        error_setg(errp, "Cannot use websockets in reverse mode");

        return -1;

    }

    if (nsaddr != 1) {

        error_setg(errp, "Expected a single address in reverse mode");

        return -1;

    }

    /* TODO SOCKET_ADDRESS_LEGACY_KIND_FD when fd has AF_UNIX */

    vd->is_unix = saddr[0]->type == SOCKET_ADDRESS_LEGACY_KIND_UNIX;

    sioc = qio_channel_socket_new();

    qio_channel_set_name(QIO_CHANNEL(sioc), "vnc-reverse");

    if (qio_channel_socket_connect_sync(sioc, saddr[0], errp) < 0) {

        return -1;

    }

    vnc_connect(vd, sioc, false, false);

    object_unref(OBJECT(sioc));

    return 0;

}


int64_t av_get_channel_layout(const char *name)

{

    int i = 0;

    do {

        if (!strcmp(channel_layout_map[i].name, name))

            return channel_layout_map[i].layout;

        i++;

    } while (channel_layout_map[i].name);

    return 0;

}


static DevicePropertyInfo *make_device_property_info(ObjectClass *klass,

                                                     const char *name,

                                                     const char *default_type,

                                                     const char *description)

{

    DevicePropertyInfo *info;

    Property *prop;

    do {

        for (prop = DEVICE_CLASS(klass)->props; prop && prop->name; prop++) {

            if (strcmp(name, prop->name) != 0) {

                continue;

            }

            /*

             * TODO Properties without a parser are just for dirty hacks.

             * qdev_prop_ptr is the only such PropertyInfo.  It's marked

             * for removal.  This conditional should be removed along with

             * it.

             */

            if (!prop->info->set) {

                return NULL;           /* no way to set it, don't show */

            }

            info = g_malloc0(sizeof(*info));

            info->name = g_strdup(prop->name);

            info->type = g_strdup(prop->info->name);

            info->has_description = !!prop->info->description;

            info->description = g_strdup(prop->info->description);

            return info;

        }

        klass = object_class_get_parent(klass);

    } while (klass != object_class_by_name(TYPE_DEVICE));

    /* Not a qdev property, use the default type */

    info = g_malloc0(sizeof(*info));

    info->name = g_strdup(name);

    info->type = g_strdup(default_type);

    info->has_description = !!description;

    info->description = g_strdup(description);

    return info;

}


static void sun4uv_init(MemoryRegion *address_space_mem,

                        QEMUMachineInitArgs *args,

                        const struct hwdef *hwdef)

{

    SPARCCPU *cpu;

    M48t59State *nvram;

    unsigned int i;

    uint64_t initrd_addr, initrd_size, kernel_addr, kernel_size, kernel_entry;

    PCIBus *pci_bus, *pci_bus2, *pci_bus3;

    ISABus *isa_bus;

    qemu_irq *ivec_irqs, *pbm_irqs;

    DriveInfo *hd[MAX_IDE_BUS * MAX_IDE_DEVS];

    DriveInfo *fd[MAX_FD];

    FWCfgState *fw_cfg;

    /* init CPUs */

    cpu = cpu_devinit(args->cpu_model, hwdef);

    /* set up devices */

    ram_init(0, args->ram_size);

    prom_init(hwdef->prom_addr, bios_name);

    ivec_irqs = qemu_allocate_irqs(cpu_set_ivec_irq, cpu, IVEC_MAX);

    pci_bus = pci_apb_init(APB_SPECIAL_BASE, APB_MEM_BASE, ivec_irqs, &pci_bus2,

                           &pci_bus3, &pbm_irqs);

    pci_vga_init(pci_bus);

    // XXX Should be pci_bus3

    isa_bus = pci_ebus_init(pci_bus, -1, pbm_irqs);

    i = 0;

    if (hwdef->console_serial_base) {

        serial_mm_init(address_space_mem, hwdef->console_serial_base, 0,

                       NULL, 115200, serial_hds[i], DEVICE_BIG_ENDIAN);

        i++;

    }

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

        if (serial_hds[i]) {

            serial_isa_init(isa_bus, i, serial_hds[i]);

        }

    }

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

        if (parallel_hds[i]) {

            parallel_init(isa_bus, i, parallel_hds[i]);

        }

    }

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

        pci_nic_init_nofail(&nd_table[i], pci_bus, "ne2k_pci", NULL);

    ide_drive_get(hd, MAX_IDE_BUS);

    pci_cmd646_ide_init(pci_bus, hd, 1);

    isa_create_simple(isa_bus, "i8042");

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

        fd[i] = drive_get(IF_FLOPPY, 0, i);

    }

    fdctrl_init_isa(isa_bus, fd);

    nvram = m48t59_init_isa(isa_bus, 0x0074, NVRAM_SIZE, 59);

    initrd_size = 0;

    initrd_addr = 0;

    kernel_size = sun4u_load_kernel(args->kernel_filename,

                                    args->initrd_filename,

                                    ram_size, &initrd_size, &initrd_addr,

                                    &kernel_addr, &kernel_entry);

    sun4u_NVRAM_set_params(nvram, NVRAM_SIZE, "Sun4u", args->ram_size,

                           args->boot_device,

                           kernel_addr, kernel_size,

                           args->kernel_cmdline,

                           initrd_addr, initrd_size,

                           /* XXX: need an option to load a NVRAM image */

                           0,

                           graphic_width, graphic_height, graphic_depth,

                           (uint8_t *)&nd_table[0].macaddr);

    fw_cfg = fw_cfg_init(BIOS_CFG_IOPORT, BIOS_CFG_IOPORT + 1, 0, 0);

    fw_cfg_add_i16(fw_cfg, FW_CFG_MAX_CPUS, (uint16_t)max_cpus);

    fw_cfg_add_i32(fw_cfg, FW_CFG_ID, 1);

    fw_cfg_add_i64(fw_cfg, FW_CFG_RAM_SIZE, (uint64_t)ram_size);

    fw_cfg_add_i16(fw_cfg, FW_CFG_MACHINE_ID, hwdef->machine_id);

    fw_cfg_add_i64(fw_cfg, FW_CFG_KERNEL_ADDR, kernel_entry);

    fw_cfg_add_i64(fw_cfg, FW_CFG_KERNEL_SIZE, kernel_size);

    if (args->kernel_cmdline) {

        fw_cfg_add_i32(fw_cfg, FW_CFG_CMDLINE_SIZE,

                       strlen(args->kernel_cmdline) + 1);

        fw_cfg_add_string(fw_cfg, FW_CFG_CMDLINE_DATA, args->kernel_cmdline);

    } else {

        fw_cfg_add_i32(fw_cfg, FW_CFG_CMDLINE_SIZE, 0);

    }

    fw_cfg_add_i64(fw_cfg, FW_CFG_INITRD_ADDR, initrd_addr);

    fw_cfg_add_i64(fw_cfg, FW_CFG_INITRD_SIZE, initrd_size);

    fw_cfg_add_i16(fw_cfg, FW_CFG_BOOT_DEVICE, args->boot_device[0]);

    fw_cfg_add_i16(fw_cfg, FW_CFG_SPARC64_WIDTH, graphic_width);

    fw_cfg_add_i16(fw_cfg, FW_CFG_SPARC64_HEIGHT, graphic_height);

    fw_cfg_add_i16(fw_cfg, FW_CFG_SPARC64_DEPTH, graphic_depth);

    qemu_register_boot_set(fw_cfg_boot_set, fw_cfg);

}


static void buffered_rate_tick(void *opaque)

{

    QEMUFileBuffered *s = opaque;

    if (s->has_error) {

        buffered_close(s);

        return;

    }

    qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 100);

    if (s->freeze_output)

        return;

    s->bytes_xfer = 0;

    buffered_flush(s);

    /* Add some checks around this */

    s->put_ready(s->opaque);

}


void nbd_client_session_close(NbdClientSession *client)

{

    struct nbd_request request = {

        .type = NBD_CMD_DISC,

        .from = 0,

        .len = 0

    };

    if (!client->bs) {

        return;

    }

    if (client->sock == -1) {

        return;

    }

    nbd_send_request(client->sock, &request);

    nbd_teardown_connection(client);

    client->bs = NULL;

}


void blk_insert_bs(BlockBackend *blk, BlockDriverState *bs)

{

    bdrv_ref(bs);

    blk->root = bdrv_root_attach_child(bs, "root", &child_root, blk);

    notifier_list_notify(&blk->insert_bs_notifiers, blk);

    if (blk->public.throttle_state) {

        throttle_timers_attach_aio_context(

            &blk->public.throttle_timers, bdrv_get_aio_context(bs));

    }

}


static void test_init(TestData *d)

{

    QPCIBus *bus;

    QTestState *qs;

    char *s;

    s = g_strdup_printf("-machine q35 %s", !d->args ? "" : d->args);

    qs = qtest_start(s);

    qtest_irq_intercept_in(qs, "ioapic");

    g_free(s);

    bus = qpci_init_pc();

    d->dev = qpci_device_find(bus, QPCI_DEVFN(0x1f, 0x00));

    g_assert(d->dev != NULL);

    /* map PCI-to-LPC bridge interface BAR */

    d->lpc_base = qpci_iomap(d->dev, 0, NULL);

    qpci_device_enable(d->dev);

    g_assert(d->lpc_base != NULL);

    /* set ACPI PM I/O space base address */

    qpci_config_writel(d->dev, (uintptr_t)d->lpc_base + ICH9_LPC_PMBASE,

                       PM_IO_BASE_ADDR | 0x1);

    /* enable ACPI I/O */

    qpci_config_writeb(d->dev, (uintptr_t)d->lpc_base + ICH9_LPC_ACPI_CTRL,

                       0x80);

    /* set Root Complex BAR */

    qpci_config_writel(d->dev, (uintptr_t)d->lpc_base + ICH9_LPC_RCBA,

                       RCBA_BASE_ADDR | 0x1);

    d->tco_io_base = (void *)((uintptr_t)PM_IO_BASE_ADDR + 0x60);

}


START_TEST(qdict_stress_test)

{

    size_t lines;

    char key[128];

    FILE *test_file;

    QDict *qdict;

    QString *value;

    const char *test_file_path = "qdict-test-data.txt";

    test_file = fopen(test_file_path, "r");

    fail_unless(test_file != NULL);

    // Create the dict

    qdict = qdict_new();

    fail_unless(qdict != NULL);

    // Add everything from the test file

    for (lines = 0;; lines++) {

        value = read_line(test_file, key);

        if (!value)

            break;

        qdict_put(qdict, key, value);

    }

    fail_unless(qdict_size(qdict) == lines);

    // Check if everything is really in there

    reset_file(test_file);

    for (;;) {

        const char *str1, *str2;

        value = read_line(test_file, key);

        if (!value)

            break;

        str1 = qstring_get_str(value);

        str2 = qdict_get_str(qdict, key);

        fail_unless(str2 != NULL);

        fail_unless(strcmp(str1, str2) == 0);

        QDECREF(value);

    }

    // Delete everything

    reset_file(test_file);

    for (;;) {

        value = read_line(test_file, key);

        if (!value)

            break;

        qdict_del(qdict, key);

        QDECREF(value);

        fail_unless(qdict_haskey(qdict, key) == 0);

    }

    fclose(test_file);

    fail_unless(qdict_size(qdict) == 0);

    QDECREF(qdict);

}


static int sl_nand_init(SysBusDevice *dev)

{

    SLNANDState *s = SL_NAND(dev);

    DriveInfo *nand;

    s->ctl = 0;

    nand = drive_get(IF_MTD, 0, 0);

    s->nand = nand_init(nand ? blk_bs(blk_by_legacy_dinfo(nand)) : NULL,

                        s->manf_id, s->chip_id);

    memory_region_init_io(&s->iomem, OBJECT(s), &sl_ops, s, "sl", 0x40);

    sysbus_init_mmio(dev, &s->iomem);

    return 0;

}


void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)

{

    QEMUPutMouseEntry *entry;

    QEMUPutMouseEvent *mouse_event;

    void *mouse_event_opaque;

    int width, height;

    if (!runstate_is_running()) {

        return;

    }

    if (QTAILQ_EMPTY(&mouse_handlers)) {

        return;

    }

    entry = QTAILQ_FIRST(&mouse_handlers);

    mouse_event = entry->qemu_put_mouse_event;

    mouse_event_opaque = entry->qemu_put_mouse_event_opaque;

    if (mouse_event) {

        if (entry->qemu_put_mouse_event_absolute) {

            width = 0x7fff;

            height = 0x7fff;

        } else {

            width = graphic_width - 1;

            height = graphic_height - 1;

        }

        switch (graphic_rotate) {

        case 0:

            mouse_event(mouse_event_opaque,

                        dx, dy, dz, buttons_state);

            break;

        case 90:

            mouse_event(mouse_event_opaque,

                        width - dy, dx, dz, buttons_state);

            break;

        case 180:

            mouse_event(mouse_event_opaque,

                        width - dx, height - dy, dz, buttons_state);

            break;

        case 270:

            mouse_event(mouse_event_opaque,

                        dy, height - dx, dz, buttons_state);

            break;

        }

    }

}


static int vmdvideo_decode_init(AVCodecContext *avctx)

{

    VmdVideoContext *s = avctx->priv_data;

    int i;

    unsigned int *palette32;

    int palette_index = 0;

    unsigned char r, g, b;

    unsigned char *vmd_header;

    unsigned char *raw_palette;

    s->avctx = avctx;

    avctx->pix_fmt = PIX_FMT_PAL8;

    dsputil_init(&s->dsp, avctx);

    /* make sure the VMD header made it */

    if (s->avctx->extradata_size != VMD_HEADER_SIZE) {

        av_log(s->avctx, AV_LOG_ERROR, "VMD video: expected extradata size of %d\n",

            VMD_HEADER_SIZE);

        return -1;

    }

    vmd_header = (unsigned char *)avctx->extradata;

    s->unpack_buffer_size = AV_RL32(&vmd_header[800]);

    s->unpack_buffer = av_malloc(s->unpack_buffer_size);

    if (!s->unpack_buffer)

        return -1;

    /* load up the initial palette */

    raw_palette = &vmd_header[28];

    palette32 = (unsigned int *)s->palette;

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

        r = raw_palette[palette_index++] * 4;

        g = raw_palette[palette_index++] * 4;

        b = raw_palette[palette_index++] * 4;

        palette32[i] = (r << 16) | (g << 8) | (b);

    }

    s->frame.data[0] = s->prev_frame.data[0] = NULL;

    return 0;

}


static int mmap_frag(abi_ulong real_start,

                     abi_ulong start, abi_ulong end,

                     int prot, int flags, int fd, abi_ulong offset)

{

    abi_ulong real_end, addr;

    void *host_start;

    int prot1, prot_new;

    real_end = real_start + qemu_host_page_size;

    host_start = g2h(real_start);

    /* get the protection of the target pages outside the mapping */

    prot1 = 0;

    for(addr = real_start; addr < real_end; addr++) {

        if (addr < start || addr >= end)

            prot1 |= page_get_flags(addr);

    }

    if (prot1 == 0) {

        /* no page was there, so we allocate one */

        void *p = mmap(host_start, qemu_host_page_size, prot,

                       flags | MAP_ANONYMOUS, -1, 0);

        if (p == MAP_FAILED)

            return -1;

        prot1 = prot;

    }

    prot1 &= PAGE_BITS;

    prot_new = prot | prot1;

    if (!(flags & MAP_ANONYMOUS)) {

        /* msync() won't work here, so we return an error if write is

           possible while it is a shared mapping */

        if ((flags & MAP_TYPE) == MAP_SHARED &&

            (prot & PROT_WRITE))

            return -EINVAL;

        /* adjust protection to be able to read */

        if (!(prot1 & PROT_WRITE))

            mprotect(host_start, qemu_host_page_size, prot1 | PROT_WRITE);

        /* read the corresponding file data */

        if (pread(fd, g2h(start), end - start, offset) == -1)

            return -1;

        /* put final protection */

        if (prot_new != (prot1 | PROT_WRITE))

            mprotect(host_start, qemu_host_page_size, prot_new);

    } else {

        /* just update the protection */

        if (prot_new != prot1) {

            mprotect(host_start, qemu_host_page_size, prot_new);

        }

    }

    return 0;

}


int qcow2_check_metadata_overlap(BlockDriverState *bs, int ign, int64_t offset,

                                 int64_t size)

{

    BDRVQcowState *s = bs->opaque;

    int chk = QCOW2_OL_DEFAULT & ~ign;

    int i, j;

    if (!size) {

        return 0;

    }

    if (chk & QCOW2_OL_MAIN_HEADER) {

        if (offset < s->cluster_size) {

            return QCOW2_OL_MAIN_HEADER;

        }

    }

    /* align range to test to cluster boundaries */

    size = align_offset(offset_into_cluster(s, offset) + size, s->cluster_size);

    offset = start_of_cluster(s, offset);

    if ((chk & QCOW2_OL_ACTIVE_L1) && s->l1_size) {

        if (overlaps_with(s->l1_table_offset, s->l1_size * sizeof(uint64_t))) {

            return QCOW2_OL_ACTIVE_L1;

        }

    }

    if ((chk & QCOW2_OL_REFCOUNT_TABLE) && s->refcount_table_size) {

        if (overlaps_with(s->refcount_table_offset,

            s->refcount_table_size * sizeof(uint64_t))) {

            return QCOW2_OL_REFCOUNT_TABLE;

        }

    }

    if ((chk & QCOW2_OL_SNAPSHOT_TABLE) && s->snapshots_size) {

        if (overlaps_with(s->snapshots_offset, s->snapshots_size)) {

            return QCOW2_OL_SNAPSHOT_TABLE;

        }

    }

    if ((chk & QCOW2_OL_INACTIVE_L1) && s->snapshots) {

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

            if (s->snapshots[i].l1_size &&

                overlaps_with(s->snapshots[i].l1_table_offset,

                s->snapshots[i].l1_size * sizeof(uint64_t))) {

                return QCOW2_OL_INACTIVE_L1;

            }

        }

    }

    if ((chk & QCOW2_OL_ACTIVE_L2) && s->l1_table) {

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

            if ((s->l1_table[i] & L1E_OFFSET_MASK) &&

                overlaps_with(s->l1_table[i] & L1E_OFFSET_MASK,

                s->cluster_size)) {

                return QCOW2_OL_ACTIVE_L2;

            }

        }

    }

    if ((chk & QCOW2_OL_REFCOUNT_BLOCK) && s->refcount_table) {

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

            if ((s->refcount_table[i] & REFT_OFFSET_MASK) &&

                overlaps_with(s->refcount_table[i] & REFT_OFFSET_MASK,

                s->cluster_size)) {

                return QCOW2_OL_REFCOUNT_BLOCK;

            }

        }

    }

    if ((chk & QCOW2_OL_INACTIVE_L2) && s->snapshots) {

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

            uint64_t l1_ofs = s->snapshots[i].l1_table_offset;

            uint32_t l1_sz  = s->snapshots[i].l1_size;

            uint64_t l1_sz2 = l1_sz * sizeof(uint64_t);

            uint64_t *l1 = g_malloc(l1_sz2);

            int ret;

            ret = bdrv_pread(bs->file, l1_ofs, l1, l1_sz2);

            if (ret < 0) {

                g_free(l1);

                return ret;

            }

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

                uint64_t l2_ofs = be64_to_cpu(l1[j]) & L1E_OFFSET_MASK;

                if (l2_ofs && overlaps_with(l2_ofs, s->cluster_size)) {

                    g_free(l1);

                    return QCOW2_OL_INACTIVE_L2;

                }

            }

            g_free(l1);

        }

    }

    return 0;

}


void tb_phys_invalidate(TranslationBlock *tb, tb_page_addr_t page_addr)

{

    CPUState *cpu;

    PageDesc *p;

    uint32_t h;

    tb_page_addr_t phys_pc;

    assert_tb_locked();

    atomic_set(&tb->invalid, true);

    /* remove the TB from the hash list */

    phys_pc = tb->page_addr[0] + (tb->pc & ~TARGET_PAGE_MASK);

    h = tb_hash_func(phys_pc, tb->pc, tb->flags, tb->trace_vcpu_dstate);

    qht_remove(&tcg_ctx.tb_ctx.htable, tb, h);

    /* remove the TB from the page list */

    if (tb->page_addr[0] != page_addr) {

        p = page_find(tb->page_addr[0] >> TARGET_PAGE_BITS);

        tb_page_remove(&p->first_tb, tb);

        invalidate_page_bitmap(p);

    }

    if (tb->page_addr[1] != -1 && tb->page_addr[1] != page_addr) {

        p = page_find(tb->page_addr[1] >> TARGET_PAGE_BITS);

        tb_page_remove(&p->first_tb, tb);

        invalidate_page_bitmap(p);

    }

    /* remove the TB from the hash list */

    h = tb_jmp_cache_hash_func(tb->pc);

    CPU_FOREACH(cpu) {

        if (atomic_read(&cpu->tb_jmp_cache[h]) == tb) {

            atomic_set(&cpu->tb_jmp_cache[h], NULL);

        }

    }

    /* suppress this TB from the two jump lists */

    tb_remove_from_jmp_list(tb, 0);

    tb_remove_from_jmp_list(tb, 1);

    /* suppress any remaining jumps to this TB */

    tb_jmp_unlink(tb);

    tcg_ctx.tb_ctx.tb_phys_invalidate_count++;

}


int nbd_client_co_flush(BlockDriverState *bs)

{

    NbdClientSession *client = nbd_get_client_session(bs);

    struct nbd_request request = { .type = NBD_CMD_FLUSH };

    struct nbd_reply reply;

    ssize_t ret;

    if (!(client->nbdflags & NBD_FLAG_SEND_FLUSH)) {

        return 0;

    }

    if (client->nbdflags & NBD_FLAG_SEND_FUA) {

        request.type |= NBD_CMD_FLAG_FUA;

    }

    request.from = 0;

    request.len = 0;

    nbd_coroutine_start(client, &request);

    ret = nbd_co_send_request(bs, &request, NULL, 0);

    if (ret < 0) {

        reply.error = -ret;

    } else {

        nbd_co_receive_reply(client, &request, &reply, NULL, 0);

    }

    nbd_coroutine_end(client, &request);

    return -reply.error;

}


void *colo_process_incoming_thread(void *opaque)

{

    MigrationIncomingState *mis = opaque;

    migrate_set_state(&mis->state, MIGRATION_STATUS_ACTIVE,

                      MIGRATION_STATUS_COLO);

    mis->to_src_file = qemu_file_get_return_path(mis->from_src_file);

    if (!mis->to_src_file) {

        error_report("COLO incoming thread: Open QEMUFile to_src_file failed");

        goto out;

    }

    /*

     * Note: the communication between Primary side and Secondary side

     * should be sequential, we set the fd to unblocked in migration incoming

     * coroutine, and here we are in the COLO incoming thread, so it is ok to

     * set the fd back to blocked.

     */

    qemu_file_set_blocking(mis->from_src_file, true);

    /* TODO: COLO checkpoint restore loop */

out:

    if (mis->to_src_file) {

        qemu_fclose(mis->to_src_file);

    }

    migration_incoming_exit_colo();

    return NULL;

}


static int v9fs_receive_status(V9fsProxy *proxy,

                               struct iovec *reply, int *status)

{

    int retval;

    ProxyHeader header;

    *status = 0;

    reply->iov_len = 0;

    retval = socket_read(proxy->sockfd, reply->iov_base, PROXY_HDR_SZ);

    if (retval < 0) {

        return retval;

    }

    reply->iov_len = PROXY_HDR_SZ;

    proxy_unmarshal(reply, 0, "dd", &header.type, &header.size);

    if (header.size != sizeof(int)) {

        *status = -ENOBUFS;

        return 0;

    }

    retval = socket_read(proxy->sockfd,

                         reply->iov_base + PROXY_HDR_SZ, header.size);

    if (retval < 0) {

        return retval;

    }

    reply->iov_len += header.size;

    proxy_unmarshal(reply, PROXY_HDR_SZ, "d", status);

    return 0;

}


static int qemu_peek_byte(QEMUFile *f)

{

    if (f->is_write)

        abort();

    if (f->buf_index >= f->buf_size) {

        qemu_fill_buffer(f);

        if (f->buf_index >= f->buf_size)

            return 0;

    }

    return f->buf[f->buf_index];

}


static void kvm_fixup_page_sizes(PowerPCCPU *cpu)

{

    static struct kvm_ppc_smmu_info smmu_info;

    static bool has_smmu_info;

    CPUPPCState *env = &cpu->env;

    long rampagesize;

    int iq, ik, jq, jk;

    /* We only handle page sizes for 64-bit server guests for now */

    if (!(env->mmu_model & POWERPC_MMU_64)) {

        return;

    }

    /* Collect MMU info from kernel if not already */

    if (!has_smmu_info) {

        kvm_get_smmu_info(cpu, &smmu_info);

        has_smmu_info = true;

    }

    rampagesize = getrampagesize();

    /* Convert to QEMU form */

    memset(&env->sps, 0, sizeof(env->sps));

    for (ik = iq = 0; ik < KVM_PPC_PAGE_SIZES_MAX_SZ; ik++) {

        struct ppc_one_seg_page_size *qsps = &env->sps.sps[iq];

        struct kvm_ppc_one_seg_page_size *ksps = &smmu_info.sps[ik];

        if (!kvm_valid_page_size(smmu_info.flags, rampagesize,

                                 ksps->page_shift)) {

            continue;

        }

        qsps->page_shift = ksps->page_shift;

        qsps->slb_enc = ksps->slb_enc;

        for (jk = jq = 0; jk < KVM_PPC_PAGE_SIZES_MAX_SZ; jk++) {

            if (!kvm_valid_page_size(smmu_info.flags, rampagesize,

                                     ksps->enc[jk].page_shift)) {

                continue;

            }

            qsps->enc[jq].page_shift = ksps->enc[jk].page_shift;

            qsps->enc[jq].pte_enc = ksps->enc[jk].pte_enc;

            if (++jq >= PPC_PAGE_SIZES_MAX_SZ) {

                break;

            }

        }

        if (++iq >= PPC_PAGE_SIZES_MAX_SZ) {

            break;

        }

    }

    env->slb_nr = smmu_info.slb_size;

    if (smmu_info.flags & KVM_PPC_1T_SEGMENTS) {

        env->mmu_model |= POWERPC_MMU_1TSEG;

    } else {

        env->mmu_model &= ~POWERPC_MMU_1TSEG;

    }

}


static unsigned long *iscsi_allocationmap_init(IscsiLun *iscsilun)

{

    return bitmap_try_new(DIV_ROUND_UP(sector_lun2qemu(iscsilun->num_blocks,

                                                       iscsilun),

                                       iscsilun->cluster_sectors));

}


static int iscsi_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)

{

    IscsiLun *iscsilun = bs->opaque;

    bdi->unallocated_blocks_are_zero = !!iscsilun->lbprz;

    bdi->can_write_zeroes_with_unmap = iscsilun->lbprz && iscsilun->lbp.lbpws;

    /* Guess the internal cluster (page) size of the iscsi target by the means

     * of opt_unmap_gran. Transfer the unmap granularity only if it has a

     * reasonable size for bdi->cluster_size */

    if (iscsilun->bl.opt_unmap_gran * iscsilun->block_size >= 64 * 1024 &&

        iscsilun->bl.opt_unmap_gran * iscsilun->block_size <= 16 * 1024 * 1024) {

        bdi->cluster_size = iscsilun->bl.opt_unmap_gran * iscsilun->block_size;

    }

    return 0;

}


static void set_port(struct sockaddr_storage *ss, int port)

{

    sockaddr_union ssu = (sockaddr_union){.storage = *ss};

    if (ss->ss_family == AF_INET)

        ssu.in.sin_port = htons(port);

#if HAVE_STRUCT_SOCKADDR_IN6

    else if (ss->ss_family == AF_INET6)

        ssu.in6.sin6_port = htons(port);

#endif

    *ss = ssu.storage;

}


void unregister_savevm(const char *idstr, void *opaque)

{

    SaveStateEntry *se, *new_se;

    TAILQ_FOREACH_SAFE(se, &savevm_handlers, entry, new_se) {

        if (strcmp(se->idstr, idstr) == 0 && se->opaque == opaque) {

            TAILQ_REMOVE(&savevm_handlers, se, entry);

            qemu_free(se);

        }

    }

}


static int virtio_net_handle_offloads(VirtIONet *n, uint8_t cmd,

                                     struct iovec *iov, unsigned int iov_cnt)

{

    VirtIODevice *vdev = VIRTIO_DEVICE(n);

    uint64_t offloads;

    size_t s;

    if (!((1 << VIRTIO_NET_F_CTRL_GUEST_OFFLOADS) & vdev->guest_features)) {

        return VIRTIO_NET_ERR;

    }

    s = iov_to_buf(iov, iov_cnt, 0, &offloads, sizeof(offloads));

    if (s != sizeof(offloads)) {

        return VIRTIO_NET_ERR;

    }

    if (cmd == VIRTIO_NET_CTRL_GUEST_OFFLOADS_SET) {

        uint64_t supported_offloads;

        if (!n->has_vnet_hdr) {

            return VIRTIO_NET_ERR;

        }

        supported_offloads = virtio_net_supported_guest_offloads(n);

        if (offloads & ~supported_offloads) {

            return VIRTIO_NET_ERR;

        }

        n->curr_guest_offloads = offloads;

        virtio_net_apply_guest_offloads(n);

        return VIRTIO_NET_OK;

    } else {

        return VIRTIO_NET_ERR;

    }

}


static int coroutine_fn sd_co_flush_to_disk(BlockDriverState *bs)

{

    BDRVSheepdogState *s = bs->opaque;

    SheepdogObjReq hdr = { 0 };

    SheepdogObjRsp *rsp = (SheepdogObjRsp *)&hdr;

    SheepdogInode *inode = &s->inode;

    int ret;

    unsigned int wlen = 0, rlen = 0;

    if (s->cache_flags != SD_FLAG_CMD_CACHE) {

        return 0;

    }

    hdr.opcode = SD_OP_FLUSH_VDI;

    hdr.oid = vid_to_vdi_oid(inode->vdi_id);

    ret = do_req(s->flush_fd, (SheepdogReq *)&hdr, NULL, &wlen, &rlen);

    if (ret) {

        error_report("failed to send a request to the sheep");

        return ret;

    }

    if (rsp->result == SD_RES_INVALID_PARMS) {

        dprintf("disable write cache since the server doesn't support it\n");

        s->cache_flags = SD_FLAG_CMD_DIRECT;

        closesocket(s->flush_fd);

        return 0;

    }

    if (rsp->result != SD_RES_SUCCESS) {

        error_report("%s", sd_strerror(rsp->result));

        return -EIO;

    }

    return 0;

}


int tlb_set_page_exec(CPUState *env, target_ulong vaddr,

                      target_phys_addr_t paddr, int prot,

                      int mmu_idx, int is_softmmu)

{

    PhysPageDesc *p;

    unsigned long pd;

    unsigned int index;

    target_ulong address;

    target_ulong code_address;

    target_phys_addr_t addend;

    int ret;

    CPUTLBEntry *te;

    CPUWatchpoint *wp;

    target_phys_addr_t iotlb;

    p = phys_page_find(paddr >> TARGET_PAGE_BITS);

    if (!p) {

        pd = IO_MEM_UNASSIGNED;

    } else {

        pd = p->phys_offset;

    }

#if defined(DEBUG_TLB)

    printf("tlb_set_page: vaddr=" TARGET_FMT_lx " paddr=0x%08x prot=%x idx=%d smmu=%d pd=0x%08lx\n",

           vaddr, (int)paddr, prot, mmu_idx, is_softmmu, pd);

#endif

    ret = 0;

    address = vaddr;

    if ((pd & ~TARGET_PAGE_MASK) > IO_MEM_ROM && !(pd & IO_MEM_ROMD)) {

        /* IO memory case (romd handled later) */

        address |= TLB_MMIO;

    }

    addend = (unsigned long)qemu_get_ram_ptr(pd & TARGET_PAGE_MASK);

    if ((pd & ~TARGET_PAGE_MASK) <= IO_MEM_ROM) {

        /* Normal RAM.  */

        iotlb = pd & TARGET_PAGE_MASK;

        if ((pd & ~TARGET_PAGE_MASK) == IO_MEM_RAM)

            iotlb |= IO_MEM_NOTDIRTY;

        else

            iotlb |= IO_MEM_ROM;

    } else {

        /* IO handlers are currently passed a physical address.

           It would be nice to pass an offset from the base address

           of that region.  This would avoid having to special case RAM,

           and avoid full address decoding in every device.

           We can't use the high bits of pd for this because

           IO_MEM_ROMD uses these as a ram address.  */

        iotlb = (pd & ~TARGET_PAGE_MASK);

        if (p) {

            iotlb += p->region_offset;

        } else {

            iotlb += paddr;

        }

    }

    code_address = address;

    /* Make accesses to pages with watchpoints go via the

       watchpoint trap routines.  */

    TAILQ_FOREACH(wp, &env->watchpoints, entry) {

        if (vaddr == (wp->vaddr & TARGET_PAGE_MASK)) {

            iotlb = io_mem_watch + paddr;

            /* TODO: The memory case can be optimized by not trapping

               reads of pages with a write breakpoint.  */

            address |= TLB_MMIO;

        }

    }

    index = (vaddr >> TARGET_PAGE_BITS) & (CPU_TLB_SIZE - 1);

    env->iotlb[mmu_idx][index] = iotlb - vaddr;

    te = &env->tlb_table[mmu_idx][index];

    te->addend = addend - vaddr;

    if (prot & PAGE_READ) {

        te->addr_read = address;

    } else {

        te->addr_read = -1;

    }

    if (prot & PAGE_EXEC) {

        te->addr_code = code_address;

    } else {

        te->addr_code = -1;

    }

    if (prot & PAGE_WRITE) {

        if ((pd & ~TARGET_PAGE_MASK) == IO_MEM_ROM ||

            (pd & IO_MEM_ROMD)) {

            /* Write access calls the I/O callback.  */

            te->addr_write = address | TLB_MMIO;

        } else if ((pd & ~TARGET_PAGE_MASK) == IO_MEM_RAM &&

                   !cpu_physical_memory_is_dirty(pd)) {

            te->addr_write = address | TLB_NOTDIRTY;

        } else {

            te->addr_write = address;

        }

    } else {

        te->addr_write = -1;

    }

    return ret;

}


int net_init_tap(QemuOpts *opts, Monitor *mon, const char *name, VLANState *vlan)

{

    TAPState *s;

    int fd, vnet_hdr = 0;

    if (qemu_opt_get(opts, "fd")) {

        if (qemu_opt_get(opts, "ifname") ||

            qemu_opt_get(opts, "script") ||

            qemu_opt_get(opts, "downscript") ||

            qemu_opt_get(opts, "vnet_hdr")) {

            qemu_error("ifname=, script=, downscript= and vnet_hdr= is invalid with fd=\n");

            return -1;

        }

        fd = net_handle_fd_param(mon, qemu_opt_get(opts, "fd"));

        if (fd == -1) {

            return -1;

        }

        fcntl(fd, F_SETFL, O_NONBLOCK);

        vnet_hdr = tap_probe_vnet_hdr(fd);

    } else {

        if (!qemu_opt_get(opts, "script")) {

            qemu_opt_set(opts, "script", DEFAULT_NETWORK_SCRIPT);

        }

        if (!qemu_opt_get(opts, "downscript")) {

            qemu_opt_set(opts, "downscript", DEFAULT_NETWORK_DOWN_SCRIPT);

        }

        fd = net_tap_init(opts, &vnet_hdr);

        if (fd == -1) {

            return -1;

        }

    }

    s = net_tap_fd_init(vlan, "tap", name, fd, vnet_hdr);

    if (!s) {

        close(fd);

        return -1;

    }

    if (tap_set_sndbuf(s->fd, opts) < 0) {

        return -1;

    }

    if (qemu_opt_get(opts, "fd")) {

        snprintf(s->nc.info_str, sizeof(s->nc.info_str), "fd=%d", fd);

    } else {

        const char *ifname, *script, *downscript;

        ifname     = qemu_opt_get(opts, "ifname");

        script     = qemu_opt_get(opts, "script");

        downscript = qemu_opt_get(opts, "downscript");

        snprintf(s->nc.info_str, sizeof(s->nc.info_str),

                 "ifname=%s,script=%s,downscript=%s",

                 ifname, script, downscript);

        if (strcmp(downscript, "no") != 0) {

            snprintf(s->down_script, sizeof(s->down_script), "%s", downscript);

            snprintf(s->down_script_arg, sizeof(s->down_script_arg), "%s", ifname);

        }

    }

    if (vlan) {

        vlan->nb_host_devs++;

    }

    return 0;

}


uint16_t acpi_pm1_evt_get_sts(ACPIREGS *ar)

{

    int64_t d = acpi_pm_tmr_get_clock();

    if (d >= ar->tmr.overflow_time) {

        ar->pm1.evt.sts |= ACPI_BITMASK_TIMER_STATUS;

    }

    return ar->pm1.evt.sts;

}


static void store_slice16_c(uint16_t *dst, const uint16_t *src,

                            int dst_linesize, int src_linesize,

                            int width, int height, int log2_scale,

                            const uint8_t dither[8][8])

{

    int y, x;

#define STORE16(pos) do {                                                   \

    temp = ((src[x + y*src_linesize + pos] << log2_scale) + (d[pos]>>1)) >> 5;   \

    if (temp & 0x400)                                                       \

        temp = ~(temp >> 31);                                               \

    dst[x + y*dst_linesize + pos] = temp;                                   \

} while (0)

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

        const uint8_t *d = dither[y];

        for (x = 0; x < width; x += 8) {

            int temp;

            STORE16(0);

            STORE16(1);

            STORE16(2);

            STORE16(3);

            STORE16(4);

            STORE16(5);

            STORE16(6);

            STORE16(7);

        }

    }

}


void mips_cpu_unassigned_access(CPUState *cs, hwaddr addr,
                                bool is_write, bool is_exec, int unused,
                                unsigned size)
{
    MIPSCPU *cpu = MIPS_CPU(cs);
    CPUMIPSState *env = &cpu->env;
    if (is_exec) {
        helper_raise_exception(env, EXCP_IBE);
    } else {
        helper_raise_exception(env, EXCP_DBE);


void pxa27x_register_keypad(struct pxa2xx_keypad_s *kp, struct keymap *map,

        int size)

{

    kp->map = (struct keymap *) qemu_mallocz(sizeof(struct keymap) * size);

    if(!map || size < 0x80) {

        fprintf(stderr, "%s - No PXA keypad map defined\n", __FUNCTION__);

        exit(-1);

    }

    kp->map = map;

    qemu_add_kbd_event_handler((QEMUPutKBDEvent *) pxa27x_keyboard_event, kp);

}


static void virtio_rng_initfn(Object *obj)

{

    VirtIORNG *vrng = VIRTIO_RNG(obj);

    object_property_add_link(obj, "rng", TYPE_RNG_BACKEND,

                             (Object **)&vrng->conf.rng, NULL);

}


print_execve(const struct syscallname *name,

             abi_long arg1, abi_long arg2, abi_long arg3,

             abi_long arg4, abi_long arg5, abi_long arg6)

{

    abi_ulong arg_ptr_addr;

    char *s;

    if (!(s = lock_user_string(arg1)))

        return;

    gemu_log("%s(\"%s\",{", name->name, s);

    unlock_user(s, arg1, 0);

    for (arg_ptr_addr = arg2; ; arg_ptr_addr += sizeof(abi_ulong)) {

        abi_ulong *arg_ptr, arg_addr, s_addr;

        arg_ptr = lock_user(VERIFY_READ, arg_ptr_addr, sizeof(abi_ulong), 1);

        if (!arg_ptr)

            return;

        arg_addr = tswapl(*arg_ptr);

        unlock_user(arg_ptr, arg_ptr_addr, 0);

        if (!arg_addr)

            break;

        if ((s = lock_user_string(arg_addr))) {

            gemu_log("\"%s\",", s);

            unlock_user(s, s_addr, 0);

        }

    }

    gemu_log("NULL})");

}


DECLARE_LOOP_FILTER(mmxext)

DECLARE_LOOP_FILTER(sse2)

DECLARE_LOOP_FILTER(ssse3)

#endif

#define VP8_LUMA_MC_FUNC(IDX, SIZE, OPT) \

    c->put_vp8_epel_pixels_tab[IDX][0][2] = ff_put_vp8_epel ## SIZE ## _h6_ ## OPT; \

    c->put_vp8_epel_pixels_tab[IDX][2][0] = ff_put_vp8_epel ## SIZE ## _v6_ ## OPT; \

    c->put_vp8_epel_pixels_tab[IDX][2][2] = ff_put_vp8_epel ## SIZE ## _h6v6_ ## OPT

#define VP8_MC_FUNC(IDX, SIZE, OPT) \

    c->put_vp8_epel_pixels_tab[IDX][0][1] = ff_put_vp8_epel ## SIZE ## _h4_ ## OPT; \

    c->put_vp8_epel_pixels_tab[IDX][1][0] = ff_put_vp8_epel ## SIZE ## _v4_ ## OPT; \

    c->put_vp8_epel_pixels_tab[IDX][1][1] = ff_put_vp8_epel ## SIZE ## _h4v4_ ## OPT; \

    c->put_vp8_epel_pixels_tab[IDX][1][2] = ff_put_vp8_epel ## SIZE ## _h6v4_ ## OPT; \

    c->put_vp8_epel_pixels_tab[IDX][2][1] = ff_put_vp8_epel ## SIZE ## _h4v6_ ## OPT; \

    VP8_LUMA_MC_FUNC(IDX, SIZE, OPT)

#define VP8_BILINEAR_MC_FUNC(IDX, SIZE, OPT) \

    c->put_vp8_bilinear_pixels_tab[IDX][0][1] = ff_put_vp8_bilinear ## SIZE ## _h_ ## OPT; \

    c->put_vp8_bilinear_pixels_tab[IDX][0][2] = ff_put_vp8_bilinear ## SIZE ## _h_ ## OPT; \

    c->put_vp8_bilinear_pixels_tab[IDX][1][0] = ff_put_vp8_bilinear ## SIZE ## _v_ ## OPT; \

    c->put_vp8_bilinear_pixels_tab[IDX][1][1] = ff_put_vp8_bilinear ## SIZE ## _hv_ ## OPT; \

    c->put_vp8_bilinear_pixels_tab[IDX][1][2] = ff_put_vp8_bilinear ## SIZE ## _hv_ ## OPT; \

    c->put_vp8_bilinear_pixels_tab[IDX][2][0] = ff_put_vp8_bilinear ## SIZE ## _v_ ## OPT; \

    c->put_vp8_bilinear_pixels_tab[IDX][2][1] = ff_put_vp8_bilinear ## SIZE ## _hv_ ## OPT; \

    c->put_vp8_bilinear_pixels_tab[IDX][2][2] = ff_put_vp8_bilinear ## SIZE ## _hv_ ## OPT

av_cold void ff_vp8dsp_init_x86(VP8DSPContext* c)

{

    mm_flags = mm_support();

#if HAVE_YASM

    if (mm_flags & FF_MM_MMX) {

        c->vp8_idct_dc_add                  = ff_vp8_idct_dc_add_mmx;

        c->vp8_idct_add                     = ff_vp8_idct_add_mmx;

        c->vp8_luma_dc_wht                  = ff_vp8_luma_dc_wht_mmx;

        c->put_vp8_epel_pixels_tab[0][0][0]     =

        c->put_vp8_bilinear_pixels_tab[0][0][0] = ff_put_vp8_pixels16_mmx;

        c->put_vp8_epel_pixels_tab[1][0][0]     =

        c->put_vp8_bilinear_pixels_tab[1][0][0] = ff_put_vp8_pixels8_mmx;

        c->vp8_v_loop_filter_simple = ff_vp8_v_loop_filter_simple_mmx;

        c->vp8_h_loop_filter_simple = ff_vp8_h_loop_filter_simple_mmx;

        c->vp8_v_loop_filter16y_inner = ff_vp8_v_loop_filter16y_inner_mmx;

        c->vp8_h_loop_filter16y_inner = ff_vp8_h_loop_filter16y_inner_mmx;

        c->vp8_v_loop_filter8uv_inner = ff_vp8_v_loop_filter8uv_inner_mmx;

        c->vp8_h_loop_filter8uv_inner = ff_vp8_h_loop_filter8uv_inner_mmx;

        c->vp8_v_loop_filter16y       = ff_vp8_v_loop_filter16y_mbedge_mmx;

        c->vp8_h_loop_filter16y       = ff_vp8_h_loop_filter16y_mbedge_mmx;

        c->vp8_v_loop_filter8uv       = ff_vp8_v_loop_filter8uv_mbedge_mmx;

        c->vp8_h_loop_filter8uv       = ff_vp8_h_loop_filter8uv_mbedge_mmx;

    }

    /* note that 4-tap width=16 functions are missing because w=16

     * is only used for luma, and luma is always a copy or sixtap. */

    if (mm_flags & FF_MM_MMX2) {

        VP8_LUMA_MC_FUNC(0, 16, mmxext);

        VP8_MC_FUNC(1, 8, mmxext);

        VP8_MC_FUNC(2, 4, mmxext);

        VP8_BILINEAR_MC_FUNC(0, 16, mmxext);

        VP8_BILINEAR_MC_FUNC(1, 8, mmxext);

        VP8_BILINEAR_MC_FUNC(2, 4, mmxext);

        c->vp8_v_loop_filter_simple = ff_vp8_v_loop_filter_simple_mmxext;

        c->vp8_h_loop_filter_simple = ff_vp8_h_loop_filter_simple_mmxext;

        c->vp8_v_loop_filter16y_inner = ff_vp8_v_loop_filter16y_inner_mmxext;

        c->vp8_h_loop_filter16y_inner = ff_vp8_h_loop_filter16y_inner_mmxext;

        c->vp8_v_loop_filter8uv_inner = ff_vp8_v_loop_filter8uv_inner_mmxext;

        c->vp8_h_loop_filter8uv_inner = ff_vp8_h_loop_filter8uv_inner_mmxext;

        c->vp8_v_loop_filter16y       = ff_vp8_v_loop_filter16y_mbedge_mmxext;

        c->vp8_h_loop_filter16y       = ff_vp8_h_loop_filter16y_mbedge_mmxext;

        c->vp8_v_loop_filter8uv       = ff_vp8_v_loop_filter8uv_mbedge_mmxext;

        c->vp8_h_loop_filter8uv       = ff_vp8_h_loop_filter8uv_mbedge_mmxext;

    }

    if (mm_flags & FF_MM_SSE) {

        c->put_vp8_epel_pixels_tab[0][0][0]     =

        c->put_vp8_bilinear_pixels_tab[0][0][0] = ff_put_vp8_pixels16_sse;

    }

    if (mm_flags & (FF_MM_SSE2|FF_MM_SSE2SLOW)) {

        VP8_LUMA_MC_FUNC(0, 16, sse2);

        VP8_MC_FUNC(1, 8, sse2);

        VP8_BILINEAR_MC_FUNC(0, 16, sse2);

        VP8_BILINEAR_MC_FUNC(1, 8, sse2);

        c->vp8_v_loop_filter_simple = ff_vp8_v_loop_filter_simple_sse2;

        c->vp8_h_loop_filter_simple = ff_vp8_h_loop_filter_simple_sse2;

        c->vp8_v_loop_filter16y_inner = ff_vp8_v_loop_filter16y_inner_sse2;

        c->vp8_v_loop_filter8uv_inner = ff_vp8_v_loop_filter8uv_inner_sse2;

        c->vp8_v_loop_filter16y       = ff_vp8_v_loop_filter16y_mbedge_mmxext;

        c->vp8_v_loop_filter8uv       = ff_vp8_v_loop_filter8uv_mbedge_mmxext;

    }

    if (mm_flags & FF_MM_SSE2) {

        c->vp8_h_loop_filter16y_inner = ff_vp8_h_loop_filter16y_inner_sse2;

        c->vp8_h_loop_filter8uv_inner = ff_vp8_h_loop_filter8uv_inner_sse2;

        //c->vp8_h_loop_filter16y       = ff_vp8_h_loop_filter16y_mbedge_sse2;

        //c->vp8_h_loop_filter8uv       = ff_vp8_h_loop_filter8uv_mbedge_sse2;

    }

    if (mm_flags & FF_MM_SSSE3) {

        VP8_LUMA_MC_FUNC(0, 16, ssse3);

        VP8_MC_FUNC(1, 8, ssse3);

        VP8_MC_FUNC(2, 4, ssse3);

        VP8_BILINEAR_MC_FUNC(0, 16, ssse3);

        VP8_BILINEAR_MC_FUNC(1, 8, ssse3);

        VP8_BILINEAR_MC_FUNC(2, 4, ssse3);

        c->vp8_v_loop_filter_simple = ff_vp8_v_loop_filter_simple_ssse3;

        c->vp8_h_loop_filter_simple = ff_vp8_h_loop_filter_simple_ssse3;

        c->vp8_v_loop_filter16y_inner = ff_vp8_v_loop_filter16y_inner_ssse3;

        c->vp8_h_loop_filter16y_inner = ff_vp8_h_loop_filter16y_inner_ssse3;

        c->vp8_v_loop_filter8uv_inner = ff_vp8_v_loop_filter8uv_inner_ssse3;

        c->vp8_h_loop_filter8uv_inner = ff_vp8_h_loop_filter8uv_inner_ssse3;

        c->vp8_v_loop_filter16y       = ff_vp8_v_loop_filter16y_mbedge_ssse3;

        //c->vp8_h_loop_filter16y       = ff_vp8_h_loop_filter16y_mbedge_ssse3;

        c->vp8_v_loop_filter8uv       = ff_vp8_v_loop_filter8uv_mbedge_ssse3;

        //c->vp8_h_loop_filter8uv       = ff_vp8_h_loop_filter8uv_mbedge_ssse3;

    }

    if (mm_flags & FF_MM_SSE4) {

        c->vp8_idct_dc_add                  = ff_vp8_idct_dc_add_sse4;

    }

#endif

}


void ff_pngdsp_init_x86(PNGDSPContext *dsp)

{

#if HAVE_YASM

    int flags = av_get_cpu_flags();

#if ARCH_X86_32

    if (flags & AV_CPU_FLAG_MMX)

        dsp->add_bytes_l2         = ff_add_bytes_l2_mmx;

#endif

    if (flags & AV_CPU_FLAG_MMXEXT)

        dsp->add_paeth_prediction = ff_add_png_paeth_prediction_mmx2;

    if (flags & AV_CPU_FLAG_SSE2)

        dsp->add_bytes_l2         = ff_add_bytes_l2_sse2;

    if (flags & AV_CPU_FLAG_SSSE3)

        dsp->add_paeth_prediction = ff_add_png_paeth_prediction_ssse3;

#endif

}


static int decode_plane(Indeo3DecodeContext *ctx, AVCodecContext *avctx,

                        Plane *plane, const uint8_t *data, int32_t data_size,

                        int32_t strip_width)

{

    Cell            curr_cell;

    int             num_vectors;

    /* each plane data starts with mc_vector_count field, */

    /* an optional array of motion vectors followed by the vq data */

    num_vectors = bytestream_get_le32(&data);

    ctx->mc_vectors  = num_vectors ? data : 0;

    /* init the bitreader */

    init_get_bits(&ctx->gb, &data[num_vectors * 2], data_size << 3);

    ctx->skip_bits   = 0;

    ctx->need_resync = 0;

    ctx->last_byte = data + data_size - 1;

    /* initialize the 1st cell and set its dimensions to whole plane */

    curr_cell.xpos   = curr_cell.ypos = 0;

    curr_cell.width  = plane->width  >> 2;

    curr_cell.height = plane->height >> 2;

    curr_cell.tree   = 0; // we are in the MC tree now

    curr_cell.mv_ptr = 0; // no motion vector = INTRA cell

    return parse_bintree(ctx, avctx, plane, INTRA_NULL, &curr_cell, CELL_STACK_MAX, strip_width);

}


static void qpci_pc_config_writel(QPCIBus *bus, int devfn, uint8_t offset, uint32_t value)

{

    outl(0xcf8, (1 << 31) | (devfn << 8) | offset);

    outl(0xcfc, value);

}


static char *get_geokey_val(int key, int val)

{

    char *ap;

    if (val == TIFF_GEO_KEY_UNDEFINED)

        return av_strdup("undefined");

    if (val == TIFF_GEO_KEY_USER_DEFINED)

        return av_strdup("User-Defined");

#define RET_GEOKEY_VAL(TYPE, array)\

    if (val >= TIFF_##TYPE##_OFFSET &&\

        val - TIFF_##TYPE##_OFFSET < FF_ARRAY_ELEMS(ff_tiff_##array##_codes))\

        return av_strdup(ff_tiff_##array##_codes[val - TIFF_##TYPE##_OFFSET]);

    switch (key) {

    case TIFF_GT_MODEL_TYPE_GEOKEY:

        RET_GEOKEY_VAL(GT_MODEL_TYPE, gt_model_type);

        break;

    case TIFF_GT_RASTER_TYPE_GEOKEY:

        RET_GEOKEY_VAL(GT_RASTER_TYPE, gt_raster_type);

        break;

    case TIFF_GEOG_LINEAR_UNITS_GEOKEY:

    case TIFF_PROJ_LINEAR_UNITS_GEOKEY:

    case TIFF_VERTICAL_UNITS_GEOKEY:

        RET_GEOKEY_VAL(LINEAR_UNIT, linear_unit);

        break;

    case TIFF_GEOG_ANGULAR_UNITS_GEOKEY:

    case TIFF_GEOG_AZIMUTH_UNITS_GEOKEY:

        RET_GEOKEY_VAL(ANGULAR_UNIT, angular_unit);

        break;

    case TIFF_GEOGRAPHIC_TYPE_GEOKEY:

        RET_GEOKEY_VAL(GCS_TYPE, gcs_type);

        RET_GEOKEY_VAL(GCSE_TYPE, gcse_type);

        break;

    case TIFF_GEOG_GEODETIC_DATUM_GEOKEY:

        RET_GEOKEY_VAL(GEODETIC_DATUM, geodetic_datum);

        RET_GEOKEY_VAL(GEODETIC_DATUM_E, geodetic_datum_e);

        break;

    case TIFF_GEOG_ELLIPSOID_GEOKEY:

        RET_GEOKEY_VAL(ELLIPSOID, ellipsoid);

        break;

    case TIFF_GEOG_PRIME_MERIDIAN_GEOKEY:

        RET_GEOKEY_VAL(PRIME_MERIDIAN, prime_meridian);

        break;

    case TIFF_PROJECTED_CS_TYPE_GEOKEY:

        return av_strdup(search_keyval(ff_tiff_proj_cs_type_codes, FF_ARRAY_ELEMS(ff_tiff_proj_cs_type_codes), val));

        break;

    case TIFF_PROJECTION_GEOKEY:

        return av_strdup(search_keyval(ff_tiff_projection_codes, FF_ARRAY_ELEMS(ff_tiff_projection_codes), val));

        break;

    case TIFF_PROJ_COORD_TRANS_GEOKEY:

        RET_GEOKEY_VAL(COORD_TRANS, coord_trans);

        break;

    case TIFF_VERTICAL_CS_TYPE_GEOKEY:

        RET_GEOKEY_VAL(VERT_CS, vert_cs);

        RET_GEOKEY_VAL(ORTHO_VERT_CS, ortho_vert_cs);

        break;

    }

    ap = av_malloc(14);

    if (ap)

        snprintf(ap, 14, "Unknown-%d", val);

    return ap;

}


void ff_float_init_arm_vfp(DSPContext* c, AVCodecContext *avctx)

{

    c->vector_fmul = vector_fmul_vfp;

    c->vector_fmul_reverse = vector_fmul_reverse_vfp;

#ifdef HAVE_ARMV6

    c->float_to_int16 = float_to_int16_vfp;

#endif

}


static inline int64_t get_sector_offset(BlockDriverState *bs,

    int64_t sector_num, int write)

{

    BDRVVPCState *s = bs->opaque;

    uint64_t offset = sector_num * 512;

    uint64_t bitmap_offset, block_offset;

    uint32_t pagetable_index, pageentry_index;

    pagetable_index = offset / s->block_size;

    pageentry_index = (offset % s->block_size) / 512;

    if (pagetable_index >= s->max_table_entries || s->pagetable[pagetable_index] == 0xffffffff)

        return -1; // not allocated

    bitmap_offset = 512 * (uint64_t) s->pagetable[pagetable_index];

    block_offset = bitmap_offset + s->bitmap_size + (512 * pageentry_index);

    // We must ensure that we don't write to any sectors which are marked as

    // unused in the bitmap. We get away with setting all bits in the block

    // bitmap each time we write to a new block. This might cause Virtual PC to

    // miss sparse read optimization, but it's not a problem in terms of

    // correctness.

    if (write && (s->last_bitmap_offset != bitmap_offset)) {

        uint8_t bitmap[s->bitmap_size];

        s->last_bitmap_offset = bitmap_offset;

        memset(bitmap, 0xff, s->bitmap_size);

        bdrv_pwrite(bs->file, bitmap_offset, bitmap, s->bitmap_size);

    }

//    printf("sector: %" PRIx64 ", index: %x, offset: %x, bioff: %" PRIx64 ", bloff: %" PRIx64 "\n",

//	sector_num, pagetable_index, pageentry_index,

//	bitmap_offset, block_offset);

// disabled by reason

#if 0

#ifdef CACHE

    if (bitmap_offset != s->last_bitmap)

    {

	lseek(s->fd, bitmap_offset, SEEK_SET);

	s->last_bitmap = bitmap_offset;

	// Scary! Bitmap is stored as big endian 32bit entries,

	// while we used to look it up byte by byte

	read(s->fd, s->pageentry_u8, 512);

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

	    be32_to_cpus(&s->pageentry_u32[i]);

    }

    if ((s->pageentry_u8[pageentry_index / 8] >> (pageentry_index % 8)) & 1)

	return -1;

#else

    lseek(s->fd, bitmap_offset + (pageentry_index / 8), SEEK_SET);

    read(s->fd, &bitmap_entry, 1);

    if ((bitmap_entry >> (pageentry_index % 8)) & 1)

	return -1; // not allocated

#endif

#endif

    return block_offset;

}


static void coroutine_fn wait_for_overlapping_requests(BlockDriverState *bs,

        BdrvTrackedRequest *self, int64_t offset, unsigned int bytes)

{

    BdrvTrackedRequest *req;

    int64_t cluster_offset;

    unsigned int cluster_bytes;

    bool retry;

    /* If we touch the same cluster it counts as an overlap.  This guarantees

     * that allocating writes will be serialized and not race with each other

     * for the same cluster.  For example, in copy-on-read it ensures that the

     * CoR read and write operations are atomic and guest writes cannot

     * interleave between them.

     */

    round_bytes_to_clusters(bs, offset, bytes, &cluster_offset, &cluster_bytes);

    do {

        retry = false;

        QLIST_FOREACH(req, &bs->tracked_requests, list) {

            if (req == self) {

                continue;

            }

            if (tracked_request_overlaps(req, cluster_offset, cluster_bytes)) {

                /* Hitting this means there was a reentrant request, for

                 * example, a block driver issuing nested requests.  This must

                 * never happen since it means deadlock.

                 */

                assert(qemu_coroutine_self() != req->co);

                qemu_co_queue_wait(&req->wait_queue);

                retry = true;

                break;

            }

        }

    } while (retry);

}


static void disas_comp_b_imm(DisasContext *s, uint32_t insn)

{

    unsigned int sf, op, rt;

    uint64_t addr;

    int label_match;

    TCGv_i64 tcg_cmp;

    sf = extract32(insn, 31, 1);

    op = extract32(insn, 24, 1); /* 0: CBZ; 1: CBNZ */

    rt = extract32(insn, 0, 5);

    addr = s->pc + sextract32(insn, 5, 19) * 4 - 4;

    tcg_cmp = read_cpu_reg(s, rt, sf);

    label_match = gen_new_label();

    tcg_gen_brcondi_i64(op ? TCG_COND_NE : TCG_COND_EQ,

                        tcg_cmp, 0, label_match);

    gen_goto_tb(s, 0, s->pc);

    gen_set_label(label_match);

    gen_goto_tb(s, 1, addr);

}


static uint64_t integratorcm_read(void *opaque, target_phys_addr_t offset,

                                  unsigned size)

{

    integratorcm_state *s = (integratorcm_state *)opaque;

    if (offset >= 0x100 && offset < 0x200) {

        /* CM_SPD */

        if (offset >= 0x180)

            return 0;

        return integrator_spd[offset >> 2];

    }

    switch (offset >> 2) {

    case 0: /* CM_ID */

        return 0x411a3001;

    case 1: /* CM_PROC */

        return 0;

    case 2: /* CM_OSC */

        return s->cm_osc;

    case 3: /* CM_CTRL */

        return s->cm_ctrl;

    case 4: /* CM_STAT */

        return 0x00100000;

    case 5: /* CM_LOCK */

        if (s->cm_lock == 0xa05f) {

            return 0x1a05f;

        } else {

            return s->cm_lock;

        }

    case 6: /* CM_LMBUSCNT */

        /* ??? High frequency timer.  */

        hw_error("integratorcm_read: CM_LMBUSCNT");

    case 7: /* CM_AUXOSC */

        return s->cm_auxosc;

    case 8: /* CM_SDRAM */

        return s->cm_sdram;

    case 9: /* CM_INIT */

        return s->cm_init;

    case 10: /* CM_REFCT */

        /* ??? High frequency timer.  */

        hw_error("integratorcm_read: CM_REFCT");

    case 12: /* CM_FLAGS */

        return s->cm_flags;

    case 14: /* CM_NVFLAGS */

        return s->cm_nvflags;

    case 16: /* CM_IRQ_STAT */

        return s->int_level & s->irq_enabled;

    case 17: /* CM_IRQ_RSTAT */

        return s->int_level;

    case 18: /* CM_IRQ_ENSET */

        return s->irq_enabled;

    case 20: /* CM_SOFT_INTSET */

        return s->int_level & 1;

    case 24: /* CM_FIQ_STAT */

        return s->int_level & s->fiq_enabled;

    case 25: /* CM_FIQ_RSTAT */

        return s->int_level;

    case 26: /* CM_FIQ_ENSET */

        return s->fiq_enabled;

    case 32: /* CM_VOLTAGE_CTL0 */

    case 33: /* CM_VOLTAGE_CTL1 */

    case 34: /* CM_VOLTAGE_CTL2 */

    case 35: /* CM_VOLTAGE_CTL3 */

        /* ??? Voltage control unimplemented.  */

        return 0;

    default:

        hw_error("integratorcm_read: Unimplemented offset 0x%x\n",

                 (int)offset);

        return 0;

    }

}


bool aio_dispatch(AioContext *ctx)

{

    bool progress;

    progress = aio_bh_poll(ctx);

    progress |= aio_dispatch_handlers(ctx, INVALID_HANDLE_VALUE);

    progress |= timerlistgroup_run_timers(&ctx->tlg);

    return progress;

}


static void sm501_draw_crt(SM501State *s)

{

    DisplaySurface *surface = qemu_console_surface(s->con);

    int y, c_x = 0, c_y = 0;

    uint8_t *hwc_src = NULL, *src = s->local_mem;

    int width = get_width(s, 1);

    int height = get_height(s, 1);

    int src_bpp = get_bpp(s, 1);

    int dst_bpp = surface_bytes_per_pixel(surface);

    uint32_t *palette = (uint32_t *)&s->dc_palette[SM501_DC_CRT_PALETTE -

                                                   SM501_DC_PANEL_PALETTE];

    uint8_t hwc_palette[3 * 3];

    int ds_depth_index = get_depth_index(surface);

    draw_line_func *draw_line = NULL;

    draw_hwc_line_func *draw_hwc_line = NULL;

    int full_update = 0;

    int y_start = -1;

    ram_addr_t page_min = ~0l;

    ram_addr_t page_max = 0l;

    ram_addr_t offset = 0;

    /* choose draw_line function */

    switch (src_bpp) {

    case 1:

        draw_line = draw_line8_funcs[ds_depth_index];

        break;

    case 2:

        draw_line = draw_line16_funcs[ds_depth_index];

        break;

    case 4:

        draw_line = draw_line32_funcs[ds_depth_index];

        break;

    default:

        printf("sm501 draw crt : invalid DC_CRT_CONTROL=%x.\n",

               s->dc_crt_control);

        abort();

        break;

    }

    /* set up to draw hardware cursor */

    if (is_hwc_enabled(s, 1)) {

        /* choose cursor draw line function */

        draw_hwc_line = draw_hwc_line_funcs[ds_depth_index];

        hwc_src = get_hwc_address(s, 1);

        c_x = get_hwc_x(s, 1);

        c_y = get_hwc_y(s, 1);

        get_hwc_palette(s, 1, hwc_palette);

    }

    /* adjust console size */

    if (s->last_width != width || s->last_height != height) {

        qemu_console_resize(s->con, width, height);

        surface = qemu_console_surface(s->con);

        s->last_width = width;

        s->last_height = height;

        full_update = 1;

    }

    /* draw each line according to conditions */

    memory_region_sync_dirty_bitmap(&s->local_mem_region);

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

        int update, update_hwc;

        ram_addr_t page0 = offset;

        ram_addr_t page1 = offset + width * src_bpp - 1;

        /* check if hardware cursor is enabled and we're within its range */

        update_hwc = draw_hwc_line && c_y <= y && y < c_y + SM501_HWC_HEIGHT;

        update = full_update || update_hwc;

        /* check dirty flags for each line */

        update |= memory_region_get_dirty(&s->local_mem_region, page0,

                                          page1 - page0, DIRTY_MEMORY_VGA);

        /* draw line and change status */

        if (update) {

            uint8_t *d = surface_data(surface);

            d +=  y * width * dst_bpp;

            /* draw graphics layer */

            draw_line(d, src, width, palette);

            /* draw hardware cursor */

            if (update_hwc) {

                draw_hwc_line(d, hwc_src, width, hwc_palette, c_x, y - c_y);

            }

            if (y_start < 0) {

                y_start = y;

            }

            if (page0 < page_min) {

                page_min = page0;

            }

            if (page1 > page_max) {

                page_max = page1;

            }

        } else {

            if (y_start >= 0) {

                /* flush to display */

                dpy_gfx_update(s->con, 0, y_start, width, y - y_start);

                y_start = -1;

            }

        }

        src += width * src_bpp;

        offset += width * src_bpp;

    }

    /* complete flush to display */

    if (y_start >= 0) {

        dpy_gfx_update(s->con, 0, y_start, width, y - y_start);

    }

    /* clear dirty flags */

    if (page_min != ~0l) {

        memory_region_reset_dirty(&s->local_mem_region,

                                  page_min, page_max + TARGET_PAGE_SIZE,

                                  DIRTY_MEMORY_VGA);

    }

}


static void test_io(void)

{

#ifndef _WIN32

/* socketpair(PF_UNIX) which does not exist on windows */

    int sv[2];

    int r;

    unsigned i, j, k, s, t;

    fd_set fds;

    unsigned niov;

    struct iovec *iov, *siov;

    unsigned char *buf;

    size_t sz;

    iov_random(&iov, &niov);

    sz = iov_size(iov, niov);

    buf = g_malloc(sz);

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

        buf[i] = i & 255;

    }

    iov_from_buf(iov, niov, 0, buf, sz);

    siov = g_memdup(iov, sizeof(*iov) * niov);

    if (socketpair(PF_UNIX, SOCK_STREAM, 0, sv) < 0) {

       perror("socketpair");

       exit(1);

    }

    FD_ZERO(&fds);

    t = 0;

    if (fork() == 0) {

       /* writer */

       close(sv[0]);

       FD_SET(sv[1], &fds);

       fcntl(sv[1], F_SETFL, O_RDWR|O_NONBLOCK);

       r = g_test_rand_int_range(sz / 2, sz);

       setsockopt(sv[1], SOL_SOCKET, SO_SNDBUF, &r, sizeof(r));

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

           for (j = i; j <= sz; ++j) {

               k = i;

               do {

                   s = g_test_rand_int_range(0, j - k + 1);

                   r = iov_send(sv[1], iov, niov, k, s);

                   g_assert(memcmp(iov, siov, sizeof(*iov)*niov) == 0);

                   if (r >= 0) {

                       k += r;

                       t += r;

                       usleep(g_test_rand_int_range(0, 30));

                   } else if (errno == EAGAIN) {

                       select(sv[1]+1, NULL, &fds, NULL, NULL);

                       continue;

                   } else {

                       perror("send");

                       exit(1);

                   }

               } while(k < j);

           }

       }

       iov_free(iov, niov);

       g_free(buf);

       g_free(siov);

       exit(0);

    } else {

       /* reader & verifier */

       close(sv[1]);

       FD_SET(sv[0], &fds);

       fcntl(sv[0], F_SETFL, O_RDWR|O_NONBLOCK);

       r = g_test_rand_int_range(sz / 2, sz);

       setsockopt(sv[0], SOL_SOCKET, SO_RCVBUF, &r, sizeof(r));

       usleep(500000);

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

           for (j = i; j <= sz; ++j) {

               k = i;

               iov_memset(iov, niov, 0, 0xff, -1);

               do {

                   s = g_test_rand_int_range(0, j - k + 1);

                   r = iov_recv(sv[0], iov, niov, k, s);

                   g_assert(memcmp(iov, siov, sizeof(*iov)*niov) == 0);

                   if (r > 0) {

                       k += r;

                       t += r;

                   } else if (!r) {

                       if (s) {

                           break;

                       }

                   } else if (errno == EAGAIN) {

                       select(sv[0]+1, &fds, NULL, NULL, NULL);

                       continue;

                   } else {

                       perror("recv");

                       exit(1);

                   }

               } while(k < j);

               test_iov_bytes(iov, niov, i, j - i);

           }

        }

       iov_free(iov, niov);

       g_free(buf);

       g_free(siov);

     }

#endif

}


static gboolean gd_motion_event(GtkWidget *widget, GdkEventMotion *motion,

                                void *opaque)

{

    GtkDisplayState *s = opaque;

    int dx, dy;

    int x, y;

    x = motion->x / s->scale_x;

    y = motion->y / s->scale_y;

    if (kbd_mouse_is_absolute()) {

        dx = x * 0x7FFF / (ds_get_width(s->ds) - 1);

        dy = y * 0x7FFF / (ds_get_height(s->ds) - 1);

    } else if (s->last_x == -1 || s->last_y == -1) {

        dx = 0;

        dy = 0;

    } else {

        dx = x - s->last_x;

        dy = y - s->last_y;

    }

    s->last_x = x;

    s->last_y = y;

    if (kbd_mouse_is_absolute()) {

        kbd_mouse_event(dx, dy, 0, s->button_mask);

    }

    return TRUE;

}


static int virtio_9p_init_pci(PCIDevice *pci_dev)

{

    VirtIOPCIProxy *proxy = DO_UPCAST(VirtIOPCIProxy, pci_dev, pci_dev);

    VirtIODevice *vdev;

    vdev = virtio_9p_init(&pci_dev->qdev, &proxy->fsconf);

    vdev->nvectors = proxy->nvectors;

    virtio_init_pci(proxy, vdev,

                    PCI_VENDOR_ID_REDHAT_QUMRANET,

                    0x1009,

                    0x2,

                    0x00);

    /* make the actual value visible */

    proxy->nvectors = vdev->nvectors;

    return 0;

}


void pc_guest_info_init(PCMachineState *pcms)

{

    int i, j;

    pcms->apic_xrupt_override = kvm_allows_irq0_override();

    pcms->numa_nodes = nb_numa_nodes;

    pcms->node_mem = g_malloc0(pcms->numa_nodes *

                                    sizeof *pcms->node_mem);

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

        pcms->node_mem[i] = numa_info[i].node_mem;

    }

    pcms->node_cpu = g_malloc0(pcms->apic_id_limit *

                                     sizeof *pcms->node_cpu);

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

        unsigned int apic_id = x86_cpu_apic_id_from_index(i);

        assert(apic_id < pcms->apic_id_limit);

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

            if (test_bit(i, numa_info[j].node_cpu)) {

                pcms->node_cpu[apic_id] = j;

                break;

            }

        }

    }

    pcms->machine_done.notify = pc_machine_done;

    qemu_add_machine_init_done_notifier(&pcms->machine_done);

}


static int encode_frame(AVCodecContext *avctx, AVPacket *pkt,

                        const AVFrame *frame, int *got_packet)

{

    SgiContext *s = avctx->priv_data;

    const AVFrame * const p = frame;

    PutByteContext pbc;

    uint8_t *in_buf, *encode_buf;

    int x, y, z, length, tablesize, ret;

    unsigned int width, height, depth, dimension;

    unsigned int bytes_per_channel, pixmax, put_be;

#if FF_API_CODED_FRAME

FF_DISABLE_DEPRECATION_WARNINGS

    avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;

    avctx->coded_frame->key_frame = 1;

FF_ENABLE_DEPRECATION_WARNINGS

#endif

#if FF_API_CODER_TYPE

FF_DISABLE_DEPRECATION_WARNINGS

    if (avctx->coder_type == FF_CODER_TYPE_RAW)

        s->rle = 0;

FF_ENABLE_DEPRECATION_WARNINGS

#endif

    width  = avctx->width;

    height = avctx->height;

    bytes_per_channel = 1;

    pixmax = 0xFF;

    put_be = HAVE_BIGENDIAN;

    switch (avctx->pix_fmt) {

    case AV_PIX_FMT_GRAY8:

        dimension = SGI_SINGLE_CHAN;

        depth     = SGI_GRAYSCALE;

        break;

    case AV_PIX_FMT_RGB24:

        dimension = SGI_MULTI_CHAN;

        depth     = SGI_RGB;

        break;

    case AV_PIX_FMT_RGBA:

        dimension = SGI_MULTI_CHAN;

        depth     = SGI_RGBA;

        break;

    case AV_PIX_FMT_GRAY16LE:

        put_be = !HAVE_BIGENDIAN;

    case AV_PIX_FMT_GRAY16BE:

        bytes_per_channel = 2;

        pixmax = 0xFFFF;

        dimension = SGI_SINGLE_CHAN;

        depth     = SGI_GRAYSCALE;

        break;

    case AV_PIX_FMT_RGB48LE:

        put_be = !HAVE_BIGENDIAN;

    case AV_PIX_FMT_RGB48BE:

        bytes_per_channel = 2;

        pixmax = 0xFFFF;

        dimension = SGI_MULTI_CHAN;

        depth     = SGI_RGB;

        break;

    case AV_PIX_FMT_RGBA64LE:

        put_be = !HAVE_BIGENDIAN;

    case AV_PIX_FMT_RGBA64BE:

        bytes_per_channel = 2;

        pixmax = 0xFFFF;

        dimension = SGI_MULTI_CHAN;

        depth     = SGI_RGBA;

        break;

    default:

        return AVERROR_INVALIDDATA;

    }

    tablesize = depth * height * 4;

    length = SGI_HEADER_SIZE;

    if (!s->rle)

        length += depth * height * width;

    else // assume sgi_rle_encode() produces at most 2x size of input

        length += tablesize * 2 + depth * height * (2 * width + 1);

    if ((ret = ff_alloc_packet(pkt, bytes_per_channel * length)) < 0) {

        av_log(avctx, AV_LOG_ERROR, "Error getting output packet of size %d.\n", length);

        return ret;

    }

    bytestream2_init_writer(&pbc, pkt->data, pkt->size);

    /* Encode header. */

    bytestream2_put_be16(&pbc, SGI_MAGIC);

    bytestream2_put_byte(&pbc, s->rle); /* RLE 1 - VERBATIM 0 */

    bytestream2_put_byte(&pbc, bytes_per_channel);

    bytestream2_put_be16(&pbc, dimension);

    bytestream2_put_be16(&pbc, width);

    bytestream2_put_be16(&pbc, height);

    bytestream2_put_be16(&pbc, depth);

    bytestream2_put_be32(&pbc, 0L); /* pixmin */

    bytestream2_put_be32(&pbc, pixmax);

    bytestream2_put_be32(&pbc, 0L); /* dummy */

    /* name */

    bytestream2_skip_p(&pbc, 80);

    /* colormap */

    bytestream2_put_be32(&pbc, 0L);

    /* The rest of the 512 byte header is unused. */

    bytestream2_skip_p(&pbc, 404);

    if (s->rle) {

        PutByteContext taboff_pcb, tablen_pcb;

        /* Skip RLE offset table. */

        bytestream2_init_writer(&taboff_pcb, pbc.buffer, tablesize);

        bytestream2_skip_p(&pbc, tablesize);

        /* Skip RLE length table. */

        bytestream2_init_writer(&tablen_pcb, pbc.buffer, tablesize);

        bytestream2_skip_p(&pbc, tablesize);

        /* Make an intermediate consecutive buffer. */

        if (!(encode_buf = av_malloc(width * bytes_per_channel)))

            return AVERROR(ENOMEM);

        for (z = 0; z < depth; z++) {

            in_buf = p->data[0] + p->linesize[0] * (height - 1) + z * bytes_per_channel;

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

                bytestream2_put_be32(&taboff_pcb, bytestream2_tell_p(&pbc));

                for (x = 0; x < width * bytes_per_channel; x += bytes_per_channel)

                    encode_buf[x] = in_buf[depth * x];

                length = sgi_rle_encode(&pbc, encode_buf, width,

                                        bytes_per_channel);

                if (length < 1) {

                    av_free(encode_buf);

                    return AVERROR_INVALIDDATA;

                }

                bytestream2_put_be32(&tablen_pcb, length);

                in_buf -= p->linesize[0];

            }

        }

        av_free(encode_buf);

    } else {

        for (z = 0; z < depth; z++) {

            in_buf = p->data[0] + p->linesize[0] * (height - 1) + z * bytes_per_channel;

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

                for (x = 0; x < width * depth; x += depth)

                    if (bytes_per_channel == 1)

                        bytestream2_put_byte(&pbc, in_buf[x]);

                    else

                        if (put_be)

                            bytestream2_put_be16(&pbc, ((uint16_t *)in_buf)[x]);

                        else

                            bytestream2_put_le16(&pbc, ((uint16_t *)in_buf)[x]);

                in_buf -= p->linesize[0];

            }

        }

    }

    /* total length */

    pkt->size   = bytestream2_tell_p(&pbc);

    pkt->flags |= AV_PKT_FLAG_KEY;

    *got_packet = 1;

    return 0;

}


static uint64_t sysbus_esp_mem_read(void *opaque, target_phys_addr_t addr,

                                    unsigned int size)

{

    SysBusESPState *sysbus = opaque;

    uint32_t saddr;

    saddr = addr >> sysbus->it_shift;

    return esp_reg_read(&sysbus->esp, saddr);

}


static int usb_bt_handle_data(USBDevice *dev, USBPacket *p)

{

    struct USBBtState *s = (struct USBBtState *) dev->opaque;

    int ret = 0;

    if (!s->config)

        goto fail;

    switch (p->pid) {

    case USB_TOKEN_IN:

        switch (p->devep & 0xf) {

        case USB_EVT_EP:

            ret = usb_bt_fifo_dequeue(&s->evt, p);

            break;

        case USB_ACL_EP:

            ret = usb_bt_fifo_dequeue(&s->acl, p);

            break;

        case USB_SCO_EP:

            ret = usb_bt_fifo_dequeue(&s->sco, p);

            break;

        default:

            goto fail;

        }

        break;

    case USB_TOKEN_OUT:

        switch (p->devep & 0xf) {

        case USB_ACL_EP:

            usb_bt_fifo_out_enqueue(s, &s->outacl, s->hci->acl_send,

                            usb_bt_hci_acl_complete, p);

            break;

        case USB_SCO_EP:

            usb_bt_fifo_out_enqueue(s, &s->outsco, s->hci->sco_send,

                            usb_bt_hci_sco_complete, p);

            break;

        default:

            goto fail;

        }

        break;

    default:

    fail:

        ret = USB_RET_STALL;

        break;

    }

    return ret;

}


void bdrv_io_unplugged_begin(BlockDriverState *bs)

{

    BdrvChild *child;

    if (bs->io_plug_disabled++ == 0 && bs->io_plugged > 0) {

        BlockDriver *drv = bs->drv;

        if (drv && drv->bdrv_io_unplug) {

            drv->bdrv_io_unplug(bs);

        }

    }

    QLIST_FOREACH(child, &bs->children, next) {

        bdrv_io_unplugged_begin(child->bs);

    }

}


static void acpi_get_pm_info(AcpiPmInfo *pm)

{

    Object *piix = piix4_pm_find();

    Object *lpc = ich9_lpc_find();

    Object *obj = NULL;

    QObject *o;

    pm->cpu_hp_io_base = 0;

    pm->pcihp_io_base = 0;

    pm->pcihp_io_len = 0;

    if (piix) {

        obj = piix;

        pm->cpu_hp_io_base = PIIX4_CPU_HOTPLUG_IO_BASE;

        pm->pcihp_io_base =

            object_property_get_int(obj, ACPI_PCIHP_IO_BASE_PROP, NULL);

        pm->pcihp_io_len =

            object_property_get_int(obj, ACPI_PCIHP_IO_LEN_PROP, NULL);

    }

    if (lpc) {

        obj = lpc;

        pm->cpu_hp_io_base = ICH9_CPU_HOTPLUG_IO_BASE;

    }

    assert(obj);

    pm->cpu_hp_io_len = ACPI_GPE_PROC_LEN;

    pm->mem_hp_io_base = ACPI_MEMORY_HOTPLUG_BASE;

    pm->mem_hp_io_len = ACPI_MEMORY_HOTPLUG_IO_LEN;

    /* Fill in optional s3/s4 related properties */

    o = object_property_get_qobject(obj, ACPI_PM_PROP_S3_DISABLED, NULL);

    if (o) {

        pm->s3_disabled = qint_get_int(qobject_to_qint(o));

    } else {

        pm->s3_disabled = false;

    }

    qobject_decref(o);

    o = object_property_get_qobject(obj, ACPI_PM_PROP_S4_DISABLED, NULL);

    if (o) {

        pm->s4_disabled = qint_get_int(qobject_to_qint(o));

    } else {

        pm->s4_disabled = false;

    }

    qobject_decref(o);

    o = object_property_get_qobject(obj, ACPI_PM_PROP_S4_VAL, NULL);

    if (o) {

        pm->s4_val = qint_get_int(qobject_to_qint(o));

    } else {

        pm->s4_val = false;

    }

    qobject_decref(o);

    /* Fill in mandatory properties */

    pm->sci_int = object_property_get_int(obj, ACPI_PM_PROP_SCI_INT, NULL);

    pm->acpi_enable_cmd = object_property_get_int(obj,

                                                  ACPI_PM_PROP_ACPI_ENABLE_CMD,

                                                  NULL);

    pm->acpi_disable_cmd = object_property_get_int(obj,

                                                  ACPI_PM_PROP_ACPI_DISABLE_CMD,

                                                  NULL);

    pm->io_base = object_property_get_int(obj, ACPI_PM_PROP_PM_IO_BASE,

                                          NULL);

    pm->gpe0_blk = object_property_get_int(obj, ACPI_PM_PROP_GPE0_BLK,

                                           NULL);

    pm->gpe0_blk_len = object_property_get_int(obj, ACPI_PM_PROP_GPE0_BLK_LEN,

                                               NULL);

    pm->pcihp_bridge_en =

        object_property_get_bool(obj, "acpi-pci-hotplug-with-bridge-support",

                                 NULL);

}


static void icp_pit_write(void *opaque, target_phys_addr_t offset,

                          uint64_t value, unsigned size)

{

    icp_pit_state *s = (icp_pit_state *)opaque;

    int n;

    n = offset >> 8;

    if (n > 2) {

        hw_error("%s: Bad timer %d\n", __func__, n);

    }

    arm_timer_write(s->timer[n], offset & 0xff, value);

}


static ram_addr_t get_current_ram_size(void)

{

    GSList *list = NULL, *item;

    ram_addr_t size = ram_size;

    pc_dimm_build_list(qdev_get_machine(), &list);

    for (item = list; item; item = g_slist_next(item)) {

        Object *obj = OBJECT(item->data);

        size += object_property_get_int(obj, PC_DIMM_SIZE_PROP, &error_abort);

    }

    g_slist_free(list);

    return size;

}