static void pc_init1(MachineState *machine)

{

    PCMachineState *pc_machine = PC_MACHINE(machine);

    MemoryRegion *system_memory = get_system_memory();

    MemoryRegion *system_io = get_system_io();

    int i;

    ram_addr_t below_4g_mem_size, above_4g_mem_size;

    PCIBus *pci_bus;

    ISABus *isa_bus;

    PCII440FXState *i440fx_state;

    int piix3_devfn = -1;

    qemu_irq *cpu_irq;

    qemu_irq *gsi;

    qemu_irq *i8259;

    qemu_irq *smi_irq;

    GSIState *gsi_state;

    DriveInfo *hd[MAX_IDE_BUS * MAX_IDE_DEVS];

    BusState *idebus[MAX_IDE_BUS];

    ISADevice *rtc_state;

    ISADevice *floppy;

    MemoryRegion *ram_memory;

    MemoryRegion *pci_memory;

    MemoryRegion *rom_memory;

    DeviceState *icc_bridge;

    FWCfgState *fw_cfg = NULL;

    PcGuestInfo *guest_info;

    ram_addr_t lowmem;

    /* Check whether RAM fits below 4G (leaving 1/2 GByte for IO memory).

     * If it doesn't, we need to split it in chunks below and above 4G.

     * In any case, try to make sure that guest addresses aligned at

     * 1G boundaries get mapped to host addresses aligned at 1G boundaries.

     * For old machine types, use whatever split we used historically to avoid

     * breaking migration.

     */

    if (machine->ram_size >= 0xe0000000) {

        lowmem = gigabyte_align ? 0xc0000000 : 0xe0000000;

    } else {

        lowmem = 0xe0000000;

    }

    /* Handle the machine opt max-ram-below-4g.  It is basically doing

     * min(qemu limit, user limit).

     */

    if (lowmem > pc_machine->max_ram_below_4g) {

        lowmem = pc_machine->max_ram_below_4g;

        if (machine->ram_size - lowmem > lowmem &&

            lowmem & ((1ULL << 30) - 1)) {

            error_report("Warning: Large machine and max_ram_below_4g(%"PRIu64

                         ") not a multiple of 1G; possible bad performance.",

                         pc_machine->max_ram_below_4g);

        }

    }

    if (machine->ram_size >= lowmem) {

        above_4g_mem_size = machine->ram_size - lowmem;

        below_4g_mem_size = lowmem;

    } else {

        above_4g_mem_size = 0;

        below_4g_mem_size = machine->ram_size;

    }

    if (xen_enabled() && xen_hvm_init(&below_4g_mem_size, &above_4g_mem_size,

                                      &ram_memory) != 0) {

        fprintf(stderr, "xen hardware virtual machine initialisation failed\n");

        exit(1);

    }

    icc_bridge = qdev_create(NULL, TYPE_ICC_BRIDGE);

    object_property_add_child(qdev_get_machine(), "icc-bridge",

                              OBJECT(icc_bridge), NULL);

    pc_cpus_init(machine->cpu_model, icc_bridge);

    if (kvm_enabled() && kvmclock_enabled) {

        kvmclock_create();

    }

    if (pci_enabled) {

        pci_memory = g_new(MemoryRegion, 1);

        memory_region_init(pci_memory, NULL, "pci", UINT64_MAX);

        rom_memory = pci_memory;

    } else {

        pci_memory = NULL;

        rom_memory = system_memory;

    }

    guest_info = pc_guest_info_init(below_4g_mem_size, above_4g_mem_size);

    guest_info->has_acpi_build = has_acpi_build;

    guest_info->legacy_acpi_table_size = legacy_acpi_table_size;

    guest_info->isapc_ram_fw = !pci_enabled;

    guest_info->has_reserved_memory = has_reserved_memory;

    guest_info->rsdp_in_ram = rsdp_in_ram;

    if (smbios_defaults) {

        MachineClass *mc = MACHINE_GET_CLASS(machine);

        /* These values are guest ABI, do not change */

        smbios_set_defaults("QEMU", "Standard PC (i440FX + PIIX, 1996)",

                            mc->name, smbios_legacy_mode, smbios_uuid_encoded);

    }

    /* allocate ram and load rom/bios */

    if (!xen_enabled()) {

        fw_cfg = pc_memory_init(machine, system_memory,

                                below_4g_mem_size, above_4g_mem_size,

                                rom_memory, &ram_memory, guest_info);

    } else if (machine->kernel_filename != NULL) {

        /* For xen HVM direct kernel boot, load linux here */

        fw_cfg = xen_load_linux(machine->kernel_filename,

                                machine->kernel_cmdline,

                                machine->initrd_filename,

                                below_4g_mem_size,

                                guest_info);

    }

    gsi_state = g_malloc0(sizeof(*gsi_state));

    if (kvm_irqchip_in_kernel()) {

        kvm_pc_setup_irq_routing(pci_enabled);

        gsi = qemu_allocate_irqs(kvm_pc_gsi_handler, gsi_state,

                                 GSI_NUM_PINS);

    } else {

        gsi = qemu_allocate_irqs(gsi_handler, gsi_state, GSI_NUM_PINS);

    }

    if (pci_enabled) {

        pci_bus = i440fx_init(&i440fx_state, &piix3_devfn, &isa_bus, gsi,

                              system_memory, system_io, machine->ram_size,

                              below_4g_mem_size,

                              above_4g_mem_size,

                              pci_memory, ram_memory);

    } else {

        pci_bus = NULL;

        i440fx_state = NULL;

        isa_bus = isa_bus_new(NULL, get_system_memory(), system_io);

        no_hpet = 1;

    }

    isa_bus_irqs(isa_bus, gsi);

    if (kvm_irqchip_in_kernel()) {

        i8259 = kvm_i8259_init(isa_bus);

    } else if (xen_enabled()) {

        i8259 = xen_interrupt_controller_init();

    } else {

        cpu_irq = pc_allocate_cpu_irq();

        i8259 = i8259_init(isa_bus, cpu_irq[0]);

    }

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

        gsi_state->i8259_irq[i] = i8259[i];

    }

    if (pci_enabled) {

        ioapic_init_gsi(gsi_state, "i440fx");

    }

    qdev_init_nofail(icc_bridge);

    pc_register_ferr_irq(gsi[13]);

    pc_vga_init(isa_bus, pci_enabled ? pci_bus : NULL);

    assert(pc_machine->vmport != ON_OFF_AUTO_MAX);

    if (pc_machine->vmport == ON_OFF_AUTO_AUTO) {

        pc_machine->vmport = xen_enabled() ? ON_OFF_AUTO_OFF : ON_OFF_AUTO_ON;

    }

    /* init basic PC hardware */

    pc_basic_device_init(isa_bus, gsi, &rtc_state, true, &floppy,

                         (pc_machine->vmport != ON_OFF_AUTO_ON), 0x4);

    pc_nic_init(isa_bus, pci_bus);

    ide_drive_get(hd, ARRAY_SIZE(hd));

    if (pci_enabled) {

        PCIDevice *dev;

        if (xen_enabled()) {

            dev = pci_piix3_xen_ide_init(pci_bus, hd, piix3_devfn + 1);

        } else {

            dev = pci_piix3_ide_init(pci_bus, hd, piix3_devfn + 1);

        }

        idebus[0] = qdev_get_child_bus(&dev->qdev, "ide.0");

        idebus[1] = qdev_get_child_bus(&dev->qdev, "ide.1");

    } else {

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

            ISADevice *dev;

            char busname[] = "ide.0";

            dev = isa_ide_init(isa_bus, ide_iobase[i], ide_iobase2[i],

                               ide_irq[i],

                               hd[MAX_IDE_DEVS * i], hd[MAX_IDE_DEVS * i + 1]);

            /*

             * The ide bus name is ide.0 for the first bus and ide.1 for the

             * second one.

             */

            busname[4] = '0' + i;

            idebus[i] = qdev_get_child_bus(DEVICE(dev), busname);

        }

    }

    pc_cmos_init(below_4g_mem_size, above_4g_mem_size, machine->boot_order,

                 machine, floppy, idebus[0], idebus[1], rtc_state);

    if (pci_enabled && usb_enabled()) {

        pci_create_simple(pci_bus, piix3_devfn + 2, "piix3-usb-uhci");

    }

    if (pci_enabled && acpi_enabled) {

        DeviceState *piix4_pm;

        I2CBus *smbus;

        smi_irq = qemu_allocate_irqs(pc_acpi_smi_interrupt, first_cpu, 1);

        /* TODO: Populate SPD eeprom data.  */

        smbus = piix4_pm_init(pci_bus, piix3_devfn + 3, 0xb100,

                              gsi[9], *smi_irq,

                              kvm_enabled(), fw_cfg, &piix4_pm);

        smbus_eeprom_init(smbus, 8, NULL, 0);

        object_property_add_link(OBJECT(machine), PC_MACHINE_ACPI_DEVICE_PROP,

                                 TYPE_HOTPLUG_HANDLER,

                                 (Object **)&pc_machine->acpi_dev,

                                 object_property_allow_set_link,

                                 OBJ_PROP_LINK_UNREF_ON_RELEASE, &error_abort);

        object_property_set_link(OBJECT(machine), OBJECT(piix4_pm),

                                 PC_MACHINE_ACPI_DEVICE_PROP, &error_abort);

    }

    if (pci_enabled) {

        pc_pci_device_init(pci_bus);

    }

}


static int get_int32_le(QEMUFile *f, void *pv, size_t size)

{

    int32_t *old = pv;

    int32_t new;

    qemu_get_sbe32s(f, &new);

    if (*old <= new) {

        return 0;

    }

    return -EINVAL;

}


static void load_asl(GArray *sdts, AcpiSdtTable *sdt)

{

    AcpiSdtTable *temp;

    GError *error = NULL;

    GString *command_line = g_string_new("'iasl' ");

    gint fd;

    gchar *out, *out_err;

    gboolean ret;

    int i;

    fd = g_file_open_tmp("asl-XXXXXX.dsl", &sdt->asl_file, &error);

    g_assert_no_error(error);

    close(fd);

    /* build command line */

    g_string_append_printf(command_line, "-p %s ", sdt->asl_file);

    for (i = 0; i < 2; ++i) { /* reference DSDT and SSDT */

        temp = &g_array_index(sdts, AcpiSdtTable, i);

        g_string_append_printf(command_line, "-e %s ", temp->aml_file);

    }

    g_string_append_printf(command_line, "-d %s", sdt->aml_file);

    /* pass 'out' and 'out_err' in order to be redirected */

    g_spawn_command_line_sync(command_line->str, &out, &out_err, NULL, &error);

    g_assert_no_error(error);

    ret = g_file_get_contents(sdt->asl_file, (gchar **)&sdt->asl,

                              &sdt->asl_len, &error);

    g_assert(ret);

    g_assert_no_error(error);

    g_assert(sdt->asl_len);

    g_free(out);

    g_free(out_err);

    g_string_free(command_line, true);

}


static void gen_advance_ccount(DisasContext *dc)

{

    if (dc->ccount_delta > 0) {

        TCGv_i32 tmp = tcg_const_i32(dc->ccount_delta);

        dc->ccount_delta = 0;

        gen_helper_advance_ccount(cpu_env, tmp);

        tcg_temp_free(tmp);

    }

}


static av_cold int libgsm_close(AVCodecContext *avctx) {

    av_freep(&avctx->coded_frame);

    gsm_destroy(avctx->priv_data);

    avctx->priv_data = NULL;

    return 0;

}


static void uhci_ioport_writel(void *opaque, uint32_t addr, uint32_t val)

{

    UHCIState *s = opaque;

    addr &= 0x1f;

#ifdef DEBUG

    printf("uhci writel port=0x%04x val=0x%08x\n", addr, val);

#endif

    switch(addr) {

    case 0x08:

        s->fl_base_addr = val & ~0xfff;

        break;

    }

}


hwaddr x86_cpu_get_phys_page_debug(CPUState *cs, vaddr addr)

{

    X86CPU *cpu = X86_CPU(cs);

    CPUX86State *env = &cpu->env;

    target_ulong pde_addr, pte_addr;

    uint64_t pte;

    hwaddr paddr;

    uint32_t page_offset;

    int page_size;

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

        target_ulong pdpe_addr;

        uint64_t pde, pdpe;

#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)

                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))

                return -1;

            pdpe_addr = ((pml4e & ~0xfff & ~(PG_NX_MASK | PG_HI_USER_MASK)) +

                         (((addr >> 30) & 0x1ff) << 3)) & env->a20_mask;

            pdpe = ldq_phys(pdpe_addr);

            if (!(pdpe & PG_PRESENT_MASK))

                return -1;

        } else

