static void gen_lea_v_seg(DisasContext *s, TCGMemOp aflag, TCGv a0,

                          int def_seg, int ovr_seg)

{

    switch (aflag) {

#ifdef TARGET_X86_64

    case MO_64:

        if (ovr_seg < 0) {

            tcg_gen_mov_tl(cpu_A0, a0);

            return;

        }

        break;

#endif

    case MO_32:

        /* 32 bit address */

        if (ovr_seg < 0) {

            if (s->addseg) {

                ovr_seg = def_seg;

            } else {

                tcg_gen_ext32u_tl(cpu_A0, a0);

                return;

            }

        }

        break;

    case MO_16:

        /* 16 bit address */

        if (ovr_seg < 0) {

            ovr_seg = def_seg;

        }

        tcg_gen_ext16u_tl(cpu_A0, a0);

        /* ADDSEG will only be false in 16-bit mode for LEA.  */

        if (!s->addseg) {

            return;

        }

        a0 = cpu_A0;

        break;

    default:

        tcg_abort();

    }

    if (ovr_seg >= 0) {

        TCGv seg = tcg_temp_new();

        tcg_gen_ld_tl(seg, cpu_env, offsetof(CPUX86State, segs[ovr_seg].base));

        if (aflag == MO_64) {

            tcg_gen_add_tl(cpu_A0, a0, seg);

        } else if (CODE64(s)) {

            tcg_gen_ext32u_tl(cpu_A0, a0);

            tcg_gen_add_tl(cpu_A0, cpu_A0, seg);

        } else {

            tcg_gen_add_tl(cpu_A0, a0, seg);

            tcg_gen_ext32u_tl(cpu_A0, cpu_A0);

        }

        tcg_temp_free(seg);

    }

}


static void coroutine_fn mirror_run(void *opaque)

{

    MirrorBlockJob *s = opaque;

    MirrorExitData *data;

    BlockDriverState *bs = blk_bs(s->common.blk);

    BlockDriverState *target_bs = blk_bs(s->target);

    int64_t length;

    BlockDriverInfo bdi;

    char backing_filename[2]; /* we only need 2 characters because we are only

                                 checking for a NULL string */

    int ret = 0;

    int target_cluster_size = BDRV_SECTOR_SIZE;

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

        goto immediate_exit;

    }

    s->bdev_length = bdrv_getlength(bs);

    if (s->bdev_length < 0) {

        ret = s->bdev_length;

        goto immediate_exit;

    } else if (s->bdev_length == 0) {

        /* Report BLOCK_JOB_READY and wait for complete. */

        block_job_event_ready(&s->common);

        s->synced = true;

        while (!block_job_is_cancelled(&s->common) && !s->should_complete) {

            block_job_yield(&s->common);

        }

        s->common.cancelled = false;

        goto immediate_exit;

    }

    length = DIV_ROUND_UP(s->bdev_length, s->granularity);

    s->in_flight_bitmap = bitmap_new(length);

    /* If we have no backing file yet in the destination, we cannot let

     * the destination do COW.  Instead, we copy sectors around the

     * dirty data if needed.  We need a bitmap to do that.

     */

    bdrv_get_backing_filename(target_bs, backing_filename,

                              sizeof(backing_filename));

    if (!bdrv_get_info(target_bs, &bdi) && bdi.cluster_size) {

        target_cluster_size = bdi.cluster_size;

    }

    if (backing_filename[0] && !target_bs->backing

        && s->granularity < target_cluster_size) {

        s->buf_size = MAX(s->buf_size, target_cluster_size);

        s->cow_bitmap = bitmap_new(length);

    }

    s->target_cluster_sectors = target_cluster_size >> BDRV_SECTOR_BITS;

    s->max_iov = MIN(bs->bl.max_iov, target_bs->bl.max_iov);

    s->buf = qemu_try_blockalign(bs, s->buf_size);

    if (s->buf == NULL) {

        ret = -ENOMEM;

        goto immediate_exit;

    }

    mirror_free_init(s);

    s->last_pause_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);

    if (!s->is_none_mode) {

        ret = mirror_dirty_init(s);

        if (ret < 0 || block_job_is_cancelled(&s->common)) {

            goto immediate_exit;

        }

    }

    assert(!s->dbi);

    s->dbi = bdrv_dirty_iter_new(s->dirty_bitmap, 0);

    for (;;) {

        uint64_t delay_ns = 0;

        int64_t cnt, delta;

        bool should_complete;

        if (s->ret < 0) {

            ret = s->ret;

            goto immediate_exit;

        }

        block_job_pause_point(&s->common);

        cnt = bdrv_get_dirty_count(s->dirty_bitmap);

        /* s->common.offset contains the number of bytes already processed so

         * far, cnt is the number of dirty sectors remaining and

         * s->sectors_in_flight is the number of sectors currently being

         * processed; together those are the current total operation length */

        s->common.len = s->common.offset +

                        (cnt + s->sectors_in_flight) * BDRV_SECTOR_SIZE;

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

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

         * We do so every SLICE_TIME nanoseconds, or when there is an error,

         * or when the source is clean, whichever comes first.

         */

        delta = qemu_clock_get_ns(QEMU_CLOCK_REALTIME) - s->last_pause_ns;

        if (delta < SLICE_TIME &&

            s->common.iostatus == BLOCK_DEVICE_IO_STATUS_OK) {

            if (s->in_flight >= MAX_IN_FLIGHT || s->buf_free_count == 0 ||

                (cnt == 0 && s->in_flight > 0)) {

                trace_mirror_yield(s, s->in_flight, s->buf_free_count, cnt);

                mirror_wait_for_io(s);

                continue;

            } else if (cnt != 0) {

                delay_ns = mirror_iteration(s);

            }

        }

        should_complete = false;

        if (s->in_flight == 0 && cnt == 0) {

            trace_mirror_before_flush(s);

            ret = blk_flush(s->target);

            if (ret < 0) {

                if (mirror_error_action(s, false, -ret) ==

                    BLOCK_ERROR_ACTION_REPORT) {

                    goto immediate_exit;

                }

            } else {

                /* We're out of the streaming phase.  From now on, if the job

                 * is cancelled we will actually complete all pending I/O and

                 * report completion.  This way, block-job-cancel will leave

                 * the target in a consistent state.

                 */

                if (!s->synced) {

                    block_job_event_ready(&s->common);

                    s->synced = true;

                }

                should_complete = s->should_complete ||

                    block_job_is_cancelled(&s->common);

                cnt = bdrv_get_dirty_count(s->dirty_bitmap);

            }

        }

        if (cnt == 0 && should_complete) {

            /* The dirty bitmap is not updated while operations are pending.

             * If we're about to exit, wait for pending operations before

             * calling bdrv_get_dirty_count(bs), or we may exit while the

             * source has dirty data to copy!

             *

             * Note that I/O can be submitted by the guest while

             * mirror_populate runs.

             */

            trace_mirror_before_drain(s, cnt);

            bdrv_co_drain(bs);

            cnt = bdrv_get_dirty_count(s->dirty_bitmap);

        }

        ret = 0;

        trace_mirror_before_sleep(s, cnt, s->synced, delay_ns);

        if (!s->synced) {

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

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

                break;

            }

        } else if (!should_complete) {

            delay_ns = (s->in_flight == 0 && cnt == 0 ? SLICE_TIME : 0);

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

        } else if (cnt == 0) {

            /* The two disks are in sync.  Exit and report successful

             * completion.

             */

            assert(QLIST_EMPTY(&bs->tracked_requests));

            s->common.cancelled = false;

            break;

        }

        s->last_pause_ns = qemu_clock_get_ns(QEMU_CLOCK_REALTIME);

    }

immediate_exit:

    if (s->in_flight > 0) {

        /* We get here only if something went wrong.  Either the job failed,

         * or it was cancelled prematurely so that we do not guarantee that

         * the target is a copy of the source.

         */

        assert(ret < 0 || (!s->synced && block_job_is_cancelled(&s->common)));

        mirror_drain(s);

    }

    assert(s->in_flight == 0);

    qemu_vfree(s->buf);

    g_free(s->cow_bitmap);

    g_free(s->in_flight_bitmap);

    bdrv_dirty_iter_free(s->dbi);

    bdrv_release_dirty_bitmap(bs, s->dirty_bitmap);

    data = g_malloc(sizeof(*data));

    data->ret = ret;

    /* Before we switch to target in mirror_exit, make sure data doesn't

     * change. */

    bdrv_drained_begin(bs);

    block_job_defer_to_main_loop(&s->common, mirror_exit, data);

}


int check_params(const char * const *params, const char *str)

{

    int name_buf_size = 1;

    const char *p;

    char *name_buf;

    int i, len;

    int ret = 0;

    for (i = 0; params[i] != NULL; i++) {

        len = strlen(params[i]) + 1;

        if (len > name_buf_size) {

            name_buf_size = len;

        }

    }

    name_buf = qemu_malloc(name_buf_size);

    p = str;

    while (*p != '\0') {

        p = get_opt_name(name_buf, name_buf_size, p, '=');

        if (*p != '=') {

            ret = -1;

            break;

        }

        p++;

        for(i = 0; params[i] != NULL; i++)

            if (!strcmp(params[i], name_buf))

                break;

        if (params[i] == NULL) {

            ret = -1;

            break;

        }

        p = get_opt_value(NULL, 0, p);

        if (*p != ',')

            break;

        p++;

    }

    qemu_free(name_buf);

    return ret;

}


static void fw_cfg_data_mem_write(void *opaque, hwaddr addr,

                                  uint64_t value, unsigned size)

{

    fw_cfg_write(opaque, (uint8_t)value);

}


static void simple_whitespace(void)

{

    int i;

    struct {

        const char *encoded;

        LiteralQObject decoded;

    } test_cases[] = {

        {

            .encoded = " [ 43 , 42 ]",

            .decoded = QLIT_QLIST(((LiteralQObject[]){

                        QLIT_QINT(43),

                        QLIT_QINT(42),

                        { }

                    })),

        },

        {

            .encoded = " [ 43 , { 'h' : 'b' }, [ ], 42 ]",

            .decoded = QLIT_QLIST(((LiteralQObject[]){

                        QLIT_QINT(43),

                        QLIT_QDICT(((LiteralQDictEntry[]){

                                    { "h", QLIT_QSTR("b") },

                                    { }})),

                        QLIT_QLIST(((LiteralQObject[]){

                                    { }})),

                        QLIT_QINT(42),

                        { }

                    })),

        },

        {

            .encoded = " [ 43 , { 'h' : 'b' , 'a' : 32 }, [ ], 42 ]",

            .decoded = QLIT_QLIST(((LiteralQObject[]){

                        QLIT_QINT(43),

                        QLIT_QDICT(((LiteralQDictEntry[]){

                                    { "h", QLIT_QSTR("b") },

                                    { "a", QLIT_QINT(32) },

                                    { }})),

                        QLIT_QLIST(((LiteralQObject[]){

                                    { }})),

                        QLIT_QINT(42),

                        { }

                    })),

        },

        { }

    };

    for (i = 0; test_cases[i].encoded; i++) {

        QObject *obj;

        QString *str;

        obj = qobject_from_json(test_cases[i].encoded);

        g_assert(obj != NULL);

        g_assert(qobject_type(obj) == QTYPE_QLIST);

        g_assert(compare_litqobj_to_qobj(&test_cases[i].decoded, obj) == 1);

        str = qobject_to_json(obj);

        qobject_decref(obj);

        obj = qobject_from_json(qstring_get_str(str));

        g_assert(obj != NULL);

        g_assert(qobject_type(obj) == QTYPE_QLIST);

        g_assert(compare_litqobj_to_qobj(&test_cases[i].decoded, obj) == 1);

        qobject_decref(obj);

        QDECREF(str);

    }

}


void cpu_x86_fsave(CPUX86State *s, uint8_t *ptr, int data32)

{

    CPUX86State *saved_env;

    saved_env = env;

    env = s;

    helper_fsave(ptr, data32);

    env = saved_env;

}


int do_migrate_set_speed(Monitor *mon, const QDict *qdict, QObject **ret_data)

{

    int64_t d;

    FdMigrationState *s;

    d = qdict_get_int(qdict, "value");

    d = MAX(0, MIN(UINT32_MAX, d));

    max_throttle = d;

    s = migrate_to_fms(current_migration);

    if (s && s->file) {

        qemu_file_set_rate_limit(s->file, max_throttle);

    }

    return 0;

}


static int proxy_renameat(FsContext *ctx, V9fsPath *olddir,

                          const char *old_name, V9fsPath *newdir,

                          const char *new_name)

{

    int ret;

    V9fsString old_full_name, new_full_name;

    v9fs_string_init(&old_full_name);

    v9fs_string_init(&new_full_name);

    v9fs_string_sprintf(&old_full_name, "%s/%s", olddir->data, old_name);

    v9fs_string_sprintf(&new_full_name, "%s/%s", newdir->data, new_name);

    ret = proxy_rename(ctx, old_full_name.data, new_full_name.data);

    v9fs_string_free(&old_full_name);

    v9fs_string_free(&new_full_name);

    return ret;

}


PCIBus *pci_register_bus(DeviceState *parent, const char *name,

                         pci_set_irq_fn set_irq, pci_map_irq_fn map_irq,

                         qemu_irq *pic, int devfn_min, int nirq)

