static inline void gen_ins(DisasContext *s, int ot)

{

    gen_string_movl_A0_EDI(s);

    gen_op_movl_T0_0();

    gen_op_st_T0_A0(ot + s->mem_index);

    gen_op_mov_TN_reg(OT_WORD, 1, R_EDX);

    tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[1]);

    tcg_gen_andi_i32(cpu_tmp2_i32, cpu_tmp2_i32, 0xffff);

    tcg_gen_helper_1_1(helper_in_func[ot], cpu_T[0], cpu_tmp2_i32);

    gen_op_st_T0_A0(ot + s->mem_index);

    gen_op_movl_T0_Dshift[ot]();

#ifdef TARGET_X86_64

    if (s->aflag == 2) {

        gen_op_addq_EDI_T0();

    } else

#endif

    if (s->aflag) {

        gen_op_addl_EDI_T0();

    } else {

        gen_op_addw_EDI_T0();

    }

}


static void vapic_map_rom_writable(VAPICROMState *s)

{

    target_phys_addr_t rom_paddr = s->rom_state_paddr & ROM_BLOCK_MASK;

    MemoryRegionSection section;

    MemoryRegion *as;

    size_t rom_size;

    uint8_t *ram;

    as = sysbus_address_space(&s->busdev);

    if (s->rom_mapped_writable) {

        memory_region_del_subregion(as, &s->rom);

        memory_region_destroy(&s->rom);

    }

    /* grab RAM memory region (region @rom_paddr may still be pc.rom) */

    section = memory_region_find(as, 0, 1);

    /* read ROM size from RAM region */

    ram = memory_region_get_ram_ptr(section.mr);

    rom_size = ram[rom_paddr + 2] * ROM_BLOCK_SIZE;

    s->rom_size = rom_size;

    /* We need to round to avoid creating subpages

     * from which we cannot run code. */

    rom_size += rom_paddr & ~TARGET_PAGE_MASK;

    rom_paddr &= TARGET_PAGE_MASK;

    rom_size = TARGET_PAGE_ALIGN(rom_size);

    memory_region_init_alias(&s->rom, "kvmvapic-rom", section.mr, rom_paddr,

                             rom_size);

    memory_region_add_subregion_overlap(as, rom_paddr, &s->rom, 1000);

    s->rom_mapped_writable = true;

}


void block_job_resume(BlockJob *job)

{

    job->paused = false;

    block_job_iostatus_reset(job);

    if (job->co && !job->busy) {

        qemu_coroutine_enter(job->co, NULL);

    }

}


static inline void vring_used_write(VirtQueue *vq, VRingUsedElem *uelem,

                                    int i)

{

    hwaddr pa;

    virtio_tswap32s(vq->vdev, &uelem->id);

    virtio_tswap32s(vq->vdev, &uelem->len);

    pa = vq->vring.used + offsetof(VRingUsed, ring[i]);

    address_space_write(&address_space_memory, pa, MEMTXATTRS_UNSPECIFIED,

                       (void *)uelem, sizeof(VRingUsedElem));

}


static int writev_f(BlockBackend *blk, int argc, char **argv)

{

    struct timeval t1, t2;

    int Cflag = 0, qflag = 0;

    int c, cnt;

    char *buf;

    int64_t offset;

    /* Some compilers get confused and warn if this is not initialized.  */

    int total = 0;

    int nr_iov;

    int pattern = 0xcd;

    QEMUIOVector qiov;

    while ((c = getopt(argc, argv, "CqP:")) != EOF) {

        switch (c) {

        case 'C':

            Cflag = 1;

            break;

        case 'q':

            qflag = 1;

            break;

        case 'P':

            pattern = parse_pattern(optarg);

            if (pattern < 0) {

                return 0;

            }

            break;

        default:

            return qemuio_command_usage(&writev_cmd);

        }

    }

    if (optind > argc - 2) {

        return qemuio_command_usage(&writev_cmd);

    }

    offset = cvtnum(argv[optind]);

    if (offset < 0) {

        printf("non-numeric length argument -- %s\n", argv[optind]);

        return 0;

    }

    optind++;

    if (offset & 0x1ff) {

        printf("offset %" PRId64 " is not sector aligned\n",

               offset);

        return 0;

    }

    nr_iov = argc - optind;

    buf = create_iovec(blk, &qiov, &argv[optind], nr_iov, pattern);

    if (buf == NULL) {

        return 0;

    }

    gettimeofday(&t1, NULL);

    cnt = do_aio_writev(blk, &qiov, offset, &total);

    gettimeofday(&t2, NULL);

    if (cnt < 0) {

        printf("writev failed: %s\n", strerror(-cnt));

        goto out;

    }

    if (qflag) {

        goto out;

    }

    /* Finally, report back -- -C gives a parsable format */

    t2 = tsub(t2, t1);

    print_report("wrote", &t2, offset, qiov.size, total, cnt, Cflag);

out:

    qemu_iovec_destroy(&qiov);

    qemu_io_free(buf);

    return 0;

}


static int cow_open(BlockDriverState *bs, QDict *options, int flags,

                    Error **errp)

{

    BDRVCowState *s = bs->opaque;

    struct cow_header_v2 cow_header;

    int bitmap_size;

    int64_t size;

    int ret;

    /* see if it is a cow image */

    ret = bdrv_pread(bs->file, 0, &cow_header, sizeof(cow_header));

    if (ret < 0) {

        goto fail;

    }

    if (be32_to_cpu(cow_header.magic) != COW_MAGIC) {

        error_setg(errp, "Image not in COW format");

        ret = -EINVAL;

        goto fail;

    }

    if (be32_to_cpu(cow_header.version) != COW_VERSION) {

        char version[64];

        snprintf(version, sizeof(version),

               "COW version %" PRIu32, cow_header.version);

        error_set(errp, QERR_UNKNOWN_BLOCK_FORMAT_FEATURE,

            bs->device_name, "cow", version);

        ret = -ENOTSUP;

        goto fail;

    }

    /* cow image found */

    size = be64_to_cpu(cow_header.size);

    bs->total_sectors = size / 512;

    pstrcpy(bs->backing_file, sizeof(bs->backing_file),

            cow_header.backing_file);

    bitmap_size = ((bs->total_sectors + 7) >> 3) + sizeof(cow_header);

    s->cow_sectors_offset = (bitmap_size + 511) & ~511;

    qemu_co_mutex_init(&s->lock);

    return 0;

 fail:

    return ret;

}


static void pc_compat_2_2(MachineState *machine)

{

    pc_compat_2_3(machine);

    rsdp_in_ram = false;

    machine->suppress_vmdesc = true;

}


void spapr_core_pre_plug(HotplugHandler *hotplug_dev, DeviceState *dev,

                         Error **errp)

{

    MachineState *machine = MACHINE(OBJECT(hotplug_dev));

    sPAPRMachineClass *smc = SPAPR_MACHINE_GET_CLASS(OBJECT(hotplug_dev));

    sPAPRMachineState *spapr = SPAPR_MACHINE(OBJECT(hotplug_dev));

    int spapr_max_cores = max_cpus / smp_threads;

    int index;

    Error *local_err = NULL;

    CPUCore *cc = CPU_CORE(dev);

    char *base_core_type = spapr_get_cpu_core_type(machine->cpu_model);

    const char *type = object_get_typename(OBJECT(dev));

    if (!smc->dr_cpu_enabled) {

        error_setg(&local_err, "CPU hotplug not supported for this machine");

        goto out;

    }

    if (strcmp(base_core_type, type)) {

        error_setg(&local_err, "CPU core type should be %s", base_core_type);

        goto out;

    }

    if (cc->nr_threads != smp_threads) {

        error_setg(&local_err, "threads must be %d", smp_threads);

        goto out;

    }

    if (cc->core_id % smp_threads) {

        error_setg(&local_err, "invalid core id %d\n", cc->core_id);

        goto out;

    }

    index = cc->core_id / smp_threads;

    if (index < 0 || index >= spapr_max_cores) {

        error_setg(&local_err, "core id %d out of range", cc->core_id);

        goto out;

    }

    if (spapr->cores[index]) {

        error_setg(&local_err, "core %d already populated", cc->core_id);

        goto out;

    }

out:

    g_free(base_core_type);

    error_propagate(errp, local_err);

}


static void scsi_disk_emulate_unmap(SCSIDiskReq *r, uint8_t *inbuf)

{

    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);

    uint8_t *p = inbuf;

    int len = r->req.cmd.xfer;

    UnmapCBData *data;

    /* Reject ANCHOR=1.  */

    if (r->req.cmd.buf[1] & 0x1) {

        goto invalid_field;

    }

    if (len < 8) {

        goto invalid_param_len;

    }

    if (len < lduw_be_p(&p[0]) + 2) {

        goto invalid_param_len;

    }

    if (len < lduw_be_p(&p[2]) + 8) {

        goto invalid_param_len;

    }

    if (lduw_be_p(&p[2]) & 15) {

        goto invalid_param_len;

    }

    if (bdrv_is_read_only(s->qdev.conf.bs)) {

        scsi_check_condition(r, SENSE_CODE(WRITE_PROTECTED));

        return;

    }

    data = g_new0(UnmapCBData, 1);

    data->r = r;

    data->inbuf = &p[8];

    data->count = lduw_be_p(&p[2]) >> 4;

    /* The matching unref is in scsi_unmap_complete, before data is freed.  */

    scsi_req_ref(&r->req);

    scsi_unmap_complete(data, 0);

    return;

invalid_param_len:

    scsi_check_condition(r, SENSE_CODE(INVALID_PARAM_LEN));

    return;

invalid_field:

    scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));

}


int bdrv_is_encrypted(BlockDriverState *bs)

{

    if (bs->backing_hd && bs->backing_hd->encrypted)

        return 1;

    return bs->encrypted;

}


void eth_get_protocols(const struct iovec *iov, int iovcnt,

                       bool *isip4, bool *isip6,

                       bool *isudp, bool *istcp,

                       size_t *l3hdr_off,

                       size_t *l4hdr_off,

                       size_t *l5hdr_off,

                       eth_ip6_hdr_info *ip6hdr_info,

                       eth_ip4_hdr_info *ip4hdr_info,

                       eth_l4_hdr_info  *l4hdr_info)

{

    int proto;

    bool fragment = false;

    size_t l2hdr_len = eth_get_l2_hdr_length_iov(iov, iovcnt);

    size_t input_size = iov_size(iov, iovcnt);

    size_t copied;

    *isip4 = *isip6 = *isudp = *istcp = false;

    proto = eth_get_l3_proto(iov, iovcnt, l2hdr_len);

    *l3hdr_off = l2hdr_len;

    if (proto == ETH_P_IP) {

        struct ip_header *iphdr = &ip4hdr_info->ip4_hdr;

        if (input_size < l2hdr_len) {

            return;

        }

        copied = iov_to_buf(iov, iovcnt, l2hdr_len, iphdr, sizeof(*iphdr));

        *isip4 = true;

        if (copied < sizeof(*iphdr)) {

            return;

        }

        if (IP_HEADER_VERSION(iphdr) == IP_HEADER_VERSION_4) {

            if (iphdr->ip_p == IP_PROTO_TCP) {

                *istcp = true;

            } else if (iphdr->ip_p == IP_PROTO_UDP) {

                *isudp = true;

            }

        }

        ip4hdr_info->fragment = IP4_IS_FRAGMENT(iphdr);

        *l4hdr_off = l2hdr_len + IP_HDR_GET_LEN(iphdr);

        fragment = ip4hdr_info->fragment;

    } else if (proto == ETH_P_IPV6) {

        *isip6 = true;

        if (eth_parse_ipv6_hdr(iov, iovcnt, l2hdr_len,

                               ip6hdr_info)) {

            if (ip6hdr_info->l4proto == IP_PROTO_TCP) {

                *istcp = true;

            } else if (ip6hdr_info->l4proto == IP_PROTO_UDP) {

                *isudp = true;

            }

        } else {

            return;

        }

        *l4hdr_off = l2hdr_len + ip6hdr_info->full_hdr_len;

        fragment = ip6hdr_info->fragment;

    }

    if (!fragment) {

        if (*istcp) {

            *istcp = _eth_copy_chunk(input_size,

                                     iov, iovcnt,

                                     *l4hdr_off, sizeof(l4hdr_info->hdr.tcp),

                                     &l4hdr_info->hdr.tcp);

            if (istcp) {

                *l5hdr_off = *l4hdr_off +

                    TCP_HEADER_DATA_OFFSET(&l4hdr_info->hdr.tcp);

                l4hdr_info->has_tcp_data =

                    _eth_tcp_has_data(proto == ETH_P_IP,

                                      &ip4hdr_info->ip4_hdr,

                                      &ip6hdr_info->ip6_hdr,

                                      *l4hdr_off - *l3hdr_off,

                                      &l4hdr_info->hdr.tcp);

            }

        } else if (*isudp) {

            *isudp = _eth_copy_chunk(input_size,

                                     iov, iovcnt,

                                     *l4hdr_off, sizeof(l4hdr_info->hdr.udp),

                                     &l4hdr_info->hdr.udp);

            *l5hdr_off = *l4hdr_off + sizeof(l4hdr_info->hdr.udp);

        }

    }

}