#endif

        {

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

                env->a20_mask;

            pdpe = ldq_phys(pdpe_addr);

            if (!(pdpe & PG_PRESENT_MASK))

                return -1;

        }

        pde_addr = ((pdpe & ~0xfff & ~(PG_NX_MASK | PG_HI_USER_MASK)) +

                    (((addr >> 21) & 0x1ff) << 3)) & env->a20_mask;

        pde = ldq_phys(pde_addr);

        if (!(pde & PG_PRESENT_MASK)) {

            return -1;

        }

        if (pde & PG_PSE_MASK) {

            /* 2 MB page */

            page_size = 2048 * 1024;

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

        } else {

            /* 4 KB page */

            pte_addr = ((pde & ~0xfff & ~(PG_NX_MASK | PG_HI_USER_MASK)) +

                        (((addr >> 12) & 0x1ff) << 3)) & env->a20_mask;

            page_size = 4096;

            pte = ldq_phys(pte_addr);

        }

        pte &= ~(PG_NX_MASK | PG_HI_USER_MASK);

        if (!(pte & PG_PRESENT_MASK))

            return -1;

    } else {

        uint32_t pde;

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

            pte = addr;

            page_size = 4096;

        } else {

            /* 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))

                return -1;

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

                pte = pde & ~0x003ff000; /* align to 4MB */

                page_size = 4096 * 1024;

            } else {

                /* page directory entry */

                pte_addr = ((pde & ~0xfff) + ((addr >> 10) & 0xffc)) & env->a20_mask;

                pte = ldl_phys(pte_addr);

                if (!(pte & PG_PRESENT_MASK))

                    return -1;

                page_size = 4096;

            }

        }

        pte = pte & env->a20_mask;

    }

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

    paddr = (pte & TARGET_PAGE_MASK) + page_offset;

    return paddr;

}


static int hda_audio_init(HDACodecDevice *hda, const struct desc_codec *desc)

{

    HDAAudioState *a = HDA_AUDIO(hda);

    HDAAudioStream *st;

    const desc_node *node;

    const desc_param *param;

    uint32_t i, type;

    a->desc = desc;

    a->name = object_get_typename(OBJECT(a));

    dprint(a, 1, "%s: cad %d\n", __FUNCTION__, a->hda.cad);

    AUD_register_card("hda", &a->card);

    for (i = 0; i < a->desc->nnodes; i++) {

        node = a->desc->nodes + i;

        param = hda_codec_find_param(node, AC_PAR_AUDIO_WIDGET_CAP);

        if (param == NULL) {

            continue;

        }

        type = (param->val & AC_WCAP_TYPE) >> AC_WCAP_TYPE_SHIFT;

        switch (type) {

        case AC_WID_AUD_OUT:

        case AC_WID_AUD_IN:

            assert(node->stindex < ARRAY_SIZE(a->st));

            st = a->st + node->stindex;

            st->state = a;

            st->node = node;

            if (type == AC_WID_AUD_OUT) {

                /* unmute output by default */

                st->gain_left = QEMU_HDA_AMP_STEPS;

                st->gain_right = QEMU_HDA_AMP_STEPS;

                st->bpos = sizeof(st->buf);

                st->output = true;

            } else {

                st->output = false;

            }

            st->format = AC_FMT_TYPE_PCM | AC_FMT_BITS_16 |

                (1 << AC_FMT_CHAN_SHIFT);

            hda_codec_parse_fmt(st->format, &st->as);

            hda_audio_setup(st);

            break;

        }

    }

    return 0;

}


static void xhci_kick_ep(XHCIState *xhci, unsigned int slotid,

                         unsigned int epid, unsigned int streamid)

{

    XHCIStreamContext *stctx;

    XHCIEPContext *epctx;

    XHCIRing *ring;

    USBEndpoint *ep = NULL;

    uint64_t mfindex;

    int length;

    int i;

    trace_usb_xhci_ep_kick(slotid, epid, streamid);

    assert(slotid >= 1 && slotid <= xhci->numslots);

    assert(epid >= 1 && epid <= 31);

    if (!xhci->slots[slotid-1].enabled) {

        DPRINTF("xhci: xhci_kick_ep for disabled slot %d\n", slotid);

        return;

    }

    epctx = xhci->slots[slotid-1].eps[epid-1];

    if (!epctx) {

        DPRINTF("xhci: xhci_kick_ep for disabled endpoint %d,%d\n",

                epid, slotid);

        return;

    }

    /* If the device has been detached, but the guest has not noticed this

       yet the 2 above checks will succeed, but we must NOT continue */

    if (!xhci->slots[slotid - 1].uport ||

        !xhci->slots[slotid - 1].uport->dev ||

        !xhci->slots[slotid - 1].uport->dev->attached) {

        return;

    }

    if (epctx->retry) {

        XHCITransfer *xfer = epctx->retry;

        trace_usb_xhci_xfer_retry(xfer);

        assert(xfer->running_retry);

        if (xfer->timed_xfer) {

            /* time to kick the transfer? */

            mfindex = xhci_mfindex_get(xhci);

            xhci_check_intr_iso_kick(xhci, xfer, epctx, mfindex);

            if (xfer->running_retry) {

                return;

            }

            xfer->timed_xfer = 0;

            xfer->running_retry = 1;

        }

        if (xfer->iso_xfer) {

            /* retry iso transfer */

            if (xhci_setup_packet(xfer) < 0) {

                return;

            }

            usb_handle_packet(xfer->packet.ep->dev, &xfer->packet);

            assert(xfer->packet.status != USB_RET_NAK);

            xhci_complete_packet(xfer);

        } else {

            /* retry nak'ed transfer */

            if (xhci_setup_packet(xfer) < 0) {

                return;

            }

            usb_handle_packet(xfer->packet.ep->dev, &xfer->packet);

            if (xfer->packet.status == USB_RET_NAK) {

                return;

            }

            xhci_complete_packet(xfer);

        }

        assert(!xfer->running_retry);

        epctx->retry = NULL;

    }

    if (epctx->state == EP_HALTED) {

        DPRINTF("xhci: ep halted, not running schedule\n");

        return;

    }

    if (epctx->nr_pstreams) {

        uint32_t err;

        stctx = xhci_find_stream(epctx, streamid, &err);

        if (stctx == NULL) {

            return;

        }

        ring = &stctx->ring;

        xhci_set_ep_state(xhci, epctx, stctx, EP_RUNNING);

    } else {

        ring = &epctx->ring;

        streamid = 0;

        xhci_set_ep_state(xhci, epctx, NULL, EP_RUNNING);

    }

    assert(ring->dequeue != 0);

    while (1) {

        XHCITransfer *xfer = &epctx->transfers[epctx->next_xfer];

        if (xfer->running_async || xfer->running_retry) {

            break;

        }

        length = xhci_ring_chain_length(xhci, ring);

        if (length < 0) {

            break;

        } else if (length == 0) {

            break;

        }

        if (xfer->trbs && xfer->trb_alloced < length) {

            xfer->trb_count = 0;

            xfer->trb_alloced = 0;

            g_free(xfer->trbs);

            xfer->trbs = NULL;

        }

        if (!xfer->trbs) {

            xfer->trbs = g_new(XHCITRB, length);

            xfer->trb_alloced = length;

        }

        xfer->trb_count = length;

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

            TRBType type;

            type = xhci_ring_fetch(xhci, ring, &xfer->trbs[i], NULL);

            assert(type);

        }

        xfer->streamid = streamid;

        if (epid == 1) {

            if (xhci_fire_ctl_transfer(xhci, xfer) >= 0) {

                epctx->next_xfer = (epctx->next_xfer + 1) % TD_QUEUE;

            } else {

                DPRINTF("xhci: error firing CTL transfer\n");

            }

        } else {

            if (xhci_fire_transfer(xhci, xfer, epctx) >= 0) {

                epctx->next_xfer = (epctx->next_xfer + 1) % TD_QUEUE;

            } else {

                if (!xfer->timed_xfer) {

                    DPRINTF("xhci: error firing data transfer\n");

                }

            }

        }

        if (epctx->state == EP_HALTED) {

            break;

        }

        if (xfer->running_retry) {

            DPRINTF("xhci: xfer nacked, stopping schedule\n");

            epctx->retry = xfer;

            break;

        }

    }

    ep = xhci_epid_to_usbep(xhci, slotid, epid);

    if (ep) {

        usb_device_flush_ep_queue(ep->dev, ep);

    }

}


static int pl181_init(SysBusDevice *sbd)

{

    DeviceState *dev = DEVICE(sbd);

    PL181State *s = PL181(dev);

    DriveInfo *dinfo;

    memory_region_init_io(&s->iomem, OBJECT(s), &pl181_ops, s, "pl181", 0x1000);

    sysbus_init_mmio(sbd, &s->iomem);

    sysbus_init_irq(sbd, &s->irq[0]);

    sysbus_init_irq(sbd, &s->irq[1]);

    qdev_init_gpio_out(dev, s->cardstatus, 2);

    dinfo = drive_get_next(IF_SD);

    s->card = sd_init(dinfo ? blk_bs(blk_by_legacy_dinfo(dinfo)) : NULL, false);

    if (s->card == NULL) {

        return -1;

    }

    return 0;

}


static void curl_readv_bh_cb(void *p)

{

    CURLState *state;

    CURLAIOCB *acb = p;

    BDRVCURLState *s = acb->common.bs->opaque;

    qemu_bh_delete(acb->bh);

    acb->bh = NULL;

    size_t start = acb->sector_num * SECTOR_SIZE;

    size_t end;

    // In case we have the requested data already (e.g. read-ahead),

    // we can just call the callback and be done.

    switch (curl_find_buf(s, start, acb->nb_sectors * SECTOR_SIZE, acb)) {

        case FIND_RET_OK:

            qemu_aio_release(acb);

            // fall through

        case FIND_RET_WAIT:

            return;

        default:

            break;

    }

    // No cache found, so let's start a new request

    state = curl_init_state(s);

    if (!state) {

        acb->common.cb(acb->common.opaque, -EIO);

        qemu_aio_release(acb);

        return;

    }

    acb->start = 0;

    acb->end = (acb->nb_sectors * SECTOR_SIZE);

    state->buf_off = 0;

    if (state->orig_buf)

        g_free(state->orig_buf);

    state->buf_start = start;

    state->buf_len = acb->end + s->readahead_size;

    end = MIN(start + state->buf_len, s->len) - 1;

    state->orig_buf = g_malloc(state->buf_len);

    state->acb[0] = acb;

    snprintf(state->range, 127, "%zd-%zd", start, end);

    DPRINTF("CURL (AIO): Reading %d at %zd (%s)\n",

            (acb->nb_sectors * SECTOR_SIZE), start, state->range);

    curl_easy_setopt(state->curl, CURLOPT_RANGE, state->range);

    curl_multi_add_handle(s->multi, state->curl);

    curl_multi_do(s);

}


static void kvm_arm_gic_put(GICState *s)

{

    uint32_t reg;

    int i;

    int cpu;

    int num_cpu;

    int num_irq;

    if (!kvm_arm_gic_can_save_restore(s)) {

            DPRINTF("Cannot put kernel gic state, no kernel interface");

            return;

    }

    /* Note: We do the restore in a slightly different order than the save

     * (where the order doesn't matter and is simply ordered according to the

     * register offset values */

    /*****************************************************************

     * Distributor State

     */

    /* s->enabled -> GICD_CTLR */

    reg = s->enabled;

    kvm_gicd_access(s, 0x0, 0, &reg, true);

    /* Sanity checking on GICD_TYPER and s->num_irq, s->num_cpu */

    kvm_gicd_access(s, 0x4, 0, &reg, false);

    num_irq = ((reg & 0x1f) + 1) * 32;

    num_cpu = ((reg & 0xe0) >> 5) + 1;

    if (num_irq < s->num_irq) {

            fprintf(stderr, "Restoring %u IRQs, but kernel supports max %d\n",

                    s->num_irq, num_irq);

            abort();

    } else if (num_cpu != s->num_cpu) {

            fprintf(stderr, "Restoring %u CPU interfaces, kernel only has %d\n",

                    s->num_cpu, num_cpu);

            /* Did we not create the VCPUs in the kernel yet? */

            abort();

    }

    /* TODO: Consider checking compatibility with the IIDR ? */

    /* irq_state[n].enabled -> GICD_ISENABLERn */

    kvm_dist_put(s, 0x180, 1, s->num_irq, translate_clear);

    kvm_dist_put(s, 0x100, 1, s->num_irq, translate_enabled);

    /* irq_state[n].group -> GICD_IGROUPRn */

    kvm_dist_put(s, 0x80, 1, s->num_irq, translate_group);

    /* s->irq_target[irq] -> GICD_ITARGETSRn

     * (restore targets before pending to ensure the pending state is set on

     * the appropriate CPU interfaces in the kernel) */

    kvm_dist_put(s, 0x800, 8, s->num_irq, translate_targets);

    /* irq_state[n].trigger -> GICD_ICFGRn

     * (restore configuration registers before pending IRQs so we treat

     * level/edge correctly) */

    kvm_dist_put(s, 0xc00, 2, s->num_irq, translate_trigger);

    /* irq_state[n].pending + irq_state[n].level -> GICD_ISPENDRn */

    kvm_dist_put(s, 0x280, 1, s->num_irq, translate_clear);

    kvm_dist_put(s, 0x200, 1, s->num_irq, translate_pending);

    /* irq_state[n].active -> GICD_ISACTIVERn */

    kvm_dist_put(s, 0x380, 1, s->num_irq, translate_clear);

    kvm_dist_put(s, 0x300, 1, s->num_irq, translate_active);

    /* s->priorityX[irq] -> ICD_IPRIORITYRn */

    kvm_dist_put(s, 0x400, 8, s->num_irq, translate_priority);

    /* s->sgi_pending -> ICD_CPENDSGIRn */

    kvm_dist_put(s, 0xf10, 8, GIC_NR_SGIS, translate_clear);

    kvm_dist_put(s, 0xf20, 8, GIC_NR_SGIS, translate_sgisource);

    /*****************************************************************

     * CPU Interface(s) State

     */

    for (cpu = 0; cpu < s->num_cpu; cpu++) {

        /* s->cpu_enabled[cpu] -> GICC_CTLR */

        reg = s->cpu_enabled[cpu];

        kvm_gicc_access(s, 0x00, cpu, &reg, true);

        /* s->priority_mask[cpu] -> GICC_PMR */

        reg = (s->priority_mask[cpu] & 0xff);

        kvm_gicc_access(s, 0x04, cpu, &reg, true);

        /* s->bpr[cpu] -> GICC_BPR */

        reg = (s->bpr[cpu] & 0x7);

        kvm_gicc_access(s, 0x08, cpu, &reg, true);

        /* s->abpr[cpu] -> GICC_ABPR */

        reg = (s->abpr[cpu] & 0x7);

        kvm_gicc_access(s, 0x1c, cpu, &reg, true);

        /* s->apr[n][cpu] -> GICC_APRn */

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

            reg = s->apr[i][cpu];

            kvm_gicc_access(s, 0xd0 + i * 4, cpu, &reg, true);

        }

    }

}


