static int nbd_co_discard(BlockDriverState *bs, int64_t sector_num,

                          int nb_sectors)

{

    BDRVNBDState *s = bs->opaque;

    struct nbd_request request;

    struct nbd_reply reply;

    if (!(s->nbdflags & NBD_FLAG_SEND_TRIM)) {

        return 0;

    }

    request.type = NBD_CMD_TRIM;

    request.from = sector_num * 512;;

    request.len = nb_sectors * 512;

    nbd_coroutine_start(s, &request);

    if (nbd_co_send_request(s, &request, NULL, 0) == -1) {

        reply.error = errno;

    } else {

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

    }

    nbd_coroutine_end(s, &request);

    return -reply.error;

}


static bool memory_region_access_valid(MemoryRegion *mr,

                                       target_phys_addr_t addr,

                                       unsigned size)

{

    if (!mr->ops->valid.unaligned && (addr & (size - 1))) {

        return false;

    }

    /* Treat zero as compatibility all valid */

    if (!mr->ops->valid.max_access_size) {

        return true;

    }

    if (size > mr->ops->valid.max_access_size

        || size < mr->ops->valid.min_access_size) {

        return false;

    }

    return true;

}


static int pci_pcnet_init(PCIDevice *pci_dev)

{

    PCIPCNetState *d = DO_UPCAST(PCIPCNetState, pci_dev, pci_dev);

    PCNetState *s = &d->state;

    uint8_t *pci_conf;

#if 0

    printf("sizeof(RMD)=%d, sizeof(TMD)=%d\n",

        sizeof(struct pcnet_RMD), sizeof(struct pcnet_TMD));

#endif

    pci_conf = pci_dev->config;

    pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_AMD);

    pci_config_set_device_id(pci_conf, PCI_DEVICE_ID_AMD_LANCE);

    pci_set_word(pci_conf + PCI_STATUS,

                 PCI_STATUS_FAST_BACK | PCI_STATUS_DEVSEL_MEDIUM);

    pci_conf[PCI_REVISION_ID] = 0x10;

    pci_config_set_class(pci_conf, PCI_CLASS_NETWORK_ETHERNET);

    pci_set_word(pci_conf + PCI_SUBSYSTEM_VENDOR_ID, 0x0);

    pci_set_word(pci_conf + PCI_SUBSYSTEM_ID, 0x0);

    pci_conf[PCI_INTERRUPT_PIN] = 1; // interrupt pin 0

    pci_conf[PCI_MIN_GNT] = 0x06;

    pci_conf[PCI_MAX_LAT] = 0xff;

    /* Handler for memory-mapped I/O */

    s->mmio_index =

      cpu_register_io_memory(pcnet_mmio_read, pcnet_mmio_write, &d->state,

                             DEVICE_NATIVE_ENDIAN);

    pci_register_bar(pci_dev, 0, PCNET_IOPORT_SIZE,

                           PCI_BASE_ADDRESS_SPACE_IO, pcnet_ioport_map);

    pci_register_bar_simple(pci_dev, 1, PCNET_PNPMMIO_SIZE, 0, s->mmio_index);

    s->irq = pci_dev->irq[0];

    s->phys_mem_read = pci_physical_memory_read;

    s->phys_mem_write = pci_physical_memory_write;

    if (!pci_dev->qdev.hotplugged) {

        static int loaded = 0;

        if (!loaded) {

            rom_add_option("pxe-pcnet.rom", -1);

            loaded = 1;

        }

    }

    return pcnet_common_init(&pci_dev->qdev, s, &net_pci_pcnet_info);

}


static int dvvideo_encode_close(AVCodecContext *avctx)

{

    av_frame_free(&avctx->coded_frame);

    return 0;

}


void ich9_pm_init(PCIDevice *lpc_pci, ICH9LPCPMRegs *pm, bool smm_enabled,

                  qemu_irq sci_irq)

{

    memory_region_init(&pm->io, OBJECT(lpc_pci), "ich9-pm", ICH9_PMIO_SIZE);

    memory_region_set_enabled(&pm->io, false);

    memory_region_add_subregion(pci_address_space_io(lpc_pci),

                                0, &pm->io);

    acpi_pm_tmr_init(&pm->acpi_regs, ich9_pm_update_sci_fn, &pm->io);

    acpi_pm1_evt_init(&pm->acpi_regs, ich9_pm_update_sci_fn, &pm->io);

    acpi_pm1_cnt_init(&pm->acpi_regs, &pm->io, pm->disable_s3, pm->disable_s4,

                      pm->s4_val);

    acpi_gpe_init(&pm->acpi_regs, ICH9_PMIO_GPE0_LEN);

    memory_region_init_io(&pm->io_gpe, OBJECT(lpc_pci), &ich9_gpe_ops, pm,

                          "acpi-gpe0", ICH9_PMIO_GPE0_LEN);

    memory_region_add_subregion(&pm->io, ICH9_PMIO_GPE0_STS, &pm->io_gpe);

    memory_region_init_io(&pm->io_smi, OBJECT(lpc_pci), &ich9_smi_ops, pm,

                          "acpi-smi", 8);

    memory_region_add_subregion(&pm->io, ICH9_PMIO_SMI_EN, &pm->io_smi);

    pm->smm_enabled = smm_enabled;

    pm->irq = sci_irq;

    qemu_register_reset(pm_reset, pm);

    pm->powerdown_notifier.notify = pm_powerdown_req;

    qemu_register_powerdown_notifier(&pm->powerdown_notifier);

    acpi_cpu_hotplug_init(pci_address_space_io(lpc_pci), OBJECT(lpc_pci),

                          &pm->gpe_cpu, ICH9_CPU_HOTPLUG_IO_BASE);

    if (pm->acpi_memory_hotplug.is_enabled) {

        acpi_memory_hotplug_init(pci_address_space_io(lpc_pci), OBJECT(lpc_pci),

                                 &pm->acpi_memory_hotplug);

    }

}


static inline int gen_intermediate_code_internal(CPUState *env,

                                                 TranslationBlock *tb,

                                                 int search_pc)

{

    DisasContext dc1, *dc = &dc1;

    uint8_t *pc_ptr;

    uint16_t *gen_opc_end;

    int flags, j, lj;

    uint8_t *pc_start;

    uint8_t *cs_base;

    /* generate intermediate code */

    pc_start = (uint8_t *)tb->pc;

    cs_base = (uint8_t *)tb->cs_base;

    flags = tb->flags;

    dc->pe = env->cr[0] & CR0_PE_MASK;

    dc->code32 = (flags >> HF_CS32_SHIFT) & 1;

    dc->ss32 = (flags >> HF_SS32_SHIFT) & 1;

    dc->addseg = (flags >> HF_ADDSEG_SHIFT) & 1;

    dc->f_st = 0;

    dc->vm86 = (flags >> VM_SHIFT) & 1;

    dc->cpl = (flags >> HF_CPL_SHIFT) & 3;

    dc->iopl = (flags >> IOPL_SHIFT) & 3;

    dc->tf = (flags >> TF_SHIFT) & 1;

    dc->singlestep_enabled = env->singlestep_enabled;

    dc->cc_op = CC_OP_DYNAMIC;

    dc->cs_base = cs_base;

    dc->tb = tb;

    dc->popl_esp_hack = 0;

    /* select memory access functions */

    dc->mem_index = 0;

    if (flags & HF_SOFTMMU_MASK) {

        if (dc->cpl == 3)

            dc->mem_index = 6;

        else

            dc->mem_index = 3;

    }

    dc->jmp_opt = !(dc->tf || env->singlestep_enabled

#ifndef CONFIG_SOFT_MMU

                    || (flags & HF_SOFTMMU_MASK)

#endif

                    );

    gen_opc_ptr = gen_opc_buf;

    gen_opc_end = gen_opc_buf + OPC_MAX_SIZE;

    gen_opparam_ptr = gen_opparam_buf;

    dc->is_jmp = DISAS_NEXT;

    pc_ptr = pc_start;

    lj = -1;

    /* if irq were inhibited for the next instruction, we can disable

       them here as it is simpler (otherwise jumps would have to

       handled as special case) */

    if (flags & HF_INHIBIT_IRQ_MASK) {

        gen_op_reset_inhibit_irq();

    }

    for(;;) {

        if (env->nb_breakpoints > 0) {

            for(j = 0; j < env->nb_breakpoints; j++) {

                if (env->breakpoints[j] == (unsigned long)pc_ptr) {

                    gen_debug(dc, pc_ptr - dc->cs_base);

                    break;

                }

            }

        }

        if (search_pc) {

            j = gen_opc_ptr - gen_opc_buf;

            if (lj < j) {

                lj++;

                while (lj < j)

                    gen_opc_instr_start[lj++] = 0;

            }

            gen_opc_pc[lj] = (uint32_t)pc_ptr;

            gen_opc_cc_op[lj] = dc->cc_op;

            gen_opc_instr_start[lj] = 1;

        }

        pc_ptr = disas_insn(dc, pc_ptr);

        /* stop translation if indicated */

        if (dc->is_jmp)

            break;

        /* if single step mode, we generate only one instruction and

           generate an exception */

        if (dc->tf || dc->singlestep_enabled) {

            gen_op_jmp_im(pc_ptr - dc->cs_base);

            gen_eob(dc);

            break;

        }

        /* if too long translation, stop generation too */

        if (gen_opc_ptr >= gen_opc_end ||

            (pc_ptr - pc_start) >= (TARGET_PAGE_SIZE - 32)) {

            gen_op_jmp_im(pc_ptr - dc->cs_base);

            gen_eob(dc);

            break;

        }

    }

    *gen_opc_ptr = INDEX_op_end;

    /* we don't forget to fill the last values */

    if (search_pc) {

        j = gen_opc_ptr - gen_opc_buf;

        lj++;

        while (lj <= j)

            gen_opc_instr_start[lj++] = 0;

    }

#ifdef DEBUG_DISAS

    if (loglevel) {

        fprintf(logfile, "----------------\n");

        fprintf(logfile, "IN: %s\n", lookup_symbol(pc_start));

	disas(logfile, pc_start, pc_ptr - pc_start, 0, !dc->code32);

        fprintf(logfile, "\n");

        fprintf(logfile, "OP:\n");

        dump_ops(gen_opc_buf, gen_opparam_buf);

        fprintf(logfile, "\n");

    }

#endif

    /* optimize flag computations */

    optimize_flags(gen_opc_buf, gen_opc_ptr - gen_opc_buf);

#ifdef DEBUG_DISAS

    if (loglevel) {

        fprintf(logfile, "AFTER FLAGS OPT:\n");

        dump_ops(gen_opc_buf, gen_opparam_buf);

        fprintf(logfile, "\n");

    }

#endif

    if (!search_pc)

        tb->size = pc_ptr - pc_start;

    return 0;

}


static void nbd_detach_aio_context(BlockDriverState *bs)

{

    BDRVNBDState *s = bs->opaque;

    nbd_client_session_detach_aio_context(&s->client);

}


void *g_malloc0_n(size_t nmemb, size_t size)

{

    size_t sz;

    void *ptr;

    __coverity_negative_sink__(nmemb);

    __coverity_negative_sink__(size);

    sz = nmemb * size;

    ptr = __coverity_alloc__(size);

    __coverity_writeall0__(ptr);

    __coverity_mark_as_afm_allocated__(ptr, AFM_free);

    return ptr;

}


static uint32_t nvram_readb (void *opaque, target_phys_addr_t addr)

{

    M48t59State *NVRAM = opaque;

    uint32_t retval;

    retval = m48t59_read(NVRAM, addr);

    return retval;

}


static void coroutine_fn commit_run(void *opaque)