static void apic_bus_deliver(const uint32_t *deliver_bitmask,

                             uint8_t delivery_mode,

                             uint8_t vector_num, uint8_t polarity,

                             uint8_t trigger_mode)

{

    APICState *apic_iter;

    switch (delivery_mode) {

        case APIC_DM_LOWPRI:

            /* XXX: search for focus processor, arbitration */

            {

                int i, d;

                d = -1;

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

                    if (deliver_bitmask[i]) {

                        d = i * 32 + ffs_bit(deliver_bitmask[i]);

                        break;

                    }

                }

                if (d >= 0) {

                    apic_iter = local_apics[d];

                    if (apic_iter) {

                        apic_set_irq(apic_iter, vector_num, trigger_mode);

                    }

                }

            }

            return;

        case APIC_DM_FIXED:

            break;

        case APIC_DM_SMI:

            foreach_apic(apic_iter, deliver_bitmask,

                cpu_interrupt(apic_iter->cpu_env, CPU_INTERRUPT_SMI) );

            return;

        case APIC_DM_NMI:

            foreach_apic(apic_iter, deliver_bitmask,

                cpu_interrupt(apic_iter->cpu_env, CPU_INTERRUPT_NMI) );

            return;

        case APIC_DM_INIT:

            /* normal INIT IPI sent to processors */

            foreach_apic(apic_iter, deliver_bitmask,

                         apic_init_ipi(apic_iter) );

            return;

        case APIC_DM_EXTINT:

            /* handled in I/O APIC code */

            break;

        default:

            return;

    }

    foreach_apic(apic_iter, deliver_bitmask,

                 apic_set_irq(apic_iter, vector_num, trigger_mode) );

}


static void print_sdp(void)

{

    char sdp[16384];

    int i;

    AVFormatContext **avc = av_malloc(sizeof(*avc) * nb_output_files);

    if (!avc)

        exit_program(1);

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

        avc[i] = output_files[i]->ctx;

    av_sdp_create(avc, nb_output_files, sdp, sizeof(sdp));

    printf("SDP:\n%s\n", sdp);

    fflush(stdout);

    av_freep(&avc);

}


void memory_region_iommu_replay(MemoryRegion *mr, Notifier *n, bool is_write)

{

    hwaddr addr, granularity;

    IOMMUTLBEntry iotlb;

    granularity = memory_region_iommu_get_min_page_size(mr);

    for (addr = 0; addr < memory_region_size(mr); addr += granularity) {

        iotlb = mr->iommu_ops->translate(mr, addr, is_write);

        if (iotlb.perm != IOMMU_NONE) {

            n->notify(n, &iotlb);

        }

        /* if (2^64 - MR size) < granularity, it's possible to get an

         * infinite loop here.  This should catch such a wraparound */

        if ((addr + granularity) < addr) {

            break;

        }

    }

}


static void pic_write(void *opaque, target_phys_addr_t addr,

                      uint64_t value, unsigned int size)

{

    struct etrax_pic *fs = opaque;

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

    if (addr == R_RW_MASK) {

        fs->regs[R_RW_MASK] = value;

        pic_update(fs);

    }

}


static int pci_cmd646_ide_initfn(PCIDevice *dev)

{

    PCIIDEState *d = DO_UPCAST(PCIIDEState, dev, dev);

    uint8_t *pci_conf = d->dev.config;

    qemu_irq *irq;

    int i;

    pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_CMD);

    pci_config_set_device_id(pci_conf, PCI_DEVICE_ID_CMD_646);

    pci_conf[PCI_REVISION_ID] = 0x07; // IDE controller revision

    pci_conf[PCI_CLASS_PROG] = 0x8f;

    pci_config_set_class(pci_conf, PCI_CLASS_STORAGE_IDE);

    pci_conf[0x51] = 0x04; // enable IDE0

    if (d->secondary) {

        /* XXX: if not enabled, really disable the seconday IDE controller */

        pci_conf[0x51] |= 0x08; /* enable IDE1 */

    }

    pci_register_bar(dev, 0, 0x8, PCI_BASE_ADDRESS_SPACE_IO, ide_map);

    pci_register_bar(dev, 1, 0x4, PCI_BASE_ADDRESS_SPACE_IO, ide_map);

    pci_register_bar(dev, 2, 0x8, PCI_BASE_ADDRESS_SPACE_IO, ide_map);

    pci_register_bar(dev, 3, 0x4, PCI_BASE_ADDRESS_SPACE_IO, ide_map);

    pci_register_bar(dev, 4, 0x10, PCI_BASE_ADDRESS_SPACE_IO, bmdma_map);

    /* TODO: RST# value should be 0 */

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

    irq = qemu_allocate_irqs(cmd646_set_irq, d, 2);

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

        ide_bus_new(&d->bus[i], &d->dev.qdev, i);

        ide_init2(&d->bus[i], irq[i]);

        bmdma_init(&d->bus[i], &d->bmdma[i]);

        d->bmdma[i].bus = &d->bus[i];

        qemu_add_vm_change_state_handler(d->bus[i].dma->ops->restart_cb,

                                         &d->bmdma[i].dma);

    }

    vmstate_register(&dev->qdev, 0, &vmstate_ide_pci, d);

    qemu_register_reset(cmd646_reset, d);

    return 0;

}


uint8_t *smbios_get_table(size_t *length)

{

    smbios_validate_table();

    *length = smbios_entries_len;

    return smbios_entries;

}


int qemu_fsdev_add(QemuOpts *opts)

{

    struct FsTypeListEntry *fsle;

    int i;

    if (qemu_opts_id(opts) == NULL) {

        fprintf(stderr, "fsdev: No id specified\n");

        return -1;

    }

     for (i = 0; i < ARRAY_SIZE(FsTypes); i++) {

        if (strcmp(FsTypes[i].name, qemu_opt_get(opts, "fstype")) == 0) {

            break;

        }

    }

    if (i == ARRAY_SIZE(FsTypes)) {

        fprintf(stderr, "fsdev: fstype %s not found\n",

                    qemu_opt_get(opts, "fstype"));

        return -1;

    }

    fsle = qemu_malloc(sizeof(*fsle));

    fsle->fse.fsdev_id = qemu_strdup(qemu_opts_id(opts));

    fsle->fse.path = qemu_strdup(qemu_opt_get(opts, "path"));

    fsle->fse.ops = FsTypes[i].ops;

    QTAILQ_INSERT_TAIL(&fstype_entries, fsle, next);

    return 0;

}


build_madt(GArray *table_data, GArray *linker, VirtGuestInfo *guest_info,

           VirtAcpiCpuInfo *cpuinfo)

{

    int madt_start = table_data->len;

    const MemMapEntry *memmap = guest_info->memmap;

    const int *irqmap = guest_info->irqmap;

    AcpiMultipleApicTable *madt;

    AcpiMadtGenericDistributor *gicd;

    AcpiMadtGenericMsiFrame *gic_msi;

    int i;

    madt = acpi_data_push(table_data, sizeof *madt);

    for (i = 0; i < guest_info->smp_cpus; i++) {

        AcpiMadtGenericInterrupt *gicc = acpi_data_push(table_data,

                                                     sizeof *gicc);

        gicc->type = ACPI_APIC_GENERIC_INTERRUPT;

        gicc->length = sizeof(*gicc);

        gicc->base_address = memmap[VIRT_GIC_CPU].base;

        gicc->cpu_interface_number = i;

        gicc->arm_mpidr = i;

        gicc->uid = i;

        if (test_bit(i, cpuinfo->found_cpus)) {

            gicc->flags = cpu_to_le32(ACPI_GICC_ENABLED);

        }

    }

    gicd = acpi_data_push(table_data, sizeof *gicd);

    gicd->type = ACPI_APIC_GENERIC_DISTRIBUTOR;

    gicd->length = sizeof(*gicd);

    gicd->base_address = memmap[VIRT_GIC_DIST].base;

    gic_msi = acpi_data_push(table_data, sizeof *gic_msi);

    gic_msi->type = ACPI_APIC_GENERIC_MSI_FRAME;

    gic_msi->length = sizeof(*gic_msi);

    gic_msi->gic_msi_frame_id = 0;

    gic_msi->base_address = cpu_to_le64(memmap[VIRT_GIC_V2M].base);

    gic_msi->flags = cpu_to_le32(1);

    gic_msi->spi_count = cpu_to_le16(NUM_GICV2M_SPIS);

    gic_msi->spi_base = cpu_to_le16(irqmap[VIRT_GIC_V2M] + ARM_SPI_BASE);

    build_header(linker, table_data,

                 (void *)(table_data->data + madt_start), "APIC",

                 table_data->len - madt_start, 3);

}


block_crypto_open_opts_init(QCryptoBlockFormat format,

                            QemuOpts *opts,

                            Error **errp)

{

    Visitor *v;

    QCryptoBlockOpenOptions *ret = NULL;

    Error *local_err = NULL;

    ret = g_new0(QCryptoBlockOpenOptions, 1);

    ret->format = format;

    v = opts_visitor_new(opts);

    visit_start_struct(v, NULL, NULL, 0, &local_err);

    if (local_err) {

        goto out;

    }

    switch (format) {

    case Q_CRYPTO_BLOCK_FORMAT_LUKS:

        visit_type_QCryptoBlockOptionsLUKS_members(

            v, &ret->u.luks, &local_err);

        break;

    default:

        error_setg(&local_err, "Unsupported block format %d", format);

        break;

    }

    if (!local_err) {

        visit_check_struct(v, &local_err);

    }

    visit_end_struct(v, NULL);

 out:

    if (local_err) {

        error_propagate(errp, local_err);

        qapi_free_QCryptoBlockOpenOptions(ret);

        ret = NULL;

    }

    visit_free(v);

    return ret;

}


gen_intermediate_code_internal(CRISCPU *cpu, TranslationBlock *tb,

                               bool search_pc)