{

    PCIBus *bus;

    static int nbus = 0;

    bus = FROM_QBUS(PCIBus, qbus_create(&pci_bus_info, parent, name));

    bus->set_irq = set_irq;

    bus->map_irq = map_irq;

    bus->irq_opaque = pic;

    bus->devfn_min = devfn_min;

    bus->nirq = nirq;

    bus->irq_count = qemu_malloc(nirq * sizeof(bus->irq_count[0]));

    bus->next = first_bus;

    first_bus = bus;

    register_savevm("PCIBUS", nbus++, 1, pcibus_save, pcibus_load, bus);

    qemu_register_reset(pci_bus_reset, bus);

    return bus;

}


static int idcin_probe(AVProbeData *p)

{

    unsigned int number;

    /*

     * This is what you could call a "probabilistic" file check: Id CIN

     * files don't have a definite file signature. In lieu of such a marker,

     * perform sanity checks on the 5 32-bit header fields:

     *  width, height: greater than 0, less than or equal to 1024

     * audio sample rate: greater than or equal to 8000, less than or

     *  equal to 48000, or 0 for no audio

     * audio sample width (bytes/sample): 0 for no audio, or 1 or 2

     * audio channels: 0 for no audio, or 1 or 2

     */

    /* cannot proceed without 20 bytes */

    if (p->buf_size < 20)

        return 0;

    /* check the video width */

    number = AV_RL32(&p->buf[0]);

    if ((number == 0) || (number > 1024))

       return 0;

    /* check the video height */

    number = AV_RL32(&p->buf[4]);

    if ((number == 0) || (number > 1024))

       return 0;

    /* check the audio sample rate */

    number = AV_RL32(&p->buf[8]);

    if ((number != 0) && ((number < 8000) | (number > 48000)))

        return 0;

    /* check the audio bytes/sample */

    number = AV_RL32(&p->buf[12]);

    if (number > 2)

        return 0;

    /* check the audio channels */

    number = AV_RL32(&p->buf[16]);

    if (number > 2)

        return 0;

    /* return half certainly since this check is a bit sketchy */

    return AVPROBE_SCORE_MAX / 2;

}


ssize_t migrate_fd_put_buffer(void *opaque, const void *data, size_t size)

{

    FdMigrationState *s = opaque;

    ssize_t ret;

    do {

        ret = s->write(s, data, size);

    } while (ret == -1 && ((s->get_error(s)) == EINTR || (s->get_error(s)) == EWOULDBLOCK));

    if (ret == -1)

        ret = -(s->get_error(s));

    if (ret == -EAGAIN)

        qemu_set_fd_handler2(s->fd, NULL, NULL, migrate_fd_put_notify, s);

    return ret;

}


static void apic_mem_writel(void *opaque, target_phys_addr_t addr, uint32_t val)

{

    DeviceState *d;

    APICCommonState *s;

    int index = (addr >> 4) & 0xff;

    if (addr > 0xfff || !index) {

        /* MSI and MMIO APIC are at the same memory location,

         * but actually not on the global bus: MSI is on PCI bus

         * APIC is connected directly to the CPU.

         * Mapping them on the global bus happens to work because

         * MSI registers are reserved in APIC MMIO and vice versa. */

        apic_send_msi(addr, val);

        return;

    }

    d = cpu_get_current_apic();

    if (!d) {

        return;

    }

    s = DO_UPCAST(APICCommonState, busdev.qdev, d);

    trace_apic_mem_writel(addr, val);

    switch(index) {

    case 0x02:

        s->id = (val >> 24);

        break;

    case 0x03:

        break;

    case 0x08:

        if (apic_report_tpr_access) {

            cpu_report_tpr_access(s->cpu_env, TPR_ACCESS_WRITE);

        }

        s->tpr = val;

        apic_sync_vapic(s, SYNC_TO_VAPIC);

        apic_update_irq(s);

        break;

    case 0x09:

    case 0x0a:

        break;

    case 0x0b: /* EOI */

        apic_eoi(s);

        break;

    case 0x0d:

        s->log_dest = val >> 24;

        break;

    case 0x0e:

        s->dest_mode = val >> 28;

        break;

    case 0x0f:

        s->spurious_vec = val & 0x1ff;

        apic_update_irq(s);

        break;

    case 0x10 ... 0x17:

    case 0x18 ... 0x1f:

    case 0x20 ... 0x27:

    case 0x28:

        break;

    case 0x30:

        s->icr[0] = val;

        apic_deliver(d, (s->icr[1] >> 24) & 0xff, (s->icr[0] >> 11) & 1,

                     (s->icr[0] >> 8) & 7, (s->icr[0] & 0xff),

                     (s->icr[0] >> 15) & 1);

        break;

    case 0x31:

        s->icr[1] = val;

        break;

    case 0x32 ... 0x37:

        {

            int n = index - 0x32;

            s->lvt[n] = val;

            if (n == APIC_LVT_TIMER) {

                apic_timer_update(s, qemu_get_clock_ns(vm_clock));

            } else if (n == APIC_LVT_LINT0 && apic_check_pic(s)) {

                apic_update_irq(s);

            }

        }

        break;

    case 0x38:

        s->initial_count = val;

        s->initial_count_load_time = qemu_get_clock_ns(vm_clock);

        apic_timer_update(s, s->initial_count_load_time);

        break;

    case 0x39:

        break;

    case 0x3e:

        {

            int v;

            s->divide_conf = val & 0xb;

            v = (s->divide_conf & 3) | ((s->divide_conf >> 1) & 4);

            s->count_shift = (v + 1) & 7;

        }

        break;

    default:

        s->esr |= ESR_ILLEGAL_ADDRESS;

        break;

    }

}


static void pxa2xx_gpio_set(void *opaque, int line, int level)

{

    PXA2xxGPIOInfo *s = (PXA2xxGPIOInfo *) opaque;

    CPUState *cpu = CPU(s->cpu);

    int bank;

    uint32_t mask;

    if (line >= s->lines) {

        printf("%s: No GPIO pin %i\n", __FUNCTION__, line);

        return;

    }

    bank = line >> 5;

    mask = 1U << (line & 31);

    if (level) {

        s->status[bank] |= s->rising[bank] & mask &

                ~s->ilevel[bank] & ~s->dir[bank];

        s->ilevel[bank] |= mask;

    } else {

        s->status[bank] |= s->falling[bank] & mask &

                s->ilevel[bank] & ~s->dir[bank];

        s->ilevel[bank] &= ~mask;

    }

    if (s->status[bank] & mask)

        pxa2xx_gpio_irq_update(s);

    /* Wake-up GPIOs */

    if (cpu->halted && (mask & ~s->dir[bank] & pxa2xx_gpio_wake[bank])) {

        cpu_interrupt(cpu, CPU_INTERRUPT_EXITTB);

    }

}


int vhost_net_start(struct vhost_net *net,

                    VirtIODevice *dev)

{

    struct vhost_vring_file file = { };

    int r;

    if (net->dev.acked_features & (1 << VIRTIO_NET_F_MRG_RXBUF)) {

        tap_set_vnet_hdr_len(net->vc,

                             sizeof(struct virtio_net_hdr_mrg_rxbuf));

    }

    net->dev.nvqs = 2;

    net->dev.vqs = net->vqs;

    r = vhost_dev_start(&net->dev, dev);

    if (r < 0) {

        return r;

    }

    net->vc->info->poll(net->vc, false);

    qemu_set_fd_handler(net->backend, NULL, NULL, NULL);

    file.fd = net->backend;

    for (file.index = 0; file.index < net->dev.nvqs; ++file.index) {

        r = ioctl(net->dev.control, VHOST_NET_SET_BACKEND, &file);

        if (r < 0) {

            r = -errno;

            goto fail;

        }

    }

    return 0;

fail:

    file.fd = -1;

    while (--file.index >= 0) {

        int r = ioctl(net->dev.control, VHOST_NET_SET_BACKEND, &file);

        assert(r >= 0);

    }

    net->vc->info->poll(net->vc, true);

    vhost_dev_stop(&net->dev, dev);

    if (net->dev.acked_features & (1 << VIRTIO_NET_F_MRG_RXBUF)) {

        tap_set_vnet_hdr_len(net->vc, sizeof(struct virtio_net_hdr));

    }

    return r;

}


static int iscsi_create(const char *filename, QEMUOptionParameter *options,

                        Error **errp)

{

    int ret = 0;

    int64_t total_size = 0;

    BlockDriverState *bs;

    IscsiLun *iscsilun = NULL;

    QDict *bs_options;

    bs = bdrv_new("");

    /* Read out options */

    while (options && options->name) {

        if (!strcmp(options->name, "size")) {

            total_size = options->value.n / BDRV_SECTOR_SIZE;

        }

        options++;

    }

    bs->opaque = g_malloc0(sizeof(struct IscsiLun));

    iscsilun = bs->opaque;

    bs_options = qdict_new();

    qdict_put(bs_options, "filename", qstring_from_str(filename));

    ret = iscsi_open(bs, bs_options, 0, NULL);

    QDECREF(bs_options);

    if (ret != 0) {

        goto out;

    }

    if (iscsilun->nop_timer) {

        timer_del(iscsilun->nop_timer);

        timer_free(iscsilun->nop_timer);

    }

    if (iscsilun->type != TYPE_DISK) {

        ret = -ENODEV;

        goto out;

    }

    if (bs->total_sectors < total_size) {

        ret = -ENOSPC;

        goto out;

    }

    ret = 0;

out:

    if (iscsilun->iscsi != NULL) {

        iscsi_destroy_context(iscsilun->iscsi);

    }

    g_free(bs->opaque);

    bs->opaque = NULL;

    bdrv_unref(bs);

    return ret;

}


static void virtio_init_region_cache(VirtIODevice *vdev, int n)

{

    VirtQueue *vq = &vdev->vq[n];

    VRingMemoryRegionCaches *old = vq->vring.caches;

    VRingMemoryRegionCaches *new;

    hwaddr addr, size;

    int event_size;

    event_size = virtio_vdev_has_feature(vq->vdev, VIRTIO_RING_F_EVENT_IDX) ? 2 : 0;

    addr = vq->vring.desc;

    if (!addr) {

        return;

    }

    new = g_new0(VRingMemoryRegionCaches, 1);

    size = virtio_queue_get_desc_size(vdev, n);

    address_space_cache_init(&new->desc, vdev->dma_as,

                             addr, size, false);

    size = virtio_queue_get_used_size(vdev, n) + event_size;

    address_space_cache_init(&new->used, vdev->dma_as,

                             vq->vring.used, size, true);

    size = virtio_queue_get_avail_size(vdev, n) + event_size;

    address_space_cache_init(&new->avail, vdev->dma_as,

                             vq->vring.avail, size, false);

    atomic_rcu_set(&vq->vring.caches, new);

    if (old) {

        call_rcu(old, virtio_free_region_cache, rcu);

    }

}


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

{

    XilinxSPIPS *s = XILINX_SPIPS(dev);

    SysBusDevice *sbd = SYS_BUS_DEVICE(dev);

    XilinxSPIPSClass *xsc = XILINX_SPIPS_GET_CLASS(s);

    int i;

    DB_PRINT("realized spips\n");

    s->spi = g_new(SSIBus *, s->num_busses);

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

        char bus_name[16];

        snprintf(bus_name, 16, "spi%d", i);

        s->spi[i] = ssi_create_bus(dev, bus_name);

    }

    s->cs_lines = g_new0(qemu_irq, s->num_cs * s->num_busses);

    ssi_auto_connect_slaves(DEVICE(s), s->cs_lines, s->spi[0]);

    ssi_auto_connect_slaves(DEVICE(s), s->cs_lines, s->spi[1]);

    sysbus_init_irq(sbd, &s->irq);

    for (i = 0; i < s->num_cs * s->num_busses; ++i) {

        sysbus_init_irq(sbd, &s->cs_lines[i]);

    }

    memory_region_init_io(&s->iomem, &spips_ops, s, "spi", R_MAX*4);

    sysbus_init_mmio(sbd, &s->iomem);

    s->irqline = -1;

    fifo8_create(&s->rx_fifo, xsc->rx_fifo_size);

    fifo8_create(&s->tx_fifo, xsc->tx_fifo_size);

}


static int read_key(void)

{

#if defined(HAVE_CONIO_H)

    if(kbhit())

        return(getch());

#elif defined(HAVE_TERMIOS_H)

    int n = 1;

    unsigned char ch;

#ifndef CONFIG_BEOS_NETSERVER

    struct timeval tv;

    fd_set rfds;

    FD_ZERO(&rfds);

    FD_SET(0, &rfds);

    tv.tv_sec = 0;

    tv.tv_usec = 0;

    n = select(1, &rfds, NULL, NULL, &tv);

#endif

    if (n > 0) {

        n = read(0, &ch, 1);

        if (n == 1)

            return ch;

        return n;

    }

#endif

    return -1;

}


static bool virtio_scsi_data_plane_handle_event(VirtIODevice *vdev,

                                                VirtQueue *vq)

{

    VirtIOSCSI *s = VIRTIO_SCSI(vdev);

    assert(s->ctx && s->dataplane_started);

    return virtio_scsi_handle_event_vq(s, vq);

}


opts_next_list(Visitor *v, GenericList **list, size_t size)