{

    CommitBlockJob *s = opaque;

    BlockDriverState *active = s->active;

    BlockDriverState *top = s->top;

    BlockDriverState *base = s->base;

    BlockDriverState *overlay_bs;

    int64_t sector_num, end;

    int ret = 0;

    int n = 0;

    void *buf;

    int bytes_written = 0;

    int64_t base_len;

    ret = s->common.len = bdrv_getlength(top);

    if (s->common.len < 0) {

        goto exit_restore_reopen;

    }

    ret = base_len = bdrv_getlength(base);

    if (base_len < 0) {

        goto exit_restore_reopen;

    }

    if (base_len < s->common.len) {

        ret = bdrv_truncate(base, s->common.len);

        if (ret) {

            goto exit_restore_reopen;

        }

    }

    end = s->common.len >> BDRV_SECTOR_BITS;

    buf = qemu_blockalign(top, COMMIT_BUFFER_SIZE);

    for (sector_num = 0; sector_num < end; sector_num += n) {

        uint64_t delay_ns = 0;

        bool copy;

wait:

        /* Note that even when no rate limit is applied we need to yield

         * with no pending I/O here so that bdrv_drain_all() returns.

         */

        block_job_sleep_ns(&s->common, QEMU_CLOCK_REALTIME, delay_ns);

        if (block_job_is_cancelled(&s->common)) {

            break;

        }

        /* Copy if allocated above the base */

        ret = bdrv_is_allocated_above(top, base, sector_num,

                                      COMMIT_BUFFER_SIZE / BDRV_SECTOR_SIZE,

                                      &n);

        copy = (ret == 1);

        trace_commit_one_iteration(s, sector_num, n, ret);

        if (copy) {

            if (s->common.speed) {

                delay_ns = ratelimit_calculate_delay(&s->limit, n);

                if (delay_ns > 0) {

                    goto wait;

                }

            }

            ret = commit_populate(top, base, sector_num, n, buf);

            bytes_written += n * BDRV_SECTOR_SIZE;

        }

        if (ret < 0) {

            if (s->on_error == BLOCKDEV_ON_ERROR_STOP ||

                s->on_error == BLOCKDEV_ON_ERROR_REPORT||

                (s->on_error == BLOCKDEV_ON_ERROR_ENOSPC && ret == -ENOSPC)) {

                goto exit_free_buf;

            } else {

                n = 0;

                continue;

            }

        }

        /* Publish progress */

        s->common.offset += n * BDRV_SECTOR_SIZE;

    }

    ret = 0;

    if (!block_job_is_cancelled(&s->common) && sector_num == end) {

        /* success */

        ret = bdrv_drop_intermediate(active, top, base, s->backing_file_str);

    }

exit_free_buf:

    qemu_vfree(buf);

exit_restore_reopen:

    /* restore base open flags here if appropriate (e.g., change the base back

     * to r/o). These reopens do not need to be atomic, since we won't abort

     * even on failure here */

    if (s->base_flags != bdrv_get_flags(base)) {

        bdrv_reopen(base, s->base_flags, NULL);

    }

    overlay_bs = bdrv_find_overlay(active, top);

    if (overlay_bs && s->orig_overlay_flags != bdrv_get_flags(overlay_bs)) {

        bdrv_reopen(overlay_bs, s->orig_overlay_flags, NULL);

    }

    g_free(s->backing_file_str);

    block_job_completed(&s->common, ret);

}


static int nvme_start_ctrl(NvmeCtrl *n)

{

    uint32_t page_bits = NVME_CC_MPS(n->bar.cc) + 12;

    uint32_t page_size = 1 << page_bits;

    if (n->cq[0] || n->sq[0] || !n->bar.asq || !n->bar.acq ||

            n->bar.asq & (page_size - 1) || n->bar.acq & (page_size - 1) ||

            NVME_CC_MPS(n->bar.cc) < NVME_CAP_MPSMIN(n->bar.cap) ||

            NVME_CC_MPS(n->bar.cc) > NVME_CAP_MPSMAX(n->bar.cap) ||

            NVME_CC_IOCQES(n->bar.cc) < NVME_CTRL_CQES_MIN(n->id_ctrl.cqes) ||

            NVME_CC_IOCQES(n->bar.cc) > NVME_CTRL_CQES_MAX(n->id_ctrl.cqes) ||

            NVME_CC_IOSQES(n->bar.cc) < NVME_CTRL_SQES_MIN(n->id_ctrl.sqes) ||

            NVME_CC_IOSQES(n->bar.cc) > NVME_CTRL_SQES_MAX(n->id_ctrl.sqes) ||

            !NVME_AQA_ASQS(n->bar.aqa) || NVME_AQA_ASQS(n->bar.aqa) > 4095 ||

            !NVME_AQA_ACQS(n->bar.aqa) || NVME_AQA_ACQS(n->bar.aqa) > 4095) {

        return -1;

    }

    n->page_bits = page_bits;

    n->page_size = page_size;

    n->max_prp_ents = n->page_size / sizeof(uint64_t);

    n->cqe_size = 1 << NVME_CC_IOCQES(n->bar.cc);

    n->sqe_size = 1 << NVME_CC_IOSQES(n->bar.cc);

    nvme_init_cq(&n->admin_cq, n, n->bar.acq, 0, 0,

        NVME_AQA_ACQS(n->bar.aqa) + 1, 1);

    nvme_init_sq(&n->admin_sq, n, n->bar.asq, 0, 0,

        NVME_AQA_ASQS(n->bar.aqa) + 1);

    return 0;

}


static void netmap_send(void *opaque)

{

    NetmapState *s = opaque;

    struct netmap_ring *ring = s->me.rx;

    /* Keep sending while there are available packets into the netmap

       RX ring and the forwarding path towards the peer is open. */

    while (!nm_ring_empty(ring) && qemu_can_send_packet(&s->nc)) {

        uint32_t i;

        uint32_t idx;

        bool morefrag;

        int iovcnt = 0;

        int iovsize;

        do {

            i = ring->cur;

            idx = ring->slot[i].buf_idx;

            morefrag = (ring->slot[i].flags & NS_MOREFRAG);

            s->iov[iovcnt].iov_base = (u_char *)NETMAP_BUF(ring, idx);

            s->iov[iovcnt].iov_len = ring->slot[i].len;

            iovcnt++;

            ring->cur = ring->head = nm_ring_next(ring, i);

        } while (!nm_ring_empty(ring) && morefrag);

        if (unlikely(nm_ring_empty(ring) && morefrag)) {

            RD(5, "[netmap_send] ran out of slots, with a pending"

                   "incomplete packet\n");

        }

        iovsize = qemu_sendv_packet_async(&s->nc, s->iov, iovcnt,

                                            netmap_send_completed);

        if (iovsize == 0) {

            /* The peer does not receive anymore. Packet is queued, stop

             * reading from the backend until netmap_send_completed()

             */

            netmap_read_poll(s, false);

            break;

        }

    }

}


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

{

    struct gpio_state_t *s = opaque;

    uint32_t r = 0;

    addr >>= 2;

    switch (addr)

    {

        case R_PA_DIN:

            r = s->regs[RW_PA_DOUT] & s->regs[RW_PA_OE];

            /* Encode pins from the nand.  */

            r |= s->nand->rdy << 7;

            break;

        case R_PD_DIN:

            r = s->regs[RW_PD_DOUT] & s->regs[RW_PD_OE];

            /* Encode temp sensor pins.  */

            r |= (!!(s->tempsensor.shiftreg & 0x10000)) << 4;

            break;

        default:

            r = s->regs[addr];

            break;

    }

    return r;

    D(printf("%s %x=%x\n", __func__, addr, r));

}


static void vfio_probe_igd_bar4_quirk(VFIOPCIDevice *vdev, int nr)

{

    struct vfio_region_info *rom = NULL, *opregion = NULL,

                            *host = NULL, *lpc = NULL;

    VFIOQuirk *quirk;

    VFIOIGDQuirk *igd;

    PCIDevice *lpc_bridge;

    int i, ret, ggms_mb, gms_mb = 0, gen;

    uint64_t *bdsm_size;

    uint32_t gmch;

    uint16_t cmd_orig, cmd;

    Error *err = NULL;

    /* This must be an Intel VGA device. */

    if (!vfio_pci_is(vdev, PCI_VENDOR_ID_INTEL, PCI_ANY_ID) ||

        !vfio_is_vga(vdev) || nr != 4) {

        return;

    }

    /*

     * IGD is not a standard, they like to change their specs often.  We

     * only attempt to support back to SandBridge and we hope that newer

     * devices maintain compatibility with generation 8.

     */

    gen = igd_gen(vdev);

    if (gen != 6 && gen != 8) {

        error_report("IGD device %s is unsupported by IGD quirks, "

                     "try SandyBridge or newer", vdev->vbasedev.name);

        return;

    }

    /*

     * Regardless of running in UPT or legacy mode, the guest graphics

     * driver may attempt to use stolen memory, however only legacy mode

     * has BIOS support for reserving stolen memory in the guest VM.

     * Emulate the GMCH register in all cases and zero out the stolen

     * memory size here. Legacy mode may request allocation and re-write

     * this below.

     */

    gmch = vfio_pci_read_config(&vdev->pdev, IGD_GMCH, 4);

    gmch &= ~((gen < 8 ? 0x1f : 0xff) << (gen < 8 ? 3 : 8));

    /* GMCH is read-only, emulated */

    pci_set_long(vdev->pdev.config + IGD_GMCH, gmch);

    pci_set_long(vdev->pdev.wmask + IGD_GMCH, 0);

    pci_set_long(vdev->emulated_config_bits + IGD_GMCH, ~0);

    /*

     * This must be at address 00:02.0 for us to even onsider enabling

     * legacy mode.  The vBIOS has dependencies on the PCI bus address.

     */

    if (&vdev->pdev != pci_find_device(pci_device_root_bus(&vdev->pdev),

                                       0, PCI_DEVFN(0x2, 0))) {

        return;

    }

    /*

     * We need to create an LPC/ISA bridge at PCI bus address 00:1f.0 that we

     * can stuff host values into, so if there's already one there and it's not

     * one we can hack on, legacy mode is no-go.  Sorry Q35.

     */

    lpc_bridge = pci_find_device(pci_device_root_bus(&vdev->pdev),

                                 0, PCI_DEVFN(0x1f, 0));

    if (lpc_bridge && !object_dynamic_cast(OBJECT(lpc_bridge),

                                           "vfio-pci-igd-lpc-bridge")) {

        error_report("IGD device %s cannot support legacy mode due to existing "

                     "devices at address 1f.0", vdev->vbasedev.name);

        return;

    }

    /*

     * Most of what we're doing here is to enable the ROM to run, so if

     * there's no ROM, there's no point in setting up this quirk.

     * NB. We only seem to get BIOS ROMs, so a UEFI VM would need CSM support.

     */

    ret = vfio_get_region_info(&vdev->vbasedev,

                               VFIO_PCI_ROM_REGION_INDEX, &rom);

    if ((ret || !rom->size) && !vdev->pdev.romfile) {

        error_report("IGD device %s has no ROM, legacy mode disabled",

                     vdev->vbasedev.name);

        goto out;

    }

    /*

     * Ignore the hotplug corner case, mark the ROM failed, we can't

     * create the devices we need for legacy mode in the hotplug scenario.

     */

    if (vdev->pdev.qdev.hotplugged) {

        error_report("IGD device %s hotplugged, ROM disabled, "

                     "legacy mode disabled", vdev->vbasedev.name);

        vdev->rom_read_failed = true;

        goto out;

    }

    /*

     * Check whether we have all the vfio device specific regions to

     * support legacy mode (added in Linux v4.6).  If not, bail.

     */

    ret = vfio_get_dev_region_info(&vdev->vbasedev,

                        VFIO_REGION_TYPE_PCI_VENDOR_TYPE | PCI_VENDOR_ID_INTEL,

                        VFIO_REGION_SUBTYPE_INTEL_IGD_OPREGION, &opregion);

    if (ret) {

        error_report("IGD device %s does not support OpRegion access,"

                     "legacy mode disabled", vdev->vbasedev.name);

        goto out;

    }

    ret = vfio_get_dev_region_info(&vdev->vbasedev,

                        VFIO_REGION_TYPE_PCI_VENDOR_TYPE | PCI_VENDOR_ID_INTEL,

                        VFIO_REGION_SUBTYPE_INTEL_IGD_HOST_CFG, &host);

    if (ret) {

        error_report("IGD device %s does not support host bridge access,"

                     "legacy mode disabled", vdev->vbasedev.name);

        goto out;

    }

    ret = vfio_get_dev_region_info(&vdev->vbasedev,

                        VFIO_REGION_TYPE_PCI_VENDOR_TYPE | PCI_VENDOR_ID_INTEL,

                        VFIO_REGION_SUBTYPE_INTEL_IGD_LPC_CFG, &lpc);

    if (ret) {

        error_report("IGD device %s does not support LPC bridge access,"

                     "legacy mode disabled", vdev->vbasedev.name);

        goto out;

    }

    /*

     * If IGD VGA Disable is clear (expected) and VGA is not already enabled,

     * try to enable it.  Probably shouldn't be using legacy mode without VGA,

     * but also no point in us enabling VGA if disabled in hardware.

     */

    if (!(gmch & 0x2) && !vdev->vga && vfio_populate_vga(vdev, &err)) {

        error_reportf_err(err, ERR_PREFIX, vdev->vbasedev.name);

        error_report("IGD device %s failed to enable VGA access, "

                     "legacy mode disabled", vdev->vbasedev.name);

        goto out;

    }

    /* Create our LPC/ISA bridge */

    ret = vfio_pci_igd_lpc_init(vdev, lpc);

    if (ret) {

        error_report("IGD device %s failed to create LPC bridge, "

                     "legacy mode disabled", vdev->vbasedev.name);

        goto out;

    }

    /* Stuff some host values into the VM PCI host bridge */

    ret = vfio_pci_igd_host_init(vdev, host);

    if (ret) {

        error_report("IGD device %s failed to modify host bridge, "

                     "legacy mode disabled", vdev->vbasedev.name);

        goto out;

    }

    /* Setup OpRegion access */

    ret = vfio_pci_igd_opregion_init(vdev, opregion, &err);

    if (ret) {

        error_append_hint(&err, "IGD legacy mode disabled\n");

        error_reportf_err(err, ERR_PREFIX, vdev->vbasedev.name);

        goto out;

    }

    /* Setup our quirk to munge GTT addresses to the VM allocated buffer */

    quirk = g_malloc0(sizeof(*quirk));

    quirk->mem = g_new0(MemoryRegion, 2);

    quirk->nr_mem = 2;

    igd = quirk->data = g_malloc0(sizeof(*igd));

    igd->vdev = vdev;

    igd->index = ~0;

    igd->bdsm = vfio_pci_read_config(&vdev->pdev, IGD_BDSM, 4);

    igd->bdsm &= ~((1 << 20) - 1); /* 1MB aligned */

    memory_region_init_io(&quirk->mem[0], OBJECT(vdev), &vfio_igd_index_quirk,

                          igd, "vfio-igd-index-quirk", 4);

    memory_region_add_subregion_overlap(vdev->bars[nr].region.mem,

                                        0, &quirk->mem[0], 1);

    memory_region_init_io(&quirk->mem[1], OBJECT(vdev), &vfio_igd_data_quirk,

                          igd, "vfio-igd-data-quirk", 4);

    memory_region_add_subregion_overlap(vdev->bars[nr].region.mem,

                                        4, &quirk->mem[1], 1);

    QLIST_INSERT_HEAD(&vdev->bars[nr].quirks, quirk, next);

    /* Determine the size of stolen memory needed for GTT */

    ggms_mb = (gmch >> (gen < 8 ? 8 : 6)) & 0x3;

    if (gen > 6) {

        ggms_mb = 1 << ggms_mb;

    }

    /*

     * Assume we have no GMS memory, but allow it to be overrided by device

     * option (experimental).  The spec doesn't actually allow zero GMS when

     * when IVD (IGD VGA Disable) is clear, but the claim is that it's unused,

     * so let's not waste VM memory for it.

     */

    if (vdev->igd_gms) {

        if (vdev->igd_gms <= 0x10) {

            gms_mb = vdev->igd_gms * 32;

            gmch |= vdev->igd_gms << (gen < 8 ? 3 : 8);

            pci_set_long(vdev->pdev.config + IGD_GMCH, gmch);

        } else {

            error_report("Unsupported IGD GMS value 0x%x", vdev->igd_gms);

            vdev->igd_gms = 0;

        }

    }

    /*

     * Request reserved memory for stolen memory via fw_cfg.  VM firmware

     * must allocate a 1MB aligned reserved memory region below 4GB with

     * the requested size (in bytes) for use by the Intel PCI class VGA

     * device at VM address 00:02.0.  The base address of this reserved

     * memory region must be written to the device BDSM regsiter at PCI

     * config offset 0x5C.

     */

    bdsm_size = g_malloc(sizeof(*bdsm_size));

    *bdsm_size = cpu_to_le64((ggms_mb + gms_mb) * 1024 * 1024);

    fw_cfg_add_file(fw_cfg_find(), "etc/igd-bdsm-size",

                    bdsm_size, sizeof(*bdsm_size));

    /* BDSM is read-write, emulated.  The BIOS needs to be able to write it */

    pci_set_long(vdev->pdev.config + IGD_BDSM, 0);

    pci_set_long(vdev->pdev.wmask + IGD_BDSM, ~0);

    pci_set_long(vdev->emulated_config_bits + IGD_BDSM, ~0);

    /*

     * This IOBAR gives us access to GTTADR, which allows us to write to

     * the GTT itself.  So let's go ahead and write zero to all the GTT

     * entries to avoid spurious DMA faults.  Be sure I/O access is enabled

     * before talking to the device.

     */

    if (pread(vdev->vbasedev.fd, &cmd_orig, sizeof(cmd_orig),

              vdev->config_offset + PCI_COMMAND) != sizeof(cmd_orig)) {

        error_report("IGD device %s - failed to read PCI command register",

                     vdev->vbasedev.name);

    }

    cmd = cmd_orig | PCI_COMMAND_IO;

    if (pwrite(vdev->vbasedev.fd, &cmd, sizeof(cmd),

               vdev->config_offset + PCI_COMMAND) != sizeof(cmd)) {

        error_report("IGD device %s - failed to write PCI command register",

                     vdev->vbasedev.name);

    }

    for (i = 1; i < vfio_igd_gtt_max(vdev); i += 4) {

        vfio_region_write(&vdev->bars[4].region, 0, i, 4);

        vfio_region_write(&vdev->bars[4].region, 4, 0, 4);

    }

    if (pwrite(vdev->vbasedev.fd, &cmd_orig, sizeof(cmd_orig),

               vdev->config_offset + PCI_COMMAND) != sizeof(cmd_orig)) {

        error_report("IGD device %s - failed to restore PCI command register",

                     vdev->vbasedev.name);

    }

    trace_vfio_pci_igd_bdsm_enabled(vdev->vbasedev.name, ggms_mb + gms_mb);

out:

    g_free(rom);

    g_free(opregion);

    g_free(host);

    g_free(lpc);

}