{

    CPUState *cs = CPU(cpu);

    CPUCRISState *env = &cpu->env;

    uint32_t pc_start;

    unsigned int insn_len;

    int j, lj;

    struct DisasContext ctx;

    struct DisasContext *dc = &ctx;

    uint32_t next_page_start;

    target_ulong npc;

    int num_insns;

    int max_insns;

    if (env->pregs[PR_VR] == 32) {

        dc->decoder = crisv32_decoder;

        dc->clear_locked_irq = 0;

    } else {

        dc->decoder = crisv10_decoder;

        dc->clear_locked_irq = 1;

    }

    /* Odd PC indicates that branch is rexecuting due to exception in the

     * delayslot, like in real hw.

     */

    pc_start = tb->pc & ~1;

    dc->cpu = cpu;

    dc->tb = tb;

    dc->is_jmp = DISAS_NEXT;

    dc->ppc = pc_start;

    dc->pc = pc_start;

    dc->singlestep_enabled = cs->singlestep_enabled;

    dc->flags_uptodate = 1;

    dc->flagx_known = 1;

    dc->flags_x = tb->flags & X_FLAG;

    dc->cc_x_uptodate = 0;

    dc->cc_mask = 0;

    dc->update_cc = 0;

    dc->clear_prefix = 0;

    cris_update_cc_op(dc, CC_OP_FLAGS, 4);

    dc->cc_size_uptodate = -1;

    /* Decode TB flags.  */

    dc->tb_flags = tb->flags & (S_FLAG | P_FLAG | U_FLAG \

            | X_FLAG | PFIX_FLAG);

    dc->delayed_branch = !!(tb->flags & 7);

    if (dc->delayed_branch) {

        dc->jmp = JMP_INDIRECT;

    } else {

        dc->jmp = JMP_NOJMP;

    }

    dc->cpustate_changed = 0;

    if (qemu_loglevel_mask(CPU_LOG_TB_IN_ASM)) {

        qemu_log(

                "srch=%d pc=%x %x flg=%" PRIx64 " bt=%x ds=%u ccs=%x\n"

                "pid=%x usp=%x\n"

                "%x.%x.%x.%x\n"

                "%x.%x.%x.%x\n"

                "%x.%x.%x.%x\n"

                "%x.%x.%x.%x\n",

                search_pc, dc->pc, dc->ppc,

                (uint64_t)tb->flags,

                env->btarget, (unsigned)tb->flags & 7,

                env->pregs[PR_CCS],

                env->pregs[PR_PID], env->pregs[PR_USP],

                env->regs[0], env->regs[1], env->regs[2], env->regs[3],

                env->regs[4], env->regs[5], env->regs[6], env->regs[7],

                env->regs[8], env->regs[9],

                env->regs[10], env->regs[11],

                env->regs[12], env->regs[13],

                env->regs[14], env->regs[15]);

        qemu_log("--------------\n");

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

    }

    next_page_start = (pc_start & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE;

    lj = -1;

    num_insns = 0;

    max_insns = tb->cflags & CF_COUNT_MASK;

    if (max_insns == 0) {

        max_insns = CF_COUNT_MASK;

    }

    gen_tb_start(tb);

    do {

        check_breakpoint(env, dc);

        if (search_pc) {

            j = tcg_op_buf_count();

            if (lj < j) {

                lj++;

                while (lj < j) {

                    tcg_ctx.gen_opc_instr_start[lj++] = 0;

                }

            }

            if (dc->delayed_branch == 1) {

                tcg_ctx.gen_opc_pc[lj] = dc->ppc | 1;

            } else {

                tcg_ctx.gen_opc_pc[lj] = dc->pc;

            }

            tcg_ctx.gen_opc_instr_start[lj] = 1;

            tcg_ctx.gen_opc_icount[lj] = num_insns;

        }

        /* Pretty disas.  */

        LOG_DIS("%8.8x:\t", dc->pc);

        if (num_insns + 1 == max_insns && (tb->cflags & CF_LAST_IO)) {

            gen_io_start();

        }

        dc->clear_x = 1;

        insn_len = dc->decoder(env, dc);

        dc->ppc = dc->pc;

        dc->pc += insn_len;

        if (dc->clear_x) {

            cris_clear_x_flag(dc);

        }

        num_insns++;

        /* Check for delayed branches here. If we do it before

           actually generating any host code, the simulator will just

           loop doing nothing for on this program location.  */

        if (dc->delayed_branch) {

            dc->delayed_branch--;

            if (dc->delayed_branch == 0) {

                if (tb->flags & 7) {

                    t_gen_mov_env_TN(dslot, tcg_const_tl(0));

                }

                if (dc->cpustate_changed || !dc->flagx_known

                    || (dc->flags_x != (tb->flags & X_FLAG))) {

                    cris_store_direct_jmp(dc);

                }

                if (dc->clear_locked_irq) {

                    dc->clear_locked_irq = 0;

                    t_gen_mov_env_TN(locked_irq, tcg_const_tl(0));

                }

                if (dc->jmp == JMP_DIRECT_CC) {

                    int l1;

                    l1 = gen_new_label();

                    cris_evaluate_flags(dc);

                    /* Conditional jmp.  */

                    tcg_gen_brcondi_tl(TCG_COND_EQ,

                               env_btaken, 0, l1);

                    gen_goto_tb(dc, 1, dc->jmp_pc);

                    gen_set_label(l1);

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

                    dc->is_jmp = DISAS_TB_JUMP;

                    dc->jmp = JMP_NOJMP;

                } else if (dc->jmp == JMP_DIRECT) {

                    cris_evaluate_flags(dc);

                    gen_goto_tb(dc, 0, dc->jmp_pc);

                    dc->is_jmp = DISAS_TB_JUMP;

                    dc->jmp = JMP_NOJMP;

                } else {

                    t_gen_cc_jmp(env_btarget, tcg_const_tl(dc->pc));

                    dc->is_jmp = DISAS_JUMP;

                }

                break;

            }

        }

        /* If we are rexecuting a branch due to exceptions on

           delay slots dont break.  */

        if (!(tb->pc & 1) && cs->singlestep_enabled) {

            break;

        }

    } while (!dc->is_jmp && !dc->cpustate_changed

            && !tcg_op_buf_full()

            && !singlestep

            && (dc->pc < next_page_start)

            && num_insns < max_insns);

    if (dc->clear_locked_irq) {

        t_gen_mov_env_TN(locked_irq, tcg_const_tl(0));

    }

    npc = dc->pc;

        if (tb->cflags & CF_LAST_IO)

            gen_io_end();

    /* Force an update if the per-tb cpu state has changed.  */

    if (dc->is_jmp == DISAS_NEXT

        && (dc->cpustate_changed || !dc->flagx_known

        || (dc->flags_x != (tb->flags & X_FLAG)))) {

        dc->is_jmp = DISAS_UPDATE;

        tcg_gen_movi_tl(env_pc, npc);

    }

    /* Broken branch+delayslot sequence.  */

    if (dc->delayed_branch == 1) {

        /* Set env->dslot to the size of the branch insn.  */

        t_gen_mov_env_TN(dslot, tcg_const_tl(dc->pc - dc->ppc));

        cris_store_direct_jmp(dc);

    }

    cris_evaluate_flags(dc);

    if (unlikely(cs->singlestep_enabled)) {

        if (dc->is_jmp == DISAS_NEXT) {

            tcg_gen_movi_tl(env_pc, npc);

        }

        t_gen_raise_exception(EXCP_DEBUG);

    } else {

        switch (dc->is_jmp) {

        case DISAS_NEXT:

            gen_goto_tb(dc, 1, npc);

            break;

        default:

        case DISAS_JUMP:

        case DISAS_UPDATE:

            /* indicate that the hash table must be used

                   to find the next TB */

            tcg_gen_exit_tb(0);

            break;

        case DISAS_SWI:

        case DISAS_TB_JUMP:

            /* nothing more to generate */

            break;

        }

    }

    gen_tb_end(tb, num_insns);

    if (search_pc) {

        j = tcg_op_buf_count();

        lj++;

        while (lj <= j) {

            tcg_ctx.gen_opc_instr_start[lj++] = 0;

        }

    } else {

        tb->size = dc->pc - pc_start;

        tb->icount = num_insns;

    }

#ifdef DEBUG_DISAS

#if !DISAS_CRIS

    if (qemu_loglevel_mask(CPU_LOG_TB_IN_ASM)) {

        log_target_disas(env, pc_start, dc->pc - pc_start,

                         env->pregs[PR_VR]);

        qemu_log("\nisize=%d osize=%d\n",

                 dc->pc - pc_start, tcg_op_buf_count());

    }

#endif

#endif

}


uint64_t float64_to_uint64_round_to_zero (float64 a STATUS_PARAM)

{

    int64_t v;

    v = int64_to_float64(INT64_MIN STATUS_VAR);

    v = float64_to_int64_round_to_zero((a + v) STATUS_VAR);

    return v - INT64_MIN;

}


static AHCIQState *ahci_boot(void)

{

    AHCIQState *s;

    const char *cli;

    s = g_malloc0(sizeof(AHCIQState));

    cli = "-drive if=none,id=drive0,file=%s,cache=writeback,serial=%s"

        ",format=raw"

        " -M q35 "

        "-device ide-hd,drive=drive0 "

        "-global ide-hd.ver=%s";

    s->parent = qtest_pc_boot(cli, tmp_path, "testdisk", "version");

    /* Verify that we have an AHCI device present. */

    s->dev = get_ahci_device(&s->fingerprint);

    return s;

}


static inline int parse_nal_units(AVCodecParserContext *s, const uint8_t *buf,

                           int buf_size, AVCodecContext *avctx)

{

    HEVCParserContext *ctx = s->priv_data;

    HEVCContext       *h   = &ctx->h;

    GetBitContext      *gb;

    SliceHeader        *sh = &h->sh;

    HEVCParamSets *ps = &h->ps;

    HEVCPacket   *pkt = &ctx->pkt;

    const uint8_t *buf_end = buf + buf_size;

    int state = -1, i;

    HEVCNAL *nal;

    int is_global = buf == avctx->extradata;

    if (!h->HEVClc)

        h->HEVClc = av_mallocz(sizeof(HEVCLocalContext));

    if (!h->HEVClc)

        return AVERROR(ENOMEM);

    gb = &h->HEVClc->gb;

    /* set some sane default values */

    s->pict_type         = AV_PICTURE_TYPE_I;

    s->key_frame         = 0;

    s->picture_structure = AV_PICTURE_STRUCTURE_UNKNOWN;

    h->avctx = avctx;

    if (!buf_size)

        return 0;

    if (pkt->nals_allocated < 1) {

        HEVCNAL *tmp = av_realloc_array(pkt->nals, 1, sizeof(*tmp));

        if (!tmp)

            return AVERROR(ENOMEM);

        pkt->nals = tmp;

        memset(pkt->nals, 0, sizeof(*tmp));

        pkt->nals_allocated = 1;

    }

    nal = &pkt->nals[0];

    for (;;) {

        int src_length, consumed;

        buf = avpriv_find_start_code(buf, buf_end, &state);

        if (--buf + 2 >= buf_end)

            break;

        src_length = buf_end - buf;

        h->nal_unit_type = (*buf >> 1) & 0x3f;

        h->temporal_id   = (*(buf + 1) & 0x07) - 1;

        if (h->nal_unit_type <= NAL_CRA_NUT) {

            // Do not walk the whole buffer just to decode slice segment header

            if (src_length > 20)

                src_length = 20;

        }

        consumed = ff_hevc_extract_rbsp(NULL, buf, src_length, nal);

        if (consumed < 0)

            return consumed;

        init_get_bits8(gb, nal->data + 2, nal->size);

        switch (h->nal_unit_type) {

        case NAL_VPS:

            ff_hevc_decode_nal_vps(gb, avctx, ps);

            break;

        case NAL_SPS:

            ff_hevc_decode_nal_sps(gb, avctx, ps, 1);

            break;

        case NAL_PPS:

            ff_hevc_decode_nal_pps(gb, avctx, ps);

            break;

        case NAL_SEI_PREFIX:

        case NAL_SEI_SUFFIX:

            ff_hevc_decode_nal_sei(h);

            break;

        case NAL_TRAIL_N:

        case NAL_TRAIL_R:

        case NAL_TSA_N:

        case NAL_TSA_R:

        case NAL_STSA_N:

        case NAL_STSA_R:

        case NAL_RADL_N:

        case NAL_RADL_R:

        case NAL_RASL_N:

        case NAL_RASL_R:

        case NAL_BLA_W_LP:

        case NAL_BLA_W_RADL:

        case NAL_BLA_N_LP:

        case NAL_IDR_W_RADL:

        case NAL_IDR_N_LP:

        case NAL_CRA_NUT:

            if (is_global) {

                av_log(avctx, AV_LOG_ERROR, "Invalid NAL unit: %d\n", h->nal_unit_type);

                return AVERROR_INVALIDDATA;

            }

            sh->first_slice_in_pic_flag = get_bits1(gb);

            s->picture_structure = h->picture_struct;

            s->field_order = h->picture_struct;

            if (IS_IRAP(h)) {

                s->key_frame = 1;

                sh->no_output_of_prior_pics_flag = get_bits1(gb);

            }

            sh->pps_id = get_ue_golomb(gb);

            if (sh->pps_id >= MAX_PPS_COUNT || !ps->pps_list[sh->pps_id]) {

                av_log(avctx, AV_LOG_ERROR, "PPS id out of range: %d\n", sh->pps_id);

                return AVERROR_INVALIDDATA;

            }

            ps->pps = (HEVCPPS*)ps->pps_list[sh->pps_id]->data;

            if (ps->pps->sps_id >= MAX_SPS_COUNT || !ps->sps_list[ps->pps->sps_id]) {

                av_log(avctx, AV_LOG_ERROR, "SPS id out of range: %d\n", ps->pps->sps_id);

                return AVERROR_INVALIDDATA;

            }

            if (ps->sps != (HEVCSPS*)ps->sps_list[ps->pps->sps_id]->data) {

                ps->sps = (HEVCSPS*)ps->sps_list[ps->pps->sps_id]->data;

                ps->vps = (HEVCVPS*)ps->vps_list[ps->sps->vps_id]->data;

            }

            if (!sh->first_slice_in_pic_flag) {

                int slice_address_length;

                if (ps->pps->dependent_slice_segments_enabled_flag)

                    sh->dependent_slice_segment_flag = get_bits1(gb);

                else

                    sh->dependent_slice_segment_flag = 0;

                slice_address_length = av_ceil_log2_c(ps->sps->ctb_width *

                                                      ps->sps->ctb_height);

                sh->slice_segment_addr = slice_address_length ? get_bits(gb, slice_address_length) : 0;

                if (sh->slice_segment_addr >= ps->sps->ctb_width * ps->sps->ctb_height) {

                    av_log(avctx, AV_LOG_ERROR, "Invalid slice segment address: %u.\n",

                           sh->slice_segment_addr);

                    return AVERROR_INVALIDDATA;

                }

            } else

                sh->dependent_slice_segment_flag = 0;

            if (sh->dependent_slice_segment_flag)

                break;

            for (i = 0; i < ps->pps->num_extra_slice_header_bits; i++)

                skip_bits(gb, 1); // slice_reserved_undetermined_flag[]

            sh->slice_type = get_ue_golomb(gb);

            if (!(sh->slice_type == I_SLICE || sh->slice_type == P_SLICE ||

                  sh->slice_type == B_SLICE)) {

                av_log(avctx, AV_LOG_ERROR, "Unknown slice type: %d.\n",

                       sh->slice_type);

                return AVERROR_INVALIDDATA;

            }

            s->pict_type = sh->slice_type == B_SLICE ? AV_PICTURE_TYPE_B :

                           sh->slice_type == P_SLICE ? AV_PICTURE_TYPE_P :

                                                       AV_PICTURE_TYPE_I;

            if (ps->pps->output_flag_present_flag)

                sh->pic_output_flag = get_bits1(gb);

            if (ps->sps->separate_colour_plane_flag)

                sh->colour_plane_id = get_bits(gb, 2);

            if (!IS_IDR(h)) {

                sh->pic_order_cnt_lsb = get_bits(gb, ps->sps->log2_max_poc_lsb);

                s->output_picture_number = h->poc = ff_hevc_compute_poc(h, sh->pic_order_cnt_lsb);

            } else

                s->output_picture_number = h->poc = 0;

            if (h->temporal_id == 0 &&

                h->nal_unit_type != NAL_TRAIL_N &&

                h->nal_unit_type != NAL_TSA_N &&

                h->nal_unit_type != NAL_STSA_N &&

                h->nal_unit_type != NAL_RADL_N &&

                h->nal_unit_type != NAL_RASL_N &&

                h->nal_unit_type != NAL_RADL_R &&

                h->nal_unit_type != NAL_RASL_R)

                h->pocTid0 = h->poc;

            return 0; /* no need to evaluate the rest */

        }

        buf += consumed;

    }

    /* didn't find a picture! */

    if (!is_global)

        av_log(h->avctx, AV_LOG_ERROR, "missing picture in access unit\n");

    return -1;

}


static void decode_colskip(uint8_t* plane, int width, int height, int stride, VC9Context *v){

    int x, y;

    GetBitContext *gb = &v->s.gb;

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

        if (!get_bits(gb, 1)) //colskip

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

                plane[y*stride] = 0;

        else

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

                plane[y*stride] = get_bits(gb, 1);

        plane ++;

    }

}