void readline_handle_byte(ReadLineState *rs, int ch)

{

    switch(rs->esc_state) {

    case IS_NORM:

        switch(ch) {

        case 1:

            readline_bol(rs);

            break;

        case 4:

            readline_delete_char(rs);

            break;

        case 5:

            readline_eol(rs);

            break;

        case 9:

            readline_completion(rs);

            break;

        case 10:

        case 13:

            rs->cmd_buf[rs->cmd_buf_size] = '\0';

            if (!rs->read_password)

                readline_hist_add(rs, rs->cmd_buf);

            monitor_printf(rs->mon, "\n");

            rs->cmd_buf_index = 0;

            rs->cmd_buf_size = 0;

            rs->last_cmd_buf_index = 0;

            rs->last_cmd_buf_size = 0;

            rs->readline_func(rs->mon, rs->cmd_buf, rs->readline_opaque);

            break;

        case 23:

            /* ^W */

            readline_backword(rs);

            break;

        case 27:

            rs->esc_state = IS_ESC;

            break;

        case 127:

        case 8:

            readline_backspace(rs);

            break;

	case 155:

            rs->esc_state = IS_CSI;

	    break;

        default:

            if (ch >= 32) {

                readline_insert_char(rs, ch);

            }

            break;

        }

        break;

    case IS_ESC:

        if (ch == '[') {

            rs->esc_state = IS_CSI;

            rs->esc_param = 0;

        } else if (ch == 'O') {

            rs->esc_state = IS_SS3;

            rs->esc_param = 0;

        } else {

            rs->esc_state = IS_NORM;

        }

        break;

    case IS_CSI:

        switch(ch) {

	case 'A':

	case 'F':

	    readline_up_char(rs);

	    break;

	case 'B':

	case 'E':

	    readline_down_char(rs);

	    break;

        case 'D':

            readline_backward_char(rs);

            break;

        case 'C':

            readline_forward_char(rs);

            break;

        case '0' ... '9':

            rs->esc_param = rs->esc_param * 10 + (ch - '0');

            goto the_end;

        case '~':

            switch(rs->esc_param) {

            case 1:

                readline_bol(rs);

                break;

            case 3:

                readline_delete_char(rs);

                break;

            case 4:

                readline_eol(rs);

                break;

            }

            break;

        default:

            break;

        }

        rs->esc_state = IS_NORM;

    the_end:

        break;

    case IS_SS3:

        switch(ch) {

        case 'F':

            readline_eol(rs);

            break;

        case 'H':

            readline_bol(rs);

            break;

        }

        rs->esc_state = IS_NORM;

        break;

    }

    readline_update(rs);

}


static void ats_write(CPUARMState *env, const ARMCPRegInfo *ri, uint64_t value)

{

    hwaddr phys_addr;

    target_ulong page_size;

    int prot;

    int ret, is_user = ri->opc2 & 2;

    int access_type = ri->opc2 & 1;

    ret = get_phys_addr(env, value, access_type, is_user,

                        &phys_addr, &prot, &page_size);

    if (extended_addresses_enabled(env)) {

        /* ret is a DFSR/IFSR value for the long descriptor

         * translation table format, but with WnR always clear.

         * Convert it to a 64-bit PAR.

         */

        uint64_t par64 = (1 << 11); /* LPAE bit always set */

        if (ret == 0) {

            par64 |= phys_addr & ~0xfffULL;

            /* We don't set the ATTR or SH fields in the PAR. */

        } else {

            par64 |= 1; /* F */

            par64 |= (ret & 0x3f) << 1; /* FS */

            /* Note that S2WLK and FSTAGE are always zero, because we don't

             * implement virtualization and therefore there can't be a stage 2

             * fault.

             */

        }

        env->cp15.par_el1 = par64;

    } else {

        /* ret is a DFSR/IFSR value for the short descriptor

         * translation table format (with WnR always clear).

         * Convert it to a 32-bit PAR.

         */

        if (ret == 0) {

            /* We do not set any attribute bits in the PAR */

            if (page_size == (1 << 24)

                && arm_feature(env, ARM_FEATURE_V7)) {

                env->cp15.par_el1 = (phys_addr & 0xff000000) | 1 << 1;

            } else {

                env->cp15.par_el1 = phys_addr & 0xfffff000;

            }

        } else {

            env->cp15.par_el1 = ((ret & (1 << 10)) >> 5) |

                ((ret & (1 << 12)) >> 6) |

                ((ret & 0xf) << 1) | 1;

        }

    }

}


static void test_hybrid_analysis(void)

{

    LOCAL_ALIGNED_16(INTFLOAT, dst0, [BUF_SIZE], [2]);

    LOCAL_ALIGNED_16(INTFLOAT, dst1, [BUF_SIZE], [2]);

    LOCAL_ALIGNED_16(INTFLOAT, in, [12], [2]);

    LOCAL_ALIGNED_16(INTFLOAT, filter, [N], [8][2]);

    declare_func(void, INTFLOAT (*out)[2], INTFLOAT (*in)[2],

                 const INTFLOAT (*filter)[8][2],

                 ptrdiff_t stride, int n);

    randomize((INTFLOAT *)in, 12 * 2);

    randomize((INTFLOAT *)filter, N * 8 * 2);

    randomize((INTFLOAT *)dst0, BUF_SIZE * 2);

    memcpy(dst1, dst0, BUF_SIZE * 2 * sizeof(INTFLOAT));

    call_ref(dst0, in, filter, STRIDE, N);

    call_new(dst1, in, filter, STRIDE, N);

    if (!float_near_abs_eps_array((float *)dst0, (float *)dst1, EPS, BUF_SIZE * 2))

        fail();

    bench_new(dst1, in, filter, STRIDE, N);

}


static void test_qemu_strtoul_full_max(void)

{

    char *str = g_strdup_printf("%lu", ULONG_MAX);

    unsigned long res = 999;

    int err;

    err = qemu_strtoul(str, NULL, 0, &res);

    g_assert_cmpint(err, ==, 0);

    g_assert_cmpint(res, ==, ULONG_MAX);

    g_free(str);

}


static uint64_t assigned_dev_ioport_read(void *opaque,

                                         target_phys_addr_t addr, unsigned size)

{

    return assigned_dev_ioport_rw(opaque, addr, size, NULL);

}


int qemu_ram_addr_from_host(void *ptr, ram_addr_t *ram_addr)

{

    RAMBlock *block;

    uint8_t *host = ptr;

    if (xen_enabled()) {

        *ram_addr = xen_ram_addr_from_mapcache(ptr);

        return 0;

    }

    QTAILQ_FOREACH(block, &ram_list.blocks, next) {

        /* This case append when the block is not mapped. */

        if (block->host == NULL) {

            continue;

        }

        if (host - block->host < block->length) {

            *ram_addr = block->offset + (host - block->host);

            return 0;

        }

    }

    return -1;

}


static void address_space_update_topology_pass(AddressSpace *as,

                                               const FlatView *old_view,

                                               const FlatView *new_view,

                                               bool adding)

{

    unsigned iold, inew;

    FlatRange *frold, *frnew;

    /* Generate a symmetric difference of the old and new memory maps.

     * Kill ranges in the old map, and instantiate ranges in the new map.

     */

    iold = inew = 0;

    while (iold < old_view->nr || inew < new_view->nr) {

        if (iold < old_view->nr) {

            frold = &old_view->ranges[iold];

        } else {

            frold = NULL;

        }

        if (inew < new_view->nr) {

            frnew = &new_view->ranges[inew];

        } else {

            frnew = NULL;

        }

        if (frold

            && (!frnew

                || int128_lt(frold->addr.start, frnew->addr.start)

                || (int128_eq(frold->addr.start, frnew->addr.start)

                    && !flatrange_equal(frold, frnew)))) {

            /* In old but not in new, or in both but attributes changed. */

            if (!adding) {

                MEMORY_LISTENER_UPDATE_REGION(frold, as, Reverse, region_del);

            }

            ++iold;

        } else if (frold && frnew && flatrange_equal(frold, frnew)) {

            /* In both and unchanged (except logging may have changed) */

            if (adding) {

                MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, region_nop);

                if (frold->dirty_log_mask && !frnew->dirty_log_mask) {

                    MEMORY_LISTENER_UPDATE_REGION(frnew, as, Reverse, log_stop);

                } else if (frnew->dirty_log_mask && !frold->dirty_log_mask) {

                    MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, log_start);

                }

            }

            ++iold;

            ++inew;

        } else {

            /* In new */

            if (adding) {

                MEMORY_LISTENER_UPDATE_REGION(frnew, as, Forward, region_add);

            }

            ++inew;

        }

    }

}


static void pxb_dev_exitfn(PCIDevice *pci_dev)

{

    PXBDev *pxb = PXB_DEV(pci_dev);

    pxb_dev_list = g_list_remove(pxb_dev_list, pxb);

}


static void ne2000_write(void *opaque, target_phys_addr_t addr,

                         uint64_t data, unsigned size)

{

    NE2000State *s = opaque;

    if (addr < 0x10 && size == 1) {

        ne2000_ioport_write(s, addr, data);

    } else if (addr == 0x10) {

        if (size <= 2) {

            ne2000_asic_ioport_write(s, addr, data);

        } else {

            ne2000_asic_ioport_writel(s, addr, data);

        }

    } else if (addr == 0x1f && size == 1) {

        ne2000_reset_ioport_write(s, addr, data);

    }

}


static void cuda_writew (void *opaque, target_phys_addr_t addr, uint32_t value)

{

}


void smbios_set_defaults(const char *manufacturer, const char *product,

                         const char *version)

{

    SMBIOS_SET_DEFAULT(type1.manufacturer, manufacturer);

    SMBIOS_SET_DEFAULT(type1.product, product);

    SMBIOS_SET_DEFAULT(type1.version, version);

}


void qio_channel_socket_dgram_async(QIOChannelSocket *ioc,

                                    SocketAddressLegacy *localAddr,

                                    SocketAddressLegacy *remoteAddr,

                                    QIOTaskFunc callback,

                                    gpointer opaque,

                                    GDestroyNotify destroy)