int cpu_x86_handle_mmu_fault(CPUX86State *env, target_ulong addr,

                             int is_write1, int mmu_idx)

{

    uint64_t ptep, pte;

    target_ulong pde_addr, pte_addr;

    int error_code, is_dirty, prot, page_size, is_write, is_user;

    target_phys_addr_t paddr;

    uint32_t page_offset;

    target_ulong vaddr, virt_addr;

    is_user = mmu_idx == MMU_USER_IDX;

#if defined(DEBUG_MMU)

    printf("MMU fault: addr=" TARGET_FMT_lx " w=%d u=%d eip=" TARGET_FMT_lx "\n",

           addr, is_write1, is_user, env->eip);

#endif

    is_write = is_write1 & 1;

    if (!(env->cr[0] & CR0_PG_MASK)) {

        pte = addr;

        virt_addr = addr & TARGET_PAGE_MASK;

        prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;

        page_size = 4096;

        goto do_mapping;

    }

    if (env->cr[4] & CR4_PAE_MASK) {

        uint64_t pde, pdpe;

        target_ulong pdpe_addr;

#ifdef TARGET_X86_64

        if (env->hflags & HF_LMA_MASK) {

            uint64_t pml4e_addr, pml4e;

            int32_t sext;

            /* test virtual address sign extension */

            sext = (int64_t)addr >> 47;

            if (sext != 0 && sext != -1) {

                env->error_code = 0;

                env->exception_index = EXCP0D_GPF;

                return 1;

            }

            pml4e_addr = ((env->cr[3] & ~0xfff) + (((addr >> 39) & 0x1ff) << 3)) &

                env->a20_mask;

            pml4e = ldq_phys(pml4e_addr);

            if (!(pml4e & PG_PRESENT_MASK)) {

                error_code = 0;

                goto do_fault;

            }

            if (!(env->efer & MSR_EFER_NXE) && (pml4e & PG_NX_MASK)) {

                error_code = PG_ERROR_RSVD_MASK;

                goto do_fault;

            }

            if (!(pml4e & PG_ACCESSED_MASK)) {

                pml4e |= PG_ACCESSED_MASK;

                stl_phys_notdirty(pml4e_addr, pml4e);

            }

            ptep = pml4e ^ PG_NX_MASK;

            pdpe_addr = ((pml4e & PHYS_ADDR_MASK) + (((addr >> 30) & 0x1ff) << 3)) &

                env->a20_mask;

            pdpe = ldq_phys(pdpe_addr);

            if (!(pdpe & PG_PRESENT_MASK)) {

                error_code = 0;

                goto do_fault;

            }

            if (!(env->efer & MSR_EFER_NXE) && (pdpe & PG_NX_MASK)) {

                error_code = PG_ERROR_RSVD_MASK;

                goto do_fault;

            }

            ptep &= pdpe ^ PG_NX_MASK;

            if (!(pdpe & PG_ACCESSED_MASK)) {

                pdpe |= PG_ACCESSED_MASK;

                stl_phys_notdirty(pdpe_addr, pdpe);

            }

        } else

#endif

        {

            /* XXX: load them when cr3 is loaded ? */

            pdpe_addr = ((env->cr[3] & ~0x1f) + ((addr >> 27) & 0x18)) &

                env->a20_mask;

            pdpe = ldq_phys(pdpe_addr);

            if (!(pdpe & PG_PRESENT_MASK)) {

                error_code = 0;

                goto do_fault;

            }

            ptep = PG_NX_MASK | PG_USER_MASK | PG_RW_MASK;

        }

        pde_addr = ((pdpe & PHYS_ADDR_MASK) + (((addr >> 21) & 0x1ff) << 3)) &

            env->a20_mask;

        pde = ldq_phys(pde_addr);

        if (!(pde & PG_PRESENT_MASK)) {

            error_code = 0;

            goto do_fault;

        }

        if (!(env->efer & MSR_EFER_NXE) && (pde & PG_NX_MASK)) {

            error_code = PG_ERROR_RSVD_MASK;

            goto do_fault;

        }

        ptep &= pde ^ PG_NX_MASK;

        if (pde & PG_PSE_MASK) {

            /* 2 MB page */

            page_size = 2048 * 1024;

            ptep ^= PG_NX_MASK;

            if ((ptep & PG_NX_MASK) && is_write1 == 2)

                goto do_fault_protect;

            if (is_user) {

                if (!(ptep & PG_USER_MASK))

                    goto do_fault_protect;

                if (is_write && !(ptep & PG_RW_MASK))

                    goto do_fault_protect;

            } else {

                if ((env->cr[0] & CR0_WP_MASK) &&

                    is_write && !(ptep & PG_RW_MASK))

                    goto do_fault_protect;

            }

            is_dirty = is_write && !(pde & PG_DIRTY_MASK);

            if (!(pde & PG_ACCESSED_MASK) || is_dirty) {

                pde |= PG_ACCESSED_MASK;

                if (is_dirty)

                    pde |= PG_DIRTY_MASK;

                stl_phys_notdirty(pde_addr, pde);

            }

            /* align to page_size */

            pte = pde & ((PHYS_ADDR_MASK & ~(page_size - 1)) | 0xfff);

            virt_addr = addr & ~(page_size - 1);

        } else {

            /* 4 KB page */

            if (!(pde & PG_ACCESSED_MASK)) {

                pde |= PG_ACCESSED_MASK;

                stl_phys_notdirty(pde_addr, pde);

            }

            pte_addr = ((pde & PHYS_ADDR_MASK) + (((addr >> 12) & 0x1ff) << 3)) &

                env->a20_mask;

            pte = ldq_phys(pte_addr);

            if (!(pte & PG_PRESENT_MASK)) {

                error_code = 0;

                goto do_fault;

            }

            if (!(env->efer & MSR_EFER_NXE) && (pte & PG_NX_MASK)) {

                error_code = PG_ERROR_RSVD_MASK;

                goto do_fault;

            }

            /* combine pde and pte nx, user and rw protections */

            ptep &= pte ^ PG_NX_MASK;

            ptep ^= PG_NX_MASK;

            if ((ptep & PG_NX_MASK) && is_write1 == 2)

                goto do_fault_protect;

            if (is_user) {

                if (!(ptep & PG_USER_MASK))

                    goto do_fault_protect;

                if (is_write && !(ptep & PG_RW_MASK))

                    goto do_fault_protect;

            } else {

                if ((env->cr[0] & CR0_WP_MASK) &&

                    is_write && !(ptep & PG_RW_MASK))

                    goto do_fault_protect;

            }

            is_dirty = is_write && !(pte & PG_DIRTY_MASK);

            if (!(pte & PG_ACCESSED_MASK) || is_dirty) {

                pte |= PG_ACCESSED_MASK;

                if (is_dirty)

                    pte |= PG_DIRTY_MASK;

                stl_phys_notdirty(pte_addr, pte);

            }

            page_size = 4096;

            virt_addr = addr & ~0xfff;

            pte = pte & (PHYS_ADDR_MASK | 0xfff);

        }

    } else {

        uint32_t pde;

        /* page directory entry */

        pde_addr = ((env->cr[3] & ~0xfff) + ((addr >> 20) & 0xffc)) &

            env->a20_mask;

        pde = ldl_phys(pde_addr);

        if (!(pde & PG_PRESENT_MASK)) {

            error_code = 0;

            goto do_fault;

        }

        /* if PSE bit is set, then we use a 4MB page */

        if ((pde & PG_PSE_MASK) && (env->cr[4] & CR4_PSE_MASK)) {

            page_size = 4096 * 1024;

            if (is_user) {

                if (!(pde & PG_USER_MASK))

                    goto do_fault_protect;

                if (is_write && !(pde & PG_RW_MASK))

                    goto do_fault_protect;

            } else {

                if ((env->cr[0] & CR0_WP_MASK) &&

                    is_write && !(pde & PG_RW_MASK))

                    goto do_fault_protect;

            }

            is_dirty = is_write && !(pde & PG_DIRTY_MASK);

            if (!(pde & PG_ACCESSED_MASK) || is_dirty) {

                pde |= PG_ACCESSED_MASK;

                if (is_dirty)

                    pde |= PG_DIRTY_MASK;

                stl_phys_notdirty(pde_addr, pde);

            }

            pte = pde & ~( (page_size - 1) & ~0xfff); /* align to page_size */

            ptep = pte;

            virt_addr = addr & ~(page_size - 1);

        } else {

            if (!(pde & PG_ACCESSED_MASK)) {

                pde |= PG_ACCESSED_MASK;

                stl_phys_notdirty(pde_addr, pde);

            }

            /* page directory entry */

            pte_addr = ((pde & ~0xfff) + ((addr >> 10) & 0xffc)) &

                env->a20_mask;

            pte = ldl_phys(pte_addr);

            if (!(pte & PG_PRESENT_MASK)) {

                error_code = 0;

                goto do_fault;

            }

            /* combine pde and pte user and rw protections */

            ptep = pte & pde;

            if (is_user) {

                if (!(ptep & PG_USER_MASK))

                    goto do_fault_protect;

                if (is_write && !(ptep & PG_RW_MASK))

                    goto do_fault_protect;

            } else {

                if ((env->cr[0] & CR0_WP_MASK) &&

                    is_write && !(ptep & PG_RW_MASK))

                    goto do_fault_protect;

            }

            is_dirty = is_write && !(pte & PG_DIRTY_MASK);

            if (!(pte & PG_ACCESSED_MASK) || is_dirty) {

                pte |= PG_ACCESSED_MASK;

                if (is_dirty)

                    pte |= PG_DIRTY_MASK;

                stl_phys_notdirty(pte_addr, pte);

            }

            page_size = 4096;

            virt_addr = addr & ~0xfff;

        }

    }

    /* the page can be put in the TLB */

    prot = PAGE_READ;

    if (!(ptep & PG_NX_MASK))

        prot |= PAGE_EXEC;

    if (pte & PG_DIRTY_MASK) {

        /* only set write access if already dirty... otherwise wait

           for dirty access */

        if (is_user) {

            if (ptep & PG_RW_MASK)

                prot |= PAGE_WRITE;

        } else {

            if (!(env->cr[0] & CR0_WP_MASK) ||

                (ptep & PG_RW_MASK))

                prot |= PAGE_WRITE;

        }

    }

 do_mapping:

    pte = pte & env->a20_mask;

    /* Even if 4MB pages, we map only one 4KB page in the cache to

       avoid filling it too fast */

    page_offset = (addr & TARGET_PAGE_MASK) & (page_size - 1);

    paddr = (pte & TARGET_PAGE_MASK) + page_offset;

    vaddr = virt_addr + page_offset;

    tlb_set_page(env, vaddr, paddr, prot, mmu_idx, page_size);

    return 0;

 do_fault_protect:

    error_code = PG_ERROR_P_MASK;

 do_fault:

    error_code |= (is_write << PG_ERROR_W_BIT);

    if (is_user)

        error_code |= PG_ERROR_U_MASK;

    if (is_write1 == 2 &&

        (env->efer & MSR_EFER_NXE) &&

        (env->cr[4] & CR4_PAE_MASK))

        error_code |= PG_ERROR_I_D_MASK;

    if (env->intercept_exceptions & (1 << EXCP0E_PAGE)) {

        /* cr2 is not modified in case of exceptions */

        stq_phys(env->vm_vmcb + offsetof(struct vmcb, control.exit_info_2),

                 addr);

    } else {

        env->cr[2] = addr;

    }

    env->error_code = error_code;

    env->exception_index = EXCP0E_PAGE;

    return 1;

}