{

    OptsVisitor *ov = to_ov(v);

    GenericList **link;

    switch (ov->list_mode) {

    case LM_STARTED:

        ov->list_mode = LM_IN_PROGRESS;

        link = list;

        break;

    case LM_SIGNED_INTERVAL:

    case LM_UNSIGNED_INTERVAL:

        link = &(*list)->next;

        if (ov->list_mode == LM_SIGNED_INTERVAL) {

            if (ov->range_next.s < ov->range_limit.s) {

                ++ov->range_next.s;

                break;

            }

        } else if (ov->range_next.u < ov->range_limit.u) {

            ++ov->range_next.u;

            break;

        }

        ov->list_mode = LM_IN_PROGRESS;

        /* range has been completed, fall through in order to pop option */

    case LM_IN_PROGRESS: {

        const QemuOpt *opt;

        opt = g_queue_pop_head(ov->repeated_opts);

        if (g_queue_is_empty(ov->repeated_opts)) {

            g_hash_table_remove(ov->unprocessed_opts, opt->name);

            return NULL;

        }

        link = &(*list)->next;

        break;

    }

    default:

        abort();

    }

    *link = g_malloc0(size);

    return *link;

}


static int vnc_display_get_addresses(QemuOpts *opts,

                                     bool reverse,

                                     SocketAddress ***retsaddr,

                                     size_t *retnsaddr,

                                     SocketAddress ***retwsaddr,

                                     size_t *retnwsaddr,

                                     Error **errp)

{

    SocketAddress *saddr = NULL;

    SocketAddress *wsaddr = NULL;

    QemuOptsIter addriter;

    const char *addr;

    int to = qemu_opt_get_number(opts, "to", 0);

    bool has_ipv4 = qemu_opt_get(opts, "ipv4");

    bool has_ipv6 = qemu_opt_get(opts, "ipv6");

    bool ipv4 = qemu_opt_get_bool(opts, "ipv4", false);

    bool ipv6 = qemu_opt_get_bool(opts, "ipv6", false);

    size_t i;

    int displaynum = -1;

    int ret = -1;

    *retsaddr = NULL;

    *retnsaddr = 0;

    *retwsaddr = NULL;

    *retnwsaddr = 0;

    addr = qemu_opt_get(opts, "vnc");

    if (addr == NULL || g_str_equal(addr, "none")) {

        ret = 0;

        goto cleanup;

    }

    if (qemu_opt_get(opts, "websocket") &&

        !qcrypto_hash_supports(QCRYPTO_HASH_ALG_SHA1)) {

        error_setg(errp,

                   "SHA1 hash support is required for websockets");

        goto cleanup;

    }

    qemu_opt_iter_init(&addriter, opts, "vnc");

    while ((addr = qemu_opt_iter_next(&addriter)) != NULL) {

        int rv;

        rv = vnc_display_get_address(addr, false, reverse, 0, to,

                                     has_ipv4, has_ipv6,

                                     ipv4, ipv6,

                                     &saddr, errp);

        if (rv < 0) {

            goto cleanup;

        }

        /* Historical compat - first listen address can be used

         * to set the default websocket port

         */

        if (displaynum == -1) {

            displaynum = rv;

        }

        *retsaddr = g_renew(SocketAddress *, *retsaddr, *retnsaddr + 1);

        (*retsaddr)[(*retnsaddr)++] = saddr;

    }

    /* If we had multiple primary displays, we don't do defaults

     * for websocket, and require explicit config instead. */

    if (*retnsaddr > 1) {

        displaynum = -1;

    }

    qemu_opt_iter_init(&addriter, opts, "websocket");

    while ((addr = qemu_opt_iter_next(&addriter)) != NULL) {

        if (vnc_display_get_address(addr, true, reverse, displaynum, to,

                                    has_ipv4, has_ipv6,

                                    ipv4, ipv6,

                                    &wsaddr, errp) < 0) {

            goto cleanup;

        }

        /* Historical compat - if only a single listen address was

         * provided, then this is used to set the default listen

         * address for websocket too

         */

        if (*retnsaddr == 1 &&

            (*retsaddr)[0]->type == SOCKET_ADDRESS_KIND_INET &&

            wsaddr->type == SOCKET_ADDRESS_KIND_INET &&

            g_str_equal(wsaddr->u.inet.data->host, "") &&

            !g_str_equal((*retsaddr)[0]->u.inet.data->host, "")) {

            g_free(wsaddr->u.inet.data->host);

            wsaddr->u.inet.data->host =

                g_strdup((*retsaddr)[0]->u.inet.data->host);

        }

        *retwsaddr = g_renew(SocketAddress *, *retwsaddr, *retnwsaddr + 1);

        (*retwsaddr)[(*retnwsaddr)++] = wsaddr;

    }

    ret = 0;

 cleanup:

    if (ret < 0) {

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

            qapi_free_SocketAddress((*retsaddr)[i]);

        }

        g_free(*retsaddr);

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

            qapi_free_SocketAddress((*retwsaddr)[i]);

        }

        g_free(*retwsaddr);

        *retsaddr = *retwsaddr = NULL;

        *retnsaddr = *retnwsaddr = 0;

    }

    return ret;

}


static int spapr_create_pci_child_dt(sPAPRPHBState *phb, PCIDevice *dev,

                                     void *fdt, int node_offset)

{

    int offset, ret;

    char nodename[FDT_NAME_MAX];

    pci_get_node_name(nodename, FDT_NAME_MAX, dev);

    offset = fdt_add_subnode(fdt, node_offset, nodename);

    ret = spapr_populate_pci_child_dt(dev, fdt, offset, phb);

    g_assert(!ret);

    if (ret) {

        return 0;

    }

    return offset;

}


static void slavio_timer_irq(void *opaque)

{

    TimerContext *tc = opaque;

    SLAVIO_TIMERState *s = tc->s;

    CPUTimerState *t = &s->cputimer[tc->timer_index];

    slavio_timer_get_out(t);

    DPRINTF("callback: count %x%08x\n", t->counthigh, t->count);

    t->reached = TIMER_REACHED;

    /* there is no interrupt if user timer or free-run */

    if (!slavio_timer_is_user(tc) && t->limit != 0) {

        qemu_irq_raise(t->irq);

    }

}


uint64_t helper_fre (uint64_t arg)

{

    CPU_DoubleU fone, farg;

    fone.ll = 0x3FF0000000000000ULL; /* 1.0 */

    farg.ll = arg;

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

        /* sNaN reciprocal */

        farg.ll = fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN);

    } else if (unlikely(float64_is_zero(farg.d))) {

        /* Zero reciprocal */

        farg.ll = float_zero_divide_excp(fone.d, farg.d);

    } else if (likely(isnormal(farg.d))) {

        farg.d = float64_div(fone.d, farg.d, &env->fp_status);

    } else {

        if (farg.ll == 0x8000000000000000ULL) {

            farg.ll = 0xFFF0000000000000ULL;

        } else if (farg.ll == 0x0000000000000000ULL) {

            farg.ll = 0x7FF0000000000000ULL;

        } else if (float64_is_nan(farg.d)) {

            farg.ll = 0x7FF8000000000000ULL;

        } else if (float64_is_neg(farg.d)) {

            farg.ll = 0x8000000000000000ULL;

        } else {

            farg.ll = 0x0000000000000000ULL;

        }

    }

    return farg.d;

}


static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)

{

    int64_t ret;

    int n;

    convert_select_part(s, sector_num);

    assert(s->total_sectors > sector_num);

    n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);

    if (s->sector_next_status <= sector_num) {

        BlockDriverState *file;

        ret = bdrv_get_block_status(blk_bs(s->src[s->src_cur]),

                                    sector_num - s->src_cur_offset,

                                    n, &n, &file);

        if (ret < 0) {

            return ret;

        }

        if (ret & BDRV_BLOCK_ZERO) {

            s->status = BLK_ZERO;

        } else if (ret & BDRV_BLOCK_DATA) {

            s->status = BLK_DATA;

        } else if (!s->target_has_backing) {

            /* Without a target backing file we must copy over the contents of

             * the backing file as well. */

            /* TODO Check block status of the backing file chain to avoid

             * needlessly reading zeroes and limiting the iteration to the

             * buffer size */

            s->status = BLK_DATA;

        } else {

            s->status = BLK_BACKING_FILE;

        }

        s->sector_next_status = sector_num + n;

    }

    n = MIN(n, s->sector_next_status - sector_num);

    if (s->status == BLK_DATA) {

        n = MIN(n, s->buf_sectors);

    }

    /* We need to write complete clusters for compressed images, so if an

     * unallocated area is shorter than that, we must consider the whole

     * cluster allocated. */

    if (s->compressed) {

        if (n < s->cluster_sectors) {

            n = MIN(s->cluster_sectors, s->total_sectors - sector_num);

            s->status = BLK_DATA;

        } else {

            n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);

        }

    }

    return n;

}


uint32_t HELPER(mvcs)(CPUS390XState *env, uint64_t l, uint64_t a1, uint64_t a2)

{

    HELPER_LOG("%s: %16" PRIx64 " %16" PRIx64 " %16" PRIx64 "\n",

               __func__, l, a1, a2);

    return mvc_asc(env, l, a1, PSW_ASC_SECONDARY, a2, PSW_ASC_PRIMARY);

}


static int oss_run_out (HWVoiceOut *hw)

{

    OSSVoiceOut *oss = (OSSVoiceOut *) hw;

    int err, rpos, live, decr;

    int samples;

    uint8_t *dst;

    st_sample_t *src;

    struct audio_buf_info abinfo;

    struct count_info cntinfo;

    int bufsize;

    live = audio_pcm_hw_get_live_out (hw);

    if (!live) {

        return 0;

    }

    bufsize = hw->samples << hw->info.shift;

    if (oss->mmapped) {

        int bytes;

        err = ioctl (oss->fd, SNDCTL_DSP_GETOPTR, &cntinfo);

        if (err < 0) {

            oss_logerr (errno, "SNDCTL_DSP_GETOPTR failed\n");

            return 0;

        }

        if (cntinfo.ptr == oss->old_optr) {

            if (abs (hw->samples - live) < 64) {

                dolog ("warning: Overrun\n");

            }

            return 0;

        }

        if (cntinfo.ptr > oss->old_optr) {

            bytes = cntinfo.ptr - oss->old_optr;

        }

        else {

            bytes = bufsize + cntinfo.ptr - oss->old_optr;

        }

        decr = audio_MIN (bytes >> hw->info.shift, live);

    }

    else {

        err = ioctl (oss->fd, SNDCTL_DSP_GETOSPACE, &abinfo);

        if (err < 0) {

            oss_logerr (errno, "SNDCTL_DSP_GETOPTR failed\n");

            return 0;

        }

        if (abinfo.bytes > bufsize) {

            if (conf.debug) {

                dolog ("warning: Invalid available size, size=%d bufsize=%d\n"

                       "please report your OS/audio hw to malc@pulsesoft.com\n",

                       abinfo.bytes, bufsize);

            }

            abinfo.bytes = bufsize;

        }

        if (abinfo.bytes < 0) {

            if (conf.debug) {

                dolog ("warning: Invalid available size, size=%d bufsize=%d\n",

                       abinfo.bytes, bufsize);

            }

            return 0;

        }

        decr = audio_MIN (abinfo.bytes >> hw->info.shift, live);

        if (!decr) {

            return 0;

        }

    }

    samples = decr;

    rpos = hw->rpos;

    while (samples) {

        int left_till_end_samples = hw->samples - rpos;

        int convert_samples = audio_MIN (samples, left_till_end_samples);

        src = hw->mix_buf + rpos;

        dst = advance (oss->pcm_buf, rpos << hw->info.shift);

        hw->clip (dst, src, convert_samples);

        if (!oss->mmapped) {

            int written;

            written = write (oss->fd, dst, convert_samples << hw->info.shift);

            /* XXX: follow errno recommendations ? */

            if (written == -1) {

                oss_logerr (

                    errno,

                    "Failed to write %d bytes of audio data from %p\n",

                    convert_samples << hw->info.shift,

                    dst

                    );

                continue;

            }

            if (written != convert_samples << hw->info.shift) {

                int wsamples = written >> hw->info.shift;

                int wbytes = wsamples << hw->info.shift;

                if (wbytes != written) {

                    dolog ("warning: Misaligned write %d (requested %d), "

                           "alignment %d\n",

                           wbytes, written, hw->info.align + 1);

                }

                decr -= wsamples;

                rpos = (rpos + wsamples) % hw->samples;

                break;

            }

        }

        rpos = (rpos + convert_samples) % hw->samples;

        samples -= convert_samples;

    }

    if (oss->mmapped) {

        oss->old_optr = cntinfo.ptr;

    }

    hw->rpos = rpos;

    return decr;

}


SwsContext *sws_getContext(int srcW, int srcH, enum PixelFormat srcFormat,

                           int dstW, int dstH, enum PixelFormat dstFormat, int flags,

                           SwsFilter *srcFilter, SwsFilter *dstFilter, const double *param)