{

    QIOTask *task = qio_task_new(

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

    struct QIOChannelSocketDGramWorkerData *data = g_new0(

        struct QIOChannelSocketDGramWorkerData, 1);

    data->localAddr = QAPI_CLONE(SocketAddressLegacy, localAddr);

    data->remoteAddr = QAPI_CLONE(SocketAddressLegacy, remoteAddr);

    trace_qio_channel_socket_dgram_async(ioc, localAddr, remoteAddr);

    qio_task_run_in_thread(task,

                           qio_channel_socket_dgram_worker,

                           data,

                           qio_channel_socket_dgram_worker_free);

}


static void spawn_thread_bh_fn(void *opaque)

{

    ThreadPool *pool = opaque;

    qemu_mutex_lock(&pool->lock);

    do_spawn_thread(pool);

    qemu_mutex_unlock(&pool->lock);

}


static void ppc_prep_init(MachineState *machine)

{

    ram_addr_t ram_size = machine->ram_size;

    const char *kernel_filename = machine->kernel_filename;

    const char *kernel_cmdline = machine->kernel_cmdline;

    const char *initrd_filename = machine->initrd_filename;

    const char *boot_device = machine->boot_order;

    MemoryRegion *sysmem = get_system_memory();

    PowerPCCPU *cpu = NULL;

    CPUPPCState *env = NULL;

    Nvram *m48t59;

#if 0

    MemoryRegion *xcsr = g_new(MemoryRegion, 1);

#endif

    int linux_boot, i, nb_nics1;

    MemoryRegion *ram = g_new(MemoryRegion, 1);

    uint32_t kernel_base, initrd_base;

    long kernel_size, initrd_size;

    DeviceState *dev;

    PCIHostState *pcihost;

    PCIBus *pci_bus;

    PCIDevice *pci;

    ISABus *isa_bus;

    ISADevice *isa;

    int ppc_boot_device;

    DriveInfo *hd[MAX_IDE_BUS * MAX_IDE_DEVS];

    sysctrl = g_malloc0(sizeof(sysctrl_t));

    linux_boot = (kernel_filename != NULL);

    /* init CPUs */

    if (machine->cpu_model == NULL)

        machine->cpu_model = "602";

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

        cpu = POWERPC_CPU(cpu_generic_init(TYPE_POWERPC_CPU,

                                           machine->cpu_model));

        if (cpu == NULL) {

            fprintf(stderr, "Unable to find PowerPC CPU definition\n");

            exit(1);

        }

        env = &cpu->env;

        if (env->flags & POWERPC_FLAG_RTC_CLK) {

            /* POWER / PowerPC 601 RTC clock frequency is 7.8125 MHz */

            cpu_ppc_tb_init(env, 7812500UL);

        } else {

            /* Set time-base frequency to 100 Mhz */

            cpu_ppc_tb_init(env, 100UL * 1000UL * 1000UL);

        }

        qemu_register_reset(ppc_prep_reset, cpu);

    }

    /* allocate RAM */

    memory_region_allocate_system_memory(ram, NULL, "ppc_prep.ram", ram_size);

    memory_region_add_subregion(sysmem, 0, ram);

    if (linux_boot) {

        kernel_base = KERNEL_LOAD_ADDR;

        /* now we can load the kernel */

        kernel_size = load_image_targphys(kernel_filename, kernel_base,

                                          ram_size - kernel_base);

        if (kernel_size < 0) {

            error_report("could not load kernel '%s'", kernel_filename);

            exit(1);

        }

        /* load initrd */

        if (initrd_filename) {

            initrd_base = INITRD_LOAD_ADDR;

            initrd_size = load_image_targphys(initrd_filename, initrd_base,

                                              ram_size - initrd_base);

            if (initrd_size < 0) {

                error_report("could not load initial ram disk '%s'",

                             initrd_filename);

                exit(1);

            }

        } else {

            initrd_base = 0;

            initrd_size = 0;

        }

        ppc_boot_device = 'm';

    } else {

        kernel_base = 0;

        kernel_size = 0;

        initrd_base = 0;

        initrd_size = 0;

        ppc_boot_device = '\0';

        /* For now, OHW cannot boot from the network. */

        for (i = 0; boot_device[i] != '\0'; i++) {

            if (boot_device[i] >= 'a' && boot_device[i] <= 'f') {

                ppc_boot_device = boot_device[i];

                break;

            }

        }

        if (ppc_boot_device == '\0') {

            fprintf(stderr, "No valid boot device for Mac99 machine\n");

            exit(1);

        }

    }

    if (PPC_INPUT(env) != PPC_FLAGS_INPUT_6xx) {

        error_report("Only 6xx bus is supported on PREP machine");

        exit(1);

    }

    dev = qdev_create(NULL, "raven-pcihost");

    if (bios_name == NULL) {

        bios_name = BIOS_FILENAME;

    }

    qdev_prop_set_string(dev, "bios-name", bios_name);

    qdev_prop_set_uint32(dev, "elf-machine", PPC_ELF_MACHINE);

    pcihost = PCI_HOST_BRIDGE(dev);

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

    qdev_init_nofail(dev);

    pci_bus = (PCIBus *)qdev_get_child_bus(dev, "pci.0");

    if (pci_bus == NULL) {

        fprintf(stderr, "Couldn't create PCI host controller.\n");

        exit(1);

    }

    sysctrl->contiguous_map_irq = qdev_get_gpio_in(dev, 0);

    /* PCI -> ISA bridge */

    pci = pci_create_simple(pci_bus, PCI_DEVFN(1, 0), "i82378");

    cpu = POWERPC_CPU(first_cpu);

    qdev_connect_gpio_out(&pci->qdev, 0,

                          cpu->env.irq_inputs[PPC6xx_INPUT_INT]);

    sysbus_connect_irq(&pcihost->busdev, 0, qdev_get_gpio_in(&pci->qdev, 9));

    sysbus_connect_irq(&pcihost->busdev, 1, qdev_get_gpio_in(&pci->qdev, 11));

    sysbus_connect_irq(&pcihost->busdev, 2, qdev_get_gpio_in(&pci->qdev, 9));

    sysbus_connect_irq(&pcihost->busdev, 3, qdev_get_gpio_in(&pci->qdev, 11));

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

    /* Super I/O (parallel + serial ports) */

    isa = isa_create(isa_bus, TYPE_PC87312);

    dev = DEVICE(isa);

    qdev_prop_set_uint8(dev, "config", 13); /* fdc, ser0, ser1, par0 */

    qdev_init_nofail(dev);

    /* init basic PC hardware */

    pci_vga_init(pci_bus);

    nb_nics1 = nb_nics;

    if (nb_nics1 > NE2000_NB_MAX)

        nb_nics1 = NE2000_NB_MAX;

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

        if (nd_table[i].model == NULL) {

	    nd_table[i].model = g_strdup("ne2k_isa");

        }

        if (strcmp(nd_table[i].model, "ne2k_isa") == 0) {

            isa_ne2000_init(isa_bus, ne2000_io[i], ne2000_irq[i],

                            &nd_table[i]);

        } else {

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

        }

    }

    ide_drive_get(hd, ARRAY_SIZE(hd));

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

        isa_ide_init(isa_bus, ide_iobase[i], ide_iobase2[i], ide_irq[i],

                     hd[2 * i],

		     hd[2 * i + 1]);

    }

    isa_create_simple(isa_bus, "i8042");

    cpu = POWERPC_CPU(first_cpu);

    sysctrl->reset_irq = cpu->env.irq_inputs[PPC6xx_INPUT_HRESET];

    portio_list_init(&prep_port_list, NULL, prep_portio_list, sysctrl, "prep");

    portio_list_add(&prep_port_list, isa_address_space_io(isa), 0x0);

    /* PowerPC control and status register group */

#if 0

    memory_region_init_io(xcsr, NULL, &PPC_XCSR_ops, NULL, "ppc-xcsr", 0x1000);

    memory_region_add_subregion(sysmem, 0xFEFF0000, xcsr);

#endif

    if (machine_usb(machine)) {

        pci_create_simple(pci_bus, -1, "pci-ohci");

    }

    m48t59 = m48t59_init_isa(isa_bus, 0x0074, NVRAM_SIZE, 2000, 59);

    if (m48t59 == NULL)

        return;

    sysctrl->nvram = m48t59;

    /* Initialise NVRAM */

    PPC_NVRAM_set_params(m48t59, NVRAM_SIZE, "PREP", ram_size,

                         ppc_boot_device,

                         kernel_base, kernel_size,

                         kernel_cmdline,

                         initrd_base, initrd_size,

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

                         0,

                         graphic_width, graphic_height, graphic_depth);

}


gen_set_condexec (DisasContext *s)

{

    if (s->condexec_mask) {

        uint32_t val = (s->condexec_cond << 4) | (s->condexec_mask >> 1);

        TCGv tmp = new_tmp();

        tcg_gen_movi_i32(tmp, val);

        store_cpu_field(tmp, condexec_bits);

    }

}


void *mcf_uart_init(qemu_irq irq, CharDriverState *chr)

{

    mcf_uart_state *s;

    s = g_malloc0(sizeof(mcf_uart_state));

    s->chr = chr;

    s->irq = irq;

    if (chr) {

        qemu_chr_add_handlers(chr, mcf_uart_can_receive, mcf_uart_receive,

                              mcf_uart_event, s);

    }

    mcf_uart_reset(s);

    return s;

}


static void parse_waveformatex(AVIOContext *pb, AVCodecParameters *par)

{

    ff_asf_guid subformat;

    par->bits_per_coded_sample = avio_rl16(pb);

    par->channel_layout        = avio_rl32(pb); /* dwChannelMask */

    ff_get_guid(pb, &subformat);

    if (!memcmp(subformat + 4,

                (const uint8_t[]){ FF_MEDIASUBTYPE_BASE_GUID }, 12)) {

        par->codec_tag = AV_RL32(subformat);

        par->codec_id  = ff_wav_codec_get_id(par->codec_tag,

                                             par->bits_per_coded_sample);

    } else {

        par->codec_id = ff_codec_guid_get_id(ff_codec_wav_guids, subformat);

        if (!par->codec_id)

            av_log(pb, AV_LOG_WARNING,

                   "unknown subformat:"FF_PRI_GUID"\n",

                   FF_ARG_GUID(subformat));

    }

}


static int local_unlinkat_common(FsContext *ctx, int dirfd, const char *name,

                                 int flags)

{

    int ret = -1;

    if (ctx->export_flags & V9FS_SM_MAPPED_FILE) {

        int map_dirfd;

        if (flags == AT_REMOVEDIR) {

            int fd;

            fd = openat(dirfd, name, O_RDONLY | O_DIRECTORY | O_PATH);

            if (fd == -1) {

                goto err_out;

            }

            /*

             * If directory remove .virtfs_metadata contained in the

             * directory

             */

            ret = unlinkat(fd, VIRTFS_META_DIR, AT_REMOVEDIR);

            close_preserve_errno(fd);

            if (ret < 0 && errno != ENOENT) {

                /*

                 * We didn't had the .virtfs_metadata file. May be file created

                 * in non-mapped mode ?. Ignore ENOENT.

                 */

                goto err_out;

            }

        }

        /*

         * Now remove the name from parent directory

         * .virtfs_metadata directory.

         */

        map_dirfd = openat_dir(dirfd, VIRTFS_META_DIR);

        ret = unlinkat(map_dirfd, name, 0);

        close_preserve_errno(map_dirfd);

        if (ret < 0 && errno != ENOENT) {

            /*

             * We didn't had the .virtfs_metadata file. May be file created

             * in non-mapped mode ?. Ignore ENOENT.

             */

            goto err_out;

        }

    }

    ret = unlinkat(dirfd, name, flags);

err_out:

    return ret;

}