static void test_qga_invalid_args(gconstpointer fix)

{

    const TestFixture *fixture = fix;

    QDict *ret, *error;

    const gchar *class, *desc;

    ret = qmp_fd(fixture->fd, "{'execute': 'guest-ping', "

                 "'arguments': {'foo': 42 }}");

    g_assert_nonnull(ret);

    error = qdict_get_qdict(ret, "error");

    class = qdict_get_try_str(error, "class");

    desc = qdict_get_try_str(error, "desc");

    g_assert_cmpstr(class, ==, "GenericError");

    g_assert_cmpstr(desc, ==, "QMP input object member 'foo' is unexpected");

    QDECREF(ret);

}


int ff_mlz_decompression(MLZ* mlz, GetBitContext* gb, int size, unsigned char *buff) {

    MLZDict *dict = mlz->dict;

    unsigned long output_chars;

    int string_code, last_string_code, char_code;

    string_code = 0;

    char_code   = -1;

    last_string_code = -1;

    output_chars = 0;

    while (output_chars < size) {

        string_code = input_code(gb, mlz->dic_code_bit);

        switch (string_code) {

            case FLUSH_CODE:

            case MAX_CODE:

                ff_mlz_flush_dict(mlz);

                char_code = -1;

                last_string_code = -1;

                break;

            case FREEZE_CODE:

                mlz->freeze_flag = 1;

                break;

            default:

                if (string_code > mlz->current_dic_index_max) {

                    av_log(mlz->context, AV_LOG_ERROR, "String code %d exceeds maximum value of %d.\n", string_code, mlz->current_dic_index_max);

                if (string_code == (int) mlz->bump_code) {

                    ++mlz->dic_code_bit;

                    mlz->current_dic_index_max *= 2;

                    mlz->bump_code = mlz->current_dic_index_max - 1;

                } else {

                    if (string_code >= mlz->next_code) {

                        int ret = decode_string(mlz, &buff[output_chars], last_string_code, &char_code, size - output_chars);

                        if (ret < 0 || ret > size - output_chars) {

                            av_log(mlz->context, AV_LOG_ERROR, "output chars overflow\n");

                        output_chars += ret;

                        ret = decode_string(mlz, &buff[output_chars], char_code, &char_code, size - output_chars);

                        if (ret < 0 || ret > size - output_chars) {

                            av_log(mlz->context, AV_LOG_ERROR, "output chars overflow\n");

                        output_chars += ret;

                        set_new_entry_dict(dict, mlz->next_code, last_string_code, char_code);

                        mlz->next_code++;

                    } else {

                        int ret = decode_string(mlz, &buff[output_chars], string_code, &char_code, size - output_chars);

                        if (ret < 0 || ret > size - output_chars) {

                            av_log(mlz->context, AV_LOG_ERROR, "output chars overflow\n");

                        output_chars += ret;

                        if (output_chars <= size && !mlz->freeze_flag) {

                            if (last_string_code != -1) {

                                set_new_entry_dict(dict, mlz->next_code, last_string_code, char_code);

                                mlz->next_code++;

                        } else {

                            break;

                    last_string_code = string_code;

                break;


static void kvm_client_set_memory(struct CPUPhysMemoryClient *client,

                                  target_phys_addr_t start_addr,

                                  ram_addr_t size, ram_addr_t phys_offset,

                                  bool log_dirty)

{

    kvm_set_phys_mem(start_addr, size, phys_offset, log_dirty);

}


static void balloon_stats_set_poll_interval(Object *obj, struct Visitor *v,

                                            void *opaque, const char *name,

                                            Error **errp)

{

    VirtIOBalloon *s = opaque;

    Error *local_err = NULL;

    int64_t value;

    visit_type_int(v, &value, name, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        return;

    }

    if (value < 0) {

        error_setg(errp, "timer value must be greater than zero");

        return;

    }

    if (value > UINT_MAX) {

        error_setg(errp, "timer value is too big");

        return;

    }

    if (value == s->stats_poll_interval) {

        return;

    }

    if (value == 0) {

        /* timer=0 disables the timer */

        balloon_stats_destroy_timer(s);

        return;

    }

    if (balloon_stats_enabled(s)) {

        /* timer interval change */

        s->stats_poll_interval = value;

        balloon_stats_change_timer(s, value);

        return;

    }

    /* create a new timer */

    g_assert(s->stats_timer == NULL);

    s->stats_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL, balloon_stats_poll_cb, s);

    s->stats_poll_interval = value;

    balloon_stats_change_timer(s, 0);

}


static OutputStream *choose_output(void)

{

    int i;

    int64_t opts_min = INT64_MAX;

    OutputStream *ost_min = NULL;

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

        OutputStream *ost = output_streams[i];

        int64_t opts = av_rescale_q(ost->st->cur_dts, ost->st->time_base,

                                    AV_TIME_BASE_Q);

        if (!ost->finished && opts < opts_min) {

            opts_min = opts;

            ost_min  = ost->unavailable ? NULL : ost;

        }

    }

    return ost_min;

}


static int vfio_msi_setup(VFIOPCIDevice *vdev, int pos)

{

    uint16_t ctrl;

    bool msi_64bit, msi_maskbit;

    int ret, entries;

    if (pread(vdev->vbasedev.fd, &ctrl, sizeof(ctrl),

              vdev->config_offset + pos + PCI_CAP_FLAGS) != sizeof(ctrl)) {

        return -errno;

    }

    ctrl = le16_to_cpu(ctrl);

    msi_64bit = !!(ctrl & PCI_MSI_FLAGS_64BIT);

    msi_maskbit = !!(ctrl & PCI_MSI_FLAGS_MASKBIT);

    entries = 1 << ((ctrl & PCI_MSI_FLAGS_QMASK) >> 1);

    trace_vfio_msi_setup(vdev->vbasedev.name, pos);

    ret = msi_init(&vdev->pdev, pos, entries, msi_64bit, msi_maskbit);

    if (ret < 0) {

        if (ret == -ENOTSUP) {

            return 0;

        }

        error_report("vfio: msi_init failed");

        return ret;

    }

    vdev->msi_cap_size = 0xa + (msi_maskbit ? 0xa : 0) + (msi_64bit ? 0x4 : 0);

    return 0;

}


static void gen_advance_ccount(DisasContext *dc)

{

    gen_advance_ccount_cond(dc);

    dc->ccount_delta = 0;

}


void init_paths(const char *prefix)

{

    char pref_buf[PATH_MAX];

    if (prefix[0] == '\0' ||

        !strcmp(prefix, "/"))

        return;

    if (prefix[0] != '/') {

        char *cwd = getcwd(NULL, 0);

        size_t pref_buf_len = sizeof(pref_buf);

        if (!cwd)

            abort();

        pstrcpy(pref_buf, sizeof(pref_buf), cwd);

        pstrcat(pref_buf, pref_buf_len, "/");

        pstrcat(pref_buf, pref_buf_len, prefix);

        free(cwd);

    } else

        pstrcpy(pref_buf, sizeof(pref_buf), prefix + 1);

    base = new_entry("", NULL, pref_buf);

    base = add_dir_maybe(base);

    if (base->num_entries == 0) {

        g_free(base->pathname);

        free(base->name);

        free(base);

        base = NULL;

    } else {

        set_parents(base, base);

    }

}


int bdrv_all_create_snapshot(QEMUSnapshotInfo *sn,

                             BlockDriverState *vm_state_bs,

                             uint64_t vm_state_size,

                             BlockDriverState **first_bad_bs)

{

    int err = 0;

    BlockDriverState *bs;

    BdrvNextIterator it;

    for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {

        AioContext *ctx = bdrv_get_aio_context(bs);

        aio_context_acquire(ctx);

        if (bs == vm_state_bs) {

            sn->vm_state_size = vm_state_size;

            err = bdrv_snapshot_create(bs, sn);

        } else if (bdrv_can_snapshot(bs)) {

            sn->vm_state_size = 0;

            err = bdrv_snapshot_create(bs, sn);

        }

        aio_context_release(ctx);

        if (err < 0) {

            goto fail;

        }

    }

fail:

    *first_bad_bs = bs;

    return err;

}


void tb_target_set_jmp_target(uintptr_t tc_ptr, uintptr_t jmp_addr,

                              uintptr_t addr)

{

    if (TCG_TARGET_REG_BITS == 64) {

        tcg_insn_unit i1, i2;

        intptr_t tb_diff = addr - tc_ptr;

        intptr_t br_diff = addr - (jmp_addr + 4);

        uint64_t pair;

        /* This does not exercise the range of the branch, but we do

           still need to be able to load the new value of TCG_REG_TB.

           But this does still happen quite often.  */

        if (tb_diff == (int16_t)tb_diff) {

            i1 = ADDI | TAI(TCG_REG_TB, TCG_REG_TB, tb_diff);

            i2 = B | (br_diff & 0x3fffffc);

        } else {

            intptr_t lo = (int16_t)tb_diff;

            intptr_t hi = (int32_t)(tb_diff - lo);

            assert(tb_diff == hi + lo);

            i1 = ADDIS | TAI(TCG_REG_TB, TCG_REG_TB, hi >> 16);

            i2 = ADDI | TAI(TCG_REG_TB, TCG_REG_TB, lo);

        }

#ifdef HOST_WORDS_BIGENDIAN

        pair = (uint64_t)i1 << 32 | i2;

#else

        pair = (uint64_t)i2 << 32 | i1;

#endif

        atomic_set((uint64_t *)jmp_addr, pair);

        flush_icache_range(jmp_addr, jmp_addr + 8);

    } else {

        intptr_t diff = addr - jmp_addr;

        tcg_debug_assert(in_range_b(diff));

        atomic_set((uint32_t *)jmp_addr, B | (diff & 0x3fffffc));

        flush_icache_range(jmp_addr, jmp_addr + 4);

    }

}


static av_always_inline int setup_classifs(vorbis_context *vc,

                                           vorbis_residue *vr,

                                           uint8_t *do_not_decode,

                                           unsigned ch_used,

                                           int partition_count)

{

    int p, j, i;

    unsigned c_p_c         = vc->codebooks[vr->classbook].dimensions;

    unsigned inverse_class = ff_inverse[vr->classifications];

    unsigned temp, temp2;

    for (p = 0, j = 0; j < ch_used; ++j) {

        if (!do_not_decode[j]) {

            temp = get_vlc2(&vc->gb, vc->codebooks[vr->classbook].vlc.table,

                                     vc->codebooks[vr->classbook].nb_bits, 3);

            av_dlog(NULL, "Classword: %u\n", temp);

            if ((int)temp < 0)

                return temp;

            av_assert0(vr->classifications > 1); //needed for inverse[]

            if (temp <= 65536) {

                for (i = partition_count + c_p_c - 1; i >= partition_count; i--) {

                    temp2 = (((uint64_t)temp) * inverse_class) >> 32;

                    if (i < vr->ptns_to_read)

                        vr->classifs[p + i] = temp - temp2 * vr->classifications;

                    temp = temp2;

                }

            } else {

                for (i = partition_count + c_p_c - 1; i >= partition_count; i--) {

                    temp2 = temp / vr->classifications;

                    if (i < vr->ptns_to_read)

                        vr->classifs[p + i] = temp - temp2 * vr->classifications;

                    temp = temp2;

                }

            }

        }

        p += vr->ptns_to_read;

    }

    return 0;

}


static int xan_unpack(uint8_t *dest, const int dest_len,

                      const uint8_t *src, const int src_len)

{

    uint8_t opcode;

    int size;

    uint8_t *orig_dest = dest;

    const uint8_t *src_end = src + src_len;

    const uint8_t *dest_end = dest + dest_len;

    while (dest < dest_end) {

        opcode = *src++;

        if (opcode < 0xe0) {

            int size2, back;

            if ((opcode & 0x80) == 0) {

                size  = opcode & 3;

                back  = ((opcode & 0x60) << 3) + *src++ + 1;

                size2 = ((opcode & 0x1c) >> 2) + 3;

            } else if ((opcode & 0x40) == 0) {

                size  = *src >> 6;

                back  = (bytestream_get_be16(&src) & 0x3fff) + 1;

                size2 = (opcode & 0x3f) + 4;

            } else {

                size  = opcode & 3;

                back  = ((opcode & 0x10) << 12) + bytestream_get_be16(&src) + 1;

                size2 = ((opcode & 0x0c) <<  6) + *src++ + 5;

                if (size + size2 > dest_end - dest)

                    break;

            }

            if (src + size > src_end || dest + size + size2 > dest_end ||

                dest - orig_dest + size < back)

                return -1;

            bytestream_get_buffer(&src, dest, size);

            dest += size;

            av_memcpy_backptr(dest, back, size2);

            dest += size2;

        } else {

            int finish = opcode >= 0xfc;

            size = finish ? opcode & 3 : ((opcode & 0x1f) << 2) + 4;

            if (src + size > src_end || dest + size > dest_end)

                return -1;

            bytestream_get_buffer(&src, dest, size);

            dest += size;

            if (finish)

                break;

        }

    }

    return dest - orig_dest;

}


static void qht_do_test(unsigned int mode, size_t init_entries)
{
    qht_init(&ht, 0, mode);
    insert(0, N);
    check(0, N, true);
    check_n(N);
    check(-N, -1, false);
    iter_check(N);
    rm(101, 102);
    check_n(N - 1);
    insert(N, N * 2);
    check_n(N + N - 1);
    rm(N, N * 2);
    check_n(N - 1);
    insert(101, 102);
    check_n(N);
    rm(10, 200);
    check_n(N - 190);
    insert(150, 200);
    check_n(N - 190 + 50);
    insert(10, 150);
    check_n(N);
    rm(1, 2);
    check_n(N - 1);
    qht_reset_size(&ht, 0);
    check(0, N, false);
    qht_destroy(&ht);
}


static int mov_write_tkhd_tag(ByteIOContext *pb, MOVTrack* track)

{

    int64_t maxTrackLenTemp;

    put_be32(pb, 0x5c); /* size (always 0x5c) */

    put_tag(pb, "tkhd");

    put_be32(pb, 0xf); /* version & flags (track enabled) */

    put_be32(pb, track->time); /* creation time */

    put_be32(pb, track->time); /* modification time */

    put_be32(pb, track->trackID); /* track-id */

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

    maxTrackLenTemp = ((int64_t)globalTimescale*(int64_t)track->trackDuration)/(int64_t)track->timescale;

    put_be32(pb, (long)maxTrackLenTemp); /* duration */

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

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

    put_be32(pb, 0x0); /* reserved (Layer & Alternate group) */

    /* Volume, only for audio */

    if(track->enc->codec_type == CODEC_TYPE_AUDIO)

        put_be16(pb, 0x0100);

    else

        put_be16(pb, 0);

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

    /* Matrix structure */

    put_be32(pb, 0x00010000); /* reserved */

    put_be32(pb, 0x0); /* reserved */

    put_be32(pb, 0x0); /* reserved */

    put_be32(pb, 0x0); /* reserved */

    put_be32(pb, 0x00010000); /* reserved */

    put_be32(pb, 0x0); /* reserved */

    put_be32(pb, 0x0); /* reserved */

    put_be32(pb, 0x0); /* reserved */

    put_be32(pb, 0x40000000); /* reserved */

    /* Track width and height, for visual only */

    if(track->enc->codec_type == CODEC_TYPE_VIDEO) {

        put_be32(pb, track->enc->width*0x10000);

        put_be32(pb, track->enc->height*0x10000);

    }

    else {

        put_be32(pb, 0);

        put_be32(pb, 0);

    }

    return 0x5c;

}


static void quantize_and_encode_band_cost_NONE_mips(struct AACEncContext *s,

                                                         PutBitContext *pb, const float *in, float *out,

                                                         const float *scaled, int size, int scale_idx,

                                                         int cb, const float lambda, const float uplim,

                                                         int *bits, const float ROUNDING) {

    av_assert0(0);

}


int qcrypto_cipher_setiv(QCryptoCipher *cipher,

                         const uint8_t *iv, size_t niv,

                         Error **errp)

{

    QCryptoCipherNettle *ctx = cipher->opaque;

    if (niv != ctx->niv) {

        error_setg(errp, "Expected IV size %zu not %zu",

                   ctx->niv, niv);

        return -1;

    }

    memcpy(ctx->iv, iv, niv);

    return 0;

}


static int uhci_handle_td(UHCIState *s, uint32_t addr, UHCI_TD *td,

                          uint32_t *int_mask, bool queuing)

{

    UHCIAsync *async;

    int len = 0, max_len;

    uint8_t pid;

    USBDevice *dev;

    USBEndpoint *ep;

    /* Is active ? */

    if (!(td->ctrl & TD_CTRL_ACTIVE))

        return TD_RESULT_NEXT_QH;

    async = uhci_async_find_td(s, addr, td);

    if (async) {

        /* Already submitted */

        async->queue->valid = 32;

        if (!async->done)

            return TD_RESULT_ASYNC_CONT;

        if (queuing) {

            /* we are busy filling the queue, we are not prepared

               to consume completed packages then, just leave them

               in async state */

            return TD_RESULT_ASYNC_CONT;

        }

        uhci_async_unlink(async);

        goto done;

    }

    /* Allocate new packet */

    async = uhci_async_alloc(uhci_queue_get(s, td), addr);

    /* valid needs to be large enough to handle 10 frame delay

     * for initial isochronous requests

     */

    async->queue->valid = 32;

    async->isoc  = td->ctrl & TD_CTRL_IOS;

    max_len = ((td->token >> 21) + 1) & 0x7ff;

    pid = td->token & 0xff;

    dev = uhci_find_device(s, (td->token >> 8) & 0x7f);

    ep = usb_ep_get(dev, pid, (td->token >> 15) & 0xf);

    usb_packet_setup(&async->packet, pid, ep);

    qemu_sglist_add(&async->sgl, td->buffer, max_len);

    usb_packet_map(&async->packet, &async->sgl);

    switch(pid) {

    case USB_TOKEN_OUT:

    case USB_TOKEN_SETUP:

        len = usb_handle_packet(dev, &async->packet);

        if (len >= 0)

            len = max_len;

        break;

    case USB_TOKEN_IN:

        len = usb_handle_packet(dev, &async->packet);

        break;

    default:

        /* invalid pid : frame interrupted */

        uhci_async_free(async);

        s->status |= UHCI_STS_HCPERR;

        uhci_update_irq(s);

        return TD_RESULT_STOP_FRAME;

    }

    if (len == USB_RET_ASYNC) {

        uhci_async_link(async);

        return TD_RESULT_ASYNC_START;

    }

    async->packet.result = len;

done:

    len = uhci_complete_td(s, td, async, int_mask);

    usb_packet_unmap(&async->packet);

    uhci_async_free(async);

    return len;

}


static int assign_intx(AssignedDevice *dev)

{

    AssignedIRQType new_type;

    PCIINTxRoute intx_route;

    bool intx_host_msi;

    int r;

    /* Interrupt PIN 0 means don't use INTx */

    if (assigned_dev_pci_read_byte(&dev->dev, PCI_INTERRUPT_PIN) == 0) {

        pci_device_set_intx_routing_notifier(&dev->dev, NULL);

        return 0;

    }

    if (!check_irqchip_in_kernel()) {

        return -ENOTSUP;

    }

    pci_device_set_intx_routing_notifier(&dev->dev,

                                         assigned_dev_update_irq_routing);

    intx_route = pci_device_route_intx_to_irq(&dev->dev, dev->intpin);

    assert(intx_route.mode != PCI_INTX_INVERTED);

    if (!pci_intx_route_changed(&dev->intx_route, &intx_route)) {

        return 0;

    }

    switch (dev->assigned_irq_type) {

    case ASSIGNED_IRQ_INTX_HOST_INTX:

    case ASSIGNED_IRQ_INTX_HOST_MSI:

        intx_host_msi = dev->assigned_irq_type == ASSIGNED_IRQ_INTX_HOST_MSI;

        r = kvm_device_intx_deassign(kvm_state, dev->dev_id, intx_host_msi);

        break;

    case ASSIGNED_IRQ_MSI:

        r = kvm_device_msi_deassign(kvm_state, dev->dev_id);

        break;

    case ASSIGNED_IRQ_MSIX:

        r = kvm_device_msix_deassign(kvm_state, dev->dev_id);

        break;

    default:

        r = 0;

        break;

    }

    if (r) {

        perror("assign_intx: deassignment of previous interrupt failed");

    }

    dev->assigned_irq_type = ASSIGNED_IRQ_NONE;

    if (intx_route.mode == PCI_INTX_DISABLED) {

        dev->intx_route = intx_route;

        return 0;

    }

retry:

    if (dev->features & ASSIGNED_DEVICE_PREFER_MSI_MASK &&

        dev->cap.available & ASSIGNED_DEVICE_CAP_MSI) {

        intx_host_msi = true;

        new_type = ASSIGNED_IRQ_INTX_HOST_MSI;

    } else {

        intx_host_msi = false;

        new_type = ASSIGNED_IRQ_INTX_HOST_INTX;

    }

    r = kvm_device_intx_assign(kvm_state, dev->dev_id, intx_host_msi,

                               intx_route.irq);

    if (r < 0) {

        if (r == -EIO && !(dev->features & ASSIGNED_DEVICE_PREFER_MSI_MASK) &&

            dev->cap.available & ASSIGNED_DEVICE_CAP_MSI) {

            /* Retry with host-side MSI. There might be an IRQ conflict and

             * either the kernel or the device doesn't support sharing. */

            error_report("Host-side INTx sharing not supported, "

                         "using MSI instead");

            error_printf("Some devices do not work properly in this mode.\n");

            dev->features |= ASSIGNED_DEVICE_PREFER_MSI_MASK;

            goto retry;

        }

        error_report("Failed to assign irq for \"%s\": %s",

                     dev->dev.qdev.id, strerror(-r));

        error_report("Perhaps you are assigning a device "

                     "that shares an IRQ with another device?");

        return r;

    }

    dev->intx_route = intx_route;

    dev->assigned_irq_type = new_type;

    return r;

}


void cpu_register_physical_memory(target_phys_addr_t start_addr,

                                  unsigned long size,

                                  unsigned long phys_offset)

{

    target_phys_addr_t addr, end_addr;

    PhysPageDesc *p;

    CPUState *env;

    unsigned long orig_size = size;

    void *subpage;

    end_addr = start_addr + (target_phys_addr_t)size;

    size = (size + TARGET_PAGE_SIZE - 1) & TARGET_PAGE_MASK;

    for(addr = start_addr; addr < end_addr; addr += TARGET_PAGE_SIZE) {

        p = phys_page_find(addr >> TARGET_PAGE_BITS);

        if (p && p->phys_offset != IO_MEM_UNASSIGNED) {

            unsigned long orig_memory = p->phys_offset;

            target_phys_addr_t start_addr2, end_addr2;

            int need_subpage = 0;

            CHECK_SUBPAGE(addr, start_addr, start_addr2, end_addr, end_addr2,

                          need_subpage);

            if (need_subpage) {

                if (!(orig_memory & IO_MEM_SUBPAGE)) {

                    subpage = subpage_init((addr & TARGET_PAGE_MASK),

                                           &p->phys_offset, orig_memory);

                } else {

                    subpage = io_mem_opaque[(orig_memory & ~TARGET_PAGE_MASK)

                                            >> IO_MEM_SHIFT];

                }

                subpage_register(subpage, start_addr2, end_addr2, phys_offset);

            } else {

                p->phys_offset = phys_offset;

                if ((phys_offset & ~TARGET_PAGE_MASK) <= IO_MEM_ROM ||

                    (phys_offset & IO_MEM_ROMD))

                    phys_offset += TARGET_PAGE_SIZE;

            }

        } else {

            p = phys_page_find_alloc(addr >> TARGET_PAGE_BITS, 1);

            p->phys_offset = phys_offset;

            if ((phys_offset & ~TARGET_PAGE_MASK) <= IO_MEM_ROM ||

                (phys_offset & IO_MEM_ROMD))

                phys_offset += TARGET_PAGE_SIZE;

            else {

                target_phys_addr_t start_addr2, end_addr2;

                int need_subpage = 0;

                CHECK_SUBPAGE(addr, start_addr, start_addr2, end_addr,

                              end_addr2, need_subpage);

                if (need_subpage) {

                    subpage = subpage_init((addr & TARGET_PAGE_MASK),

                                           &p->phys_offset, IO_MEM_UNASSIGNED);

                    subpage_register(subpage, start_addr2, end_addr2,

                                     phys_offset);

                }

            }

        }

    }

    /* since each CPU stores ram addresses in its TLB cache, we must

       reset the modified entries */

    /* XXX: slow ! */

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

        tlb_flush(env, 1);

    }

}


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

{

    int i, j, ret;

    int scaler_count = 0, resampler_count = 0;

    int count_queried = 0;        /* successful calls to query_formats() */

    int count_merged = 0;         /* successful merge of formats lists */

    int count_already_merged = 0; /* lists already merged */

    int count_delayed = 0;        /* lists that need to be merged later */

    for (i = 0; i < graph->nb_filters; i++) {

        AVFilterContext *f = graph->filters[i];

        if (formats_declared(f))

            continue;

        if (f->filter->query_formats)

            ret = filter_query_formats(f);

        else

            ret = ff_default_query_formats(f);

        if (ret < 0 && ret != AVERROR(EAGAIN))

            return ret;

        /* note: EAGAIN could indicate a partial success, not counted yet */

        count_queried += ret >= 0;

    }

    /* go through and merge as many format lists as possible */

    for (i = 0; i < graph->nb_filters; i++) {

        AVFilterContext *filter = graph->filters[i];

        for (j = 0; j < filter->nb_inputs; j++) {

            AVFilterLink *link = filter->inputs[j];

            int convert_needed = 0;

            if (!link)

                continue;

            if (link->in_formats != link->out_formats

                && link->in_formats && link->out_formats)

                if (!can_merge_formats(link->in_formats, link->out_formats,

                                      link->type, 0))

                    convert_needed = 1;

            if (link->type == AVMEDIA_TYPE_AUDIO) {

                if (link->in_samplerates != link->out_samplerates

                    && link->in_samplerates && link->out_samplerates)

                    if (!can_merge_formats(link->in_samplerates,

                                           link->out_samplerates,

                                           0, 1))

                        convert_needed = 1;

            }

#define MERGE_DISPATCH(field, statement)                                     \

            if (!(link->in_ ## field && link->out_ ## field)) {              \

                count_delayed++;                                             \

            } else if (link->in_ ## field == link->out_ ## field) {          \

                count_already_merged++;                                      \

            } else if (!convert_needed) {                                    \

                count_merged++;                                              \

                statement                                                    \

            }

            if (link->type == AVMEDIA_TYPE_AUDIO) {

                MERGE_DISPATCH(channel_layouts,

                    if (!ff_merge_channel_layouts(link->in_channel_layouts,

                                                  link->out_channel_layouts))

                        convert_needed = 1;

                )

                MERGE_DISPATCH(samplerates,

                    if (!ff_merge_samplerates(link->in_samplerates,

                                              link->out_samplerates))

                        convert_needed = 1;

                )

            }

            MERGE_DISPATCH(formats,

                if (!ff_merge_formats(link->in_formats, link->out_formats,

                                      link->type))

                    convert_needed = 1;

            )

#undef MERGE_DISPATCH

            if (convert_needed) {

                AVFilterContext *convert;

                AVFilter *filter;

                AVFilterLink *inlink, *outlink;

                char scale_args[256];

                char inst_name[30];

                /* couldn't merge format lists. auto-insert conversion filter */

                switch (link->type) {

                case AVMEDIA_TYPE_VIDEO:

                    if (!(filter = avfilter_get_by_name("scale"))) {

                        av_log(log_ctx, AV_LOG_ERROR, "'scale' filter "

                               "not present, cannot convert pixel formats.\n");

                        return AVERROR(EINVAL);

                    }

                    snprintf(inst_name, sizeof(inst_name), "auto-inserted scaler %d",

                             scaler_count++);

                    if ((ret = avfilter_graph_create_filter(&convert, filter,

                                                            inst_name, graph->scale_sws_opts, NULL,

                                                            graph)) < 0)

                        return ret;

                    break;

                case AVMEDIA_TYPE_AUDIO:

                    if (!(filter = avfilter_get_by_name("aresample"))) {

                        av_log(log_ctx, AV_LOG_ERROR, "'aresample' filter "

                               "not present, cannot convert audio formats.\n");

                        return AVERROR(EINVAL);

                    }

                    snprintf(inst_name, sizeof(inst_name), "auto-inserted resampler %d",

                             resampler_count++);

                    scale_args[0] = '\0';

                    if (graph->aresample_swr_opts)

                        snprintf(scale_args, sizeof(scale_args), "%s",

                                 graph->aresample_swr_opts);

                    if ((ret = avfilter_graph_create_filter(&convert, filter,

                                                            inst_name, graph->aresample_swr_opts,

                                                            NULL, graph)) < 0)

                        return ret;

                    break;

                default:

                    return AVERROR(EINVAL);

                }

                if ((ret = avfilter_insert_filter(link, convert, 0, 0)) < 0)

                    return ret;

                filter_query_formats(convert);

                inlink  = convert->inputs[0];

                outlink = convert->outputs[0];

                av_assert0( inlink-> in_formats->refcount > 0);

                av_assert0( inlink->out_formats->refcount > 0);

                av_assert0(outlink-> in_formats->refcount > 0);

                av_assert0(outlink->out_formats->refcount > 0);

                if (outlink->type == AVMEDIA_TYPE_AUDIO) {

                    av_assert0( inlink-> in_samplerates->refcount > 0);

                    av_assert0( inlink->out_samplerates->refcount > 0);

                    av_assert0(outlink-> in_samplerates->refcount > 0);

                    av_assert0(outlink->out_samplerates->refcount > 0);

                    av_assert0( inlink-> in_channel_layouts->refcount > 0);

                    av_assert0( inlink->out_channel_layouts->refcount > 0);

                    av_assert0(outlink-> in_channel_layouts->refcount > 0);

                    av_assert0(outlink->out_channel_layouts->refcount > 0);

                }

                if (!ff_merge_formats( inlink->in_formats,  inlink->out_formats,  inlink->type) ||

                    !ff_merge_formats(outlink->in_formats, outlink->out_formats, outlink->type))

                    ret = AVERROR(ENOSYS);

                if (inlink->type == AVMEDIA_TYPE_AUDIO &&

                    (!ff_merge_samplerates(inlink->in_samplerates,

                                           inlink->out_samplerates) ||

                     !ff_merge_channel_layouts(inlink->in_channel_layouts,

                                               inlink->out_channel_layouts)))

                    ret = AVERROR(ENOSYS);

                if (outlink->type == AVMEDIA_TYPE_AUDIO &&

                    (!ff_merge_samplerates(outlink->in_samplerates,

                                           outlink->out_samplerates) ||

                     !ff_merge_channel_layouts(outlink->in_channel_layouts,

                                               outlink->out_channel_layouts)))

                    ret = AVERROR(ENOSYS);

                if (ret < 0) {

                    av_log(log_ctx, AV_LOG_ERROR,

                           "Impossible to convert between the formats supported by the filter "

                           "'%s' and the filter '%s'\n", link->src->name, link->dst->name);

                    return ret;

                }

            }

        }

    }

    av_log(graph, AV_LOG_DEBUG, "query_formats: "

           "%d queried, %d merged, %d already done, %d delayed\n",

           count_queried, count_merged, count_already_merged, count_delayed);

    if (count_delayed) {

        AVBPrint bp;

        /* if count_queried > 0, one filter at least did set its formats,

           that will give additional information to its neighbour;

           if count_merged > 0, one pair of formats lists at least was merged,

           that will give additional information to all connected filters;

           in both cases, progress was made and a new round must be done */

        if (count_queried || count_merged)

            return AVERROR(EAGAIN);

        av_bprint_init(&bp, 0, AV_BPRINT_SIZE_AUTOMATIC);

        for (i = 0; i < graph->nb_filters; i++)

            if (!formats_declared(graph->filters[i]))

                av_bprintf(&bp, "%s%s", bp.len ? ", " : "",

                          graph->filters[i]->name);

        av_log(graph, AV_LOG_ERROR,

               "The following filters could not choose their formats: %s\n"

               "Consider inserting the (a)format filter near their input or "

               "output.\n", bp.str);

        return AVERROR(EIO);

    }

    return 0;

}


void mpeg1_encode_init(MpegEncContext *s)

{

    static int done=0;

    if(!done){

        int f_code;

        int mv;

        done=1;

        for(f_code=1; f_code<=MAX_FCODE; f_code++){

            for(mv=-MAX_MV; mv<=MAX_MV; mv++){

                int len;

                if(mv==0) len= mbMotionVectorTable[0][1];

                else{

                    int val, bit_size, range, code;

                    bit_size = s->f_code - 1;

                    range = 1 << bit_size;

                    val=mv;

                    if (val < 0)

                        val = -val;

                    val--;

                    code = (val >> bit_size) + 1;

                    if(code<17){

                        len= mbMotionVectorTable[code][1] + 1 + bit_size;

                    }else{

                        len= mbMotionVectorTable[16][1] + 2 + bit_size;

                    }

                }

                mv_penalty[f_code][mv+MAX_MV]= len;

            }

        }

        for(f_code=MAX_FCODE; f_code>0; f_code--){

            for(mv=-(8<<f_code); mv<(8<<f_code); mv++){

                fcode_tab[mv+MAX_MV]= f_code;

            }

        }

    }

    s->mv_penalty= mv_penalty;

    s->fcode_tab= fcode_tab;

}


static int cook_decode_close(AVCodecContext *avctx)

{

    int i;

    COOKContext *q = avctx->priv_data;

    av_log(NULL,AV_LOG_DEBUG, "Deallocating memory.\n");

    /* Free allocated memory buffers. */

    av_free(q->mlt_window);

    av_free(q->mlt_precos);

    av_free(q->mlt_presin);

    av_free(q->mlt_postcos);

    av_free(q->frame_reorder_index);

    av_free(q->frame_reorder_buffer);

    av_free(q->decoded_bytes_buffer);

    /* Free the transform. */

    ff_fft_end(&q->fft_ctx);

    /* Free the VLC tables. */

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

        free_vlc(&q->envelope_quant_index[i]);

    }

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

        free_vlc(&q->sqvh[i]);

    }

    if(q->nb_channels==2 && q->joint_stereo==1 ){

        free_vlc(&q->ccpl);

    }

    av_log(NULL,AV_LOG_DEBUG,"Memory deallocated.\n");

    return 0;

}


static int compute_pkt_fields2(AVFormatContext *s, AVStream *st, AVPacket *pkt){

    int delay = FFMAX(st->codec->has_b_frames, !!st->codec->max_b_frames);

    int num, den, frame_size, i;

    av_dlog(s, "compute_pkt_fields2: pts:%"PRId64" dts:%"PRId64" cur_dts:%"PRId64" b:%d size:%d st:%d\n",

            pkt->pts, pkt->dts, st->cur_dts, delay, pkt->size, pkt->stream_index);

/*    if(pkt->pts == AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE)

        return AVERROR(EINVAL);*/

    /* duration field */

    if (pkt->duration == 0) {

        compute_frame_duration(&num, &den, st, NULL, pkt);

        if (den && num) {

            pkt->duration = av_rescale(1, num * (int64_t)st->time_base.den * st->codec->ticks_per_frame, den * (int64_t)st->time_base.num);

        }

    }

    if(pkt->pts == AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && delay==0)

        pkt->pts= pkt->dts;

    //XXX/FIXME this is a temporary hack until all encoders output pts

    if((pkt->pts == 0 || pkt->pts == AV_NOPTS_VALUE) && pkt->dts == AV_NOPTS_VALUE && !delay){

        pkt->dts=

//        pkt->pts= st->cur_dts;

        pkt->pts= st->pts.val;

    }

    //calculate dts from pts

    if(pkt->pts != AV_NOPTS_VALUE && pkt->dts == AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){

        st->pts_buffer[0]= pkt->pts;

        for(i=1; i<delay+1 && st->pts_buffer[i] == AV_NOPTS_VALUE; i++)

            st->pts_buffer[i]= pkt->pts + (i-delay-1) * pkt->duration;

        for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)

            FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);

        pkt->dts= st->pts_buffer[0];

    }

    if(st->cur_dts && st->cur_dts != AV_NOPTS_VALUE && ((!(s->oformat->flags & AVFMT_TS_NONSTRICT) && st->cur_dts >= pkt->dts) || st->cur_dts > pkt->dts)){

        av_log(s, AV_LOG_ERROR,

               "Application provided invalid, non monotonically increasing dts to muxer in stream %d: %"PRId64" >= %"PRId64"\n",

               st->index, st->cur_dts, pkt->dts);

        return AVERROR(EINVAL);

    }

    if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts < pkt->dts){

        av_log(s, AV_LOG_ERROR, "pts < dts in stream %d\n", st->index);

        return AVERROR(EINVAL);

    }

//    av_log(s, AV_LOG_DEBUG, "av_write_frame: pts2:%"PRId64" dts2:%"PRId64"\n", pkt->pts, pkt->dts);

    st->cur_dts= pkt->dts;

    st->pts.val= pkt->dts;

    /* update pts */

    switch (st->codec->codec_type) {

    case AVMEDIA_TYPE_AUDIO:

        frame_size = get_audio_frame_size(st->codec, pkt->size);

        /* HACK/FIXME, we skip the initial 0 size packets as they are most

           likely equal to the encoder delay, but it would be better if we

           had the real timestamps from the encoder */

        if (frame_size >= 0 && (pkt->size || st->pts.num!=st->pts.den>>1 || st->pts.val)) {

            frac_add(&st->pts, (int64_t)st->time_base.den * frame_size);

        }

        break;

    case AVMEDIA_TYPE_VIDEO:

        frac_add(&st->pts, (int64_t)st->time_base.den * st->codec->time_base.num);

        break;

    default:

        break;

    }

    return 0;

}


static void monitor_fdset_cleanup(MonFdset *mon_fdset)

{

    MonFdsetFd *mon_fdset_fd;

    MonFdsetFd *mon_fdset_fd_next;

    QLIST_FOREACH_SAFE(mon_fdset_fd, &mon_fdset->fds, next, mon_fdset_fd_next) {

        if (mon_fdset_fd->removed) {

            close(mon_fdset_fd->fd);

            g_free(mon_fdset_fd->opaque);

            QLIST_REMOVE(mon_fdset_fd, next);

            g_free(mon_fdset_fd);

        }

    }

    if (QLIST_EMPTY(&mon_fdset->fds) && QLIST_EMPTY(&mon_fdset->dup_fds)) {

        QLIST_REMOVE(mon_fdset, next);

        g_free(mon_fdset);

    }

}


int ff_h264_check_intra_pred_mode(H264Context *h, int mode){

    MpegEncContext * const s = &h->s;

    static const int8_t top [7]= {LEFT_DC_PRED8x8, 1,-1,-1};

    static const int8_t left[7]= { TOP_DC_PRED8x8,-1, 2,-1,DC_128_PRED8x8};

    if(mode > 6U) {

        av_log(h->s.avctx, AV_LOG_ERROR, "out of range intra chroma pred mode at %d %d\n", s->mb_x, s->mb_y);

        return -1;

    }

    if(!(h->top_samples_available&0x8000)){

        mode= top[ mode ];

        if(mode<0){

            av_log(h->s.avctx, AV_LOG_ERROR, "top block unavailable for requested intra mode at %d %d\n", s->mb_x, s->mb_y);

            return -1;

        }

    }

    if((h->left_samples_available&0x8080) != 0x8080){

        mode= left[ mode ];

        if(h->left_samples_available&0x8080){ //mad cow disease mode, aka MBAFF + constrained_intra_pred

            mode= ALZHEIMER_DC_L0T_PRED8x8 + (!(h->left_samples_available&0x8000)) + 2*(mode == DC_128_PRED8x8);

        }

        if(mode<0){

            av_log(h->s.avctx, AV_LOG_ERROR, "left block unavailable for requested intra mode at %d %d\n", s->mb_x, s->mb_y);

            return -1;

        }

    }

    return mode;

}


static inline void chroma_4mv_motion_lowres(MpegEncContext *s,

                                            uint8_t *dest_cb, uint8_t *dest_cr,

                                            uint8_t **ref_picture,

                                            h264_chroma_mc_func * pix_op,

                                            int mx, int my)

{

    const int lowres     = s->avctx->lowres;

    const int op_index   = FFMIN(lowres, 2);

    const int block_s    = 8 >> lowres;

    const int s_mask     = (2 << lowres) - 1;

    const int h_edge_pos = s->h_edge_pos >> lowres + 1;

    const int v_edge_pos = s->v_edge_pos >> lowres + 1;

    int emu = 0, src_x, src_y, offset, sx, sy;

    uint8_t *ptr;

    if (s->quarter_sample) {

        mx /= 2;

        my /= 2;

    }

    /* In case of 8X8, we construct a single chroma motion vector

       with a special rounding */

    mx = ff_h263_round_chroma(mx);

    my = ff_h263_round_chroma(my);

    sx = mx & s_mask;

    sy = my & s_mask;

    src_x = s->mb_x * block_s + (mx >> lowres + 1);

    src_y = s->mb_y * block_s + (my >> lowres + 1);

    offset = src_y * s->uvlinesize + src_x;

    ptr = ref_picture[1] + offset;

    if (s->flags & CODEC_FLAG_EMU_EDGE) {

        if ((unsigned) src_x > h_edge_pos - (!!sx) - block_s ||

            (unsigned) src_y > v_edge_pos - (!!sy) - block_s) {

            s->dsp.emulated_edge_mc(s->edge_emu_buffer, ptr, s->uvlinesize,

                                    9, 9, src_x, src_y, h_edge_pos, v_edge_pos);

            ptr = s->edge_emu_buffer;

            emu = 1;

        }

    }

    sx = (sx << 2) >> lowres;

    sy = (sy << 2) >> lowres;

    pix_op[op_index](dest_cb, ptr, s->uvlinesize, block_s, sx, sy);

    ptr = ref_picture[2] + offset;

    if (emu) {

        s->dsp.emulated_edge_mc(s->edge_emu_buffer, ptr, s->uvlinesize, 9, 9,

                                src_x, src_y, h_edge_pos, v_edge_pos);

        ptr = s->edge_emu_buffer;

    }

    pix_op[op_index](dest_cr, ptr, s->uvlinesize, block_s, sx, sy);

}


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

{

    MOVFragment *frag = &c->fragment;

    AVStream *st = NULL;

    MOVStreamContext *sc;

    MOVStts *ctts_data;

    uint64_t offset;

    int64_t dts;

    int data_offset = 0;

    unsigned entries, first_sample_flags = frag->flags;

    int flags, distance, i;

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

        if (c->fc->streams[i]->id == frag->track_id) {

            st = c->fc->streams[i];

            break;

        }

    }

    if (!st) {

        av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %u\n", frag->track_id);

        return AVERROR_INVALIDDATA;

    }

    sc = st->priv_data;

    if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1)

        return 0;

    avio_r8(pb); /* version */

    flags = avio_rb24(pb);

    entries = avio_rb32(pb);

    av_log(c->fc, AV_LOG_TRACE, "flags 0x%x entries %u\n", flags, entries);

    /* Always assume the presence of composition time offsets.

     * Without this assumption, for instance, we cannot deal with a track in fragmented movies that meet the following.

     *  1) in the initial movie, there are no samples.

     *  2) in the first movie fragment, there is only one sample without composition time offset.

     *  3) in the subsequent movie fragments, there are samples with composition time offset. */

    if (!sc->ctts_count && sc->sample_count)

    {

        /* Complement ctts table if moov atom doesn't have ctts atom. */

        ctts_data = av_fast_realloc(NULL, &sc->ctts_allocated_size, sizeof(*sc->ctts_data) * sc->sample_count);

        if (!ctts_data)

            return AVERROR(ENOMEM);

        /* Don't use a count greater than 1 here since it will leave a gap in

         * the ctts index which the code below relies on being sequential. */

        sc->ctts_data = ctts_data;

        for (i = 0; i < sc->sample_count; i++) {

            sc->ctts_data[sc->ctts_count].count = 1;

            sc->ctts_data[sc->ctts_count].duration = 0;

            sc->ctts_count++;

        }

    }

    if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))

        return AVERROR_INVALIDDATA;

    if (flags & MOV_TRUN_DATA_OFFSET)        data_offset        = avio_rb32(pb);

    if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb);

    dts    = sc->track_end - sc->time_offset;

    offset = frag->base_data_offset + data_offset;

    distance = 0;

    av_log(c->fc, AV_LOG_TRACE, "first sample flags 0x%x\n", first_sample_flags);

    for (i = 0; i < entries && !pb->eof_reached; i++) {

        unsigned sample_size = frag->size;

        int sample_flags = i ? frag->flags : first_sample_flags;

        unsigned sample_duration = frag->duration;

        unsigned ctts_duration = 0;

        int keyframe = 0;

        int ctts_index = 0;

        int old_nb_index_entries = st->nb_index_entries;

        if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb);

        if (flags & MOV_TRUN_SAMPLE_SIZE)     sample_size     = avio_rb32(pb);

        if (flags & MOV_TRUN_SAMPLE_FLAGS)    sample_flags    = avio_rb32(pb);

        if (flags & MOV_TRUN_SAMPLE_CTS)      ctts_duration   = avio_rb32(pb);

        mov_update_dts_shift(sc, ctts_duration);

        if (frag->time != AV_NOPTS_VALUE) {

            if (c->use_mfra_for == FF_MOV_FLAG_MFRA_PTS) {

                int64_t pts = frag->time;

                av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64

                        " sc->dts_shift %d ctts.duration %d"

                        " sc->time_offset %"PRId64" flags & MOV_TRUN_SAMPLE_CTS %d\n", pts,

                        sc->dts_shift, ctts_duration,

                        sc->time_offset, flags & MOV_TRUN_SAMPLE_CTS);

                dts = pts - sc->dts_shift;

                if (flags & MOV_TRUN_SAMPLE_CTS) {

                    dts -= ctts_duration;

                } else {

                    dts -= sc->time_offset;

                }

                av_log(c->fc, AV_LOG_DEBUG, "calculated into dts %"PRId64"\n", dts);

            } else {

                dts = frag->time - sc->time_offset;

                av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64

                        ", using it for dts\n", dts);

            }

            frag->time = AV_NOPTS_VALUE;

        }

        if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)

            keyframe = 1;

        else

            keyframe =

                !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC |

                                  MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES));

        if (keyframe)

            distance = 0;

        ctts_index = av_add_index_entry(st, offset, dts, sample_size, distance,

                                        keyframe ? AVINDEX_KEYFRAME : 0);

        if (ctts_index >= 0 && old_nb_index_entries < st->nb_index_entries) {

            unsigned int size_needed = st->nb_index_entries * sizeof(*sc->ctts_data);

            unsigned int request_size = size_needed > sc->ctts_allocated_size ?

                FFMAX(size_needed, 2 * sc->ctts_allocated_size) : size_needed;

            ctts_data = av_fast_realloc(sc->ctts_data, &sc->ctts_allocated_size, request_size);

            if (!ctts_data) {

                av_freep(&sc->ctts_data);

                return AVERROR(ENOMEM);

            }

            sc->ctts_data = ctts_data;

            if (ctts_index != old_nb_index_entries) {

                memmove(sc->ctts_data + ctts_index + 1, sc->ctts_data + ctts_index,

                        sizeof(*sc->ctts_data) * (sc->ctts_count - ctts_index));

                if (ctts_index <= sc->current_sample) {

                    // if we inserted a new item before the current sample, move the

                    // counter ahead so it is still pointing to the same sample.

                    sc->current_sample++;

                }

            }

            sc->ctts_data[ctts_index].count = 1;

            sc->ctts_data[ctts_index].duration = ctts_duration;

            sc->ctts_count++;

        } else {

            av_log(c->fc, AV_LOG_ERROR, "Failed to add index entry\n");

        }

        av_log(c->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "

                "size %u, distance %d, keyframe %d\n", st->index, ctts_index,

                offset, dts, sample_size, distance, keyframe);

        distance++;

        dts += sample_duration;

        offset += sample_size;

        sc->data_size += sample_size;

        sc->duration_for_fps += sample_duration;

        sc->nb_frames_for_fps ++;

    }

    if (pb->eof_reached)

        return AVERROR_EOF;

    frag->implicit_offset = offset;

    sc->track_end = dts + sc->time_offset;

    if (st->duration < sc->track_end)

        st->duration = sc->track_end;

    return 0;

}