{

    SwsContext *c;

    int i;

    int usesVFilter, usesHFilter;

    int unscaled;

    int srcRange, dstRange;

    SwsFilter dummyFilter= {NULL, NULL, NULL, NULL};

#if ARCH_X86

    if (flags & SWS_CPU_CAPS_MMX)

        __asm__ volatile("emms\n\t"::: "memory");

#endif

#if !CONFIG_RUNTIME_CPUDETECT //ensure that the flags match the compiled variant if cpudetect is off

    flags &= ~(SWS_CPU_CAPS_MMX|SWS_CPU_CAPS_MMX2|SWS_CPU_CAPS_3DNOW|SWS_CPU_CAPS_ALTIVEC|SWS_CPU_CAPS_BFIN);

    flags |= ff_hardcodedcpuflags();

#endif /* CONFIG_RUNTIME_CPUDETECT */

    if (!rgb15to16) sws_rgb2rgb_init(flags);

    unscaled = (srcW == dstW && srcH == dstH);

    srcRange = handle_jpeg(&srcFormat);

    dstRange = handle_jpeg(&dstFormat);

    if (!isSupportedIn(srcFormat)) {

        av_log(NULL, AV_LOG_ERROR, "swScaler: %s is not supported as input pixel format\n", sws_format_name(srcFormat));

        return NULL;

    }

    if (!isSupportedOut(dstFormat)) {

        av_log(NULL, AV_LOG_ERROR, "swScaler: %s is not supported as output pixel format\n", sws_format_name(dstFormat));

        return NULL;

    }

    i= flags & ( SWS_POINT

                |SWS_AREA

                |SWS_BILINEAR

                |SWS_FAST_BILINEAR

                |SWS_BICUBIC

                |SWS_X

                |SWS_GAUSS

                |SWS_LANCZOS

                |SWS_SINC

                |SWS_SPLINE

                |SWS_BICUBLIN);

    if(!i || (i & (i-1))) {

        av_log(NULL, AV_LOG_ERROR, "swScaler: Exactly one scaler algorithm must be chosen\n");

        return NULL;

    }

    /* sanity check */

    if (srcW<4 || srcH<1 || dstW<8 || dstH<1) { //FIXME check if these are enough and try to lowwer them after fixing the relevant parts of the code

        av_log(NULL, AV_LOG_ERROR, "swScaler: %dx%d -> %dx%d is invalid scaling dimension\n",

               srcW, srcH, dstW, dstH);

        return NULL;

    }

    if(srcW > VOFW || dstW > VOFW) {

        av_log(NULL, AV_LOG_ERROR, "swScaler: Compile-time maximum width is "AV_STRINGIFY(VOFW)" change VOF/VOFW and recompile\n");

        return NULL;

    }

    if (!dstFilter) dstFilter= &dummyFilter;

    if (!srcFilter) srcFilter= &dummyFilter;

    FF_ALLOCZ_OR_GOTO(NULL, c, sizeof(SwsContext), fail);

    c->av_class = &sws_context_class;

    c->srcW= srcW;

    c->srcH= srcH;

    c->dstW= dstW;

    c->dstH= dstH;

    c->lumXInc= ((srcW<<16) + (dstW>>1))/dstW;

    c->lumYInc= ((srcH<<16) + (dstH>>1))/dstH;

    c->flags= flags;

    c->dstFormat= dstFormat;

    c->srcFormat= srcFormat;

    c->dstFormatBpp = av_get_bits_per_pixel(&av_pix_fmt_descriptors[dstFormat]);

    c->srcFormatBpp = av_get_bits_per_pixel(&av_pix_fmt_descriptors[srcFormat]);

    c->vRounder= 4* 0x0001000100010001ULL;

    usesVFilter = (srcFilter->lumV && srcFilter->lumV->length>1) ||

                  (srcFilter->chrV && srcFilter->chrV->length>1) ||

                  (dstFilter->lumV && dstFilter->lumV->length>1) ||

                  (dstFilter->chrV && dstFilter->chrV->length>1);

    usesHFilter = (srcFilter->lumH && srcFilter->lumH->length>1) ||

                  (srcFilter->chrH && srcFilter->chrH->length>1) ||

                  (dstFilter->lumH && dstFilter->lumH->length>1) ||

                  (dstFilter->chrH && dstFilter->chrH->length>1);

    getSubSampleFactors(&c->chrSrcHSubSample, &c->chrSrcVSubSample, srcFormat);

    getSubSampleFactors(&c->chrDstHSubSample, &c->chrDstVSubSample, dstFormat);

    // reuse chroma for 2 pixels RGB/BGR unless user wants full chroma interpolation

    if (isAnyRGB(dstFormat) && !(flags&SWS_FULL_CHR_H_INT)) c->chrDstHSubSample=1;

    // drop some chroma lines if the user wants it

    c->vChrDrop= (flags&SWS_SRC_V_CHR_DROP_MASK)>>SWS_SRC_V_CHR_DROP_SHIFT;

    c->chrSrcVSubSample+= c->vChrDrop;

    // drop every other pixel for chroma calculation unless user wants full chroma

    if (isAnyRGB(srcFormat) && !(flags&SWS_FULL_CHR_H_INP)

      && srcFormat!=PIX_FMT_RGB8      && srcFormat!=PIX_FMT_BGR8

      && srcFormat!=PIX_FMT_RGB4      && srcFormat!=PIX_FMT_BGR4

      && srcFormat!=PIX_FMT_RGB4_BYTE && srcFormat!=PIX_FMT_BGR4_BYTE

      && ((dstW>>c->chrDstHSubSample) <= (srcW>>1) || (flags&(SWS_FAST_BILINEAR|SWS_POINT))))

        c->chrSrcHSubSample=1;

    if (param) {

        c->param[0] = param[0];

        c->param[1] = param[1];

    } else {

        c->param[0] =

        c->param[1] = SWS_PARAM_DEFAULT;

    }

    // Note the -((-x)>>y) is so that we always round toward +inf.

    c->chrSrcW= -((-srcW) >> c->chrSrcHSubSample);

    c->chrSrcH= -((-srcH) >> c->chrSrcVSubSample);

    c->chrDstW= -((-dstW) >> c->chrDstHSubSample);

    c->chrDstH= -((-dstH) >> c->chrDstVSubSample);

    sws_setColorspaceDetails(c, ff_yuv2rgb_coeffs[SWS_CS_DEFAULT], srcRange, ff_yuv2rgb_coeffs[SWS_CS_DEFAULT] /* FIXME*/, dstRange, 0, 1<<16, 1<<16);

    /* unscaled special cases */

    if (unscaled && !usesHFilter && !usesVFilter && (srcRange == dstRange || isAnyRGB(dstFormat))) {

        ff_get_unscaled_swscale(c);

        if (c->swScale) {

            if (flags&SWS_PRINT_INFO)

                av_log(c, AV_LOG_INFO, "using unscaled %s -> %s special converter\n",

                       sws_format_name(srcFormat), sws_format_name(dstFormat));

            return c;

        }

    }

    if (flags & SWS_CPU_CAPS_MMX2) {

        c->canMMX2BeUsed= (dstW >=srcW && (dstW&31)==0 && (srcW&15)==0) ? 1 : 0;

        if (!c->canMMX2BeUsed && dstW >=srcW && (srcW&15)==0 && (flags&SWS_FAST_BILINEAR)) {

            if (flags&SWS_PRINT_INFO)

                av_log(c, AV_LOG_INFO, "output width is not a multiple of 32 -> no MMX2 scaler\n");

        }

        if (usesHFilter) c->canMMX2BeUsed=0;

    }

    else

        c->canMMX2BeUsed=0;

    c->chrXInc= ((c->chrSrcW<<16) + (c->chrDstW>>1))/c->chrDstW;

    c->chrYInc= ((c->chrSrcH<<16) + (c->chrDstH>>1))/c->chrDstH;

    // match pixel 0 of the src to pixel 0 of dst and match pixel n-2 of src to pixel n-2 of dst

    // but only for the FAST_BILINEAR mode otherwise do correct scaling

    // n-2 is the last chrominance sample available

    // this is not perfect, but no one should notice the difference, the more correct variant

    // would be like the vertical one, but that would require some special code for the

    // first and last pixel

    if (flags&SWS_FAST_BILINEAR) {

        if (c->canMMX2BeUsed) {

            c->lumXInc+= 20;

            c->chrXInc+= 20;

        }

        //we don't use the x86 asm scaler if MMX is available

        else if (flags & SWS_CPU_CAPS_MMX) {

            c->lumXInc = ((srcW-2)<<16)/(dstW-2) - 20;

            c->chrXInc = ((c->chrSrcW-2)<<16)/(c->chrDstW-2) - 20;

        }

    }

    /* precalculate horizontal scaler filter coefficients */

    {

#if ARCH_X86 && (HAVE_MMX2 || CONFIG_RUNTIME_CPUDETECT) && CONFIG_GPL

// can't downscale !!!

        if (c->canMMX2BeUsed && (flags & SWS_FAST_BILINEAR)) {

            c->lumMmx2FilterCodeSize = initMMX2HScaler(      dstW, c->lumXInc, NULL, NULL, NULL, 8);

            c->chrMmx2FilterCodeSize = initMMX2HScaler(c->chrDstW, c->chrXInc, NULL, NULL, NULL, 4);

#ifdef MAP_ANONYMOUS

            c->lumMmx2FilterCode = mmap(NULL, c->lumMmx2FilterCodeSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);

            c->chrMmx2FilterCode = mmap(NULL, c->chrMmx2FilterCodeSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0);

#elif HAVE_VIRTUALALLOC

            c->lumMmx2FilterCode = VirtualAlloc(NULL, c->lumMmx2FilterCodeSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE);

            c->chrMmx2FilterCode = VirtualAlloc(NULL, c->chrMmx2FilterCodeSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE);

#else

            c->lumMmx2FilterCode = av_malloc(c->lumMmx2FilterCodeSize);

            c->chrMmx2FilterCode = av_malloc(c->chrMmx2FilterCodeSize);

#endif

            if (!c->lumMmx2FilterCode || !c->chrMmx2FilterCode)

                goto fail;

            FF_ALLOCZ_OR_GOTO(c, c->hLumFilter   , (dstW        /8+8)*sizeof(int16_t), fail);

            FF_ALLOCZ_OR_GOTO(c, c->hChrFilter   , (c->chrDstW  /4+8)*sizeof(int16_t), fail);

            FF_ALLOCZ_OR_GOTO(c, c->hLumFilterPos, (dstW      /2/8+8)*sizeof(int32_t), fail);

            FF_ALLOCZ_OR_GOTO(c, c->hChrFilterPos, (c->chrDstW/2/4+8)*sizeof(int32_t), fail);

            initMMX2HScaler(      dstW, c->lumXInc, c->lumMmx2FilterCode, c->hLumFilter, c->hLumFilterPos, 8);

            initMMX2HScaler(c->chrDstW, c->chrXInc, c->chrMmx2FilterCode, c->hChrFilter, c->hChrFilterPos, 4);

#ifdef MAP_ANONYMOUS

            mprotect(c->lumMmx2FilterCode, c->lumMmx2FilterCodeSize, PROT_EXEC | PROT_READ);

            mprotect(c->chrMmx2FilterCode, c->chrMmx2FilterCodeSize, PROT_EXEC | PROT_READ);

#endif

        } else

#endif /* ARCH_X86 && (HAVE_MMX2 || CONFIG_RUNTIME_CPUDETECT) && CONFIG_GPL */

        {

            const int filterAlign=

                (flags & SWS_CPU_CAPS_MMX) ? 4 :

                (flags & SWS_CPU_CAPS_ALTIVEC) ? 8 :

                1;

            if (initFilter(&c->hLumFilter, &c->hLumFilterPos, &c->hLumFilterSize, c->lumXInc,

                           srcW      ,       dstW, filterAlign, 1<<14,

                           (flags&SWS_BICUBLIN) ? (flags|SWS_BICUBIC)  : flags,

                           srcFilter->lumH, dstFilter->lumH, c->param) < 0)

                goto fail;

            if (initFilter(&c->hChrFilter, &c->hChrFilterPos, &c->hChrFilterSize, c->chrXInc,

                           c->chrSrcW, c->chrDstW, filterAlign, 1<<14,

                           (flags&SWS_BICUBLIN) ? (flags|SWS_BILINEAR) : flags,

                           srcFilter->chrH, dstFilter->chrH, c->param) < 0)

                goto fail;

        }

    } // initialize horizontal stuff

    /* precalculate vertical scaler filter coefficients */

    {

        const int filterAlign=

            (flags & SWS_CPU_CAPS_MMX) && (flags & SWS_ACCURATE_RND) ? 2 :

            (flags & SWS_CPU_CAPS_ALTIVEC) ? 8 :

            1;

        if (initFilter(&c->vLumFilter, &c->vLumFilterPos, &c->vLumFilterSize, c->lumYInc,

                       srcH      ,        dstH, filterAlign, (1<<12),

                       (flags&SWS_BICUBLIN) ? (flags|SWS_BICUBIC)  : flags,

                       srcFilter->lumV, dstFilter->lumV, c->param) < 0)

            goto fail;

        if (initFilter(&c->vChrFilter, &c->vChrFilterPos, &c->vChrFilterSize, c->chrYInc,

                       c->chrSrcH, c->chrDstH, filterAlign, (1<<12),

                       (flags&SWS_BICUBLIN) ? (flags|SWS_BILINEAR) : flags,

                       srcFilter->chrV, dstFilter->chrV, c->param) < 0)

            goto fail;

#if ARCH_PPC && HAVE_ALTIVEC

        FF_ALLOC_OR_GOTO(c, c->vYCoeffsBank, sizeof (vector signed short)*c->vLumFilterSize*c->dstH, fail);

        FF_ALLOC_OR_GOTO(c, c->vCCoeffsBank, sizeof (vector signed short)*c->vChrFilterSize*c->chrDstH, fail);

        for (i=0;i<c->vLumFilterSize*c->dstH;i++) {

            int j;

            short *p = (short *)&c->vYCoeffsBank[i];

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

                p[j] = c->vLumFilter[i];

        }

        for (i=0;i<c->vChrFilterSize*c->chrDstH;i++) {

            int j;

            short *p = (short *)&c->vCCoeffsBank[i];

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

                p[j] = c->vChrFilter[i];

        }

#endif

    }

    // calculate buffer sizes so that they won't run out while handling these damn slices

    c->vLumBufSize= c->vLumFilterSize;

    c->vChrBufSize= c->vChrFilterSize;

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

        int chrI= i*c->chrDstH / dstH;

        int nextSlice= FFMAX(c->vLumFilterPos[i   ] + c->vLumFilterSize - 1,

                           ((c->vChrFilterPos[chrI] + c->vChrFilterSize - 1)<<c->chrSrcVSubSample));

        nextSlice>>= c->chrSrcVSubSample;

        nextSlice<<= c->chrSrcVSubSample;

        if (c->vLumFilterPos[i   ] + c->vLumBufSize < nextSlice)

            c->vLumBufSize= nextSlice - c->vLumFilterPos[i];

        if (c->vChrFilterPos[chrI] + c->vChrBufSize < (nextSlice>>c->chrSrcVSubSample))

            c->vChrBufSize= (nextSlice>>c->chrSrcVSubSample) - c->vChrFilterPos[chrI];

    }

    // allocate pixbufs (we use dynamic allocation because otherwise we would need to

    // allocate several megabytes to handle all possible cases)

    FF_ALLOC_OR_GOTO(c, c->lumPixBuf, c->vLumBufSize*2*sizeof(int16_t*), fail);

    FF_ALLOC_OR_GOTO(c, c->chrPixBuf, c->vChrBufSize*2*sizeof(int16_t*), fail);

    if (CONFIG_SWSCALE_ALPHA && isALPHA(c->srcFormat) && isALPHA(c->dstFormat))

        FF_ALLOCZ_OR_GOTO(c, c->alpPixBuf, c->vLumBufSize*2*sizeof(int16_t*), fail);

    //Note we need at least one pixel more at the end because of the MMX code (just in case someone wanna replace the 4000/8000)

    /* align at 16 bytes for AltiVec */

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

        FF_ALLOCZ_OR_GOTO(c, c->lumPixBuf[i+c->vLumBufSize], VOF+1, fail);

        c->lumPixBuf[i] = c->lumPixBuf[i+c->vLumBufSize];

    }

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

        FF_ALLOC_OR_GOTO(c, c->chrPixBuf[i+c->vChrBufSize], (VOF+1)*2, fail);

        c->chrPixBuf[i] = c->chrPixBuf[i+c->vChrBufSize];

    }

    if (CONFIG_SWSCALE_ALPHA && c->alpPixBuf)

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

            FF_ALLOCZ_OR_GOTO(c, c->alpPixBuf[i+c->vLumBufSize], VOF+1, fail);

            c->alpPixBuf[i] = c->alpPixBuf[i+c->vLumBufSize];

        }

    //try to avoid drawing green stuff between the right end and the stride end

    for (i=0; i<c->vChrBufSize; i++) memset(c->chrPixBuf[i], 64, (VOF+1)*2);

    assert(2*VOFW == VOF);

    assert(c->chrDstH <= dstH);

    if (flags&SWS_PRINT_INFO) {

        if (flags&SWS_FAST_BILINEAR)

            av_log(c, AV_LOG_INFO, "FAST_BILINEAR scaler, ");

        else if (flags&SWS_BILINEAR)

            av_log(c, AV_LOG_INFO, "BILINEAR scaler, ");

        else if (flags&SWS_BICUBIC)

            av_log(c, AV_LOG_INFO, "BICUBIC scaler, ");

        else if (flags&SWS_X)

            av_log(c, AV_LOG_INFO, "Experimental scaler, ");

        else if (flags&SWS_POINT)

            av_log(c, AV_LOG_INFO, "Nearest Neighbor / POINT scaler, ");

        else if (flags&SWS_AREA)

            av_log(c, AV_LOG_INFO, "Area Averaging scaler, ");

        else if (flags&SWS_BICUBLIN)

            av_log(c, AV_LOG_INFO, "luma BICUBIC / chroma BILINEAR scaler, ");

        else if (flags&SWS_GAUSS)

            av_log(c, AV_LOG_INFO, "Gaussian scaler, ");

        else if (flags&SWS_SINC)

            av_log(c, AV_LOG_INFO, "Sinc scaler, ");

        else if (flags&SWS_LANCZOS)

            av_log(c, AV_LOG_INFO, "Lanczos scaler, ");

        else if (flags&SWS_SPLINE)

            av_log(c, AV_LOG_INFO, "Bicubic spline scaler, ");

        else

            av_log(c, AV_LOG_INFO, "ehh flags invalid?! ");

        av_log(c, AV_LOG_INFO, "from %s to %s%s ",

               sws_format_name(srcFormat),

#ifdef DITHER1XBPP

               dstFormat == PIX_FMT_BGR555 || dstFormat == PIX_FMT_BGR565 ||

               dstFormat == PIX_FMT_RGB444BE || dstFormat == PIX_FMT_RGB444LE ||

               dstFormat == PIX_FMT_BGR444BE || dstFormat == PIX_FMT_BGR444LE ? "dithered " : "",

#else

               "",

#endif

               sws_format_name(dstFormat));

        if (flags & SWS_CPU_CAPS_MMX2)

            av_log(c, AV_LOG_INFO, "using MMX2\n");

        else if (flags & SWS_CPU_CAPS_3DNOW)

            av_log(c, AV_LOG_INFO, "using 3DNOW\n");

        else if (flags & SWS_CPU_CAPS_MMX)

            av_log(c, AV_LOG_INFO, "using MMX\n");

        else if (flags & SWS_CPU_CAPS_ALTIVEC)

            av_log(c, AV_LOG_INFO, "using AltiVec\n");

        else

            av_log(c, AV_LOG_INFO, "using C\n");

        if (flags & SWS_CPU_CAPS_MMX) {

            if (c->canMMX2BeUsed && (flags&SWS_FAST_BILINEAR))

                av_log(c, AV_LOG_VERBOSE, "using FAST_BILINEAR MMX2 scaler for horizontal scaling\n");

            else {

                if (c->hLumFilterSize==4)

                    av_log(c, AV_LOG_VERBOSE, "using 4-tap MMX scaler for horizontal luminance scaling\n");

                else if (c->hLumFilterSize==8)

                    av_log(c, AV_LOG_VERBOSE, "using 8-tap MMX scaler for horizontal luminance scaling\n");

                else

                    av_log(c, AV_LOG_VERBOSE, "using n-tap MMX scaler for horizontal luminance scaling\n");

                if (c->hChrFilterSize==4)

                    av_log(c, AV_LOG_VERBOSE, "using 4-tap MMX scaler for horizontal chrominance scaling\n");

                else if (c->hChrFilterSize==8)

                    av_log(c, AV_LOG_VERBOSE, "using 8-tap MMX scaler for horizontal chrominance scaling\n");

                else

                    av_log(c, AV_LOG_VERBOSE, "using n-tap MMX scaler for horizontal chrominance scaling\n");

            }

        } else {

#if ARCH_X86

            av_log(c, AV_LOG_VERBOSE, "using x86 asm scaler for horizontal scaling\n");

#else

            if (flags & SWS_FAST_BILINEAR)

                av_log(c, AV_LOG_VERBOSE, "using FAST_BILINEAR C scaler for horizontal scaling\n");

            else

                av_log(c, AV_LOG_VERBOSE, "using C scaler for horizontal scaling\n");

#endif

        }

        if (isPlanarYUV(dstFormat)) {

            if (c->vLumFilterSize==1)

                av_log(c, AV_LOG_VERBOSE, "using 1-tap %s \"scaler\" for vertical scaling (YV12 like)\n", (flags & SWS_CPU_CAPS_MMX) ? "MMX" : "C");

            else

                av_log(c, AV_LOG_VERBOSE, "using n-tap %s scaler for vertical scaling (YV12 like)\n", (flags & SWS_CPU_CAPS_MMX) ? "MMX" : "C");

        } else {

            if (c->vLumFilterSize==1 && c->vChrFilterSize==2)

                av_log(c, AV_LOG_VERBOSE, "using 1-tap %s \"scaler\" for vertical luminance scaling (BGR)\n"

                       "      2-tap scaler for vertical chrominance scaling (BGR)\n", (flags & SWS_CPU_CAPS_MMX) ? "MMX" : "C");

            else if (c->vLumFilterSize==2 && c->vChrFilterSize==2)

                av_log(c, AV_LOG_VERBOSE, "using 2-tap linear %s scaler for vertical scaling (BGR)\n", (flags & SWS_CPU_CAPS_MMX) ? "MMX" : "C");

            else

                av_log(c, AV_LOG_VERBOSE, "using n-tap %s scaler for vertical scaling (BGR)\n", (flags & SWS_CPU_CAPS_MMX) ? "MMX" : "C");

        }

        if (dstFormat==PIX_FMT_BGR24)

            av_log(c, AV_LOG_VERBOSE, "using %s YV12->BGR24 converter\n",

                   (flags & SWS_CPU_CAPS_MMX2) ? "MMX2" : ((flags & SWS_CPU_CAPS_MMX) ? "MMX" : "C"));

        else if (dstFormat==PIX_FMT_RGB32)

            av_log(c, AV_LOG_VERBOSE, "using %s YV12->BGR32 converter\n", (flags & SWS_CPU_CAPS_MMX) ? "MMX" : "C");

        else if (dstFormat==PIX_FMT_BGR565)

            av_log(c, AV_LOG_VERBOSE, "using %s YV12->BGR16 converter\n", (flags & SWS_CPU_CAPS_MMX) ? "MMX" : "C");

        else if (dstFormat==PIX_FMT_BGR555)

            av_log(c, AV_LOG_VERBOSE, "using %s YV12->BGR15 converter\n", (flags & SWS_CPU_CAPS_MMX) ? "MMX" : "C");

        else if (dstFormat == PIX_FMT_RGB444BE || dstFormat == PIX_FMT_RGB444LE ||

                 dstFormat == PIX_FMT_BGR444BE || dstFormat == PIX_FMT_BGR444LE)

            av_log(c, AV_LOG_VERBOSE, "using %s YV12->BGR12 converter\n", (flags & SWS_CPU_CAPS_MMX) ? "MMX" : "C");

        av_log(c, AV_LOG_VERBOSE, "%dx%d -> %dx%d\n", srcW, srcH, dstW, dstH);

        av_log(c, AV_LOG_DEBUG, "lum srcW=%d srcH=%d dstW=%d dstH=%d xInc=%d yInc=%d\n",

               c->srcW, c->srcH, c->dstW, c->dstH, c->lumXInc, c->lumYInc);

        av_log(c, AV_LOG_DEBUG, "chr srcW=%d srcH=%d dstW=%d dstH=%d xInc=%d yInc=%d\n",

               c->chrSrcW, c->chrSrcH, c->chrDstW, c->chrDstH, c->chrXInc, c->chrYInc);

    }

    c->swScale= ff_getSwsFunc(c);

    return c;