gen_intermediate_code_internal (CPUState *env, TranslationBlock *tb,

                                int search_pc)

{

    DisasContext ctx;

    target_ulong pc_start;

    uint16_t *gen_opc_end;

    int j, lj = -1;

    if (search_pc && loglevel)

        fprintf (logfile, "search pc %d\n", search_pc);

    pc_start = tb->pc;

    gen_opc_end = gen_opc_buf + OPC_MAX_SIZE;

    ctx.pc = pc_start;

    ctx.saved_pc = -1;

    ctx.tb = tb;

    ctx.bstate = BS_NONE;

    /* Restore delay slot state from the tb context.  */

    ctx.hflags = (uint32_t)tb->flags; /* FIXME: maybe use 64 bits here? */

    restore_cpu_state(env, &ctx);

#if defined(CONFIG_USER_ONLY)

    ctx.mem_idx = MIPS_HFLAG_UM;

#else

    ctx.mem_idx = ctx.hflags & MIPS_HFLAG_KSU;

#endif

#ifdef DEBUG_DISAS

    if (loglevel & CPU_LOG_TB_CPU) {

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

        /* FIXME: This may print out stale hflags from env... */

        cpu_dump_state(env, logfile, fprintf, 0);

    }

#endif

#ifdef MIPS_DEBUG_DISAS

    if (loglevel & CPU_LOG_TB_IN_ASM)

        fprintf(logfile, "\ntb %p idx %d hflags %04x\n",

                tb, ctx.mem_idx, ctx.hflags);

#endif

    while (ctx.bstate == BS_NONE && gen_opc_ptr < gen_opc_end) {

        if (env->nb_breakpoints > 0) {

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

                if (env->breakpoints[j] == ctx.pc) {

                    save_cpu_state(&ctx, 1);

                    ctx.bstate = BS_BRANCH;

                    gen_op_debug();

                    /* Include the breakpoint location or the tb won't

                     * be flushed when it must be.  */

                    ctx.pc += 4;

                    goto done_generating;

                }

            }

        }

        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] = ctx.pc;

            gen_opc_hflags[lj] = ctx.hflags & MIPS_HFLAG_BMASK;

            gen_opc_instr_start[lj] = 1;

        }

        ctx.opcode = ldl_code(ctx.pc);

        decode_opc(env, &ctx);

        ctx.pc += 4;

        if (env->singlestep_enabled)

            break;

        if ((ctx.pc & (TARGET_PAGE_SIZE - 1)) == 0)

            break;

#if defined (MIPS_SINGLE_STEP)

        break;

#endif

    }

    if (env->singlestep_enabled) {

        save_cpu_state(&ctx, ctx.bstate == BS_NONE);

        gen_op_debug();

    } else {

	switch (ctx.bstate) {

        case BS_STOP:

            tcg_gen_helper_0_0(do_interrupt_restart);

            gen_goto_tb(&ctx, 0, ctx.pc);

            break;

        case BS_NONE:

            save_cpu_state(&ctx, 0);

            gen_goto_tb(&ctx, 0, ctx.pc);

            break;

        case BS_EXCP:

            tcg_gen_helper_0_0(do_interrupt_restart);

            tcg_gen_exit_tb(0);

            break;

        case BS_BRANCH:

        default:

            break;

	}

    }

done_generating:

    *gen_opc_ptr = INDEX_op_end;

    if (search_pc) {

        j = gen_opc_ptr - gen_opc_buf;

        lj++;

        while (lj <= j)

            gen_opc_instr_start[lj++] = 0;

    } else {

        tb->size = ctx.pc - pc_start;

    }

#ifdef DEBUG_DISAS

#if defined MIPS_DEBUG_DISAS

    if (loglevel & CPU_LOG_TB_IN_ASM)

        fprintf(logfile, "\n");

#endif

    if (loglevel & CPU_LOG_TB_IN_ASM) {

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

        target_disas(logfile, pc_start, ctx.pc - pc_start, 0);

        fprintf(logfile, "\n");

    }

    if (loglevel & CPU_LOG_TB_CPU) {

        fprintf(logfile, "---------------- %d %08x\n", ctx.bstate, ctx.hflags);

    }

#endif

    return 0;

}


e1000_autoneg_timer(void *opaque)

{

    E1000State *s = opaque;

    qemu_get_queue(s->nic)->link_down = false;

    e1000_link_up(s);

    s->phy_reg[PHY_STATUS] |= MII_SR_AUTONEG_COMPLETE;

    DBGOUT(PHY, "Auto negotiation is completed\n");

}