void qemu_cpu_kick(CPUState *cpu)

{

    qemu_cond_broadcast(cpu->halt_cond);

    if (tcg_enabled()) {

        cpu_exit(cpu);

        /* Also ensure current RR cpu is kicked */

        qemu_cpu_kick_rr_cpu();

    } else {

        if (hax_enabled()) {

            /*

             * FIXME: race condition with the exit_request check in

             * hax_vcpu_hax_exec

             */

            cpu->exit_request = 1;

        }

        qemu_cpu_kick_thread(cpu);

    }

}


static void exec_accept_incoming_migration(void *opaque)

{

    QEMUFile *f = opaque;

    qemu_set_fd_handler2(qemu_get_fd(f), NULL, NULL, NULL, NULL);

    process_incoming_migration(f);

}


static int vnc_auth_sasl_check_access(VncState *vs)

{

    const void *val;

    int err;

    int allow;

    err = sasl_getprop(vs->sasl.conn, SASL_USERNAME, &val);

    if (err != SASL_OK) {

        VNC_DEBUG("cannot query SASL username on connection %d (%s), denying access\n",

                  err, sasl_errstring(err, NULL, NULL));

        return -1;

    }

    if (val == NULL) {

        VNC_DEBUG("no client username was found, denying access\n");

        return -1;

    }

    VNC_DEBUG("SASL client username %s\n", (const char *)val);

    vs->sasl.username = g_strdup((const char*)val);

    if (vs->vd->sasl.acl == NULL) {

        VNC_DEBUG("no ACL activated, allowing access\n");

        return 0;

    }

    allow = qemu_acl_party_is_allowed(vs->vd->sasl.acl, vs->sasl.username);

    VNC_DEBUG("SASL client %s %s by ACL\n", vs->sasl.username,

              allow ? "allowed" : "denied");

    return allow ? 0 : -1;

}