fail:

    sws_freeContext(c);

    return NULL;

}


IDEDevice *ide_create_drive(IDEBus *bus, int unit, DriveInfo *drive)

{

    DeviceState *dev;

    dev = qdev_create(&bus->qbus, drive->media_cd ? "ide-cd" : "ide-hd");

    qdev_prop_set_uint32(dev, "unit", unit);

    qdev_prop_set_drive_nofail(dev, "drive",

                               blk_bs(blk_by_legacy_dinfo(drive)));

    qdev_init_nofail(dev);

    return DO_UPCAST(IDEDevice, qdev, dev);

}


void qmp_block_set_io_throttle(const char *device, int64_t bps, int64_t bps_rd,

                               int64_t bps_wr, int64_t iops, int64_t iops_rd,

                               int64_t iops_wr, Error **errp)

{

    BlockIOLimit io_limits;

    BlockDriverState *bs;

    bs = bdrv_find(device);

    if (!bs) {

        error_set(errp, QERR_DEVICE_NOT_FOUND, device);

        return;

    }

    io_limits.bps[BLOCK_IO_LIMIT_TOTAL] = bps;

    io_limits.bps[BLOCK_IO_LIMIT_READ]  = bps_rd;

    io_limits.bps[BLOCK_IO_LIMIT_WRITE] = bps_wr;

    io_limits.iops[BLOCK_IO_LIMIT_TOTAL]= iops;

    io_limits.iops[BLOCK_IO_LIMIT_READ] = iops_rd;

    io_limits.iops[BLOCK_IO_LIMIT_WRITE]= iops_wr;

    if (!do_check_io_limits(&io_limits)) {

        error_set(errp, QERR_INVALID_PARAMETER_COMBINATION);

        return;

    }

    bs->io_limits = io_limits;

    bs->slice_time = BLOCK_IO_SLICE_TIME;

    if (!bs->io_limits_enabled && bdrv_io_limits_enabled(bs)) {

        bdrv_io_limits_enable(bs);

    } else if (bs->io_limits_enabled && !bdrv_io_limits_enabled(bs)) {

        bdrv_io_limits_disable(bs);

    } else {

        if (bs->block_timer) {

            qemu_mod_timer(bs->block_timer, qemu_get_clock_ns(vm_clock));

        }

    }

}


void os_host_main_loop_wait(int *timeout)

{

    int ret, ret2, i;

    PollingEntry *pe;

    /* XXX: need to suppress polling by better using win32 events */

    ret = 0;

    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {

        ret |= pe->func(pe->opaque);

    }

    if (ret == 0) {

        int err;

        WaitObjects *w = &wait_objects;

        qemu_mutex_unlock_iothread();

        ret = WaitForMultipleObjects(w->num, w->events, FALSE, *timeout);

        qemu_mutex_lock_iothread();

        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {

            if (w->func[ret - WAIT_OBJECT_0])

                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);

            /* Check for additional signaled events */

            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {

                /* Check if event is signaled */

                ret2 = WaitForSingleObject(w->events[i], 0);

                if(ret2 == WAIT_OBJECT_0) {

                    if (w->func[i])

                        w->func[i](w->opaque[i]);

                } else if (ret2 == WAIT_TIMEOUT) {

                } else {

                    err = GetLastError();

                    fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);

                }

            }

        } else if (ret == WAIT_TIMEOUT) {

        } else {

            err = GetLastError();

            fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);

        }

    }

    *timeout = 0;

}