blkdebug_co_pwritev(BlockDriverState *bs, uint64_t offset, uint64_t bytes,
                    QEMUIOVector *qiov, int flags)
{
    BDRVBlkdebugState *s = bs->opaque;
    BlkdebugRule *rule = NULL;
    QSIMPLEQ_FOREACH(rule, &s->active_rules, active_next) {
        uint64_t inject_offset = rule->options.inject.offset;
        if (inject_offset == -1 ||
            (inject_offset >= offset && inject_offset < offset + bytes))
        {
            break;
    if (rule && rule->options.inject.error) {
        return inject_error(bs, rule);
    return bdrv_co_pwritev(bs->file, offset, bytes, qiov, flags);


static void vc1_h_overlap_c(uint8_t* src, int stride)

{

    int i;

    int a, b, c, d;

    int d1, d2;

    int rnd = 1;

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

        a = src[-2];

        b = src[-1];

        c = src[0];

        d = src[1];

        d1 = (a - d + 3 + rnd) >> 3;

        d2 = (a - d + b - c + 4 - rnd) >> 3;

        src[-2] = a - d1;

        src[-1] = b - d2;

        src[0] = c + d2;

        src[1] = d + d1;

        src += stride;

        rnd = !rnd;

    }

}


int ff_msmpeg4_decode_block(MpegEncContext * s, int16_t * block,

                              int n, int coded, const uint8_t *scan_table)

{

    int level, i, last, run, run_diff;

    int av_uninit(dc_pred_dir);

    RLTable *rl;

    RL_VLC_ELEM *rl_vlc;

    int qmul, qadd;

    if (s->mb_intra) {

        qmul=1;

        qadd=0;

        /* DC coef */

        level = msmpeg4_decode_dc(s, n, &dc_pred_dir);

        if (level < 0){

            av_log(s->avctx, AV_LOG_ERROR, "dc overflow- block: %d qscale: %d//\n", n, s->qscale);

            if(s->inter_intra_pred) level=0;

            else                    return -1;

        }

        if (n < 4) {

            rl = &ff_rl_table[s->rl_table_index];

            if(level > 256*s->y_dc_scale){

                av_log(s->avctx, AV_LOG_ERROR, "dc overflow+ L qscale: %d//\n", s->qscale);

                if(!s->inter_intra_pred) return -1;

            }

        } else {

            rl = &ff_rl_table[3 + s->rl_chroma_table_index];

            if(level > 256*s->c_dc_scale){

                av_log(s->avctx, AV_LOG_ERROR, "dc overflow+ C qscale: %d//\n", s->qscale);

                if(!s->inter_intra_pred) return -1;

            }

        }

        block[0] = level;

        run_diff = s->msmpeg4_version >= 4;

        i = 0;

        if (!coded) {

            goto not_coded;

        }

        if (s->ac_pred) {

            if (dc_pred_dir == 0)

                scan_table = s->intra_v_scantable.permutated; /* left */

            else

                scan_table = s->intra_h_scantable.permutated; /* top */

        } else {

            scan_table = s->intra_scantable.permutated;

        }

        rl_vlc= rl->rl_vlc[0];

    } else {

        qmul = s->qscale << 1;

        qadd = (s->qscale - 1) | 1;

        i = -1;

        rl = &ff_rl_table[3 + s->rl_table_index];

        if(s->msmpeg4_version==2)

            run_diff = 0;

        else

            run_diff = 1;

        if (!coded) {

            s->block_last_index[n] = i;

            return 0;

        }

        if(!scan_table)

            scan_table = s->inter_scantable.permutated;

        rl_vlc= rl->rl_vlc[s->qscale];

    }

  {

    OPEN_READER(re, &s->gb);

    for(;;) {

        UPDATE_CACHE(re, &s->gb);

        GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 0);

        if (level==0) {

            int cache;

            cache= GET_CACHE(re, &s->gb);

            /* escape */

            if (s->msmpeg4_version==1 || (cache&0x80000000)==0) {

                if (s->msmpeg4_version==1 || (cache&0x40000000)==0) {

                    /* third escape */

                    if(s->msmpeg4_version!=1) LAST_SKIP_BITS(re, &s->gb, 2);

                    UPDATE_CACHE(re, &s->gb);

                    if(s->msmpeg4_version<=3){

                        last=  SHOW_UBITS(re, &s->gb, 1); SKIP_CACHE(re, &s->gb, 1);

                        run=   SHOW_UBITS(re, &s->gb, 6); SKIP_CACHE(re, &s->gb, 6);

                        level= SHOW_SBITS(re, &s->gb, 8);

                        SKIP_COUNTER(re, &s->gb, 1+6+8);

                    }else{

                        int sign;

                        last=  SHOW_UBITS(re, &s->gb, 1); SKIP_BITS(re, &s->gb, 1);

                        if(!s->esc3_level_length){

                            int ll;

                            av_dlog(s->avctx, "ESC-3 %X at %d %d\n",

                                    show_bits(&s->gb, 24), s->mb_x, s->mb_y);

                            if(s->qscale<8){

                                ll= SHOW_UBITS(re, &s->gb, 3); SKIP_BITS(re, &s->gb, 3);

                                if(ll==0){

                                    ll= 8+SHOW_UBITS(re, &s->gb, 1); SKIP_BITS(re, &s->gb, 1);

                                }

                            }else{

                                ll=2;

                                while(ll<8 && SHOW_UBITS(re, &s->gb, 1)==0){

                                    ll++;

                                    SKIP_BITS(re, &s->gb, 1);

                                }

                                if(ll<8) SKIP_BITS(re, &s->gb, 1);

                            }

                            s->esc3_level_length= ll;

                            s->esc3_run_length= SHOW_UBITS(re, &s->gb, 2) + 3; SKIP_BITS(re, &s->gb, 2);

                            UPDATE_CACHE(re, &s->gb);

                        }

                        run=   SHOW_UBITS(re, &s->gb, s->esc3_run_length);

                        SKIP_BITS(re, &s->gb, s->esc3_run_length);

                        sign=  SHOW_UBITS(re, &s->gb, 1);

                        SKIP_BITS(re, &s->gb, 1);

                        level= SHOW_UBITS(re, &s->gb, s->esc3_level_length);

                        SKIP_BITS(re, &s->gb, s->esc3_level_length);

                        if(sign) level= -level;

                    }

#if 0 // waste of time / this will detect very few errors

                    {

                        const int abs_level= FFABS(level);

                        const int run1= run - rl->max_run[last][abs_level] - run_diff;

                        if(abs_level<=MAX_LEVEL && run<=MAX_RUN){

                            if(abs_level <= rl->max_level[last][run]){

                                av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, vlc encoding possible\n");

                                return DECODING_AC_LOST;

                            }

                            if(abs_level <= rl->max_level[last][run]*2){

                                av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 1 encoding possible\n");

                                return DECODING_AC_LOST;

                            }

                            if(run1>=0 && abs_level <= rl->max_level[last][run1]){

                                av_log(s->avctx, AV_LOG_ERROR, "illegal 3. esc, esc 2 encoding possible\n");

                                return DECODING_AC_LOST;

                            }

                        }

                    }

#endif

                    //level = level * qmul + (level>0) * qadd - (level<=0) * qadd ;

                    if (level>0) level= level * qmul + qadd;

                    else         level= level * qmul - qadd;

#if 0 // waste of time too :(

                    if(level>2048 || level<-2048){

                        av_log(s->avctx, AV_LOG_ERROR, "|level| overflow in 3. esc\n");

                        return DECODING_AC_LOST;

                    }

#endif

                    i+= run + 1;

                    if(last) i+=192;

#ifdef ERROR_DETAILS

                if(run==66)

                    av_log(s->avctx, AV_LOG_ERROR, "illegal vlc code in ESC3 level=%d\n", level);

                else if((i>62 && i<192) || i>192+63)

                    av_log(s->avctx, AV_LOG_ERROR, "run overflow in ESC3 i=%d run=%d level=%d\n", i, run, level);

#endif

                } else {

                    /* second escape */

                    SKIP_BITS(re, &s->gb, 2);

                    GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1);

                    i+= run + rl->max_run[run>>7][level/qmul] + run_diff; //FIXME opt indexing

                    level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);

                    LAST_SKIP_BITS(re, &s->gb, 1);

#ifdef ERROR_DETAILS

                if(run==66)

                    av_log(s->avctx, AV_LOG_ERROR, "illegal vlc code in ESC2 level=%d\n", level);

                else if((i>62 && i<192) || i>192+63)

                    av_log(s->avctx, AV_LOG_ERROR, "run overflow in ESC2 i=%d run=%d level=%d\n", i, run, level);

#endif

                }

            } else {

                /* first escape */

                SKIP_BITS(re, &s->gb, 1);

                GET_RL_VLC(level, run, re, &s->gb, rl_vlc, TEX_VLC_BITS, 2, 1);

                i+= run;

                level = level + rl->max_level[run>>7][(run-1)&63] * qmul;//FIXME opt indexing

                level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);

                LAST_SKIP_BITS(re, &s->gb, 1);

#ifdef ERROR_DETAILS

                if(run==66)

                    av_log(s->avctx, AV_LOG_ERROR, "illegal vlc code in ESC1 level=%d\n", level);

                else if((i>62 && i<192) || i>192+63)

                    av_log(s->avctx, AV_LOG_ERROR, "run overflow in ESC1 i=%d run=%d level=%d\n", i, run, level);

#endif

            }

        } else {

            i+= run;

            level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);

            LAST_SKIP_BITS(re, &s->gb, 1);

#ifdef ERROR_DETAILS

                if(run==66)

                    av_log(s->avctx, AV_LOG_ERROR, "illegal vlc code level=%d\n", level);

                else if((i>62 && i<192) || i>192+63)

                    av_log(s->avctx, AV_LOG_ERROR, "run overflow i=%d run=%d level=%d\n", i, run, level);

#endif

        }

        if (i > 62){

            i-= 192;

            if(i&(~63)){

                const int left= get_bits_left(&s->gb);

                if(((i+192 == 64 && level/qmul==-1) || !(s->err_recognition&(AV_EF_BITSTREAM|AV_EF_COMPLIANT))) && left>=0){

                    av_log(s->avctx, AV_LOG_ERROR, "ignoring overflow at %d %d\n", s->mb_x, s->mb_y);

                    i = 63;

                    break;

                }else{

                    av_log(s->avctx, AV_LOG_ERROR, "ac-tex damaged at %d %d\n", s->mb_x, s->mb_y);

                    return -1;

                }

            }

            block[scan_table[i]] = level;

            break;

        }

        block[scan_table[i]] = level;

    }

    CLOSE_READER(re, &s->gb);

  }

 not_coded:

    if (s->mb_intra) {

        ff_mpeg4_pred_ac(s, block, n, dc_pred_dir);

        if (s->ac_pred) {

            i = 63; /* XXX: not optimal */

        }

    }

    if(s->msmpeg4_version>=4 && i>0) i=63; //FIXME/XXX optimize

    s->block_last_index[n] = i;

    return 0;

}


static int svq1_decode_frame(AVCodecContext *avctx, void *data,

                             int *got_frame, AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size       = avpkt->size;

    SVQ1Context     *s = avctx->priv_data;

    AVFrame       *cur = data;

    uint8_t *current;

    int result, i, x, y, width, height;

    svq1_pmv *pmv;

    /* initialize bit buffer */

    init_get_bits(&s->gb, buf, buf_size * 8);

    /* decode frame header */

    s->frame_code = get_bits(&s->gb, 22);

    if ((s->frame_code & ~0x70) || !(s->frame_code & 0x60))

        return AVERROR_INVALIDDATA;

    /* swap some header bytes (why?) */

    if (s->frame_code != 0x20) {

        uint32_t *src = (uint32_t *)(buf + 4);

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

            src[i] = ((src[i] << 16) | (src[i] >> 16)) ^ src[7 - i];

    }

    result = svq1_decode_frame_header(avctx, cur);

    if (result != 0) {

        av_dlog(avctx, "Error in svq1_decode_frame_header %i\n", result);

        return result;

    }

    result = ff_set_dimensions(avctx, s->width, s->height);

    if (result < 0)

        return result;

    if ((avctx->skip_frame >= AVDISCARD_NONREF && s->nonref) ||

        (avctx->skip_frame >= AVDISCARD_NONKEY &&

         cur->pict_type != AV_PICTURE_TYPE_I) ||

        avctx->skip_frame >= AVDISCARD_ALL)

        return buf_size;

    result = ff_get_buffer(avctx, cur, s->nonref ? 0 : AV_GET_BUFFER_FLAG_REF);

    if (result < 0)

        return result;

    pmv = av_malloc((FFALIGN(s->width, 16) / 8 + 3) * sizeof(*pmv));

    if (!pmv)

        return AVERROR(ENOMEM);

    /* decode y, u and v components */

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

        int linesize = cur->linesize[i];

        if (i == 0) {

            width    = FFALIGN(s->width,  16);

            height   = FFALIGN(s->height, 16);

        } else {

            if (avctx->flags & CODEC_FLAG_GRAY)

                break;

            width    = FFALIGN(s->width  / 4, 16);

            height   = FFALIGN(s->height / 4, 16);

        }

        current = cur->data[i];

        if (cur->pict_type == AV_PICTURE_TYPE_I) {

            /* keyframe */

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

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

                    result = svq1_decode_block_intra(&s->gb, &current[x],

                                                     linesize);

                    if (result != 0) {

                        av_log(avctx, AV_LOG_INFO,

                               "Error in svq1_decode_block %i (keyframe)\n",

                               result);

                        goto err;

                    }

                }

                current += 16 * linesize;

            }

        } else {

            /* delta frame */

            uint8_t *previous = s->prev->data[i];

            if (!previous ||

                s->prev->width != s->width || s->prev->height != s->height) {

                av_log(avctx, AV_LOG_ERROR, "Missing reference frame.\n");

                result = AVERROR_INVALIDDATA;

                goto err;

            }

            memset(pmv, 0, ((width / 8) + 3) * sizeof(svq1_pmv));

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

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

                    result = svq1_decode_delta_block(avctx, &s->hdsp,

                                                     &s->gb, &current[x],

                                                     previous, linesize,

                                                     pmv, x, y, width, height);

                    if (result != 0) {

                        av_dlog(avctx,

                                "Error in svq1_decode_delta_block %i\n",

                                result);

                        goto err;

                    }

                }

                pmv[0].x     =

                    pmv[0].y = 0;

                current += 16 * linesize;

            }

        }

    }

    if (!s->nonref) {

        av_frame_unref(s->prev);

        result = av_frame_ref(s->prev, cur);

        if (result < 0)

            goto err;

    }

    *got_frame = 1;

    result     = buf_size;

err:

    av_free(pmv);

    return result;

}


static void pci_get_node_name(char *nodename, int len, PCIDevice *dev)

{

    int slot = PCI_SLOT(dev->devfn);

    int func = PCI_FUNC(dev->devfn);

    uint32_t ccode = pci_default_read_config(dev, PCI_CLASS_PROG, 3);

    const char *name;

    name = pci_find_device_name((ccode >> 16) & 0xff, (ccode >> 8) & 0xff,

                                ccode & 0xff);

    if (func != 0) {

        snprintf(nodename, len, "%s@%x,%x", name, slot, func);

    } else {

        snprintf(nodename, len, "%s@%x", name, slot);

    }

}