static int enable_write_target(BDRVVVFATState *s)

{

    BlockDriver *bdrv_qcow;

    QEMUOptionParameter *options;

    int ret;

    int size = sector2cluster(s, s->sector_count);

    s->used_clusters = calloc(size, 1);

    array_init(&(s->commits), sizeof(commit_t));

    s->qcow_filename = g_malloc(1024);

    ret = get_tmp_filename(s->qcow_filename, 1024);

    if (ret < 0) {

        g_free(s->qcow_filename);

        s->qcow_filename = NULL;

        return ret;

    }

    bdrv_qcow = bdrv_find_format("qcow");

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

    set_option_parameter_int(options, BLOCK_OPT_SIZE, s->sector_count * 512);

    set_option_parameter(options, BLOCK_OPT_BACKING_FILE, "fat:");

    if (bdrv_create(bdrv_qcow, s->qcow_filename, options) < 0)

	return -1;

    s->qcow = bdrv_new("");

    if (s->qcow == NULL) {

        return -1;

    }

    ret = bdrv_open(s->qcow, s->qcow_filename, NULL,

            BDRV_O_RDWR | BDRV_O_CACHE_WB | BDRV_O_NO_FLUSH, bdrv_qcow);

    if (ret < 0) {

	return ret;

    }

#ifndef _WIN32

    unlink(s->qcow_filename);

#endif

    s->bs->backing_hd = calloc(sizeof(BlockDriverState), 1);

    s->bs->backing_hd->drv = &vvfat_write_target;

    s->bs->backing_hd->opaque = g_malloc(sizeof(void*));

    *(void**)s->bs->backing_hd->opaque = s;

    return 0;

}