static void thread_pool_completion_bh(void *opaque)

{

    ThreadPool *pool = opaque;

    ThreadPoolElement *elem, *next;

restart:

    QLIST_FOREACH_SAFE(elem, &pool->head, all, next) {

        if (elem->state != THREAD_DONE) {

            continue;

        }

        trace_thread_pool_complete(pool, elem, elem->common.opaque,

                                   elem->ret);

        QLIST_REMOVE(elem, all);

        if (elem->common.cb) {

            /* Read state before ret.  */

            smp_rmb();

            /* Schedule ourselves in case elem->common.cb() calls aio_poll() to

             * wait for another request that completed at the same time.

             */

            qemu_bh_schedule(pool->completion_bh);

            elem->common.cb(elem->common.opaque, elem->ret);

            qemu_aio_unref(elem);

            goto restart;

        } else {

            qemu_aio_unref(elem);

        }

    }

}


static void test_commands(void)

{

    char *response;

    int i;

    for (i = 0; hmp_cmds[i] != NULL; i++) {

        if (verbose) {

            fprintf(stderr, "\t%s\n", hmp_cmds[i]);

        }

        response = hmp(hmp_cmds[i]);

        g_free(response);

    }

}


static void tcg_out_movi(TCGContext *s, TCGType type, TCGReg rd,

                         tcg_target_long value)

{

    AArch64Insn insn;

    if (type == TCG_TYPE_I32) {

        value = (uint32_t)value;

    }

    /* count trailing zeros in 16 bit steps, mapping 64 to 0. Emit the

       first MOVZ with the half-word immediate skipping the zeros, with a shift

       (LSL) equal to this number. Then all next instructions use MOVKs.

       Zero the processed half-word in the value, continue until empty.

       We build the final result 16bits at a time with up to 4 instructions,

       but do not emit instructions for 16bit zero holes. */

    insn = I3405_MOVZ;

    do {

        unsigned shift = ctz64(value) & (63 & -16);

        tcg_out_insn_3405(s, insn, shift >= 32, rd, value >> shift, shift);

        value &= ~(0xffffUL << shift);

        insn = I3405_MOVK;

    } while (value);

}


static void exynos4210_uart_write(void *opaque, target_phys_addr_t offset,

                               uint64_t val, unsigned size)

{

    Exynos4210UartState *s = (Exynos4210UartState *)opaque;

    uint8_t ch;

    PRINT_DEBUG_EXTEND("UART%d: <0x%04x> %s <- 0x%08llx\n", s->channel,

        offset, exynos4210_uart_regname(offset), (long long unsigned int)val);

    switch (offset) {

    case ULCON:

    case UBRDIV:

    case UFRACVAL:

        s->reg[I_(offset)] = val;

        exynos4210_uart_update_parameters(s);

        break;

    case UFCON:

        s->reg[I_(UFCON)] = val;

        if (val & UFCON_Rx_FIFO_RESET) {

            fifo_reset(&s->rx);

            s->reg[I_(UFCON)] &= ~UFCON_Rx_FIFO_RESET;

            PRINT_DEBUG("UART%d: Rx FIFO Reset\n", s->channel);

        }

        if (val & UFCON_Tx_FIFO_RESET) {

            fifo_reset(&s->tx);

            s->reg[I_(UFCON)] &= ~UFCON_Tx_FIFO_RESET;

            PRINT_DEBUG("UART%d: Tx FIFO Reset\n", s->channel);

        }

        break;

    case UTXH:

        if (s->chr) {

            s->reg[I_(UTRSTAT)] &= ~(UTRSTAT_TRANSMITTER_EMPTY |

                    UTRSTAT_Tx_BUFFER_EMPTY);

            ch = (uint8_t)val;

            qemu_chr_fe_write(s->chr, &ch, 1);

#if DEBUG_Tx_DATA

            fprintf(stderr, "%c", ch);

#endif

            s->reg[I_(UTRSTAT)] |= UTRSTAT_TRANSMITTER_EMPTY |

                    UTRSTAT_Tx_BUFFER_EMPTY;

            s->reg[I_(UINTSP)]  |= UINTSP_TXD;

            exynos4210_uart_update_irq(s);

        }

        break;

    case UINTP:

        s->reg[I_(UINTP)] &= ~val;

        s->reg[I_(UINTSP)] &= ~val;

        PRINT_DEBUG("UART%d: UINTP [%04x] have been cleared: %08x\n",

                    s->channel, offset, s->reg[I_(UINTP)]);

        exynos4210_uart_update_irq(s);

        break;

    case UTRSTAT:

    case UERSTAT:

    case UFSTAT:

    case UMSTAT:

    case URXH:

        PRINT_DEBUG("UART%d: Trying to write into RO register: %s [%04x]\n",

                    s->channel, exynos4210_uart_regname(offset), offset);

        break;

    case UINTSP:

        s->reg[I_(UINTSP)]  &= ~val;

        break;

    case UINTM:

        s->reg[I_(UINTM)] = val;

        exynos4210_uart_update_irq(s);

        break;

    case UCON:

    case UMCON:

    default:

        s->reg[I_(offset)] = val;

        break;

    }

}


void FUNC(ff_emulated_edge_mc)(uint8_t *buf, const uint8_t *src, int linesize, int block_w, int block_h,

                                    int src_x, int src_y, int w, int h){

    int x, y;

    int start_y, start_x, end_y, end_x;

    if(src_y>= h){

        src+= (h-1-src_y)*linesize;

        src_y=h-1;

    }else if(src_y<=-block_h){

        src+= (1-block_h-src_y)*linesize;

        src_y=1-block_h;

    }

    if(src_x>= w){

        src+= (w-1-src_x)*sizeof(pixel);

        src_x=w-1;

    }else if(src_x<=-block_w){

        src+= (1-block_w-src_x)*sizeof(pixel);

        src_x=1-block_w;

    }

    start_y= FFMAX(0, -src_y);

    start_x= FFMAX(0, -src_x);

    end_y= FFMIN(block_h, h-src_y);

    end_x= FFMIN(block_w, w-src_x);

    av_assert2(start_y < end_y && block_h);

    av_assert2(start_x < end_x && block_w);

    w    = end_x - start_x;

    src += start_y*linesize + start_x*sizeof(pixel);

    buf += start_x*sizeof(pixel);

    //top

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

        memcpy(buf, src, w*sizeof(pixel));

        buf += linesize;

    }

    // copy existing part

    for(; y<end_y; y++){

        memcpy(buf, src, w*sizeof(pixel));

        src += linesize;

        buf += linesize;

    }

    //bottom

    src -= linesize;

    for(; y<block_h; y++){

        memcpy(buf, src, w*sizeof(pixel));

        buf += linesize;

    }

    buf -= block_h * linesize + start_x*sizeof(pixel);

    while (block_h--){

        pixel *bufp = (pixel*)buf;

       //left

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

            bufp[x] = bufp[start_x];

        }

       //right

        for(x=end_x; x<block_w; x++){

            bufp[x] = bufp[end_x - 1];

        }

        buf += linesize;

    }

}


static void test_separators(const AVDictionary *m, const char pair, const char val)

{

    AVDictionary *dict = NULL;

    char pairs[] = {pair , '\0'};

    char vals[]  = {val, '\0'};

    char *buffer = NULL;

    av_dict_copy(&dict, m, 0);

    print_dict(dict);

    av_dict_get_string(dict, &buffer, val, pair);

    printf("%s\n", buffer);

    av_dict_free(&dict);

    av_dict_parse_string(&dict, buffer, vals, pairs, 0);

    av_freep(&buffer);

    print_dict(dict);

    av_dict_free(&dict);

}


static int flac_read_header(AVFormatContext *s)

{

    int ret, metadata_last=0, metadata_type, metadata_size, found_streaminfo=0;

    uint8_t header[4];

    uint8_t *buffer=NULL;

    FLACDecContext *flac = s->priv_data;

    AVStream *st = avformat_new_stream(s, NULL);

    if (!st)

        return AVERROR(ENOMEM);

    st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO;

    st->codecpar->codec_id = AV_CODEC_ID_FLAC;

    st->need_parsing = AVSTREAM_PARSE_FULL_RAW;

    /* the parameters will be extracted from the compressed bitstream */

    /* if fLaC marker is not found, assume there is no header */

    if (avio_rl32(s->pb) != MKTAG('f','L','a','C')) {

        avio_seek(s->pb, -4, SEEK_CUR);

        return 0;

    }

    /* process metadata blocks */

    while (!avio_feof(s->pb) && !metadata_last) {

        avio_read(s->pb, header, 4);

        flac_parse_block_header(header, &metadata_last, &metadata_type,

                                   &metadata_size);

        switch (metadata_type) {

        /* allocate and read metadata block for supported types */

        case FLAC_METADATA_TYPE_STREAMINFO:

        case FLAC_METADATA_TYPE_CUESHEET:

        case FLAC_METADATA_TYPE_PICTURE:

        case FLAC_METADATA_TYPE_VORBIS_COMMENT:

        case FLAC_METADATA_TYPE_SEEKTABLE:

            buffer = av_mallocz(metadata_size + AV_INPUT_BUFFER_PADDING_SIZE);

            if (!buffer) {

                return AVERROR(ENOMEM);

            }

            if (avio_read(s->pb, buffer, metadata_size) != metadata_size) {

                RETURN_ERROR(AVERROR(EIO));

            }

            break;

        /* skip metadata block for unsupported types */

        default:

            ret = avio_skip(s->pb, metadata_size);

            if (ret < 0)

                return ret;

        }

        if (metadata_type == FLAC_METADATA_TYPE_STREAMINFO) {

            uint32_t samplerate;

            uint64_t samples;

            /* STREAMINFO can only occur once */

            if (found_streaminfo) {

                RETURN_ERROR(AVERROR_INVALIDDATA);

            }

            if (metadata_size != FLAC_STREAMINFO_SIZE) {

                RETURN_ERROR(AVERROR_INVALIDDATA);

            }

            found_streaminfo = 1;

            st->codecpar->extradata      = buffer;

            st->codecpar->extradata_size = metadata_size;

            buffer = NULL;

            /* get sample rate and sample count from STREAMINFO header;

             * other parameters will be extracted by the parser */

            samplerate = AV_RB24(st->codecpar->extradata + 10) >> 4;

            samples    = (AV_RB64(st->codecpar->extradata + 13) >> 24) & ((1ULL << 36) - 1);

            /* set time base and duration */

            if (samplerate > 0) {

                avpriv_set_pts_info(st, 64, 1, samplerate);

                if (samples > 0)

                    st->duration = samples;

            }

        } else if (metadata_type == FLAC_METADATA_TYPE_CUESHEET) {

            uint8_t isrc[13];

            uint64_t start;

            const uint8_t *offset;

            int i, chapters, track, ti;

            if (metadata_size < 431)

                RETURN_ERROR(AVERROR_INVALIDDATA);

            offset = buffer + 395;

            chapters = bytestream_get_byte(&offset) - 1;

            if (chapters <= 0)

                RETURN_ERROR(AVERROR_INVALIDDATA);

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

                if (offset + 36 - buffer > metadata_size)

                    RETURN_ERROR(AVERROR_INVALIDDATA);

                start = bytestream_get_be64(&offset);

                track = bytestream_get_byte(&offset);

                bytestream_get_buffer(&offset, isrc, 12);

                isrc[12] = 0;

                offset += 14;

                ti = bytestream_get_byte(&offset);

                if (ti <= 0) RETURN_ERROR(AVERROR_INVALIDDATA);

                offset += ti * 12;

                avpriv_new_chapter(s, track, st->time_base, start, AV_NOPTS_VALUE, isrc);

            }

            av_freep(&buffer);

        } else if (metadata_type == FLAC_METADATA_TYPE_PICTURE) {

            ret = ff_flac_parse_picture(s, buffer, metadata_size);

            av_freep(&buffer);

            if (ret < 0) {

                av_log(s, AV_LOG_ERROR, "Error parsing attached picture.\n");

                return ret;

            }

        } else if (metadata_type == FLAC_METADATA_TYPE_SEEKTABLE) {

            const uint8_t *seekpoint = buffer;

            int i, seek_point_count = metadata_size/SEEKPOINT_SIZE;

            flac->found_seektable = 1;

            if ((s->flags&AVFMT_FLAG_FAST_SEEK)) {

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

                    int64_t timestamp = bytestream_get_be64(&seekpoint);

                    int64_t pos = bytestream_get_be64(&seekpoint);

                    /* skip number of samples */

                    bytestream_get_be16(&seekpoint);

                    av_add_index_entry(st, pos, timestamp, 0, 0, AVINDEX_KEYFRAME);

                }

            }

            av_freep(&buffer);

        }

        else {

            /* STREAMINFO must be the first block */

            if (!found_streaminfo) {

                RETURN_ERROR(AVERROR_INVALIDDATA);

            }

            /* process supported blocks other than STREAMINFO */

            if (metadata_type == FLAC_METADATA_TYPE_VORBIS_COMMENT) {

                AVDictionaryEntry *chmask;

                ret = ff_vorbis_comment(s, &s->metadata, buffer, metadata_size, 1);

                if (ret < 0) {

                    av_log(s, AV_LOG_WARNING, "error parsing VorbisComment metadata\n");

                } else if (ret > 0) {

                    s->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;

                }

                /* parse the channels mask if present */

                chmask = av_dict_get(s->metadata, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", NULL, 0);

                if (chmask) {

                    uint64_t mask = strtol(chmask->value, NULL, 0);

                    if (!mask || mask & ~0x3ffffULL) {

                        av_log(s, AV_LOG_WARNING,

                               "Invalid value of WAVEFORMATEXTENSIBLE_CHANNEL_MASK\n");

                    } else {

                        st->codecpar->channel_layout = mask;

                        av_dict_set(&s->metadata, "WAVEFORMATEXTENSIBLE_CHANNEL_MASK", NULL, 0);

                    }

                }

            }

            av_freep(&buffer);

        }

    }

    ret = ff_replaygain_export(st, s->metadata);

    if (ret < 0)

        return ret;

    reset_index_position(avio_tell(s->pb), st);

    return 0;