static void vc1_mc_4mv_luma(VC1Context *v, int n, int dir)
{
    MpegEncContext *s = &v->s;
    DSPContext *dsp = &v->s.dsp;
    uint8_t *srcY;
    int dxy, mx, my, src_x, src_y;
    int off;
    int fieldmv = (v->fcm == ILACE_FRAME) ? v->blk_mv_type[s->block_index[n]] : 0;
    int v_edge_pos = s->v_edge_pos >> v->field_mode;
    if ((!v->field_mode ||
         (v->ref_field_type[dir] == 1 && v->cur_field_type == 1)) &&
        !v->s.last_picture.f.data[0])
    mx = s->mv[dir][n][0];
    my = s->mv[dir][n][1];
    if (!dir) {
        if (v->field_mode) {
            if ((v->cur_field_type != v->ref_field_type[dir]) && v->second_field)
                srcY = s->current_picture.f.data[0];
            else
                srcY = s->last_picture.f.data[0];
        } else
            srcY = s->last_picture.f.data[0];
    } else
        srcY = s->next_picture.f.data[0];
    if (v->field_mode) {
        if (v->cur_field_type != v->ref_field_type[dir])
            my = my - 2 + 4 * v->cur_field_type;
    }
    if (s->pict_type == AV_PICTURE_TYPE_P && n == 3 && v->field_mode) {
        int same_count = 0, opp_count = 0, k;
        int chosen_mv[2][4][2], f;
        int tx, ty;
        for (k = 0; k < 4; k++) {
            f = v->mv_f[0][s->block_index[k] + v->blocks_off];
            chosen_mv[f][f ? opp_count : same_count][0] = s->mv[0][k][0];
            chosen_mv[f][f ? opp_count : same_count][1] = s->mv[0][k][1];
            opp_count  += f;
            same_count += 1 - f;
        }
        f = opp_count > same_count;
        switch (f ? opp_count : same_count) {
        case 4:
            tx = median4(chosen_mv[f][0][0], chosen_mv[f][1][0],
                         chosen_mv[f][2][0], chosen_mv[f][3][0]);
            ty = median4(chosen_mv[f][0][1], chosen_mv[f][1][1],
                         chosen_mv[f][2][1], chosen_mv[f][3][1]);
            break;
        case 3:
            tx = mid_pred(chosen_mv[f][0][0], chosen_mv[f][1][0], chosen_mv[f][2][0]);
            ty = mid_pred(chosen_mv[f][0][1], chosen_mv[f][1][1], chosen_mv[f][2][1]);
            break;
        case 2:
            tx = (chosen_mv[f][0][0] + chosen_mv[f][1][0]) / 2;
            ty = (chosen_mv[f][0][1] + chosen_mv[f][1][1]) / 2;
            break;
        default:
            av_assert2(0);
        }
        s->current_picture.f.motion_val[1][s->block_index[0] + v->blocks_off][0] = tx;
        s->current_picture.f.motion_val[1][s->block_index[0] + v->blocks_off][1] = ty;
        for (k = 0; k < 4; k++)
            v->mv_f[1][s->block_index[k] + v->blocks_off] = f;
    }
    if (v->fcm == ILACE_FRAME) {  // not sure if needed for other types of picture
        int qx, qy;
        int width  = s->avctx->coded_width;
        int height = s->avctx->coded_height >> 1;
        qx = (s->mb_x * 16) + (mx >> 2);
        qy = (s->mb_y *  8) + (my >> 3);
        if (qx < -17)
            mx -= 4 * (qx + 17);
        else if (qx > width)
            mx -= 4 * (qx - width);
        if (qy < -18)
            my -= 8 * (qy + 18);
        else if (qy > height + 1)
            my -= 8 * (qy - height - 1);
    }
    if ((v->fcm == ILACE_FRAME) && fieldmv)
        off = ((n > 1) ? s->linesize : 0) + (n & 1) * 8;
    else
        off = s->linesize * 4 * (n & 2) + (n & 1) * 8;
    if (v->field_mode && v->second_field)
        off += s->current_picture_ptr->f.linesize[0];
    src_x = s->mb_x * 16 + (n & 1) * 8 + (mx >> 2);
    if (!fieldmv)
        src_y = s->mb_y * 16 + (n & 2) * 4 + (my >> 2);
    else
        src_y = s->mb_y * 16 + ((n > 1) ? 1 : 0) + (my >> 2);
    if (v->profile != PROFILE_ADVANCED) {
        src_x = av_clip(src_x, -16, s->mb_width  * 16);
        src_y = av_clip(src_y, -16, s->mb_height * 16);
    } else {
        src_x = av_clip(src_x, -17, s->avctx->coded_width);
        if (v->fcm == ILACE_FRAME) {
            if (src_y & 1)
                src_y = av_clip(src_y, -17, s->avctx->coded_height + 1);
            else
                src_y = av_clip(src_y, -18, s->avctx->coded_height);
        } else {
            src_y = av_clip(src_y, -18, s->avctx->coded_height + 1);
        }
    }
    srcY += src_y * s->linesize + src_x;
    if (v->field_mode && v->ref_field_type[dir])
        srcY += s->current_picture_ptr->f.linesize[0];
    if (fieldmv && !(src_y & 1))
        v_edge_pos--;
    if (fieldmv && (src_y & 1) && src_y < 4)
        src_y--;
    if (v->rangeredfrm || (v->mv_mode == MV_PMODE_INTENSITY_COMP)
        || s->h_edge_pos < 13 || v_edge_pos < 23
        || (unsigned)(src_x - s->mspel) > s->h_edge_pos - (mx & 3) - 8 - s->mspel * 2
        || (unsigned)(src_y - (s->mspel << fieldmv)) > v_edge_pos - (my & 3) - ((8 + s->mspel * 2) << fieldmv)) {
        srcY -= s->mspel * (1 + (s->linesize << fieldmv));
        /* check emulate edge stride and offset */
        s->dsp.emulated_edge_mc(s->edge_emu_buffer, srcY, s->linesize,
                                9 + s->mspel * 2, (9 + s->mspel * 2) << fieldmv,
                                src_x - s->mspel, src_y - (s->mspel << fieldmv),
                                s->h_edge_pos, v_edge_pos);
        srcY = s->edge_emu_buffer;
        /* if we deal with range reduction we need to scale source blocks */
        if (v->rangeredfrm) {
            int i, j;
            uint8_t *src;
            src = srcY;
            for (j = 0; j < 9 + s->mspel * 2; j++) {
                for (i = 0; i < 9 + s->mspel * 2; i++)
                    src[i] = ((src[i] - 128) >> 1) + 128;
                src += s->linesize << fieldmv;
            }
        }
        /* if we deal with intensity compensation we need to scale source blocks */
        if (v->mv_mode == MV_PMODE_INTENSITY_COMP) {
            int i, j;
            uint8_t *src;
            src = srcY;
            for (j = 0; j < 9 + s->mspel * 2; j++) {
                for (i = 0; i < 9 + s->mspel * 2; i++)
                    src[i] = v->luty[src[i]];
                src += s->linesize << fieldmv;
            }
        }
        srcY += s->mspel * (1 + (s->linesize << fieldmv));
    }
    if (s->mspel) {
        dxy = ((my & 3) << 2) | (mx & 3);
        v->vc1dsp.put_vc1_mspel_pixels_tab[dxy](s->dest[0] + off, srcY, s->linesize << fieldmv, v->rnd);
    } else { // hpel mc - always used for luma
        dxy = (my & 2) | ((mx & 2) >> 1);
        if (!v->rnd)
            dsp->put_pixels_tab[1][dxy](s->dest[0] + off, srcY, s->linesize, 8);
        else
            dsp->put_no_rnd_pixels_tab[1][dxy](s->dest[0] + off, srcY, s->linesize, 8);
    }
}


int main(int argc, char **argv)