void ide_atapi_cmd(IDEState *s)

{

    uint8_t *buf = s->io_buffer;

    const struct AtapiCmd *cmd = &atapi_cmd_table[s->io_buffer[0]];

#ifdef DEBUG_IDE_ATAPI

    {

        int i;

        printf("ATAPI limit=0x%x packet:", s->lcyl | (s->hcyl << 8));

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

            printf(" %02x", buf[i]);

        }

        printf("\n");

    }

#endif

    /*

     * If there's a UNIT_ATTENTION condition pending, only command flagged with

     * ALLOW_UA are allowed to complete. with other commands getting a CHECK

     * condition response unless a higher priority status, defined by the drive

     * here, is pending.

     */

    if (s->sense_key == UNIT_ATTENTION && !(cmd->flags & ALLOW_UA)) {

        ide_atapi_cmd_check_status(s);

        return;

    }

    /*

     * When a CD gets changed, we have to report an ejected state and

     * then a loaded state to guests so that they detect tray

     * open/close and media change events.  Guests that do not use

     * GET_EVENT_STATUS_NOTIFICATION to detect such tray open/close

     * states rely on this behavior.

     */

    if (!(cmd->flags & ALLOW_UA) &&

        !s->tray_open && blk_is_inserted(s->blk) && s->cdrom_changed) {

        if (s->cdrom_changed == 1) {

            ide_atapi_cmd_error(s, NOT_READY, ASC_MEDIUM_NOT_PRESENT);

            s->cdrom_changed = 2;

        } else {

            ide_atapi_cmd_error(s, UNIT_ATTENTION, ASC_MEDIUM_MAY_HAVE_CHANGED);

            s->cdrom_changed = 0;

        }

        return;

    }

    /* Report a Not Ready condition if appropriate for the command */

    if ((cmd->flags & CHECK_READY) &&

        (!media_present(s) || !blk_is_inserted(s->blk)))

    {

        ide_atapi_cmd_error(s, NOT_READY, ASC_MEDIUM_NOT_PRESENT);

        return;

    }

    /* Nondata commands permit the byte_count_limit to be 0.

     * If this is a data-transferring PIO command and BCL is 0,

     * we abort at the /ATA/ level, not the ATAPI level.

     * See ATA8 ACS3 section 7.17.6.49 and 7.21.5 */

    if (cmd->handler && !(cmd->flags & NONDATA)) {

        /* TODO: Check IDENTIFY data word 125 for default BCL (currently 0) */

        if (!(atapi_byte_count_limit(s) || s->atapi_dma)) {

            /* TODO: Move abort back into core.c and make static inline again */

            ide_abort_command(s);

            return;

        }

    }

    /* Execute the command */

    if (cmd->handler) {

        cmd->handler(s, buf);

        return;

    }

    ide_atapi_cmd_error(s, ILLEGAL_REQUEST, ASC_ILLEGAL_OPCODE);

}