fail:

    av_free(buffer);

    return ret;

}


static int ogg_write_packet(AVFormatContext *avfcontext,

			    int stream_index,

			    const uint8_t *buf, int size, int64_t pts)

{

    OggContext *context = avfcontext->priv_data ;

    AVCodecContext *avctx= &avfcontext->streams[stream_index]->codec;

    ogg_packet *op= &context->op;

    ogg_page og ;

    pts= av_rescale(pts, avctx->sample_rate, AV_TIME_BASE);

    if(!size){

//        av_log(avfcontext, AV_LOG_DEBUG, "zero packet\n");

        return 0;

    }

//    av_log(avfcontext, AV_LOG_DEBUG, "M%d\n", size);

    /* flush header packets so audio starts on a new page */

    if(!context->header_handled) {

	while(ogg_stream_flush(&context->os, &og)) {

	    put_buffer(&avfcontext->pb, og.header, og.header_len) ;

	    put_buffer(&avfcontext->pb, og.body, og.body_len) ;

	    put_flush_packet(&avfcontext->pb);

	}

	context->header_handled = 1 ;

    }

    op->packet = (uint8_t*) buf;

    op->bytes  = size;

    op->b_o_s  = op->packetno == 0;

    op->granulepos= pts;

    /* correct the fields in the packet -- essential for streaming */

    ogg_stream_packetin(&context->os, op);

    while(ogg_stream_pageout(&context->os, &og)) {

        put_buffer(&avfcontext->pb, og.header, og.header_len);

	put_buffer(&avfcontext->pb, og.body, og.body_len);

	put_flush_packet(&avfcontext->pb);

    }

    op->packetno++;

    return 0;

}


uint64_t helper_cvttq_svic(CPUAlphaState *env, uint64_t a)

{

    return inline_cvttq(env, a, float_round_to_zero, 1);

}


void rdma_start_incoming_migration(const char *host_port, Error **errp)

{

    int ret;

    RDMAContext *rdma;

    Error *local_err = NULL;

    DPRINTF("Starting RDMA-based incoming migration\n");

    rdma = qemu_rdma_data_init(host_port, &local_err);

    if (rdma == NULL) {

        goto err;

    }

    ret = qemu_rdma_dest_init(rdma, &local_err);

    if (ret) {

        goto err;

    }

    DPRINTF("qemu_rdma_dest_init success\n");

    ret = rdma_listen(rdma->listen_id, 5);

    if (ret) {

        ERROR(errp, "listening on socket!");

        goto err;

    }

    DPRINTF("rdma_listen success\n");

    qemu_set_fd_handler2(rdma->channel->fd, NULL,

                         rdma_accept_incoming_migration, NULL,

                            (void *)(intptr_t) rdma);

    return;

err:

    error_propagate(errp, local_err);

    g_free(rdma);

}


int hmp_pcie_aer_inject_error(Monitor *mon,

                             const QDict *qdict, QObject **ret_data)

{

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

    const char *error_name;

    uint32_t error_status;

    bool correctable;

    PCIDevice *dev;

    PCIEAERErr err;

    int ret;

    ret = pci_qdev_find_device(id, &dev);

    if (ret < 0) {

        monitor_printf(mon,

                       "id or pci device path is invalid or device not "

                       "found. %s\n", id);

        return ret;

    }

    if (!pci_is_express(dev)) {

        monitor_printf(mon, "the device doesn't support pci express. %s\n",

                       id);

        return -ENOSYS;

    }

    error_name = qdict_get_str(qdict, "error_status");

    if (pcie_aer_parse_error_string(error_name, &error_status, &correctable)) {

        char *e = NULL;

        error_status = strtoul(error_name, &e, 0);

        correctable = qdict_get_try_bool(qdict, "correctable", 0);

        if (!e || *e != '\0') {

            monitor_printf(mon, "invalid error status value. \"%s\"",

                           error_name);

            return -EINVAL;

        }

    }

    err.status = error_status;

    err.source_id = (pci_bus_num(dev->bus) << 8) | dev->devfn;

    err.flags = 0;

    if (correctable) {

        err.flags |= PCIE_AER_ERR_IS_CORRECTABLE;

    }

    if (qdict_get_try_bool(qdict, "advisory_non_fatal", 0)) {

        err.flags |= PCIE_AER_ERR_MAYBE_ADVISORY;

    }

    if (qdict_haskey(qdict, "header0")) {

        err.flags |= PCIE_AER_ERR_HEADER_VALID;

    }

    if (qdict_haskey(qdict, "prefix0")) {

        err.flags |= PCIE_AER_ERR_TLP_PREFIX_PRESENT;

    }

    err.header[0] = qdict_get_try_int(qdict, "header0", 0);

    err.header[1] = qdict_get_try_int(qdict, "header1", 0);

    err.header[2] = qdict_get_try_int(qdict, "header2", 0);

    err.header[3] = qdict_get_try_int(qdict, "header3", 0);

    err.prefix[0] = qdict_get_try_int(qdict, "prefix0", 0);

    err.prefix[1] = qdict_get_try_int(qdict, "prefix1", 0);

    err.prefix[2] = qdict_get_try_int(qdict, "prefix2", 0);

    err.prefix[3] = qdict_get_try_int(qdict, "prefix3", 0);

    ret = pcie_aer_inject_error(dev, &err);

    *ret_data = qobject_from_jsonf("{'id': %s, "

                                   "'root_bus': %s, 'bus': %d, 'devfn': %d, "

                                   "'ret': %d}",

                                   id, pci_root_bus_path(dev),

                                   pci_bus_num(dev->bus), dev->devfn,

                                   ret);

    assert(*ret_data);

    return 0;

}


static void test_opts_parse_number(void)

{

    Error *err = NULL;

    QemuOpts *opts;

    /* Lower limit zero */

    opts = qemu_opts_parse(&opts_list_01, "number1=0", false, &error_abort);

    g_assert_cmpuint(opts_count(opts), ==, 1);

    g_assert_cmpuint(qemu_opt_get_number(opts, "number1", 1), ==, 0);

    /* Upper limit 2^64-1 */

    opts = qemu_opts_parse(&opts_list_01,

                           "number1=18446744073709551615,number2=-1",

                           false, &error_abort);

    g_assert_cmpuint(opts_count(opts), ==, 2);

    g_assert_cmphex(qemu_opt_get_number(opts, "number1", 1), ==, UINT64_MAX);

    g_assert_cmphex(qemu_opt_get_number(opts, "number2", 0), ==, UINT64_MAX);

    /* Above upper limit */

    opts = qemu_opts_parse(&opts_list_01, "number1=18446744073709551616",

                           false, &error_abort);

    /* BUG: should reject */

    g_assert_cmpuint(opts_count(opts), ==, 1);

    g_assert_cmpuint(qemu_opt_get_number(opts, "number1", 1), ==, UINT64_MAX);

    /* Below lower limit */

    opts = qemu_opts_parse(&opts_list_01, "number1=-18446744073709551616",

                           false, &error_abort);

    /* BUG: should reject */

    g_assert_cmpuint(opts_count(opts), ==, 1);

    g_assert_cmpuint(qemu_opt_get_number(opts, "number1", 1), ==, UINT64_MAX);

    /* Hex and octal */

    opts = qemu_opts_parse(&opts_list_01, "number1=0x2a,number2=052",

                           false, &error_abort);

    g_assert_cmpuint(opts_count(opts), ==, 2);

    g_assert_cmpuint(qemu_opt_get_number(opts, "number1", 1), ==, 42);

    g_assert_cmpuint(qemu_opt_get_number(opts, "number2", 0), ==, 42);

    /* Invalid */

    opts = qemu_opts_parse(&opts_list_01, "number1=", false, &err);

    /* BUG: should reject */

    g_assert_cmpuint(opts_count(opts), ==, 1);

    g_assert_cmpuint(qemu_opt_get_number(opts, "number1", 1), ==, 0);

    opts = qemu_opts_parse(&opts_list_01, "number1=eins", false, &err);

    error_free_or_abort(&err);

    g_assert(!opts);

    /* Leading whitespace */

    opts = qemu_opts_parse(&opts_list_01, "number1= \t42",

                           false, &error_abort);

    g_assert_cmpuint(opts_count(opts), ==, 1);

    g_assert_cmpuint(qemu_opt_get_number(opts, "number1", 1), ==, 42);

    /* Trailing crap */

    opts = qemu_opts_parse(&opts_list_01, "number1=3.14", false, &err);

    error_free_or_abort(&err);

    g_assert(!opts);

    opts = qemu_opts_parse(&opts_list_01, "number1=08", false, &err);

    error_free_or_abort(&err);

    g_assert(!opts);

    opts = qemu_opts_parse(&opts_list_01, "number1=0 ", false, &err);

    error_free_or_abort(&err);

    g_assert(!opts);

    qemu_opts_reset(&opts_list_01);

}


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 int timebase_post_load(void *opaque, int version_id)

{

    PPCTimebase *tb_remote = opaque;

    CPUState *cpu;

    PowerPCCPU *first_ppc_cpu = POWERPC_CPU(first_cpu);

    int64_t tb_off_adj, tb_off, ns_diff;

    int64_t migration_duration_ns, migration_duration_tb, guest_tb, host_ns;

    unsigned long freq;

    if (!first_ppc_cpu->env.tb_env) {

        error_report("No timebase object");

        return -1;

    }

    freq = first_ppc_cpu->env.tb_env->tb_freq;

    /*

     * Calculate timebase on the destination side of migration.

     * The destination timebase must be not less than the source timebase.

     * We try to adjust timebase by downtime if host clocks are not

     * too much out of sync (1 second for now).

     */

    host_ns = qemu_clock_get_ns(QEMU_CLOCK_HOST);

    ns_diff = MAX(0, host_ns - tb_remote->time_of_the_day_ns);

    migration_duration_ns = MIN(NANOSECONDS_PER_SECOND, ns_diff);

    migration_duration_tb = muldiv64(migration_duration_ns, freq,

                                     NANOSECONDS_PER_SECOND);

    guest_tb = tb_remote->guest_timebase + MIN(0, migration_duration_tb);

    tb_off_adj = guest_tb - cpu_get_host_ticks();

    tb_off = first_ppc_cpu->env.tb_env->tb_offset;

    trace_ppc_tb_adjust(tb_off, tb_off_adj, tb_off_adj - tb_off,

                        (tb_off_adj - tb_off) / freq);

    /* Set new offset to all CPUs */

    CPU_FOREACH(cpu) {

        PowerPCCPU *pcpu = POWERPC_CPU(cpu);

        pcpu->env.tb_env->tb_offset = tb_off_adj;

    }

    return 0;

}


void *av_malloc(size_t size)

{

    void *ptr = NULL;

#if CONFIG_MEMALIGN_HACK

    long diff;

#endif

    /* let's disallow possible ambiguous cases */

    if(size > (INT_MAX-32) )

        return NULL;

#if CONFIG_MEMALIGN_HACK

    ptr = malloc(size+32);

    if(!ptr)

        return ptr;

    diff= ((-(long)ptr - 1)&31) + 1;

    ptr = (char*)ptr + diff;

    ((char*)ptr)[-1]= diff;

#elif HAVE_POSIX_MEMALIGN

    if (posix_memalign(&ptr,32,size))

        ptr = NULL;

#elif HAVE_MEMALIGN

    ptr = memalign(32,size);

    /* Why 64?

       Indeed, we should align it:

         on 4 for 386

         on 16 for 486

         on 32 for 586, PPro - K6-III

         on 64 for K7 (maybe for P3 too).

       Because L1 and L2 caches are aligned on those values.

       But I don't want to code such logic here!

     */

     /* Why 32?

        For AVX ASM. SSE / NEON needs only 16.

        Why not larger? Because I did not see a difference in benchmarks ...

     */

     /* benchmarks with P3

        memalign(64)+1          3071,3051,3032

        memalign(64)+2          3051,3032,3041

        memalign(64)+4          2911,2896,2915

        memalign(64)+8          2545,2554,2550

        memalign(64)+16         2543,2572,2563

        memalign(64)+32         2546,2545,2571

        memalign(64)+64         2570,2533,2558

        BTW, malloc seems to do 8-byte alignment by default here.

     */

#else

    ptr = malloc(size);

#endif

    return ptr;

}


static void decor_c(int32_t *dst, const int32_t *src, int coeff, ptrdiff_t len)

{

    int i;

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

        dst[i] += (int)(src[i] * (SUINT)coeff + (1 << 2)) >> 3;

}