void kqemu_flush_page(CPUState *env, target_ulong addr)

{

    LOG_INT("kqemu_flush_page: addr=" TARGET_FMT_lx "\n", addr);

    if (nb_pages_to_flush >= KQEMU_MAX_PAGES_TO_FLUSH)

        nb_pages_to_flush = KQEMU_FLUSH_ALL;

    else

        pages_to_flush[nb_pages_to_flush++] = addr;

}


void helper_lcall_real_T0_T1(int shift, int next_eip)

{

    int new_cs, new_eip;

    uint32_t esp, esp_mask;

    uint8_t *ssp;

    new_cs = T0;

    new_eip = T1;

    esp = env->regs[R_ESP];

    esp_mask = 0xffffffff;

    if (!(env->segs[R_SS].flags & DESC_B_MASK))

        esp_mask = 0xffff;

    ssp = env->segs[R_SS].base;

    if (shift) {

        esp -= 4;

        stl(ssp + (esp & esp_mask), env->segs[R_CS].selector);

        esp -= 4;

        stl(ssp + (esp & esp_mask), next_eip);

    } else {

        esp -= 2;

        stw(ssp + (esp & esp_mask), env->segs[R_CS].selector);

        esp -= 2;

        stw(ssp + (esp & esp_mask), next_eip);

    }

    if (!(env->segs[R_SS].flags & DESC_B_MASK))

        env->regs[R_ESP] = (env->regs[R_ESP] & ~0xffff) | (esp & 0xffff);

    else

        env->regs[R_ESP] = esp;

    env->eip = new_eip;

    env->segs[R_CS].selector = new_cs;

    env->segs[R_CS].base = (uint8_t *)(new_cs << 4);

}


static void handle_port_owner_write(EHCIState *s, int port, uint32_t owner)

{

    USBDevice *dev = s->ports[port].dev;

    uint32_t *portsc = &s->portsc[port];

    uint32_t orig;

    if (s->companion_ports[port] == NULL)

        return;

    owner = owner & PORTSC_POWNER;

    orig  = *portsc & PORTSC_POWNER;

    if (!(owner ^ orig)) {

        return;

    }

    if (dev) {

        usb_attach(&s->ports[port], NULL);

    }

    *portsc &= ~PORTSC_POWNER;

    *portsc |= owner;

    if (dev) {

        usb_attach(&s->ports[port], dev);

    }

}


static void test_visitor_out_native_list_str(TestOutputVisitorData *data,

                                              const void *unused)

{

    test_native_list(data, unused, USER_DEF_NATIVE_LIST_UNION_KIND_STRING);

}


PCIBus *i440fx_init(const char *host_type, const char *pci_type,

                    PCII440FXState **pi440fx_state,

                    int *piix3_devfn,

                    ISABus **isa_bus, qemu_irq *pic,

                    MemoryRegion *address_space_mem,

                    MemoryRegion *address_space_io,

                    ram_addr_t ram_size,

                    ram_addr_t below_4g_mem_size,

                    ram_addr_t above_4g_mem_size,

                    MemoryRegion *pci_address_space,

                    MemoryRegion *ram_memory)

{

    DeviceState *dev;

    PCIBus *b;

    PCIDevice *d;

    PCIHostState *s;

    PIIX3State *piix3;

    PCII440FXState *f;

    unsigned i;

    I440FXState *i440fx;

    dev = qdev_create(NULL, host_type);

    s = PCI_HOST_BRIDGE(dev);

    b = pci_bus_new(dev, NULL, pci_address_space,

                    address_space_io, 0, TYPE_PCI_BUS);

    s->bus = b;

    object_property_add_child(qdev_get_machine(), "i440fx", OBJECT(dev), NULL);

    qdev_init_nofail(dev);

    d = pci_create_simple(b, 0, pci_type);

    *pi440fx_state = I440FX_PCI_DEVICE(d);

    f = *pi440fx_state;

    f->system_memory = address_space_mem;

    f->pci_address_space = pci_address_space;

    f->ram_memory = ram_memory;

    i440fx = I440FX_PCI_HOST_BRIDGE(dev);

    i440fx->pci_hole.begin = below_4g_mem_size;

    i440fx->pci_hole.end = IO_APIC_DEFAULT_ADDRESS;

    /* setup pci memory mapping */

    pc_pci_as_mapping_init(OBJECT(f), f->system_memory,

                           f->pci_address_space);

    /* if *disabled* show SMRAM to all CPUs */

    memory_region_init_alias(&f->smram_region, OBJECT(d), "smram-region",

                             f->pci_address_space, 0xa0000, 0x20000);

    memory_region_add_subregion_overlap(f->system_memory, 0xa0000,

                                        &f->smram_region, 1);

    memory_region_set_enabled(&f->smram_region, true);

    /* smram, as seen by SMM CPUs */

    memory_region_init(&f->smram, OBJECT(d), "smram", 1ull << 32);

    memory_region_set_enabled(&f->smram, true);

    memory_region_init_alias(&f->low_smram, OBJECT(d), "smram-low",

                             f->ram_memory, 0xa0000, 0x20000);

    memory_region_set_enabled(&f->low_smram, true);

    memory_region_add_subregion(&f->smram, 0xa0000, &f->low_smram);

    object_property_add_const_link(qdev_get_machine(), "smram",

                                   OBJECT(&f->smram), &error_abort);

    init_pam(dev, f->ram_memory, f->system_memory, f->pci_address_space,

             &f->pam_regions[0], PAM_BIOS_BASE, PAM_BIOS_SIZE);

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

        init_pam(dev, f->ram_memory, f->system_memory, f->pci_address_space,

                 &f->pam_regions[i+1], PAM_EXPAN_BASE + i * PAM_EXPAN_SIZE,

                 PAM_EXPAN_SIZE);

    }

    /* Xen supports additional interrupt routes from the PCI devices to

     * the IOAPIC: the four pins of each PCI device on the bus are also

     * connected to the IOAPIC directly.

     * These additional routes can be discovered through ACPI. */

    if (xen_enabled()) {

        PCIDevice *pci_dev = pci_create_simple_multifunction(b,

                             -1, true, "PIIX3-xen");

        piix3 = PIIX3_PCI_DEVICE(pci_dev);

        pci_bus_irqs(b, xen_piix3_set_irq, xen_pci_slot_get_pirq,

                piix3, XEN_PIIX_NUM_PIRQS);

    } else {

        PCIDevice *pci_dev = pci_create_simple_multifunction(b,

                             -1, true, "PIIX3");

        piix3 = PIIX3_PCI_DEVICE(pci_dev);

        pci_bus_irqs(b, piix3_set_irq, pci_slot_get_pirq, piix3,

                PIIX_NUM_PIRQS);

        pci_bus_set_route_irq_fn(b, piix3_route_intx_pin_to_irq);

    }

    piix3->pic = pic;

    *isa_bus = ISA_BUS(qdev_get_child_bus(DEVICE(piix3), "isa.0"));

    *piix3_devfn = piix3->dev.devfn;

    ram_size = ram_size / 8 / 1024 / 1024;

    if (ram_size > 255) {

        ram_size = 255;

    }

    d->config[I440FX_COREBOOT_RAM_SIZE] = ram_size;

    i440fx_update_memory_mappings(f);

    return b;

}


void qio_channel_socket_connect_async(QIOChannelSocket *ioc,

                                      SocketAddressLegacy *addr,

                                      QIOTaskFunc callback,

                                      gpointer opaque,

                                      GDestroyNotify destroy)

{

    QIOTask *task = qio_task_new(

        OBJECT(ioc), callback, opaque, destroy);

    SocketAddressLegacy *addrCopy;

    addrCopy = QAPI_CLONE(SocketAddressLegacy, addr);

    /* socket_connect() does a non-blocking connect(), but it

     * still blocks in DNS lookups, so we must use a thread */

    trace_qio_channel_socket_connect_async(ioc, addr);

    qio_task_run_in_thread(task,

                           qio_channel_socket_connect_worker,

                           addrCopy,

                           (GDestroyNotify)qapi_free_SocketAddressLegacy);

}


static av_cold int targa_encode_close(AVCodecContext *avctx)

{

    av_frame_free(&avctx->coded_frame);

    return 0;

}


static int vnc_set_x509_credential_dir(VncDisplay *vs,

				       const char *certdir)

{

    if (vnc_set_x509_credential(vs, certdir, X509_CA_CERT_FILE, &vs->x509cacert, 0) < 0)

	goto cleanup;

    if (vnc_set_x509_credential(vs, certdir, X509_CA_CRL_FILE, &vs->x509cacrl, 1) < 0)

	goto cleanup;

    if (vnc_set_x509_credential(vs, certdir, X509_SERVER_CERT_FILE, &vs->x509cert, 0) < 0)

	goto cleanup;

    if (vnc_set_x509_credential(vs, certdir, X509_SERVER_KEY_FILE, &vs->x509key, 0) < 0)

	goto cleanup;

    return 0;

 cleanup:

    qemu_free(vs->x509cacert);

    qemu_free(vs->x509cacrl);

    qemu_free(vs->x509cert);

    qemu_free(vs->x509key);

    vs->x509cacert = vs->x509cacrl = vs->x509cert = vs->x509key = NULL;

    return -1;

}


static inline uint32_t xen_vcpu_eport(shared_iopage_t *shared_page, int i)

{

    return shared_page->vcpu_iodata[i].vp_eport;

}


int bdrv_flush_all(void)

{

    BlockDriverState *bs = NULL;

    int result = 0;

    while ((bs = bdrv_next(bs))) {

        AioContext *aio_context = bdrv_get_aio_context(bs);

        int ret;

        aio_context_acquire(aio_context);

        ret = bdrv_flush(bs);

        if (ret < 0 && !result) {

            result = ret;

        }

        aio_context_release(aio_context);

    }

    return result;

}


static inline void gen_movcf_s (int fs, int fd, int cc, int tf)

{

    uint32_t ccbit;

    int cond;

    TCGv r_tmp1 = tcg_temp_local_new(TCG_TYPE_I32);

    TCGv fp0 = tcg_temp_local_new(TCG_TYPE_I32);

    TCGv fp1 = tcg_temp_local_new(TCG_TYPE_I32);

    int l1 = gen_new_label();

    if (cc)

        ccbit = 1 << (24 + cc);

    else

        ccbit = 1 << 23;

    if (tf)

        cond = TCG_COND_EQ;

    else

        cond = TCG_COND_NE;

    gen_load_fpr32(fp0, fs);

    gen_load_fpr32(fp1, fd);

    tcg_gen_andi_i32(r_tmp1, fpu_fcr31, ccbit);

    tcg_gen_brcondi_i32(cond, r_tmp1, 0, l1);

    tcg_gen_mov_i32(fp1, fp0);

    tcg_temp_free(fp0);

    gen_set_label(l1);

    tcg_temp_free(r_tmp1);

    gen_store_fpr32(fp1, fd);

    tcg_temp_free(fp1);

}


static void notdirty_mem_writel(void *opaque, target_phys_addr_t ram_addr,

                                uint32_t val)

{

    int dirty_flags;

    dirty_flags = phys_ram_dirty[ram_addr >> TARGET_PAGE_BITS];

    if (!(dirty_flags & CODE_DIRTY_FLAG)) {

#if !defined(CONFIG_USER_ONLY)

        tb_invalidate_phys_page_fast(ram_addr, 4);

        dirty_flags = phys_ram_dirty[ram_addr >> TARGET_PAGE_BITS];

#endif

    }

    stl_p(qemu_get_ram_ptr(ram_addr), val);

    dirty_flags |= (0xff & ~CODE_DIRTY_FLAG);

    phys_ram_dirty[ram_addr >> TARGET_PAGE_BITS] = dirty_flags;

    /* we remove the notdirty callback only if the code has been

       flushed */

    if (dirty_flags == 0xff)

        tlb_set_dirty(cpu_single_env, cpu_single_env->mem_io_vaddr);

}


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