static void numa_node_parse(NumaNodeOptions *node, QemuOpts *opts, Error **errp)

{

    uint16_t nodenr;

    uint16List *cpus = NULL;

    if (node->has_nodeid) {

        nodenr = node->nodeid;

    } else {

        nodenr = nb_numa_nodes;

    }

    if (nodenr >= MAX_NODES) {

        error_setg(errp, "Max number of NUMA nodes reached: %"

                   PRIu16 "", nodenr);

        return;

    }

    if (numa_info[nodenr].present) {

        error_setg(errp, "Duplicate NUMA nodeid: %" PRIu16, nodenr);

        return;

    }

    for (cpus = node->cpus; cpus; cpus = cpus->next) {

        if (cpus->value > MAX_CPUMASK_BITS) {

            error_setg(errp, "CPU number %" PRIu16 " is bigger than %d",

                       cpus->value, MAX_CPUMASK_BITS);

            return;

        }

        bitmap_set(numa_info[nodenr].node_cpu, cpus->value, 1);

    }

    if (node->has_mem && node->has_memdev) {

        error_setg(errp, "qemu: cannot specify both mem= and memdev=");

        return;

    }

    if (have_memdevs == -1) {

        have_memdevs = node->has_memdev;

    }

    if (node->has_memdev != have_memdevs) {

        error_setg(errp, "qemu: memdev option must be specified for either "

                   "all or no nodes");

        return;

    }

    if (node->has_mem) {

        uint64_t mem_size = node->mem;

        const char *mem_str = qemu_opt_get(opts, "mem");

        /* Fix up legacy suffix-less format */

        if (g_ascii_isdigit(mem_str[strlen(mem_str) - 1])) {

            mem_size <<= 20;

        }

        numa_info[nodenr].node_mem = mem_size;

    }

    if (node->has_memdev) {

        Object *o;

        o = object_resolve_path_type(node->memdev, TYPE_MEMORY_BACKEND, NULL);

        if (!o) {

            error_setg(errp, "memdev=%s is ambiguous", node->memdev);

            return;

        }

        object_ref(o);

        numa_info[nodenr].node_mem = object_property_get_int(o, "size", NULL);

        numa_info[nodenr].node_memdev = MEMORY_BACKEND(o);

    }

    numa_info[nodenr].present = true;

    max_numa_nodeid = MAX(max_numa_nodeid, nodenr + 1);

}


static int vfio_msix_vector_do_use(PCIDevice *pdev, unsigned int nr,

                                   MSIMessage *msg, IOHandler *handler)

{

    VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, pdev);

    VFIOMSIVector *vector;

    int ret;

    trace_vfio_msix_vector_do_use(vdev->vbasedev.name, nr);

    vector = &vdev->msi_vectors[nr];

    if (!vector->use) {

        vector->vdev = vdev;

        vector->virq = -1;

        if (event_notifier_init(&vector->interrupt, 0)) {

            error_report("vfio: Error: event_notifier_init failed");

        }

        vector->use = true;

        msix_vector_use(pdev, nr);

    }

    qemu_set_fd_handler(event_notifier_get_fd(&vector->interrupt),

                        handler, NULL, vector);

    /*

     * Attempt to enable route through KVM irqchip,

     * default to userspace handling if unavailable.

     */

    if (vector->virq >= 0) {

        if (!msg) {

            vfio_remove_kvm_msi_virq(vector);

        } else {

            vfio_update_kvm_msi_virq(vector, *msg, pdev);

        }

    } else {

        vfio_add_kvm_msi_virq(vdev, vector, nr, true);

    }

    /*

     * We don't want to have the host allocate all possible MSI vectors

     * for a device if they're not in use, so we shutdown and incrementally

     * increase them as needed.

     */

    if (vdev->nr_vectors < nr + 1) {

        vfio_disable_irqindex(&vdev->vbasedev, VFIO_PCI_MSIX_IRQ_INDEX);

        vdev->nr_vectors = nr + 1;

        ret = vfio_enable_vectors(vdev, true);

        if (ret) {

            error_report("vfio: failed to enable vectors, %d", ret);

        }

    } else {

        int argsz;

        struct vfio_irq_set *irq_set;

        int32_t *pfd;

        argsz = sizeof(*irq_set) + sizeof(*pfd);

        irq_set = g_malloc0(argsz);

        irq_set->argsz = argsz;

        irq_set->flags = VFIO_IRQ_SET_DATA_EVENTFD |

                         VFIO_IRQ_SET_ACTION_TRIGGER;

        irq_set->index = VFIO_PCI_MSIX_IRQ_INDEX;

        irq_set->start = nr;

        irq_set->count = 1;

        pfd = (int32_t *)&irq_set->data;

        if (vector->virq >= 0) {

            *pfd = event_notifier_get_fd(&vector->kvm_interrupt);

        } else {

            *pfd = event_notifier_get_fd(&vector->interrupt);

        }

        ret = ioctl(vdev->vbasedev.fd, VFIO_DEVICE_SET_IRQS, irq_set);

        g_free(irq_set);

        if (ret) {

            error_report("vfio: failed to modify vector, %d", ret);

        }

    }

    /* Disable PBA emulation when nothing more is pending. */

    clear_bit(nr, vdev->msix->pending);

    if (find_first_bit(vdev->msix->pending,

                       vdev->nr_vectors) == vdev->nr_vectors) {

        memory_region_set_enabled(&vdev->pdev.msix_pba_mmio, false);

        trace_vfio_msix_pba_disable(vdev->vbasedev.name);

    }

    return 0;

}


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

{

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

    const char *filename = qdict_get_str(qdict, "target");

    const char *format = qdict_get_try_str(qdict, "format");

    int reuse = qdict_get_try_bool(qdict, "reuse", 0);

    int full = qdict_get_try_bool(qdict, "full", 0);

    enum NewImageMode mode;

    Error *errp = NULL;

    if (!filename) {

        error_set(&errp, QERR_MISSING_PARAMETER, "target");

        hmp_handle_error(mon, &errp);

        return;

    }

    if (reuse) {

        mode = NEW_IMAGE_MODE_EXISTING;

    } else {

        mode = NEW_IMAGE_MODE_ABSOLUTE_PATHS;

    }

    qmp_drive_mirror(device, filename, !!format, format,

                     full ? MIRROR_SYNC_MODE_FULL : MIRROR_SYNC_MODE_TOP,

                     true, mode, false, 0, &errp);

    hmp_handle_error(mon, &errp);

}