static void msix_mmio_writel(void *opaque, target_phys_addr_t addr,

                             uint32_t val)

{

    PCIDevice *dev = opaque;

    unsigned int offset = addr & (MSIX_PAGE_SIZE - 1);

    int vector = offset / MSIX_ENTRY_SIZE;

    memcpy(dev->msix_table_page + offset, &val, 4);

    if (!msix_is_masked(dev, vector) && msix_is_pending(dev, vector)) {

        msix_clr_pending(dev, vector);

        msix_notify(dev, vector);

    }

}


QEMUFile *qemu_fopen_ops(void *opaque, const QEMUFileOps *ops)

{

    QEMUFile *f;

    f = g_malloc0(sizeof(QEMUFile));

    f->opaque = opaque;

    f->ops = ops;

    return f;

}


void tcg_exec_init(unsigned long tb_size)

{

    cpu_gen_init();

    code_gen_alloc(tb_size);

    page_init();

#if defined(CONFIG_SOFTMMU)

    /* There's no guest base to take into account, so go ahead and

       initialize the prologue now.  */

    tcg_prologue_init(&tcg_ctx);

#endif

}


static void bufp_free(USBRedirDevice *dev, struct buf_packet *bufp,

    uint8_t ep)

{

    QTAILQ_REMOVE(&dev->endpoint[EP2I(ep)].bufpq, bufp, next);

    dev->endpoint[EP2I(ep)].bufpq_size--;

    free(bufp->data);

    g_free(bufp);

}


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

{

    MSDState *s = (MSDState *)dev;

    int ret = 0;

    struct usb_msd_cbw cbw;

    uint8_t devep = p->devep;

    uint8_t *data = p->data;

    int len = p->len;

    switch (p->pid) {

    case USB_TOKEN_OUT:

        if (devep != 2)

            goto fail;

        switch (s->mode) {

        case USB_MSDM_CBW:

            if (len != 31) {

                fprintf(stderr, "usb-msd: Bad CBW size");

                goto fail;

            }

            memcpy(&cbw, data, 31);

            if (le32_to_cpu(cbw.sig) != 0x43425355) {

                fprintf(stderr, "usb-msd: Bad signature %08x\n",

                        le32_to_cpu(cbw.sig));

                goto fail;

            }

            DPRINTF("Command on LUN %d\n", cbw.lun);

            if (cbw.lun != 0) {

                fprintf(stderr, "usb-msd: Bad LUN %d\n", cbw.lun);

                goto fail;

            }

            s->tag = le32_to_cpu(cbw.tag);

            s->data_len = le32_to_cpu(cbw.data_len);

            if (s->data_len == 0) {

                s->mode = USB_MSDM_CSW;

            } else if (cbw.flags & 0x80) {

                s->mode = USB_MSDM_DATAIN;

            } else {

                s->mode = USB_MSDM_DATAOUT;

            }

            DPRINTF("Command tag 0x%x flags %08x len %d data %d\n",

                    s->tag, cbw.flags, cbw.cmd_len, s->data_len);

            s->residue = 0;

            s->scsi_len = 0;

            s->req = scsi_req_new(s->scsi_dev, s->tag, 0, NULL);

            scsi_req_enqueue(s->req, cbw.cmd);

            /* ??? Should check that USB and SCSI data transfer

               directions match.  */

            if (s->mode != USB_MSDM_CSW && s->residue == 0) {

                scsi_req_continue(s->req);

            }

            ret = len;

            break;

        case USB_MSDM_DATAOUT:

            DPRINTF("Data out %d/%d\n", len, s->data_len);

            if (len > s->data_len)

                goto fail;

            s->usb_buf = data;

            s->usb_len = len;

            if (s->scsi_len) {

                usb_msd_copy_data(s);

            }

            if (s->residue && s->usb_len) {

                s->data_len -= s->usb_len;

                if (s->data_len == 0)

                    s->mode = USB_MSDM_CSW;

                s->usb_len = 0;

            }

            if (s->usb_len) {

                DPRINTF("Deferring packet %p\n", p);

                s->packet = p;

                ret = USB_RET_ASYNC;

            } else {

                ret = len;

            }

            break;

        default:

            DPRINTF("Unexpected write (len %d)\n", len);

            goto fail;

        }

        break;

    case USB_TOKEN_IN:

        if (devep != 1)

            goto fail;

        switch (s->mode) {

        case USB_MSDM_DATAOUT:

            if (s->data_len != 0 || len < 13)

                goto fail;

            /* Waiting for SCSI write to complete.  */

            s->packet = p;

            ret = USB_RET_ASYNC;

            break;

        case USB_MSDM_CSW:

            DPRINTF("Command status %d tag 0x%x, len %d\n",

                    s->result, s->tag, len);

            if (len < 13)

                goto fail;

            usb_msd_send_status(s, p);

            s->mode = USB_MSDM_CBW;

            ret = 13;

            break;

        case USB_MSDM_DATAIN:

            DPRINTF("Data in %d/%d, scsi_len %d\n", len, s->data_len, s->scsi_len);

            if (len > s->data_len)

                len = s->data_len;

            s->usb_buf = data;

            s->usb_len = len;

            if (s->scsi_len) {

                usb_msd_copy_data(s);

            }

            if (s->residue && s->usb_len) {

                s->data_len -= s->usb_len;

                memset(s->usb_buf, 0, s->usb_len);

                if (s->data_len == 0)

                    s->mode = USB_MSDM_CSW;

                s->usb_len = 0;

            }

            if (s->usb_len) {

                DPRINTF("Deferring packet %p\n", p);

                s->packet = p;

                ret = USB_RET_ASYNC;

            } else {

                ret = len;

            }

            break;

        default:

            DPRINTF("Unexpected read (len %d)\n", len);

            goto fail;

        }

        break;

    default:

        DPRINTF("Bad token\n");

    fail:

        ret = USB_RET_STALL;

        break;

    }

    return ret;

}


static Visitor *validate_test_init_internal(TestInputVisitorData *data,
                                            const char *json_string,
                                            va_list *ap)
{
    Visitor *v;
    data->obj = qobject_from_jsonv(json_string, ap);
    g_assert(data->obj);
    data->qiv = qmp_input_visitor_new_strict(data->obj);
    g_assert(data->qiv);
    v = qmp_input_get_visitor(data->qiv);
    g_assert(v);
    return v;
}


static inline void RENAME(rgb32to16)(const uint8_t *src, uint8_t *dst, unsigned src_size)

{

	const uint8_t *s = src;

	const uint8_t *end;

#ifdef HAVE_MMX

	const uint8_t *mm_end;

#endif

	uint16_t *d = (uint16_t *)dst;

	end = s + src_size;

#ifdef HAVE_MMX

	mm_end = end - 15;

#if 1 //is faster only if multiplies are reasonable fast (FIXME figure out on which cpus this is faster, on Athlon its slightly faster)

	asm volatile(

		"movq %3, %%mm5			\n\t"

		"movq %4, %%mm6			\n\t"

		"movq %5, %%mm7			\n\t"

		".balign 16			\n\t"

		"1:				\n\t"

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

		"movd	(%1), %%mm0		\n\t"

		"movd	4(%1), %%mm3		\n\t"

		"punpckldq 8(%1), %%mm0		\n\t"

		"punpckldq 12(%1), %%mm3	\n\t"

		"movq %%mm0, %%mm1		\n\t"

		"movq %%mm3, %%mm4		\n\t"

		"pand %%mm6, %%mm0		\n\t"

		"pand %%mm6, %%mm3		\n\t"

		"pmaddwd %%mm7, %%mm0		\n\t"

		"pmaddwd %%mm7, %%mm3		\n\t"

		"pand %%mm5, %%mm1		\n\t"

		"pand %%mm5, %%mm4		\n\t"

		"por %%mm1, %%mm0		\n\t"

		"por %%mm4, %%mm3		\n\t"

		"psrld $5, %%mm0		\n\t"

		"pslld $11, %%mm3		\n\t"

		"por %%mm3, %%mm0		\n\t"

		MOVNTQ"	%%mm0, (%0)		\n\t"

		"add $16, %1			\n\t"

		"add $8, %0			\n\t"

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

		" jb 1b				\n\t"

		: "+r" (d), "+r"(s)

		: "r" (mm_end), "m" (mask3216g), "m" (mask3216br), "m" (mul3216)

	);

#else

	__asm __volatile(PREFETCH"	%0"::"m"(*src):"memory");

	__asm __volatile(

	    "movq	%0, %%mm7\n\t"

	    "movq	%1, %%mm6\n\t"

	    ::"m"(red_16mask),"m"(green_16mask));

	while(s < mm_end)

	{

	    __asm __volatile(

		PREFETCH" 32%1\n\t"

		"movd	%1, %%mm0\n\t"

		"movd	4%1, %%mm3\n\t"

		"punpckldq 8%1, %%mm0\n\t"

		"punpckldq 12%1, %%mm3\n\t"

		"movq	%%mm0, %%mm1\n\t"

		"movq	%%mm0, %%mm2\n\t"

		"movq	%%mm3, %%mm4\n\t"

		"movq	%%mm3, %%mm5\n\t"

		"psrlq	$3, %%mm0\n\t"

		"psrlq	$3, %%mm3\n\t"

		"pand	%2, %%mm0\n\t"

		"pand	%2, %%mm3\n\t"

		"psrlq	$5, %%mm1\n\t"

		"psrlq	$5, %%mm4\n\t"

		"pand	%%mm6, %%mm1\n\t"

		"pand	%%mm6, %%mm4\n\t"

		"psrlq	$8, %%mm2\n\t"

		"psrlq	$8, %%mm5\n\t"

		"pand	%%mm7, %%mm2\n\t"

		"pand	%%mm7, %%mm5\n\t"

		"por	%%mm1, %%mm0\n\t"

		"por	%%mm4, %%mm3\n\t"

		"por	%%mm2, %%mm0\n\t"

		"por	%%mm5, %%mm3\n\t"

		"psllq	$16, %%mm3\n\t"

		"por	%%mm3, %%mm0\n\t"

		MOVNTQ"	%%mm0, %0\n\t"

		:"=m"(*d):"m"(*s),"m"(blue_16mask):"memory");

		d += 4;

		s += 16;

	}

#endif

	__asm __volatile(SFENCE:::"memory");

	__asm __volatile(EMMS:::"memory");

#endif

	while(s < end)

	{

		register int rgb = *(uint32_t*)s; s += 4;

		*d++ = ((rgb&0xFF)>>3) + ((rgb&0xFC00)>>5) + ((rgb&0xF80000)>>8);

	}

}


static void spapr_core_pre_plug(HotplugHandler *hotplug_dev, DeviceState *dev,

                                Error **errp)

{

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

    MachineClass *mc = MACHINE_GET_CLASS(hotplug_dev);

    Error *local_err = NULL;

    CPUCore *cc = CPU_CORE(dev);

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

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

    CPUArchId *core_slot;

    int index;

    if (dev->hotplugged && !mc->has_hotpluggable_cpus) {

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

        goto out;

    }

    if (strcmp(base_core_type, type)) {

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

        goto out;

    }

    if (cc->core_id % smp_threads) {

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

        goto out;

    }

    /*

     * In general we should have homogeneous threads-per-core, but old

     * (pre hotplug support) machine types allow the last core to have

     * reduced threads as a compatibility hack for when we allowed

     * total vcpus not a multiple of threads-per-core.

     */

    if (mc->has_hotpluggable_cpus && (cc->nr_threads != smp_threads)) {

        error_setg(errp, "invalid nr-threads %d, must be %d",

                   cc->nr_threads, smp_threads);

        return;

    }

    core_slot = spapr_find_cpu_slot(MACHINE(hotplug_dev), cc->core_id, &index);

    if (!core_slot) {

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

        goto out;

    }

    if (core_slot->cpu) {

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

        goto out;

    }

    numa_cpu_pre_plug(core_slot, dev, &local_err);

out:

    g_free(base_core_type);

    error_propagate(errp, local_err);

}


static av_cold int pulse_write_header(AVFormatContext *h)

{

    PulseData *s = h->priv_data;

    AVStream *st = NULL;

    int ret;

    unsigned int i;

    pa_sample_spec ss;

    pa_buffer_attr attr = { -1, -1, -1, -1, -1 };

    const char *stream_name = s->stream_name;

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

        if (h->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO) {

            st = h->streams[i];

            s->stream_index = i;

            break;

        }

    }

    if (!st) {

        av_log(s, AV_LOG_ERROR, "No audio stream found.\n");

        return AVERROR(EINVAL);

    }

    if (!stream_name) {

        if (h->filename[0])

            stream_name = h->filename;

        else

            stream_name = "Playback";

    }

    ss.format = codec_id_to_pulse_format(st->codec->codec_id);

    ss.rate = st->codec->sample_rate;

    ss.channels = st->codec->channels;

    s->pa = pa_simple_new(s->server,                 // Server

                          s->name,                   // Application name

                          PA_STREAM_PLAYBACK,

                          s->device,                 // Device

                          stream_name,               // Description of a stream

                          &ss,                       // Sample format

                          NULL,                      // Use default channel map

                          &attr,                     // Buffering attributes

                          &ret);                     // Result

    if (!s->pa) {

        av_log(s, AV_LOG_ERROR, "pa_simple_new failed: %s\n", pa_strerror(ret));

        return AVERROR(EIO);

    }

    avpriv_set_pts_info(st, 64, 1, 1000000);  /* 64 bits pts in us */

    return 0;

}