{

    int ret = EXIT_SUCCESS;

    GAState *s = g_new0(GAState, 1);

    GAConfig *config = g_new0(GAConfig, 1);

    config->log_level = G_LOG_LEVEL_ERROR | G_LOG_LEVEL_CRITICAL;

    module_call_init(MODULE_INIT_QAPI);

    init_dfl_pathnames();

    config_load(config);

    config_parse(config, argc, argv);

    if (config->pid_filepath == NULL) {

        config->pid_filepath = g_strdup(dfl_pathnames.pidfile);

    if (config->state_dir == NULL) {

        config->state_dir = g_strdup(dfl_pathnames.state_dir);

    if (config->method == NULL) {

        config->method = g_strdup("virtio-serial");

    if (config->channel_path == NULL) {

        if (strcmp(config->method, "virtio-serial") == 0) {

            /* try the default path for the virtio-serial port */

            config->channel_path = g_strdup(QGA_VIRTIO_PATH_DEFAULT);

        } else if (strcmp(config->method, "isa-serial") == 0) {

            /* try the default path for the serial port - COM1 */

            config->channel_path = g_strdup(QGA_SERIAL_PATH_DEFAULT);

        } else {

            g_critical("must specify a path for this channel");

            ret = EXIT_FAILURE;

            goto end;

    s->log_level = config->log_level;

    s->log_file = stderr;

#ifdef CONFIG_FSFREEZE

    s->fsfreeze_hook = config->fsfreeze_hook;

#endif

    s->pstate_filepath = g_strdup_printf("%s/qga.state", config->state_dir);

    s->state_filepath_isfrozen = g_strdup_printf("%s/qga.state.isfrozen",

                                                 config->state_dir);

    s->frozen = check_is_frozen(s);

    if (config->dumpconf) {

        config_dump(config);

        goto end;

    ret = run_agent(s, config);

end:

    if (s->command_state) {

        ga_command_state_cleanup_all(s->command_state);

        ga_command_state_free(s->command_state);

        json_message_parser_destroy(&s->parser);

    if (s->channel) {

        ga_channel_free(s->channel);

    g_free(s->pstate_filepath);

    g_free(s->state_filepath_isfrozen);

    if (config->daemonize) {

        unlink(config->pid_filepath);

    config_free(config);

    return ret;


static int gen_rp_interrupts_init(PCIDevice *d, Error **errp)

{

    int rc;

    rc = msix_init_exclusive_bar(d, GEN_PCIE_ROOT_PORT_MSIX_NR_VECTOR, 0);

    if (rc < 0) {

        assert(rc == -ENOTSUP);

        error_setg(errp, "Unable to init msix vectors");

    } else {

        msix_vector_use(d, 0);

    }

    return rc;

}


static int vaapi_decode_make_config(AVCodecContext *avctx)

{

    VAAPIDecodeContext *ctx = avctx->internal->hwaccel_priv_data;

    AVVAAPIHWConfig       *hwconfig    = NULL;

    AVHWFramesConstraints *constraints = NULL;

    VAStatus vas;

    int err, i, j;

    const AVCodecDescriptor *codec_desc;

    VAProfile profile, *profile_list = NULL;

    int profile_count, exact_match, alt_profile;

    const AVPixFmtDescriptor *sw_desc, *desc;

    codec_desc = avcodec_descriptor_get(avctx->codec_id);

    if (!codec_desc) {

        err = AVERROR(EINVAL);

        goto fail;

    }

    profile_count = vaMaxNumProfiles(ctx->hwctx->display);

    profile_list  = av_malloc_array(profile_count,

                                    sizeof(VAProfile));

    if (!profile_list) {

        err = AVERROR(ENOMEM);

        goto fail;

    }

    vas = vaQueryConfigProfiles(ctx->hwctx->display,

                                profile_list, &profile_count);

    if (vas != VA_STATUS_SUCCESS) {

        av_log(avctx, AV_LOG_ERROR, "Failed to query profiles: "

               "%d (%s).\n", vas, vaErrorStr(vas));

        err = AVERROR(ENOSYS);

        goto fail;

    }

    profile = VAProfileNone;

    exact_match = 0;

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

        int profile_match = 0;

        if (avctx->codec_id != vaapi_profile_map[i].codec_id)

            continue;

        if (avctx->profile == vaapi_profile_map[i].codec_profile ||

            vaapi_profile_map[i].codec_profile == FF_PROFILE_UNKNOWN)

            profile_match = 1;

        profile = vaapi_profile_map[i].va_profile;

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

            if (profile == profile_list[j]) {

                exact_match = profile_match;

                break;

            }

        }

        if (j < profile_count) {

            if (exact_match)

                break;

            alt_profile = vaapi_profile_map[i].codec_profile;

        }

    }

    av_freep(&profile_list);

    if (profile == VAProfileNone) {

        av_log(avctx, AV_LOG_ERROR, "No support for codec %s "

               "profile %d.\n", codec_desc->name, avctx->profile);

        err = AVERROR(ENOSYS);

        goto fail;

    }

    if (!exact_match) {

        if (avctx->hwaccel_flags &

            AV_HWACCEL_FLAG_ALLOW_PROFILE_MISMATCH) {

            av_log(avctx, AV_LOG_VERBOSE, "Codec %s profile %d not "

                   "supported for hardware decode.\n",

                   codec_desc->name, avctx->profile);

            av_log(avctx, AV_LOG_WARNING, "Using possibly-"

                   "incompatible profile %d instead.\n",

                   alt_profile);

        } else {

            av_log(avctx, AV_LOG_VERBOSE, "Codec %s profile %d not "

                   "supported for hardware decode.\n",

                   codec_desc->name, avctx->profile);

            err = AVERROR(EINVAL);

            goto fail;

        }

    }

    ctx->va_profile    = profile;

    ctx->va_entrypoint = VAEntrypointVLD;

    vas = vaCreateConfig(ctx->hwctx->display, ctx->va_profile,

                         ctx->va_entrypoint, NULL, 0,

                         &ctx->va_config);

    if (vas != VA_STATUS_SUCCESS) {

        av_log(avctx, AV_LOG_ERROR, "Failed to create decode "

               "configuration: %d (%s).\n", vas, vaErrorStr(vas));

        err = AVERROR(EIO);

        goto fail;

    }

    hwconfig = av_hwdevice_hwconfig_alloc(avctx->hw_device_ctx ?

                                          avctx->hw_device_ctx :

                                          ctx->frames->device_ref);

    if (!hwconfig) {

        err = AVERROR(ENOMEM);

        goto fail;

    }

    hwconfig->config_id = ctx->va_config;

    constraints =

        av_hwdevice_get_hwframe_constraints(avctx->hw_device_ctx ?

                                            avctx->hw_device_ctx :

                                            ctx->frames->device_ref,

                                            hwconfig);

    if (!constraints) {

        err = AVERROR(ENOMEM);

        goto fail;

    }

    if (avctx->coded_width  < constraints->min_width  ||

        avctx->coded_height < constraints->min_height ||

        avctx->coded_width  > constraints->max_width  ||

        avctx->coded_height > constraints->max_height) {

        av_log(avctx, AV_LOG_ERROR, "Hardware does not support image "

               "size %dx%d (constraints: width %d-%d height %d-%d).\n",

               avctx->coded_width, avctx->coded_height,

               constraints->min_width,  constraints->max_width,

               constraints->min_height, constraints->max_height);

        err = AVERROR(EINVAL);

        goto fail;

    }

    if (!constraints->valid_sw_formats ||

        constraints->valid_sw_formats[0] == AV_PIX_FMT_NONE) {

        av_log(avctx, AV_LOG_ERROR, "Hardware does not offer any "

               "usable surface formats.\n");

        err = AVERROR(EINVAL);

        goto fail;

    }

    // Find the first format in the list which matches the expected

    // bit depth and subsampling.  If none are found (this can happen

    // when 10-bit streams are decoded to 8-bit surfaces, for example)

    // then just take the first format on the list.

    ctx->surface_format = constraints->valid_sw_formats[0];

    sw_desc = av_pix_fmt_desc_get(avctx->sw_pix_fmt);

    for (i = 0; constraints->valid_sw_formats[i] != AV_PIX_FMT_NONE; i++) {

        desc = av_pix_fmt_desc_get(constraints->valid_sw_formats[i]);

        if (desc->nb_components != sw_desc->nb_components ||

            desc->log2_chroma_w != sw_desc->log2_chroma_w ||

            desc->log2_chroma_h != sw_desc->log2_chroma_h)

            continue;

        for (j = 0; j < desc->nb_components; j++) {

            if (desc->comp[j].depth != sw_desc->comp[j].depth)

                break;

        }

        if (j < desc->nb_components)

            continue;

        ctx->surface_format = constraints->valid_sw_formats[i];

        break;

    }

    // Start with at least four surfaces.

    ctx->surface_count = 4;

    // Add per-codec number of surfaces used for storing reference frames.

    switch (avctx->codec_id) {

    case AV_CODEC_ID_H264:

    case AV_CODEC_ID_HEVC:

        ctx->surface_count += 16;

        break;

    case AV_CODEC_ID_VP9:

        ctx->surface_count += 8;

        break;

    case AV_CODEC_ID_VP8:

        ctx->surface_count += 3;

        break;

    default:

        ctx->surface_count += 2;

    }

    // Add an additional surface per thread is frame threading is enabled.

    if (avctx->active_thread_type & FF_THREAD_FRAME)

        ctx->surface_count += avctx->thread_count;

    av_hwframe_constraints_free(&constraints);

    av_freep(&hwconfig);

    return 0;

fail:

    av_hwframe_constraints_free(&constraints);

    av_freep(&hwconfig);

    if (ctx->va_config != VA_INVALID_ID) {

        vaDestroyConfig(ctx->hwctx->display, ctx->va_config);

        ctx->va_config = VA_INVALID_ID;

    }

    av_freep(&profile_list);

    return err;

}


static int parse_sandbox(void *opaque, QemuOpts *opts, Error **errp)
{
    if (qemu_opt_get_bool(opts, "enable", false)) {
#ifdef CONFIG_SECCOMP
        uint32_t seccomp_opts = QEMU_SECCOMP_SET_DEFAULT
                | QEMU_SECCOMP_SET_OBSOLETE;
        const char *value = NULL;
        value = qemu_opt_get(opts, "obsolete");
            if (g_str_equal(value, "allow")) {
                seccomp_opts &= ~QEMU_SECCOMP_SET_OBSOLETE;
            } else if (g_str_equal(value, "deny")) {
                /* this is the default option, this if is here
                 * to provide a little bit of consistency for
                 * the command line */
                error_report("invalid argument for obsolete");
        if (seccomp_start(seccomp_opts) < 0) {
            error_report("failed to install seccomp syscall filter "
                         "in the kernel");
#else
        error_report("seccomp support is disabled");
#endif
    return 0;


static const char *search_keyval(const TiffGeoTagKeyName *keys, int n, int id)

{

    return ((TiffGeoTagKeyName*)bsearch(&id, keys, n, sizeof(keys[0]), cmp_id_key))->name;

}


static int wm8750_tx(I2CSlave *i2c, uint8_t data)

{

    WM8750State *s = (WM8750State *) i2c;

    uint8_t cmd;

    uint16_t value;

    if (s->i2c_len >= 2) {

        printf("%s: long message (%i bytes)\n", __FUNCTION__, s->i2c_len);

#ifdef VERBOSE

        return 1;

#endif

    }

    s->i2c_data[s->i2c_len ++] = data;

    if (s->i2c_len != 2)

        return 0;

    cmd = s->i2c_data[0] >> 1;

    value = ((s->i2c_data[0] << 8) | s->i2c_data[1]) & 0x1ff;

    switch (cmd) {

    case WM8750_LADCIN:	/* ADC Signal Path Control (Left) */

        s->diff[0] = (((value >> 6) & 3) == 3);	/* LINSEL */

        if (s->diff[0])

            s->in[0] = &s->adc_voice[0 + s->ds * 1];

        else

            s->in[0] = &s->adc_voice[((value >> 6) & 3) * 1 + 0];

        break;

    case WM8750_RADCIN:	/* ADC Signal Path Control (Right) */

        s->diff[1] = (((value >> 6) & 3) == 3);	/* RINSEL */

        if (s->diff[1])

            s->in[1] = &s->adc_voice[0 + s->ds * 1];

        else

            s->in[1] = &s->adc_voice[((value >> 6) & 3) * 1 + 0];

        break;

    case WM8750_ADCIN:	/* ADC Input Mode */

        s->ds = (value >> 8) & 1;	/* DS */

        if (s->diff[0])

            s->in[0] = &s->adc_voice[0 + s->ds * 1];

        if (s->diff[1])

            s->in[1] = &s->adc_voice[0 + s->ds * 1];

        s->monomix[0] = (value >> 6) & 3;	/* MONOMIX */

        break;

    case WM8750_ADCTL1:	/* Additional Control (1) */

        s->monomix[1] = (value >> 1) & 1;	/* DMONOMIX */

        break;

    case WM8750_PWR1:	/* Power Management (1) */

        s->enable = ((value >> 6) & 7) == 3;	/* VMIDSEL, VREF */

        wm8750_set_format(s);

        break;

    case WM8750_LINVOL:	/* Left Channel PGA */

        s->invol[0] = value & 0x3f;		/* LINVOL */

        s->inmute[0] = (value >> 7) & 1;	/* LINMUTE */

        wm8750_vol_update(s);

        break;

    case WM8750_RINVOL:	/* Right Channel PGA */

        s->invol[1] = value & 0x3f;		/* RINVOL */

        s->inmute[1] = (value >> 7) & 1;	/* RINMUTE */

        wm8750_vol_update(s);

        break;

    case WM8750_ADCDAC:	/* ADC and DAC Control */

        s->pol = (value >> 5) & 3;		/* ADCPOL */

        s->mute = (value >> 3) & 1;		/* DACMU */

        wm8750_vol_update(s);

        break;

    case WM8750_ADCTL3:	/* Additional Control (3) */

        break;

    case WM8750_LADC:	/* Left ADC Digital Volume */

        s->invol[2] = value & 0xff;		/* LADCVOL */

        wm8750_vol_update(s);

        break;

    case WM8750_RADC:	/* Right ADC Digital Volume */

        s->invol[3] = value & 0xff;		/* RADCVOL */

        wm8750_vol_update(s);

        break;

    case WM8750_ALC1:	/* ALC Control (1) */

        s->alc = (value >> 7) & 3;		/* ALCSEL */

        break;

    case WM8750_NGATE:	/* Noise Gate Control */

    case WM8750_3D:	/* 3D enhance */

        break;

    case WM8750_LDAC:	/* Left Channel Digital Volume */

        s->outvol[0] = value & 0xff;		/* LDACVOL */

        wm8750_vol_update(s);

        break;

    case WM8750_RDAC:	/* Right Channel Digital Volume */

        s->outvol[1] = value & 0xff;		/* RDACVOL */

        wm8750_vol_update(s);

        break;

    case WM8750_BASS:	/* Bass Control */

        break;

    case WM8750_LOUTM1:	/* Left Mixer Control (1) */

        s->path[0] = (value >> 8) & 1;		/* LD2LO */

        /* TODO: mute/unmute respective paths */

        wm8750_vol_update(s);

        break;

    case WM8750_LOUTM2:	/* Left Mixer Control (2) */

        s->path[1] = (value >> 8) & 1;		/* RD2LO */

        /* TODO: mute/unmute respective paths */

        wm8750_vol_update(s);

        break;

    case WM8750_ROUTM1:	/* Right Mixer Control (1) */

        s->path[2] = (value >> 8) & 1;		/* LD2RO */

        /* TODO: mute/unmute respective paths */

        wm8750_vol_update(s);

        break;

    case WM8750_ROUTM2:	/* Right Mixer Control (2) */

        s->path[3] = (value >> 8) & 1;		/* RD2RO */

        /* TODO: mute/unmute respective paths */

        wm8750_vol_update(s);

        break;

    case WM8750_MOUTM1:	/* Mono Mixer Control (1) */

        s->mpath[0] = (value >> 8) & 1;		/* LD2MO */

        /* TODO: mute/unmute respective paths */

        wm8750_vol_update(s);

        break;

    case WM8750_MOUTM2:	/* Mono Mixer Control (2) */

        s->mpath[1] = (value >> 8) & 1;		/* RD2MO */

        /* TODO: mute/unmute respective paths */

        wm8750_vol_update(s);

        break;

    case WM8750_LOUT1V:	/* LOUT1 Volume */

        s->outvol[2] = value & 0x7f;		/* LOUT1VOL */

        wm8750_vol_update(s);

        break;

    case WM8750_LOUT2V:	/* LOUT2 Volume */

        s->outvol[4] = value & 0x7f;		/* LOUT2VOL */

        wm8750_vol_update(s);

        break;

    case WM8750_ROUT1V:	/* ROUT1 Volume */

        s->outvol[3] = value & 0x7f;		/* ROUT1VOL */

        wm8750_vol_update(s);

        break;

    case WM8750_ROUT2V:	/* ROUT2 Volume */

        s->outvol[5] = value & 0x7f;		/* ROUT2VOL */

        wm8750_vol_update(s);

        break;

    case WM8750_MOUTV:	/* MONOOUT Volume */

        s->outvol[6] = value & 0x7f;		/* MONOOUTVOL */

        wm8750_vol_update(s);

        break;

    case WM8750_ADCTL2:	/* Additional Control (2) */

        break;

    case WM8750_PWR2:	/* Power Management (2) */

        s->power = value & 0x7e;

        /* TODO: mute/unmute respective paths */

        wm8750_vol_update(s);

        break;

    case WM8750_IFACE:	/* Digital Audio Interface Format */

        s->format = value;

        s->master = (value >> 6) & 1;			/* MS */

        wm8750_clk_update(s, s->master);

        break;

    case WM8750_SRATE:	/* Clocking and Sample Rate Control */

        s->rate = &wm_rate_table[(value >> 1) & 0x1f];

        wm8750_clk_update(s, 0);

        break;

    case WM8750_RESET:	/* Reset */

        wm8750_reset(&s->i2c);

        break;

#ifdef VERBOSE

    default:

        printf("%s: unknown register %02x\n", __FUNCTION__, cmd);

#endif

    }

    return 0;

}


static QDict *qmp_dispatch_check_obj(const QObject *request, Error **errp)

{

    const QDictEntry *ent;

    const char *arg_name;

    const QObject *arg_obj;

    bool has_exec_key = false;

    QDict *dict = NULL;

    dict = qobject_to_qdict(request);

    if (!dict) {

        error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT,

                   "request is not a dictionary");

        return NULL;

    }

    for (ent = qdict_first(dict); ent;

         ent = qdict_next(dict, ent)) {

        arg_name = qdict_entry_key(ent);

        arg_obj = qdict_entry_value(ent);

        if (!strcmp(arg_name, "execute")) {

            if (qobject_type(arg_obj) != QTYPE_QSTRING) {

                error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT_MEMBER, "execute",

                           "string");

                return NULL;

            }

            has_exec_key = true;

        } else if (!strcmp(arg_name, "arguments")) {

            if (qobject_type(arg_obj) != QTYPE_QDICT) {

                error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT_MEMBER,

                           "arguments", "object");

                return NULL;

            }

        } else {

            error_setg(errp, QERR_QMP_EXTRA_MEMBER, arg_name);

            return NULL;

        }

    }

    if (!has_exec_key) {

        error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT, "execute");

        return NULL;

    }

    return dict;

}


static void j2k_flush(J2kDecoderContext *s)

{

    if (*s->buf == 0xff)

        s->buf++;

    s->bit_index = 8;

    s->buf++;

}


av_cold int ff_ac3_encode_close(AVCodecContext *avctx)

{

    int blk, ch;

    AC3EncodeContext *s = avctx->priv_data;

    av_freep(&s->windowed_samples);

    for (ch = 0; ch < s->channels; ch++)

        av_freep(&s->planar_samples[ch]);

    av_freep(&s->planar_samples);

    av_freep(&s->bap_buffer);

    av_freep(&s->bap1_buffer);

    av_freep(&s->mdct_coef_buffer);

    av_freep(&s->fixed_coef_buffer);

    av_freep(&s->exp_buffer);

    av_freep(&s->grouped_exp_buffer);

    av_freep(&s->psd_buffer);

    av_freep(&s->band_psd_buffer);

    av_freep(&s->mask_buffer);

    av_freep(&s->qmant_buffer);

    av_freep(&s->cpl_coord_exp_buffer);

    av_freep(&s->cpl_coord_mant_buffer);

    for (blk = 0; blk < s->num_blocks; blk++) {

        AC3Block *block = &s->blocks[blk];

        av_freep(&block->mdct_coef);

        av_freep(&block->fixed_coef);

        av_freep(&block->exp);

        av_freep(&block->grouped_exp);

        av_freep(&block->psd);

        av_freep(&block->band_psd);

        av_freep(&block->mask);

        av_freep(&block->qmant);

        av_freep(&block->cpl_coord_exp);

        av_freep(&block->cpl_coord_mant);

    }

    s->mdct_end(s);

    return 0;

}


static uint64_t pit_ioport_read(void *opaque, hwaddr addr,
                                unsigned size)
{
    PITCommonState *pit = opaque;
    int ret, count;
    PITChannelState *s;
    addr &= 3;
    s = &pit->channels[addr];
    if (s->status_latched) {
        s->status_latched = 0;
        ret = s->status;
    } else if (s->count_latched) {
        switch(s->count_latched) {
        default:
        case RW_STATE_LSB:
            ret = s->latched_count & 0xff;
            s->count_latched = 0;
            break;
        case RW_STATE_MSB:
            ret = s->latched_count >> 8;
            s->count_latched = 0;
            break;
        case RW_STATE_WORD0:
            ret = s->latched_count & 0xff;
            s->count_latched = RW_STATE_MSB;
            break;
    } else {
        switch(s->read_state) {
        default:
        case RW_STATE_LSB:
            count = pit_get_count(s);
            ret = count & 0xff;
            break;
        case RW_STATE_MSB:
            count = pit_get_count(s);
            ret = (count >> 8) & 0xff;
            break;
        case RW_STATE_WORD0:
            count = pit_get_count(s);
            ret = count & 0xff;
            s->read_state = RW_STATE_WORD1;
            break;
        case RW_STATE_WORD1:
            count = pit_get_count(s);
            ret = (count >> 8) & 0xff;
            s->read_state = RW_STATE_WORD0;
            break;
    return ret;


static int ff_asf_parse_packet(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt)

{

    ASFContext *asf = s->priv_data;

    ASFStream *asf_st = 0;

    for (;;) {

        int ret;

        if(pb->eof_reached)

            return AVERROR_EOF;

        if (asf->packet_size_left < FRAME_HEADER_SIZE

            || asf->packet_segments < 1) {

            //asf->packet_size_left <= asf->packet_padsize) {

            int ret = asf->packet_size_left + asf->packet_padsize;

            //printf("PacketLeftSize:%d  Pad:%d Pos:%"PRId64"\n", asf->packet_size_left, asf->packet_padsize, avio_tell(pb));

            assert(ret>=0);

            /* fail safe */

            avio_skip(pb, ret);

            asf->packet_pos= avio_tell(pb);

            if (asf->data_object_size != (uint64_t)-1 &&

                (asf->packet_pos - asf->data_object_offset >= asf->data_object_size))

                return AVERROR_EOF; /* Do not exceed the size of the data object */

            return 1;

        }

        if (asf->packet_time_start == 0) {

            if(asf_read_frame_header(s, pb) < 0){

                asf->packet_segments= 0;

                continue;

            }

            if (asf->stream_index < 0

                || s->streams[asf->stream_index]->discard >= AVDISCARD_ALL

                || (!asf->packet_key_frame && s->streams[asf->stream_index]->discard >= AVDISCARD_NONKEY)

                ) {

                asf->packet_time_start = 0;

                /* unhandled packet (should not happen) */

                avio_skip(pb, asf->packet_frag_size);

                asf->packet_size_left -= asf->packet_frag_size;

                if(asf->stream_index < 0)

                    av_log(s, AV_LOG_ERROR, "ff asf skip %d (unknown stream)\n", asf->packet_frag_size);

                continue;

            }

            asf->asf_st = s->streams[asf->stream_index]->priv_data;

        }

        asf_st = asf->asf_st;

        if (asf->packet_replic_size == 1) {

            // frag_offset is here used as the beginning timestamp

            asf->packet_frag_timestamp = asf->packet_time_start;

            asf->packet_time_start += asf->packet_time_delta;

            asf->packet_obj_size = asf->packet_frag_size = avio_r8(pb);

            asf->packet_size_left--;

            asf->packet_multi_size--;

            if (asf->packet_multi_size < asf->packet_obj_size)

            {

                asf->packet_time_start = 0;

                avio_skip(pb, asf->packet_multi_size);

                asf->packet_size_left -= asf->packet_multi_size;

                continue;

            }

            asf->packet_multi_size -= asf->packet_obj_size;

            //printf("COMPRESS size  %d  %d  %d   ms:%d\n", asf->packet_obj_size, asf->packet_frag_timestamp, asf->packet_size_left, asf->packet_multi_size);

        }

        if(   /*asf->packet_frag_size == asf->packet_obj_size*/

              asf_st->frag_offset + asf->packet_frag_size <= asf_st->pkt.size

           && asf_st->frag_offset + asf->packet_frag_size > asf->packet_obj_size){

            av_log(s, AV_LOG_INFO, "ignoring invalid packet_obj_size (%d %d %d %d)\n",

                asf_st->frag_offset, asf->packet_frag_size,

                asf->packet_obj_size, asf_st->pkt.size);

            asf->packet_obj_size= asf_st->pkt.size;

        }

        if (   asf_st->pkt.size != asf->packet_obj_size

            || asf_st->frag_offset + asf->packet_frag_size > asf_st->pkt.size) { //FIXME is this condition sufficient?

            if(asf_st->pkt.data){

                av_log(s, AV_LOG_INFO, "freeing incomplete packet size %d, new %d\n", asf_st->pkt.size, asf->packet_obj_size);

                asf_st->frag_offset = 0;

                av_free_packet(&asf_st->pkt);

            }

            /* new packet */

            av_new_packet(&asf_st->pkt, asf->packet_obj_size);

            asf_st->seq = asf->packet_seq;

            asf_st->pkt.dts = asf->packet_frag_timestamp - asf->hdr.preroll;

            asf_st->pkt.stream_index = asf->stream_index;

            asf_st->pkt.pos =

            asf_st->packet_pos= asf->packet_pos;

            if (asf_st->pkt.data && asf_st->palette_changed) {

                uint8_t *pal;

                pal = av_packet_new_side_data(&asf_st->pkt, AV_PKT_DATA_PALETTE,

                                              AVPALETTE_SIZE);

                if (!pal) {

                    av_log(s, AV_LOG_ERROR, "Cannot append palette to packet\n");

                } else {

                    memcpy(pal, asf_st->palette, AVPALETTE_SIZE);

                    asf_st->palette_changed = 0;

                }

            }

//printf("new packet: stream:%d key:%d packet_key:%d audio:%d size:%d\n",

//asf->stream_index, asf->packet_key_frame, asf_st->pkt.flags & AV_PKT_FLAG_KEY,

//s->streams[asf->stream_index]->codec->codec_type == AVMEDIA_TYPE_AUDIO, asf->packet_obj_size);

            if (s->streams[asf->stream_index]->codec->codec_type == AVMEDIA_TYPE_AUDIO)

                asf->packet_key_frame = 1;

            if (asf->packet_key_frame)

                asf_st->pkt.flags |= AV_PKT_FLAG_KEY;

        }

        /* read data */

        //printf("READ PACKET s:%d  os:%d  o:%d,%d  l:%d   DATA:%p\n",

        //       s->packet_size, asf_st->pkt.size, asf->packet_frag_offset,

        //       asf_st->frag_offset, asf->packet_frag_size, asf_st->pkt.data);

        asf->packet_size_left -= asf->packet_frag_size;

        if (asf->packet_size_left < 0)

            continue;

        if(   asf->packet_frag_offset >= asf_st->pkt.size

           || asf->packet_frag_size > asf_st->pkt.size - asf->packet_frag_offset){

            av_log(s, AV_LOG_ERROR, "packet fragment position invalid %u,%u not in %u\n",

                asf->packet_frag_offset, asf->packet_frag_size, asf_st->pkt.size);

            continue;

        }

        ret = avio_read(pb, asf_st->pkt.data + asf->packet_frag_offset,

                         asf->packet_frag_size);

        if (ret != asf->packet_frag_size) {

            if (ret < 0 || asf->packet_frag_offset + ret == 0)

                return ret < 0 ? ret : AVERROR_EOF;

            if (asf_st->ds_span > 1) {

                // scrambling, we can either drop it completely or fill the remainder

                // TODO: should we fill the whole packet instead of just the current

                // fragment?

                memset(asf_st->pkt.data + asf->packet_frag_offset + ret, 0,

                       asf->packet_frag_size - ret);

                ret = asf->packet_frag_size;

            } else

                // no scrambling, so we can return partial packets

                av_shrink_packet(&asf_st->pkt, asf->packet_frag_offset + ret);

        }

        if (s->key && s->keylen == 20)

            ff_asfcrypt_dec(s->key, asf_st->pkt.data + asf->packet_frag_offset,

                            ret);

        asf_st->frag_offset += ret;

        /* test if whole packet is read */

        if (asf_st->frag_offset == asf_st->pkt.size) {

            //workaround for macroshit radio DVR-MS files

            if(   s->streams[asf->stream_index]->codec->codec_id == CODEC_ID_MPEG2VIDEO

               && asf_st->pkt.size > 100){

                int i;

                for(i=0; i<asf_st->pkt.size && !asf_st->pkt.data[i]; i++);

                if(i == asf_st->pkt.size){

                    av_log(s, AV_LOG_DEBUG, "discarding ms fart\n");

                    asf_st->frag_offset = 0;

                    av_free_packet(&asf_st->pkt);

                    continue;

                }

            }

            /* return packet */

            if (asf_st->ds_span > 1) {

              if(asf_st->pkt.size != asf_st->ds_packet_size * asf_st->ds_span){

                    av_log(s, AV_LOG_ERROR, "pkt.size != ds_packet_size * ds_span (%d %d %d)\n", asf_st->pkt.size, asf_st->ds_packet_size, asf_st->ds_span);

              }else{

                /* packet descrambling */

                uint8_t *newdata = av_malloc(asf_st->pkt.size + FF_INPUT_BUFFER_PADDING_SIZE);

                if (newdata) {

                    int offset = 0;

                    memset(newdata + asf_st->pkt.size, 0, FF_INPUT_BUFFER_PADDING_SIZE);

                    while (offset < asf_st->pkt.size) {

                        int off = offset / asf_st->ds_chunk_size;

                        int row = off / asf_st->ds_span;

                        int col = off % asf_st->ds_span;

                        int idx = row + col * asf_st->ds_packet_size / asf_st->ds_chunk_size;

                        //printf("off:%d  row:%d  col:%d  idx:%d\n", off, row, col, idx);

                        assert(offset + asf_st->ds_chunk_size <= asf_st->pkt.size);

                        assert(idx+1 <= asf_st->pkt.size / asf_st->ds_chunk_size);

                        memcpy(newdata + offset,

                               asf_st->pkt.data + idx * asf_st->ds_chunk_size,

                               asf_st->ds_chunk_size);

                        offset += asf_st->ds_chunk_size;

                    }

                    av_free(asf_st->pkt.data);

                    asf_st->pkt.data = newdata;

                }

              }

            }

            asf_st->frag_offset = 0;

            *pkt= asf_st->pkt;

            //printf("packet %d %d\n", asf_st->pkt.size, asf->packet_frag_size);

            asf_st->pkt.size = 0;

            asf_st->pkt.data = 0;

            break; // packet completed

        }

    }

    return 0;

}


static int h264_slice_header_init(H264Context *h, int reinit)

{

    MpegEncContext *const s  = &h->s;

    int i, ret;

    if(   FFALIGN(s->avctx->width , 16                                 ) == s->width

        && FFALIGN(s->avctx->height, 16*(2 - h->sps.frame_mbs_only_flag)) == s->height

        && !h->sps.crop_right && !h->sps.crop_bottom

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

    ) {

        av_log(h->s.avctx, AV_LOG_DEBUG, "Using externally provided dimensions\n");

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

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

    } else{

        avcodec_set_dimensions(s->avctx, s->width, s->height);

        s->avctx->width  -= (2>>CHROMA444)*FFMIN(h->sps.crop_right, (8<<CHROMA444)-1);

        s->avctx->height -= (1<<s->chroma_y_shift)*FFMIN(h->sps.crop_bottom, (16>>s->chroma_y_shift)-1) * (2 - h->sps.frame_mbs_only_flag);

    }

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

    av_assert0(s->avctx->sample_aspect_ratio.den);

    if (h->sps.timing_info_present_flag) {

        int64_t den = h->sps.time_scale;

        if (h->x264_build < 44U)

            den *= 2;

        av_reduce(&s->avctx->time_base.num, &s->avctx->time_base.den,

                  h->sps.num_units_in_tick, den, 1 << 30);

    }

    s->avctx->hwaccel = ff_find_hwaccel(s->avctx->codec->id, s->avctx->pix_fmt);

    if (reinit) {

        free_tables(h, 0);

        if ((ret = ff_MPV_common_frame_size_change(s)) < 0) {

            av_log(h->s.avctx, AV_LOG_ERROR, "ff_MPV_common_frame_size_change() failed.\n");

            return ret;

        }

    } else {

        if ((ret = ff_MPV_common_init(s) < 0)) {

            av_log(h->s.avctx, AV_LOG_ERROR, "ff_MPV_common_init() failed.\n");

            return ret;

        }

    }

    s->first_field = 0;

    h->prev_interlaced_frame = 1;

    init_scan_tables(h);

    if (ff_h264_alloc_tables(h) < 0) {

        av_log(h->s.avctx, AV_LOG_ERROR,

               "Could not allocate memory for h264\n");

        return AVERROR(ENOMEM);

    }

    if (!HAVE_THREADS || !(s->avctx->active_thread_type & FF_THREAD_SLICE)) {

        if (context_init(h) < 0) {

            av_log(h->s.avctx, AV_LOG_ERROR, "context_init() failed.\n");

            return -1;

        }

    } else {

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

            H264Context *c;

            c = h->thread_context[i] = av_malloc(sizeof(H264Context));

            memcpy(c, h->s.thread_context[i], sizeof(MpegEncContext));

            memset(&c->s + 1, 0, sizeof(H264Context) - sizeof(MpegEncContext));

            c->h264dsp     = h->h264dsp;

            c->sps         = h->sps;

            c->pps         = h->pps;

            c->pixel_shift = h->pixel_shift;

            c->cur_chroma_format_idc = h->cur_chroma_format_idc;

            init_scan_tables(c);

            clone_tables(c, h, i);

        }

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

            if (context_init(h->thread_context[i]) < 0) {

                av_log(h->s.avctx, AV_LOG_ERROR, "context_init() failed.\n");

                return -1;

            }

    }

    return 0;

}


void qpci_io_writeb(QPCIDevice *dev, void *data, uint8_t value)

{

    uintptr_t addr = (uintptr_t)data;

    if (addr < QPCI_PIO_LIMIT) {

        dev->bus->pio_writeb(dev->bus, addr, value);

    } else {

        dev->bus->memwrite(dev->bus, addr, &value, sizeof(value));

    }

}


static inline void RENAME(hyscale)(uint16_t *dst, long dstWidth, uint8_t *src, int srcW, int xInc,

				   int flags, int canMMX2BeUsed, int16_t *hLumFilter,

				   int16_t *hLumFilterPos, int hLumFilterSize, void *funnyYCode,

				   int srcFormat, uint8_t *formatConvBuffer, int16_t *mmx2Filter,

				   int32_t *mmx2FilterPos, uint8_t *pal)

{

    if(srcFormat==PIX_FMT_YUYV422 || srcFormat==PIX_FMT_GRAY16BE)

    {

	RENAME(yuy2ToY)(formatConvBuffer, src, srcW);

	src= formatConvBuffer;

    }

    else if(srcFormat==PIX_FMT_UYVY422 || srcFormat==PIX_FMT_GRAY16LE)

    {

	RENAME(uyvyToY)(formatConvBuffer, src, srcW);

	src= formatConvBuffer;

    }

    else if(srcFormat==PIX_FMT_RGB32)

    {

	RENAME(bgr32ToY)(formatConvBuffer, src, srcW);

	src= formatConvBuffer;

    }

    else if(srcFormat==PIX_FMT_BGR24)

    {

	RENAME(bgr24ToY)(formatConvBuffer, src, srcW);

	src= formatConvBuffer;

    }

    else if(srcFormat==PIX_FMT_BGR565)

    {

	RENAME(bgr16ToY)(formatConvBuffer, src, srcW);

	src= formatConvBuffer;

    }

    else if(srcFormat==PIX_FMT_BGR555)

    {

	RENAME(bgr15ToY)(formatConvBuffer, src, srcW);

	src= formatConvBuffer;

    }

    else if(srcFormat==PIX_FMT_BGR32)

    {

	RENAME(rgb32ToY)(formatConvBuffer, src, srcW);

	src= formatConvBuffer;

    }

    else if(srcFormat==PIX_FMT_RGB24)

    {

	RENAME(rgb24ToY)(formatConvBuffer, src, srcW);

	src= formatConvBuffer;

    }

    else if(srcFormat==PIX_FMT_RGB565)

    {

	RENAME(rgb16ToY)(formatConvBuffer, src, srcW);

	src= formatConvBuffer;

    }

    else if(srcFormat==PIX_FMT_RGB555)

    {

	RENAME(rgb15ToY)(formatConvBuffer, src, srcW);

	src= formatConvBuffer;

    }

    else if(srcFormat==PIX_FMT_RGB8 || srcFormat==PIX_FMT_BGR8 || srcFormat==PIX_FMT_PAL8 || srcFormat==PIX_FMT_BGR4_BYTE  || srcFormat==PIX_FMT_RGB4_BYTE)

    {

	RENAME(palToY)(formatConvBuffer, src, srcW, pal);

	src= formatConvBuffer;

    }

#ifdef HAVE_MMX

	// use the new MMX scaler if the mmx2 can't be used (its faster than the x86asm one)

    if(!(flags&SWS_FAST_BILINEAR) || (!canMMX2BeUsed))

#else

    if(!(flags&SWS_FAST_BILINEAR))

#endif

    {

    	RENAME(hScale)(dst, dstWidth, src, srcW, xInc, hLumFilter, hLumFilterPos, hLumFilterSize);

    }

    else // Fast Bilinear upscale / crap downscale

    {

#if defined(ARCH_X86)

#ifdef HAVE_MMX2

	int i;

#if defined(PIC)

	uint64_t ebxsave __attribute__((aligned(8)));

#endif

	if(canMMX2BeUsed)

	{

		asm volatile(

#if defined(PIC)

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

#endif

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

			"mov %0, %%"REG_c"		\n\t"

			"mov %1, %%"REG_D"		\n\t"

			"mov %2, %%"REG_d"		\n\t"

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

			"xor %%"REG_a", %%"REG_a"	\n\t" // i

			PREFETCH" (%%"REG_c")		\n\t"

			PREFETCH" 32(%%"REG_c")		\n\t"

			PREFETCH" 64(%%"REG_c")		\n\t"

#ifdef ARCH_X86_64

#define FUNNY_Y_CODE \

			"movl (%%"REG_b"), %%esi	\n\t"\

			"call *%4			\n\t"\

			"movl (%%"REG_b", %%"REG_a"), %%esi\n\t"\

			"add %%"REG_S", %%"REG_c"	\n\t"\

			"add %%"REG_a", %%"REG_D"	\n\t"\

			"xor %%"REG_a", %%"REG_a"	\n\t"\

#else

#define FUNNY_Y_CODE \

			"movl (%%"REG_b"), %%esi	\n\t"\

			"call *%4			\n\t"\

			"addl (%%"REG_b", %%"REG_a"), %%"REG_c"\n\t"\

			"add %%"REG_a", %%"REG_D"	\n\t"\

			"xor %%"REG_a", %%"REG_a"	\n\t"\

#endif

FUNNY_Y_CODE

FUNNY_Y_CODE

FUNNY_Y_CODE

FUNNY_Y_CODE

FUNNY_Y_CODE

FUNNY_Y_CODE

FUNNY_Y_CODE

FUNNY_Y_CODE

#if defined(PIC)

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

#endif

			:: "m" (src), "m" (dst), "m" (mmx2Filter), "m" (mmx2FilterPos),

			"m" (funnyYCode)

#if defined(PIC)

			,"m" (ebxsave)

#endif

			: "%"REG_a, "%"REG_c, "%"REG_d, "%"REG_S, "%"REG_D

#if !defined(PIC)

			,"%"REG_b

#endif

		);

		for(i=dstWidth-1; (i*xInc)>>16 >=srcW-1; i--) dst[i] = src[srcW-1]*128;

	}

	else

	{

#endif

	long xInc_shr16 = xInc >> 16;

	uint16_t xInc_mask = xInc & 0xffff;

	//NO MMX just normal asm ...

	asm volatile(

		"xor %%"REG_a", %%"REG_a"	\n\t" // i

		"xor %%"REG_d", %%"REG_d"	\n\t" // xx

		"xorl %%ecx, %%ecx		\n\t" // 2*xalpha

		ASMALIGN(4)

		"1:				\n\t"

		"movzbl  (%0, %%"REG_d"), %%edi	\n\t" //src[xx]

		"movzbl 1(%0, %%"REG_d"), %%esi	\n\t" //src[xx+1]

		"subl %%edi, %%esi		\n\t" //src[xx+1] - src[xx]

		"imull %%ecx, %%esi		\n\t" //(src[xx+1] - src[xx])*2*xalpha

		"shll $16, %%edi		\n\t"

		"addl %%edi, %%esi		\n\t" //src[xx+1]*2*xalpha + src[xx]*(1-2*xalpha)

		"mov %1, %%"REG_D"		\n\t"

		"shrl $9, %%esi			\n\t"

		"movw %%si, (%%"REG_D", %%"REG_a", 2)\n\t"

		"addw %4, %%cx			\n\t" //2*xalpha += xInc&0xFF

		"adc %3, %%"REG_d"		\n\t" //xx+= xInc>>8 + carry

		"movzbl (%0, %%"REG_d"), %%edi	\n\t" //src[xx]

		"movzbl 1(%0, %%"REG_d"), %%esi	\n\t" //src[xx+1]

		"subl %%edi, %%esi		\n\t" //src[xx+1] - src[xx]

		"imull %%ecx, %%esi		\n\t" //(src[xx+1] - src[xx])*2*xalpha

		"shll $16, %%edi		\n\t"

		"addl %%edi, %%esi		\n\t" //src[xx+1]*2*xalpha + src[xx]*(1-2*xalpha)

		"mov %1, %%"REG_D"		\n\t"

		"shrl $9, %%esi			\n\t"

		"movw %%si, 2(%%"REG_D", %%"REG_a", 2)\n\t"

		"addw %4, %%cx			\n\t" //2*xalpha += xInc&0xFF

		"adc %3, %%"REG_d"		\n\t" //xx+= xInc>>8 + carry

		"add $2, %%"REG_a"		\n\t"

		"cmp %2, %%"REG_a"		\n\t"

		" jb 1b				\n\t"

		:: "r" (src), "m" (dst), "m" (dstWidth), "m" (xInc_shr16), "m" (xInc_mask)

		: "%"REG_a, "%"REG_d, "%ecx", "%"REG_D, "%esi"

		);

#ifdef HAVE_MMX2

	} //if MMX2 can't be used

#endif

#else

	int i;

	unsigned int xpos=0;

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

	{

		register unsigned int xx=xpos>>16;

		register unsigned int xalpha=(xpos&0xFFFF)>>9;

		dst[i]= (src[xx]<<7) + (src[xx+1] - src[xx])*xalpha;

		xpos+=xInc;

	}

#endif

    }

}


static void ich9_smb_class_init(ObjectClass *klass, void *data)

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);

    k->vendor_id = PCI_VENDOR_ID_INTEL;

    k->device_id = PCI_DEVICE_ID_INTEL_ICH9_6;

    k->revision = ICH9_A2_SMB_REVISION;

    k->class_id = PCI_CLASS_SERIAL_SMBUS;

    dc->no_user = 1;

    dc->vmsd = &vmstate_ich9_smbus;

    dc->desc = "ICH9 SMBUS Bridge";

    k->init = ich9_smbus_initfn;

    k->config_write = ich9_smbus_write_config;

}


bool qemu_file_mode_is_not_valid(const char *mode)

{

    if (mode == NULL ||

        (mode[0] != 'r' && mode[0] != 'w') ||

        mode[1] != 'b' || mode[2] != 0) {

        fprintf(stderr, "qemu_fopen: Argument validity check failed\n");

        return true;

    }

    return false;

}


void qemu_mutex_unlock(QemuMutex *mutex)

{

    assert(mutex->owner == GetCurrentThreadId());

    mutex->owner = 0;

    LeaveCriticalSection(&mutex->lock);

}


void register_watchdogs(void)

{

    wdt_ib700_init();

    wdt_i6300esb_init();

}


static int rtmp_write(URLContext *s, const uint8_t *buf, int size)
{
    RTMPContext *rt = s->priv_data;
    int size_temp = size;
    int pktsize, pkttype;
    uint32_t ts;
    const uint8_t *buf_temp = buf;
    uint8_t c;
    int ret;
    do {
        if (rt->skip_bytes) {
            int skip = FFMIN(rt->skip_bytes, size_temp);
            buf_temp       += skip;
            size_temp      -= skip;
            rt->skip_bytes -= skip;
            continue;
        if (rt->flv_header_bytes < 11) {
            const uint8_t *header = rt->flv_header;
            int copy = FFMIN(11 - rt->flv_header_bytes, size_temp);
            bytestream_get_buffer(&buf_temp, rt->flv_header + rt->flv_header_bytes, copy);
            rt->flv_header_bytes += copy;
            size_temp            -= copy;
            if (rt->flv_header_bytes < 11)
                break;
            pkttype = bytestream_get_byte(&header);
            pktsize = bytestream_get_be24(&header);
            ts = bytestream_get_be24(&header);
            ts |= bytestream_get_byte(&header) << 24;
            bytestream_get_be24(&header);
            rt->flv_size = pktsize;
            //force 12bytes header
            if (((pkttype == RTMP_PT_VIDEO || pkttype == RTMP_PT_AUDIO) && ts == 0) ||
                pkttype == RTMP_PT_NOTIFY) {
                if (pkttype == RTMP_PT_NOTIFY)
                    pktsize += 16;
                rt->prev_pkt[1][RTMP_SOURCE_CHANNEL].channel_id = 0;
            //this can be a big packet, it's better to send it right here
            if ((ret = ff_rtmp_packet_create(&rt->out_pkt, RTMP_SOURCE_CHANNEL,
                                             pkttype, ts, pktsize)) < 0)
            rt->out_pkt.extra = rt->main_channel_id;
            rt->flv_data = rt->out_pkt.data;
            if (pkttype == RTMP_PT_NOTIFY)
                ff_amf_write_string(&rt->flv_data, "@setDataFrame");
        if (rt->flv_size - rt->flv_off > size_temp) {
            bytestream_get_buffer(&buf_temp, rt->flv_data + rt->flv_off, size_temp);
            rt->flv_off += size_temp;
            size_temp = 0;
        } else {
            bytestream_get_buffer(&buf_temp, rt->flv_data + rt->flv_off, rt->flv_size - rt->flv_off);
            size_temp   -= rt->flv_size - rt->flv_off;
            rt->flv_off += rt->flv_size - rt->flv_off;
        if (rt->flv_off == rt->flv_size) {
            rt->skip_bytes = 4;
            if ((ret = ff_rtmp_packet_write(rt->stream, &rt->out_pkt,
                                            rt->chunk_size, rt->prev_pkt[1])) < 0)
            ff_rtmp_packet_destroy(&rt->out_pkt);
            rt->flv_size = 0;
            rt->flv_off = 0;
            rt->flv_header_bytes = 0;
    } while (buf_temp - buf < size);


void ff_thread_flush(AVCodecContext *avctx)

{

    FrameThreadContext *fctx = avctx->thread_opaque;

    if (!avctx->thread_opaque) return;

    park_frame_worker_threads(fctx, avctx->thread_count);

    if (fctx->prev_thread)

        update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0);

    fctx->next_decoding = fctx->next_finished = 0;

    fctx->delaying = 1;

    fctx->prev_thread = NULL;

}


static int check_strtox_error(const char **next, char *endptr,

                              int err)

{

    if (!next && *endptr) {

        return -EINVAL;

    }

    if (next) {

        *next = endptr;

    }

    return -err;

}