{

    BDRVQcow2State *s = bs->opaque;

    int flags = s->flags;

    QCryptoCipher *cipher = NULL;

    QDict *options;

    Error *local_err = NULL;

    int ret;

    /*

     * Backing files are read-only which makes all of their metadata immutable,

     * that means we don't have to worry about reopening them here.

     */

    cipher = s->cipher;

    s->cipher = NULL;

    qcow2_close(bs);

    bdrv_invalidate_cache(bs->file->bs, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        bs->drv = NULL;

        return;

    }

    memset(s, 0, sizeof(BDRVQcow2State));

    options = qdict_clone_shallow(bs->options);

    flags &= ~BDRV_O_INACTIVE;

    ret = qcow2_open(bs, options, flags, &local_err);

    QDECREF(options);

    if (local_err) {

        error_propagate(errp, local_err);

        error_prepend(errp, "Could not reopen qcow2 layer: ");

        bs->drv = NULL;

        return;

    } else if (ret < 0) {

        error_setg_errno(errp, -ret, "Could not reopen qcow2 layer");

        bs->drv = NULL;

        return;

    }

    s->cipher = cipher;

}


static inline void gen_evmwumiaa(DisasContext *ctx)

{

    TCGv_i64 acc;

    TCGv_i64 tmp;

    if (unlikely(!ctx->spe_enabled)) {

        gen_exception(ctx, POWERPC_EXCP_APU);

        return;

    }

    gen_evmwumi(ctx);           /* rD := rA * rB */

    acc = tcg_temp_new_i64();

    tmp = tcg_temp_new_i64();

    /* tmp := rD */

    gen_load_gpr64(tmp, rD(ctx->opcode));

    /* Load acc */

    tcg_gen_ld_i64(acc, cpu_env, offsetof(CPUState, spe_acc));

    /* acc := tmp + acc */

    tcg_gen_add_i64(acc, acc, tmp);

    /* Store acc */

    tcg_gen_st_i64(acc, cpu_env, offsetof(CPUState, spe_acc));

    /* rD := acc */

    gen_store_gpr64(rD(ctx->opcode), acc);

    tcg_temp_free_i64(acc);

    tcg_temp_free_i64(tmp);

}


void qemu_system_reset(void)

{

    QEMUResetEntry *re, *nre;

    /* reset all devices */

    TAILQ_FOREACH_SAFE(re, &reset_handlers, entry, nre) {

        re->func(re->opaque);

    }

}


static int cpu_can_run(CPUState *env)

{

    if (env->stop)

        return 0;

    if (env->stopped)

        return 0;

    if (!vm_running)

        return 0;

    return 1;

}


static void cpu_common_parse_features(const char *typename, char *features,

                                      Error **errp)

{

    char *featurestr; /* Single "key=value" string being parsed */

    char *val;

    static bool cpu_globals_initialized;

    /* TODO: all callers of ->parse_features() need to be changed to

     * call it only once, so we can remove this check (or change it

     * to assert(!cpu_globals_initialized).

     * Current callers of ->parse_features() are:

     * - cpu_generic_init()

     * - cpu_x86_create()

     */

    if (cpu_globals_initialized) {

        return;

    }

    cpu_globals_initialized = true;

    featurestr = features ? strtok(features, ",") : NULL;

    while (featurestr) {

        val = strchr(featurestr, '=');

        if (val) {

            GlobalProperty *prop = g_new0(typeof(*prop), 1);

            *val = 0;

            val++;

            prop->driver = typename;

            prop->property = g_strdup(featurestr);

            prop->value = g_strdup(val);

            prop->errp = &error_fatal;

            qdev_prop_register_global(prop);

        } else {

            error_setg(errp, "Expected key=value format, found %s.",

                       featurestr);

            return;

        }

        featurestr = strtok(NULL, ",");

    }

}


static void ich9_lpc_update_apic(ICH9LPCState *lpc, int gsi)

{

    int level = 0;

    assert(gsi >= ICH9_LPC_PIC_NUM_PINS);

    level |= pci_bus_get_irq_level(lpc->d.bus, ich9_gsi_to_pirq(gsi));

    if (gsi == lpc->sci_gsi) {

        level |= lpc->sci_level;

    }

    qemu_set_irq(lpc->gsi[gsi], level);

}


static int32_t scsi_disk_emulate_command(SCSIRequest *req, uint8_t *buf)

{

    SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);

    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);

    uint64_t nb_sectors;

    uint8_t *outbuf;

    int buflen;

    switch (req->cmd.buf[0]) {

    case INQUIRY:

    case MODE_SENSE:

    case MODE_SENSE_10:

    case RESERVE:

    case RESERVE_10:

    case RELEASE:

    case RELEASE_10:

    case START_STOP:

    case ALLOW_MEDIUM_REMOVAL:

    case GET_CONFIGURATION:

    case GET_EVENT_STATUS_NOTIFICATION:

    case MECHANISM_STATUS:

    case REQUEST_SENSE:

        break;

    default:

        if (s->tray_open || !bdrv_is_inserted(s->qdev.conf.bs)) {

            scsi_check_condition(r, SENSE_CODE(NO_MEDIUM));

            return 0;

        }

        break;

    }

    if (!r->iov.iov_base) {

        /*

         * FIXME: we shouldn't return anything bigger than 4k, but the code

         * requires the buffer to be as big as req->cmd.xfer in several

         * places.  So, do not allow CDBs with a very large ALLOCATION

         * LENGTH.  The real fix would be to modify scsi_read_data and

         * dma_buf_read, so that they return data beyond the buflen

         * as all zeros.

         */

        if (req->cmd.xfer > 65536) {

            goto illegal_request;

        }

        r->buflen = MAX(4096, req->cmd.xfer);

        r->iov.iov_base = qemu_blockalign(s->qdev.conf.bs, r->buflen);

    }

    buflen = req->cmd.xfer;

    outbuf = r->iov.iov_base;

    switch (req->cmd.buf[0]) {

    case TEST_UNIT_READY:

        assert(!s->tray_open && bdrv_is_inserted(s->qdev.conf.bs));

        break;

    case INQUIRY:

        buflen = scsi_disk_emulate_inquiry(req, outbuf);

        if (buflen < 0) {

            goto illegal_request;

        }

        break;

    case MODE_SENSE:

    case MODE_SENSE_10:

        buflen = scsi_disk_emulate_mode_sense(r, outbuf);

        if (buflen < 0) {

            goto illegal_request;

        }

        break;

    case READ_TOC:

        buflen = scsi_disk_emulate_read_toc(req, outbuf);

        if (buflen < 0) {

            goto illegal_request;

        }

        break;

    case RESERVE:

        if (req->cmd.buf[1] & 1) {

            goto illegal_request;

        }

        break;

    case RESERVE_10:

        if (req->cmd.buf[1] & 3) {

            goto illegal_request;

        }

        break;

    case RELEASE:

        if (req->cmd.buf[1] & 1) {

            goto illegal_request;

        }

        break;

    case RELEASE_10:

        if (req->cmd.buf[1] & 3) {

            goto illegal_request;

        }

        break;

    case START_STOP:

        if (scsi_disk_emulate_start_stop(r) < 0) {

            return 0;

        }

        break;

    case ALLOW_MEDIUM_REMOVAL:

        s->tray_locked = req->cmd.buf[4] & 1;

        bdrv_lock_medium(s->qdev.conf.bs, req->cmd.buf[4] & 1);

        break;

    case READ_CAPACITY_10:

        /* The normal LEN field for this command is zero.  */

        memset(outbuf, 0, 8);

        bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors);

        if (!nb_sectors) {

            scsi_check_condition(r, SENSE_CODE(LUN_NOT_READY));

            return -1;

        }

        if ((req->cmd.buf[8] & 1) == 0 && req->cmd.lba) {

            goto illegal_request;

        }

        nb_sectors /= s->qdev.blocksize / 512;

        /* Returned value is the address of the last sector.  */

        nb_sectors--;

        /* Remember the new size for read/write sanity checking. */

        s->qdev.max_lba = nb_sectors;

        /* Clip to 2TB, instead of returning capacity modulo 2TB. */

        if (nb_sectors > UINT32_MAX) {

            nb_sectors = UINT32_MAX;

        }

        outbuf[0] = (nb_sectors >> 24) & 0xff;

        outbuf[1] = (nb_sectors >> 16) & 0xff;

        outbuf[2] = (nb_sectors >> 8) & 0xff;

        outbuf[3] = nb_sectors & 0xff;

        outbuf[4] = 0;

        outbuf[5] = 0;

        outbuf[6] = s->qdev.blocksize >> 8;

        outbuf[7] = 0;

        buflen = 8;

        break;

    case REQUEST_SENSE:

        /* Just return "NO SENSE".  */

        buflen = scsi_build_sense(NULL, 0, outbuf, r->buflen,

                                  (req->cmd.buf[1] & 1) == 0);

        break;

    case MECHANISM_STATUS:

        buflen = scsi_emulate_mechanism_status(s, outbuf);

        if (buflen < 0) {

            goto illegal_request;

        }

        break;

    case GET_CONFIGURATION:

        buflen = scsi_get_configuration(s, outbuf);

        if (buflen < 0) {

            goto illegal_request;

        }

        break;

    case GET_EVENT_STATUS_NOTIFICATION:

        buflen = scsi_get_event_status_notification(s, r, outbuf);

        if (buflen < 0) {

            goto illegal_request;

        }

        break;

    case READ_DISC_INFORMATION:

        buflen = scsi_read_disc_information(s, r, outbuf);

        if (buflen < 0) {

            goto illegal_request;

        }

        break;

    case READ_DVD_STRUCTURE:

        buflen = scsi_read_dvd_structure(s, r, outbuf);

        if (buflen < 0) {

            goto illegal_request;

        }

        break;

    case SERVICE_ACTION_IN_16:

        /* Service Action In subcommands. */

        if ((req->cmd.buf[1] & 31) == SAI_READ_CAPACITY_16) {

            DPRINTF("SAI READ CAPACITY(16)\n");

            memset(outbuf, 0, req->cmd.xfer);

            bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors);

            if (!nb_sectors) {

                scsi_check_condition(r, SENSE_CODE(LUN_NOT_READY));

                return -1;

            }

            if ((req->cmd.buf[14] & 1) == 0 && req->cmd.lba) {

                goto illegal_request;

            }

            nb_sectors /= s->qdev.blocksize / 512;

            /* Returned value is the address of the last sector.  */

            nb_sectors--;

            /* Remember the new size for read/write sanity checking. */

            s->qdev.max_lba = nb_sectors;

            outbuf[0] = (nb_sectors >> 56) & 0xff;

            outbuf[1] = (nb_sectors >> 48) & 0xff;

            outbuf[2] = (nb_sectors >> 40) & 0xff;

            outbuf[3] = (nb_sectors >> 32) & 0xff;

            outbuf[4] = (nb_sectors >> 24) & 0xff;

            outbuf[5] = (nb_sectors >> 16) & 0xff;

            outbuf[6] = (nb_sectors >> 8) & 0xff;

            outbuf[7] = nb_sectors & 0xff;

            outbuf[8] = 0;

            outbuf[9] = 0;

            outbuf[10] = s->qdev.blocksize >> 8;

            outbuf[11] = 0;

            outbuf[12] = 0;

            outbuf[13] = get_physical_block_exp(&s->qdev.conf);

            /* set TPE bit if the format supports discard */

            if (s->qdev.conf.discard_granularity) {

                outbuf[14] = 0x80;

            }

            /* Protection, exponent and lowest lba field left blank. */

            buflen = req->cmd.xfer;

            break;

        }

        DPRINTF("Unsupported Service Action In\n");

        goto illegal_request;

    case SYNCHRONIZE_CACHE:

        /* The request is used as the AIO opaque value, so add a ref.  */

        scsi_req_ref(&r->req);

        bdrv_acct_start(s->qdev.conf.bs, &r->acct, 0, BDRV_ACCT_FLUSH);

        r->req.aiocb = bdrv_aio_flush(s->qdev.conf.bs, scsi_aio_complete, r);

        return 0;

    case SEEK_10:

        DPRINTF("Seek(10) (sector %" PRId64 ")\n", r->req.cmd.lba);

        if (r->req.cmd.lba > s->qdev.max_lba) {

            goto illegal_lba;

        }

        break;

    case MODE_SELECT:

        DPRINTF("Mode Select(6) (len %lu)\n", (long)r->req.cmd.xfer);

        /* We don't support mode parameter changes.

           Allow the mode parameter header + block descriptors only. */

        if (r->req.cmd.xfer > 12) {

            goto illegal_request;

        }

        break;

    case MODE_SELECT_10:

        DPRINTF("Mode Select(10) (len %lu)\n", (long)r->req.cmd.xfer);

        /* We don't support mode parameter changes.

           Allow the mode parameter header + block descriptors only. */

        if (r->req.cmd.xfer > 16) {

            goto illegal_request;

        }

        break;

    case WRITE_SAME_10:

        nb_sectors = lduw_be_p(&req->cmd.buf[7]);

        goto write_same;

    case WRITE_SAME_16:

        nb_sectors = ldl_be_p(&req->cmd.buf[10]) & 0xffffffffULL;

    write_same:

        if (r->req.cmd.lba > s->qdev.max_lba) {

            goto illegal_lba;

        }

        /*

         * We only support WRITE SAME with the unmap bit set for now.

         */

        if (!(req->cmd.buf[1] & 0x8)) {

            goto illegal_request;

        }

        /* The request is used as the AIO opaque value, so add a ref.  */

        scsi_req_ref(&r->req);

        r->req.aiocb = bdrv_aio_discard(s->qdev.conf.bs,

                                        r->req.cmd.lba * (s->qdev.blocksize / 512),

                                        nb_sectors * (s->qdev.blocksize / 512),

                                        scsi_aio_complete, r);

        return 0;

    default:

        DPRINTF("Unknown SCSI command (%2.2x)\n", buf[0]);

        scsi_check_condition(r, SENSE_CODE(INVALID_OPCODE));

        return 0;

    }

    assert(!r->req.aiocb);

    r->iov.iov_len = MIN(buflen, req->cmd.xfer);

    if (r->iov.iov_len == 0) {

        scsi_req_complete(&r->req, GOOD);

    }

    if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {

        assert(r->iov.iov_len == req->cmd.xfer);

        return -r->iov.iov_len;

    } else {

        return r->iov.iov_len;

    }

illegal_request:

    if (r->req.status == -1) {

        scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));

    }

    return 0;

illegal_lba:

    scsi_check_condition(r, SENSE_CODE(LBA_OUT_OF_RANGE));

    return 0;

}


static void qmp_input_start_list(Visitor *v, const char *name,

                                 GenericList **list, size_t size, Error **errp)

{

    QmpInputVisitor *qiv = to_qiv(v);

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

    const QListEntry *entry;

    if (!qobj) {

        return;

    }

    if (qobject_type(qobj) != QTYPE_QLIST) {

        if (list) {

            *list = NULL;

        }

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

                   "list");

        return;

    }

    entry = qmp_input_push(qiv, qobj, list, errp);

    if (list) {

        if (entry) {

            *list = g_malloc0(size);

        } else {

            *list = NULL;

        }

    }

}


static int pci_e1000_init(PCIDevice *pci_dev)

{

    E1000State *d = DO_UPCAST(E1000State, dev, pci_dev);

    uint8_t *pci_conf;

    uint16_t checksum = 0;

    int i;

    uint8_t *macaddr;

    pci_conf = d->dev.config;

    pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_INTEL);

    pci_config_set_device_id(pci_conf, E1000_DEVID);

    *(uint16_t *)(pci_conf+0x04) = cpu_to_le16(0x0407);

    *(uint16_t *)(pci_conf+0x06) = cpu_to_le16(0x0010);

    pci_conf[0x08] = 0x03;

    pci_config_set_class(pci_conf, PCI_CLASS_NETWORK_ETHERNET);

    pci_conf[0x0c] = 0x10;

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

    d->mmio_index = cpu_register_io_memory(e1000_mmio_read,

            e1000_mmio_write, d);

    pci_register_bar((PCIDevice *)d, 0, PNPMMIO_SIZE,

                           PCI_ADDRESS_SPACE_MEM, e1000_mmio_map);

    pci_register_bar((PCIDevice *)d, 1, IOPORT_SIZE,

                           PCI_ADDRESS_SPACE_IO, ioport_map);

    memmove(d->eeprom_data, e1000_eeprom_template,

        sizeof e1000_eeprom_template);

    qemu_macaddr_default_if_unset(&d->conf.macaddr);

    macaddr = d->conf.macaddr.a;

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

        d->eeprom_data[i] = (macaddr[2*i+1]<<8) | macaddr[2*i];

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

        checksum += d->eeprom_data[i];

    checksum = (uint16_t) EEPROM_SUM - checksum;

    d->eeprom_data[EEPROM_CHECKSUM_REG] = checksum;

    d->vc = qemu_new_vlan_client(NET_CLIENT_TYPE_NIC,

                                 d->conf.vlan, d->conf.peer,

                                 d->dev.qdev.info->name, d->dev.qdev.id,

                                 e1000_can_receive, e1000_receive, NULL,

                                 NULL, e1000_cleanup, d);

    d->vc->link_status_changed = e1000_set_link_status;

    qemu_format_nic_info_str(d->vc, macaddr);

    vmstate_register(-1, &vmstate_e1000, d);

    e1000_reset(d);

#if 0 /* rom bev support is broken -> can't load unconditionally */

    if (!pci_dev->qdev.hotplugged) {

        static int loaded = 0;

        if (!loaded) {

            rom_add_option("pxe-e1000.bin");

            loaded = 1;

        }

    }

#endif

    return 0;

}


void qemu_clock_notify(QEMUClockType type)

{

    QEMUTimerList *timer_list;

    QEMUClock *clock = qemu_clock_ptr(type);

    QLIST_FOREACH(timer_list, &clock->timerlists, list) {

        timerlist_notify(timer_list);

    }

}


static void backward_filter(RA288Context *ractx)

{

    float temp1[37]; // RTMP in the spec

    float temp2[11]; // GPTPMP in the spec

    do_hybrid_window(36, 40, 35, ractx->sp_block, temp1, ractx->sp_hist,

                     ractx->sp_rec, syn_window);

    if (!eval_lpc_coeffs(temp1, ractx->sp_lpc, 36))

        colmult(ractx->sp_lpc, ractx->sp_lpc, syn_bw_tab, 36);

    do_hybrid_window(10, 8, 20, ractx->gain_block, temp2, ractx->gain_hist,

                     ractx->gain_rec, gain_window);

    if (!eval_lpc_coeffs(temp2, ractx->gain_lpc, 10))

        colmult(ractx->gain_lpc, ractx->gain_lpc, gain_bw_tab, 10);

}


int target_mprotect(abi_ulong start, abi_ulong len, int prot)

{

    abi_ulong end, host_start, host_end, addr;

    int prot1, ret;

#ifdef DEBUG_MMAP

    printf("mprotect: start=0x" TARGET_FMT_lx

           "len=0x" TARGET_FMT_lx " prot=%c%c%c\n", start, len,

           prot & PROT_READ ? 'r' : '-',

           prot & PROT_WRITE ? 'w' : '-',

           prot & PROT_EXEC ? 'x' : '-');

#endif

    if ((start & ~TARGET_PAGE_MASK) != 0)

        return -EINVAL;

    len = TARGET_PAGE_ALIGN(len);

    end = start + len;

    if (end < start)

        return -EINVAL;

    if (prot & ~(PROT_READ | PROT_WRITE | PROT_EXEC))

        return -EINVAL;

    if (len == 0)

        return 0;

    host_start = start & qemu_host_page_mask;

    host_end = HOST_PAGE_ALIGN(end);

    if (start > host_start) {

        /* handle host page containing start */

        prot1 = prot;

        for(addr = host_start; addr < start; addr += TARGET_PAGE_SIZE) {

            prot1 |= page_get_flags(addr);

        }

        if (host_end == host_start + qemu_host_page_size) {

            for(addr = end; addr < host_end; addr += TARGET_PAGE_SIZE) {

                prot1 |= page_get_flags(addr);

            }

            end = host_end;

        }

        ret = mprotect(g2h(host_start), qemu_host_page_size, prot1 & PAGE_BITS);

        if (ret != 0)

            return ret;

        host_start += qemu_host_page_size;

    }

    if (end < host_end) {

        prot1 = prot;

        for(addr = end; addr < host_end; addr += TARGET_PAGE_SIZE) {

            prot1 |= page_get_flags(addr);

        }

        ret = mprotect(g2h(host_end - qemu_host_page_size), qemu_host_page_size,

                       prot1 & PAGE_BITS);

        if (ret != 0)

            return ret;

        host_end -= qemu_host_page_size;

    }

    /* handle the pages in the middle */

    if (host_start < host_end) {

        ret = mprotect(g2h(host_start), host_end - host_start, prot);

        if (ret != 0)

            return ret;

    }

    page_set_flags(start, start + len, prot | PAGE_VALID);

    return 0;

}


static int local_open(FsContext *ctx, V9fsPath *fs_path,

                      int flags, V9fsFidOpenState *fs)

{

    char buffer[PATH_MAX];

    char *path = fs_path->data;

    fs->fd = open(rpath(ctx, path, buffer), flags | O_NOFOLLOW);

    return fs->fd;

}


void qmp_block_commit(const char *device,

                      bool has_base, const char *base,

                      bool has_top, const char *top,

                      bool has_backing_file, const char *backing_file,

                      bool has_speed, int64_t speed,

                      Error **errp)

{

    BlockDriverState *bs;

    BlockDriverState *base_bs, *top_bs;

    Error *local_err = NULL;

    /* This will be part of the QMP command, if/when the

     * BlockdevOnError change for blkmirror makes it in

     */

    BlockdevOnError on_error = BLOCKDEV_ON_ERROR_REPORT;

    if (!has_speed) {

        speed = 0;

    }

    /* drain all i/o before commits */

    bdrv_drain_all();

    /* Important Note:

     *  libvirt relies on the DeviceNotFound error class in order to probe for

     *  live commit feature versions; for this to work, we must make sure to

     *  perform the device lookup before any generic errors that may occur in a

     *  scenario in which all optional arguments are omitted. */

    bs = bdrv_find(device);

    if (!bs) {

        error_set(errp, QERR_DEVICE_NOT_FOUND, device);

        return;

    }

    if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT, errp)) {

        return;

    }

    /* default top_bs is the active layer */

    top_bs = bs;

    if (has_top && top) {

        if (strcmp(bs->filename, top) != 0) {

            top_bs = bdrv_find_backing_image(bs, top);

        }

    }

    if (top_bs == NULL) {

        error_setg(errp, "Top image file %s not found", top ? top : "NULL");

        return;

    }

    if (has_base && base) {

        base_bs = bdrv_find_backing_image(top_bs, base);

    } else {

        base_bs = bdrv_find_base(top_bs);

    }

    if (base_bs == NULL) {

        error_set(errp, QERR_BASE_NOT_FOUND, base ? base : "NULL");

        return;

    }

    /* Do not allow attempts to commit an image into itself */

    if (top_bs == base_bs) {

        error_setg(errp, "cannot commit an image into itself");

        return;

    }

    if (top_bs == bs) {

        if (has_backing_file) {

            error_setg(errp, "'backing-file' specified,"

                             " but 'top' is the active layer");

            return;

        }

        commit_active_start(bs, base_bs, speed, on_error, block_job_cb,

                            bs, &local_err);

    } else {

        commit_start(bs, base_bs, top_bs, speed, on_error, block_job_cb, bs,

                     has_backing_file ? backing_file : NULL, &local_err);

    }

    if (local_err != NULL) {

        error_propagate(errp, local_err);

        return;

    }

}


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

{

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

    BlockDriverState *bs;

    if (!strcmp(device, "all")) {

        bdrv_commit_all();

    } else {

        bs = bdrv_find(device);

        if (!bs) {

            qerror_report(QERR_DEVICE_NOT_FOUND, device);

            return;

        }

        bdrv_commit(bs);

    }

}


static QmpOutputVisitor *to_qov(Visitor *v)

{

    return container_of(v, QmpOutputVisitor, visitor);

}