static int decode_subframe_lpc(ShortenContext *s, int command, int channel,

                               int residual_size, int32_t coffset)

{

    int pred_order, sum, qshift, init_sum, i, j;

    const int *coeffs;

    if (command == FN_QLPC) {

        /* read/validate prediction order */

        pred_order = get_ur_golomb_shorten(&s->gb, LPCQSIZE);

        if (pred_order > s->nwrap) {

            av_log(s->avctx, AV_LOG_ERROR, "invalid pred_order %d\n",

                   pred_order);

            return AVERROR(EINVAL);

        }

        /* read LPC coefficients */

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

            s->coeffs[i] = get_sr_golomb_shorten(&s->gb, LPCQUANT);

        coeffs = s->coeffs;

        qshift = LPCQUANT;

    } else {

        /* fixed LPC coeffs */

        pred_order = command;

        if (pred_order >= FF_ARRAY_ELEMS(fixed_coeffs)) {

            av_log(s->avctx, AV_LOG_ERROR, "invalid pred_order %d\n",

                   pred_order);

            return AVERROR_INVALIDDATA;

        }

        coeffs     = fixed_coeffs[pred_order];

        qshift     = 0;

    }

    /* subtract offset from previous samples to use in prediction */

    if (command == FN_QLPC && coffset)

        for (i = -pred_order; i < 0; i++)

            s->decoded[channel][i] -= coffset;

    /* decode residual and do LPC prediction */

    init_sum = pred_order ? (command == FN_QLPC ? s->lpcqoffset : 0) : coffset;

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

        sum = init_sum;

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

            sum += coeffs[j] * s->decoded[channel][i - j - 1];

        s->decoded[channel][i] = get_sr_golomb_shorten(&s->gb, residual_size) +

                                 (sum >> qshift);

    }

    /* add offset to current samples */

    if (command == FN_QLPC && coffset)

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

            s->decoded[channel][i] += coffset;

    return 0;

}


static int coroutine_fn blkreplay_co_pwritev(BlockDriverState *bs,

    uint64_t offset, uint64_t bytes, QEMUIOVector *qiov, int flags)

{

    uint64_t reqid = request_id++;

    int ret = bdrv_co_pwritev(bs->file->bs, offset, bytes, qiov, flags);

    block_request_create(reqid, bs, qemu_coroutine_self());

    qemu_coroutine_yield();

    return ret;

}


static void hmp_handle_error(Monitor *mon, Error **errp)

{

    if (error_is_set(errp)) {

        monitor_printf(mon, "%s\n", error_get_pretty(*errp));

        error_free(*errp);

    }

}


void mips_r4k_init (ram_addr_t ram_size,

                    const char *boot_device,

                    const char *kernel_filename, const char *kernel_cmdline,

                    const char *initrd_filename, const char *cpu_model)

{

    char *filename;

    MemoryRegion *address_space_mem = get_system_memory();

    MemoryRegion *ram = g_new(MemoryRegion, 1);

    MemoryRegion *bios;

    MemoryRegion *iomem = g_new(MemoryRegion, 1);

    int bios_size;

    CPUState *env;

    ResetData *reset_info;

    int i;

    qemu_irq *i8259;

    DriveInfo *hd[MAX_IDE_BUS * MAX_IDE_DEVS];

    DriveInfo *dinfo;

    int be;

    /* init CPUs */

    if (cpu_model == NULL) {

#ifdef TARGET_MIPS64

        cpu_model = "R4000";

#else

        cpu_model = "24Kf";

#endif

    }

    env = cpu_init(cpu_model);

    if (!env) {

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

        exit(1);

    }

    reset_info = g_malloc0(sizeof(ResetData));

    reset_info->env = env;

    reset_info->vector = env->active_tc.PC;

    qemu_register_reset(main_cpu_reset, reset_info);

    /* allocate RAM */

    if (ram_size > (256 << 20)) {

        fprintf(stderr,

                "qemu: Too much memory for this machine: %d MB, maximum 256 MB\n",

                ((unsigned int)ram_size / (1 << 20)));

        exit(1);

    }

    memory_region_init_ram(ram, NULL, "mips_r4k.ram", ram_size);

    memory_region_add_subregion(address_space_mem, 0, ram);

    memory_region_init_io(iomem, &mips_qemu_ops, NULL, "mips-qemu", 0x10000);

    memory_region_add_subregion(address_space_mem, 0x1fbf0000, iomem);

    /* Try to load a BIOS image. If this fails, we continue regardless,

       but initialize the hardware ourselves. When a kernel gets

       preloaded we also initialize the hardware, since the BIOS wasn't

       run. */

    if (bios_name == NULL)

        bios_name = BIOS_FILENAME;

    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);

    if (filename) {

        bios_size = get_image_size(filename);

    } else {

        bios_size = -1;

    }

#ifdef TARGET_WORDS_BIGENDIAN

    be = 1;

#else

    be = 0;

#endif

    if ((bios_size > 0) && (bios_size <= BIOS_SIZE)) {

        bios = g_new(MemoryRegion, 1);

        memory_region_init_ram(bios, NULL, "mips_r4k.bios", BIOS_SIZE);

        memory_region_set_readonly(bios, true);

        memory_region_add_subregion(get_system_memory(), 0x1fc00000, bios);

        load_image_targphys(filename, 0x1fc00000, BIOS_SIZE);

    } else if ((dinfo = drive_get(IF_PFLASH, 0, 0)) != NULL) {

        uint32_t mips_rom = 0x00400000;

        if (!pflash_cfi01_register(0x1fc00000, NULL, "mips_r4k.bios", mips_rom,

                                   dinfo->bdrv, sector_len,

                                   mips_rom / sector_len,

                                   4, 0, 0, 0, 0, be)) {

            fprintf(stderr, "qemu: Error registering flash memory.\n");

	}

    }

    else {

	/* not fatal */

        fprintf(stderr, "qemu: Warning, could not load MIPS bios '%s'\n",

		bios_name);

    }

    if (filename) {

        g_free(filename);

    }

    if (kernel_filename) {

        loaderparams.ram_size = ram_size;

        loaderparams.kernel_filename = kernel_filename;

        loaderparams.kernel_cmdline = kernel_cmdline;

        loaderparams.initrd_filename = initrd_filename;

        reset_info->vector = load_kernel();

    }

    /* Init CPU internal devices */

    cpu_mips_irq_init_cpu(env);

    cpu_mips_clock_init(env);

    /* The PIC is attached to the MIPS CPU INT0 pin */

    i8259 = i8259_init(env->irq[2]);

    isa_bus_new(NULL, get_system_io());

    isa_bus_irqs(i8259);

    rtc_init(2000, NULL);

    /* Register 64 KB of ISA IO space at 0x14000000 */

    isa_mmio_init(0x14000000, 0x00010000);

    isa_mem_base = 0x10000000;

    pit = pit_init(0x40, 0);

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

        if (serial_hds[i]) {

            serial_isa_init(i, serial_hds[i]);

        }

    }

    isa_vga_init();

    if (nd_table[0].vlan)

        isa_ne2000_init(0x300, 9, &nd_table[0]);

    ide_drive_get(hd, MAX_IDE_BUS);

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

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

                     hd[MAX_IDE_DEVS * i],

		     hd[MAX_IDE_DEVS * i + 1]);

    isa_create_simple("i8042");

}


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

                    Error **errp)

{

    BDRVDMGState *s = bs->opaque;

    DmgHeaderState ds;

    uint64_t rsrc_fork_offset, rsrc_fork_length;

    uint64_t plist_xml_offset, plist_xml_length;

    int64_t offset;

    int ret;

    bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file,

                               false, errp);

    if (!bs->file) {

        return -EINVAL;

    }

    block_module_load_one("dmg-bz2");

    bs->read_only = true;

    s->n_chunks = 0;

    s->offsets = s->lengths = s->sectors = s->sectorcounts = NULL;

    /* used by dmg_read_mish_block to keep track of the current I/O position */

    ds.data_fork_offset = 0;

    ds.max_compressed_size = 1;

    ds.max_sectors_per_chunk = 1;

    /* locate the UDIF trailer */

    offset = dmg_find_koly_offset(bs->file, errp);

    if (offset < 0) {

        ret = offset;

        goto fail;

    }

    /* offset of data fork (DataForkOffset) */

    ret = read_uint64(bs, offset + 0x18, &ds.data_fork_offset);

    if (ret < 0) {

        goto fail;

    } else if (ds.data_fork_offset > offset) {

        ret = -EINVAL;

        goto fail;

    }

    /* offset of resource fork (RsrcForkOffset) */

    ret = read_uint64(bs, offset + 0x28, &rsrc_fork_offset);

    if (ret < 0) {

        goto fail;

    }

    ret = read_uint64(bs, offset + 0x30, &rsrc_fork_length);

    if (ret < 0) {

        goto fail;

    }

    if (rsrc_fork_offset >= offset ||

        rsrc_fork_length > offset - rsrc_fork_offset) {

        ret = -EINVAL;

        goto fail;

    }

    /* offset of property list (XMLOffset) */

    ret = read_uint64(bs, offset + 0xd8, &plist_xml_offset);

    if (ret < 0) {

        goto fail;

    }

    ret = read_uint64(bs, offset + 0xe0, &plist_xml_length);

    if (ret < 0) {

        goto fail;

    }

    if (plist_xml_offset >= offset ||

        plist_xml_length > offset - plist_xml_offset) {

        ret = -EINVAL;

        goto fail;

    }

    ret = read_uint64(bs, offset + 0x1ec, (uint64_t *)&bs->total_sectors);

    if (ret < 0) {

        goto fail;

    }

    if (bs->total_sectors < 0) {

        ret = -EINVAL;

        goto fail;

    }

    if (rsrc_fork_length != 0) {

        ret = dmg_read_resource_fork(bs, &ds,

                                     rsrc_fork_offset, rsrc_fork_length);

        if (ret < 0) {

            goto fail;

        }

    } else if (plist_xml_length != 0) {

        ret = dmg_read_plist_xml(bs, &ds, plist_xml_offset, plist_xml_length);

        if (ret < 0) {

            goto fail;

        }

    } else {

        ret = -EINVAL;

        goto fail;

    }

    /* initialize zlib engine */

    s->compressed_chunk = qemu_try_blockalign(bs->file->bs,

                                              ds.max_compressed_size + 1);

    s->uncompressed_chunk = qemu_try_blockalign(bs->file->bs,

                                                512 * ds.max_sectors_per_chunk);

    if (s->compressed_chunk == NULL || s->uncompressed_chunk == NULL) {

        ret = -ENOMEM;

        goto fail;

    }

    if (inflateInit(&s->zstream) != Z_OK) {

        ret = -EINVAL;

        goto fail;

    }

    s->current_chunk = s->n_chunks;

    qemu_co_mutex_init(&s->lock);

    return 0;

fail:

    g_free(s->types);

    g_free(s->offsets);

    g_free(s->lengths);

    g_free(s->sectors);

    g_free(s->sectorcounts);

    qemu_vfree(s->compressed_chunk);

    qemu_vfree(s->uncompressed_chunk);

    return ret;

}


void bdrv_detach_aio_context(BlockDriverState *bs)

{

    BdrvAioNotifier *baf;

    if (!bs->drv) {

        return;

    }

    QLIST_FOREACH(baf, &bs->aio_notifiers, list) {

        baf->detach_aio_context(baf->opaque);

    }

    if (bs->io_limits_enabled) {

        throttle_timers_detach_aio_context(&bs->throttle_timers);

    }

    if (bs->drv->bdrv_detach_aio_context) {

        bs->drv->bdrv_detach_aio_context(bs);

    }

    if (bs->file) {

        bdrv_detach_aio_context(bs->file->bs);

    }

    if (bs->backing) {

        bdrv_detach_aio_context(bs->backing->bs);

    }

    bs->aio_context = NULL;

}


static int virtio_rng_load(QEMUFile *f, void *opaque, int version_id)

{

    VirtIORNG *vrng = opaque;

    VirtIODevice *vdev = VIRTIO_DEVICE(vrng);

    if (version_id != 1) {

        return -EINVAL;

    }

    virtio_load(vdev, f, version_id);

    /* We may have an element ready but couldn't process it due to a quota

     * limit.  Make sure to try again after live migration when the quota may

     * have been reset.

     */

    virtio_rng_process(vrng);

    return 0;

}


static av_cold int roq_dpcm_encode_init(AVCodecContext *avctx)

{

    ROQDPCMContext *context = avctx->priv_data;

    if (avctx->channels > 2) {

        av_log(avctx, AV_LOG_ERROR, "Audio must be mono or stereo\n");

        return -1;

    }

    if (avctx->sample_rate != 22050) {

        av_log(avctx, AV_LOG_ERROR, "Audio must be 22050 Hz\n");

        return -1;

    }

    if (avctx->sample_fmt != AV_SAMPLE_FMT_S16) {

        av_log(avctx, AV_LOG_ERROR, "Audio must be signed 16-bit\n");

        return -1;

    }

    avctx->frame_size = ROQ_FIRST_FRAME_SIZE;

    context->lastSample[0] = context->lastSample[1] = 0;

    avctx->coded_frame= avcodec_alloc_frame();

    if (!avctx->coded_frame)

        return AVERROR(ENOMEM);

    return 0;

}


static void kvm_mce_inj_srar_dataload(CPUState *env, target_phys_addr_t paddr)

{

    struct kvm_x86_mce mce = {

        .bank = 9,

        .status = MCI_STATUS_VAL | MCI_STATUS_UC | MCI_STATUS_EN

                  | MCI_STATUS_MISCV | MCI_STATUS_ADDRV | MCI_STATUS_S

                  | MCI_STATUS_AR | 0x134,

        .mcg_status = MCG_STATUS_MCIP | MCG_STATUS_EIPV,

        .addr = paddr,

        .misc = (MCM_ADDR_PHYS << 6) | 0xc,

    };

    int r;

    r = kvm_set_mce(env, &mce);

    if (r < 0) {

        fprintf(stderr, "kvm_set_mce: %s\n", strerror(errno));

        abort();

    }

    kvm_mce_broadcast_rest(env);

}


int qemu_global_option(const char *str)

{

    char driver[64], property[64];

    QemuOpts *opts;

    int rc, offset;

    rc = sscanf(str, "%63[^.].%63[^=]%n", driver, property, &offset);

    if (rc < 2 || str[offset] != '=') {

        error_report("can't parse: \"%s\"", str);

        return -1;

    }

    opts = qemu_opts_create(&qemu_global_opts, NULL, 0, &error_abort);

    qemu_opt_set(opts, "driver", driver, &error_abort);

    qemu_opt_set(opts, "property", property, &error_abort);

    qemu_opt_set(opts, "value", str + offset + 1, &error_abort);

    return 0;

}


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

{

    UHCIState *s = opaque;

    addr &= 0x1f;

    DPRINTF("uhci: writew port=0x%04x val=0x%04x\n", addr, val);

    switch(addr) {

    case 0x00:

        if ((val & UHCI_CMD_RS) && !(s->cmd & UHCI_CMD_RS)) {

            /* start frame processing */

            s->expire_time = qemu_get_clock_ns(vm_clock) +

                (get_ticks_per_sec() / FRAME_TIMER_FREQ);

            qemu_mod_timer(s->frame_timer, qemu_get_clock_ns(vm_clock));

            s->status &= ~UHCI_STS_HCHALTED;

        } else if (!(val & UHCI_CMD_RS)) {

            s->status |= UHCI_STS_HCHALTED;

        }

        if (val & UHCI_CMD_GRESET) {

            UHCIPort *port;

            USBDevice *dev;

            int i;

            /* send reset on the USB bus */

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

                port = &s->ports[i];

                dev = port->port.dev;

                if (dev) {

                    usb_send_msg(dev, USB_MSG_RESET);

                }

            }

            uhci_reset(s);

            return;

        }

        if (val & UHCI_CMD_HCRESET) {

            uhci_reset(s);

            return;

        }

        s->cmd = val;

        break;

    case 0x02:

        s->status &= ~val;

        /* XXX: the chip spec is not coherent, so we add a hidden

           register to distinguish between IOC and SPD */

        if (val & UHCI_STS_USBINT)

            s->status2 = 0;

        uhci_update_irq(s);

        break;

    case 0x04:

        s->intr = val;

        uhci_update_irq(s);

        break;

    case 0x06:

        if (s->status & UHCI_STS_HCHALTED)

            s->frnum = val & 0x7ff;

        break;

    case 0x10 ... 0x1f:

        {

            UHCIPort *port;

            USBDevice *dev;

            int n;

            n = (addr >> 1) & 7;

            if (n >= NB_PORTS)

                return;

            port = &s->ports[n];

            dev = port->port.dev;

            if (dev) {

                /* port reset */

                if ( (val & UHCI_PORT_RESET) &&

                     !(port->ctrl & UHCI_PORT_RESET) ) {

                    usb_send_msg(dev, USB_MSG_RESET);

                }

            }

            port->ctrl &= UHCI_PORT_READ_ONLY;

            port->ctrl |= (val & ~UHCI_PORT_READ_ONLY);

            /* some bits are reset when a '1' is written to them */

            port->ctrl &= ~(val & UHCI_PORT_WRITE_CLEAR);

        }

        break;

    }

}


static void tlb_info_pae32(Monitor *mon, CPUState *env)

{

    int l1, l2, l3;

    uint64_t pdpe, pde, pte;

    uint64_t pdp_addr, pd_addr, pt_addr;

    pdp_addr = env->cr[3] & ~0x1f;

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

        cpu_physical_memory_read(pdp_addr + l1 * 8, &pdpe, 8);

        pdpe = le64_to_cpu(pdpe);

        if (pdpe & PG_PRESENT_MASK) {

            pd_addr = pdpe & 0x3fffffffff000ULL;

            for (l2 = 0; l2 < 512; l2++) {

                cpu_physical_memory_read(pd_addr + l2 * 8, &pde, 8);

                pde = le64_to_cpu(pde);

                if (pde & PG_PRESENT_MASK) {

                    if (pde & PG_PSE_MASK) {

                        /* 2M pages with PAE, CR4.PSE is ignored */

                        print_pte(mon, (l1 << 30 ) + (l2 << 21), pde,

                                  ~((target_phys_addr_t)(1 << 20) - 1));

                    } else {

                        pt_addr = pde & 0x3fffffffff000ULL;

                        for (l3 = 0; l3 < 512; l3++) {

                            cpu_physical_memory_read(pt_addr + l3 * 8, &pte, 8);

                            pte = le64_to_cpu(pte);

                            if (pte & PG_PRESENT_MASK) {

                                print_pte(mon, (l1 << 30 ) + (l2 << 21)

                                          + (l3 << 12),

                                          pte & ~PG_PSE_MASK,

                                          ~(target_phys_addr_t)0xfff);

                            }

                        }

                    }

                }

            }

        }

    }

}


void *paio_init(void)

{

    struct sigaction act;

    PosixAioState *s;

    int fds[2];

    int ret;

    if (posix_aio_state)

        return posix_aio_state;

    s = qemu_malloc(sizeof(PosixAioState));

    sigfillset(&act.sa_mask);

    act.sa_flags = 0; /* do not restart syscalls to interrupt select() */

    act.sa_handler = aio_signal_handler;

    sigaction(SIGUSR2, &act, NULL);

    s->first_aio = NULL;

    if (pipe(fds) == -1) {

        fprintf(stderr, "failed to create pipe\n");

        return NULL;

    }

    s->rfd = fds[0];

    s->wfd = fds[1];

    fcntl(s->rfd, F_SETFL, O_NONBLOCK);

    fcntl(s->wfd, F_SETFL, O_NONBLOCK);

    qemu_aio_set_fd_handler(s->rfd, posix_aio_read, NULL, posix_aio_flush, s);

    ret = pthread_attr_init(&attr);

    if (ret)

        die2(ret, "pthread_attr_init");

    ret = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

    if (ret)

        die2(ret, "pthread_attr_setdetachstate");

    TAILQ_INIT(&request_list);

    posix_aio_state = s;

    return posix_aio_state;

}


static void close_slaves(AVFormatContext *avf)

{

    TeeContext *tee = avf->priv_data;

    AVFormatContext *avf2;

    unsigned i, j;

    for (i = 0; i < tee->nb_slaves; i++) {

        avf2 = tee->slaves[i].avf;

        for (j = 0; j < avf2->nb_streams; j++) {

            AVBitStreamFilterContext *bsf_next, *bsf = tee->slaves[i].bsfs[j];

            while (bsf) {

                bsf_next = bsf->next;

                av_bitstream_filter_close(bsf);

                bsf = bsf_next;

            }

        }

        av_freep(&tee->slaves[i].stream_map);

        avio_close(avf2->pb);

        avf2->pb = NULL;

        avformat_free_context(avf2);

        tee->slaves[i].avf = NULL;

    }

}


static int update_context_from_thread(AVCodecContext *dst, AVCodecContext *src, int for_user)

{

    int err = 0;

    if (dst != src) {

        dst->sub_id    = src->sub_id;

        dst->time_base = src->time_base;

        dst->width     = src->width;

        dst->height    = src->height;

        dst->pix_fmt   = src->pix_fmt;

        dst->coded_width  = src->coded_width;

        dst->coded_height = src->coded_height;

        dst->has_b_frames = src->has_b_frames;

        dst->idct_algo    = src->idct_algo;

        dst->slice_count  = src->slice_count;

        dst->bits_per_coded_sample = src->bits_per_coded_sample;

        dst->sample_aspect_ratio   = src->sample_aspect_ratio;

        dst->dtg_active_format     = src->dtg_active_format;

        dst->profile = src->profile;

        dst->level   = src->level;

        dst->bits_per_raw_sample = src->bits_per_raw_sample;

        dst->ticks_per_frame     = src->ticks_per_frame;

        dst->color_primaries     = src->color_primaries;

        dst->color_trc   = src->color_trc;

        dst->colorspace  = src->colorspace;

        dst->color_range = src->color_range;

        dst->chroma_sample_location = src->chroma_sample_location;

    }

    if (for_user) {

        dst->coded_frame   = src->coded_frame;

        dst->has_b_frames += src->thread_count - 1;

    } else {

        if (dst->codec->update_thread_context)

            err = dst->codec->update_thread_context(dst, src);

    }

    return err;

}


static int v4l2_set_parameters(AVFormatContext *s1)

{

    struct video_data *s = s1->priv_data;

    struct v4l2_standard standard = { 0 };

    struct v4l2_streamparm streamparm = { 0 };

    struct v4l2_fract *tpf;

    AVRational framerate_q = { 0 };

    int i, ret;

    if (s->framerate &&

        (ret = av_parse_video_rate(&framerate_q, s->framerate)) < 0) {

        av_log(s1, AV_LOG_ERROR, "Could not parse framerate '%s'.\n",

               s->framerate);

        return ret;

    }

    if (s->standard) {

        if (s->std_id) {

            ret = 0;

            av_log(s1, AV_LOG_DEBUG, "Setting standard: %s\n", s->standard);

            /* set tv standard */

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

                standard.index = i;

                if (v4l2_ioctl(s->fd, VIDIOC_ENUMSTD, &standard) < 0) {

                    ret = AVERROR(errno);

                    break;

                }

                if (!av_strcasecmp(standard.name, s->standard))

                    break;

            }

            if (ret < 0) {

                av_log(s1, AV_LOG_ERROR, "Unknown or unsupported standard '%s'\n", s->standard);

                return ret;

            }

            if (v4l2_ioctl(s->fd, VIDIOC_S_STD, &standard.id) < 0) {

                ret = AVERROR(errno);

                av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_S_STD): %s\n", av_err2str(ret));

                return ret;

            }

        } else {

            av_log(s1, AV_LOG_WARNING,

                   "This device does not support any standard\n");

        }

    }

    /* get standard */

    if (v4l2_ioctl(s->fd, VIDIOC_G_STD, &s->std_id) == 0) {

        tpf = &standard.frameperiod;

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

            standard.index = i;

            if (v4l2_ioctl(s->fd, VIDIOC_ENUMSTD, &standard) < 0) {

                ret = AVERROR(errno);

                if (ret == AVERROR(EINVAL)) {

                    tpf = &streamparm.parm.capture.timeperframe;

                    break;

                }

                av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_ENUMSTD): %s\n", av_err2str(ret));

                return ret;

            }

            if (standard.id == s->std_id) {

                av_log(s1, AV_LOG_DEBUG,

                       "Current standard: %s, id: %"PRIx64", frameperiod: %d/%d\n",

                       standard.name, (uint64_t)standard.id, tpf->numerator, tpf->denominator);

                break;

            }

        }

    } else {

        tpf = &streamparm.parm.capture.timeperframe;

    }

    streamparm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;

    if (v4l2_ioctl(s->fd, VIDIOC_G_PARM, &streamparm) < 0) {

        ret = AVERROR(errno);

        av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_G_PARM): %s\n", av_err2str(ret));

        return ret;

    }

    if (framerate_q.num && framerate_q.den) {

        if (streamparm.parm.capture.capability & V4L2_CAP_TIMEPERFRAME) {

            tpf = &streamparm.parm.capture.timeperframe;

            av_log(s1, AV_LOG_DEBUG, "Setting time per frame to %d/%d\n",

                   framerate_q.den, framerate_q.num);

            tpf->numerator   = framerate_q.den;

            tpf->denominator = framerate_q.num;

            if (v4l2_ioctl(s->fd, VIDIOC_S_PARM, &streamparm) < 0) {

                ret = AVERROR(errno);

                av_log(s1, AV_LOG_ERROR, "ioctl(VIDIOC_S_PARM): %s\n", av_err2str(ret));

                return ret;

            }

            if (framerate_q.num != tpf->denominator ||

                framerate_q.den != tpf->numerator) {

                av_log(s1, AV_LOG_INFO,

                       "The driver changed the time per frame from "

                       "%d/%d to %d/%d\n",

                       framerate_q.den, framerate_q.num,

                       tpf->numerator, tpf->denominator);

            }

        } else {

            av_log(s1, AV_LOG_WARNING,

                   "The driver does not allow to change time per frame\n");

        }

    }

    if (tpf->denominator > 0 && tpf->numerator > 0) {

        s1->streams[0]->avg_frame_rate.num = tpf->denominator;

        s1->streams[0]->avg_frame_rate.den = tpf->numerator;

        s1->streams[0]->r_frame_rate = s1->streams[0]->avg_frame_rate;

    } else

        av_log(s1, AV_LOG_WARNING, "Time per frame unknown\n");

    return 0;

}


static target_long monitor_get_tbu (const struct MonitorDef *md, int val)

{

    CPUState *env = mon_get_cpu();

    if (!env)

        return 0;

    return cpu_ppc_load_tbu(env);

}


static void decorrelation(PSContext *ps, INTFLOAT (*out)[32][2], const INTFLOAT (*s)[32][2], int is34)

{

    LOCAL_ALIGNED_16(INTFLOAT, power, [34], [PS_QMF_TIME_SLOTS]);

    LOCAL_ALIGNED_16(INTFLOAT, transient_gain, [34], [PS_QMF_TIME_SLOTS]);

    INTFLOAT *peak_decay_nrg = ps->peak_decay_nrg;

    INTFLOAT *power_smooth = ps->power_smooth;

    INTFLOAT *peak_decay_diff_smooth = ps->peak_decay_diff_smooth;

    INTFLOAT (*delay)[PS_QMF_TIME_SLOTS + PS_MAX_DELAY][2] = ps->delay;

    INTFLOAT (*ap_delay)[PS_AP_LINKS][PS_QMF_TIME_SLOTS + PS_MAX_AP_DELAY][2] = ps->ap_delay;

#if !USE_FIXED

    const float transient_impact  = 1.5f;

    const float a_smooth          = 0.25f; ///< Smoothing coefficient

#endif /* USE_FIXED */

    const int8_t *k_to_i = is34 ? k_to_i_34 : k_to_i_20;

    int i, k, m, n;

    int n0 = 0, nL = 32;

    const INTFLOAT peak_decay_factor = Q31(0.76592833836465f);

    memset(power, 0, 34 * sizeof(*power));

    if (is34 != ps->is34bands_old) {

        memset(ps->peak_decay_nrg,         0, sizeof(ps->peak_decay_nrg));

        memset(ps->power_smooth,           0, sizeof(ps->power_smooth));

        memset(ps->peak_decay_diff_smooth, 0, sizeof(ps->peak_decay_diff_smooth));

        memset(ps->delay,                  0, sizeof(ps->delay));

        memset(ps->ap_delay,               0, sizeof(ps->ap_delay));

    }

    for (k = 0; k < NR_BANDS[is34]; k++) {

        int i = k_to_i[k];

        ps->dsp.add_squares(power[i], s[k], nL - n0);

    }

    //Transient detection

#if USE_FIXED

    for (i = 0; i < NR_PAR_BANDS[is34]; i++) {

        for (n = n0; n < nL; n++) {

            int decayed_peak;

            int denom;

            decayed_peak = (int)(((int64_t)peak_decay_factor * \

                                           peak_decay_nrg[i] + 0x40000000) >> 31);

            peak_decay_nrg[i] = FFMAX(decayed_peak, power[i][n]);

            power_smooth[i] += (power[i][n] - power_smooth[i] + 2) >> 2;

            peak_decay_diff_smooth[i] += (peak_decay_nrg[i] - power[i][n] - \

                                          peak_decay_diff_smooth[i] + 2) >> 2;

            denom = peak_decay_diff_smooth[i] + (peak_decay_diff_smooth[i] >> 1);

            if (denom > power_smooth[i]) {

              int p = power_smooth[i];

              while (denom < 0x40000000) {

                denom <<= 1;

                p <<= 1;

              }

              transient_gain[i][n] = p / (denom >> 16);

            }

            else {

              transient_gain[i][n] = 1 << 16;

            }

        }

    }

#else

    for (i = 0; i < NR_PAR_BANDS[is34]; i++) {

        for (n = n0; n < nL; n++) {

            float decayed_peak = peak_decay_factor * peak_decay_nrg[i];

            float denom;

            peak_decay_nrg[i] = FFMAX(decayed_peak, power[i][n]);

            power_smooth[i] += a_smooth * (power[i][n] - power_smooth[i]);

            peak_decay_diff_smooth[i] += a_smooth * (peak_decay_nrg[i] - power[i][n] - peak_decay_diff_smooth[i]);

            denom = transient_impact * peak_decay_diff_smooth[i];

            transient_gain[i][n]   = (denom > power_smooth[i]) ?

                                         power_smooth[i] / denom : 1.0f;

        }

    }

#endif /* USE_FIXED */

    //Decorrelation and transient reduction

    //                         PS_AP_LINKS - 1

    //                               -----

    //                                | |  Q_fract_allpass[k][m]*z^-link_delay[m] - a[m]*g_decay_slope[k]

    //H[k][z] = z^-2 * phi_fract[k] * | | ----------------------------------------------------------------

    //                                | | 1 - a[m]*g_decay_slope[k]*Q_fract_allpass[k][m]*z^-link_delay[m]

    //                               m = 0

    //d[k][z] (out) = transient_gain_mapped[k][z] * H[k][z] * s[k][z]

    for (k = 0; k < NR_ALLPASS_BANDS[is34]; k++) {

        int b = k_to_i[k];

#if USE_FIXED

        int g_decay_slope;

        if (k - DECAY_CUTOFF[is34] <= 0) {

          g_decay_slope = 1 << 30;

        }

        else if (k - DECAY_CUTOFF[is34] >= 20) {

          g_decay_slope = 0;

        }

        else {

          g_decay_slope = (1 << 30) - DECAY_SLOPE * (k - DECAY_CUTOFF[is34]);

        }

#else

        float g_decay_slope = 1.f - DECAY_SLOPE * (k - DECAY_CUTOFF[is34]);

        g_decay_slope = av_clipf(g_decay_slope, 0.f, 1.f);

#endif /* USE_FIXED */

        memcpy(delay[k], delay[k]+nL, PS_MAX_DELAY*sizeof(delay[k][0]));

        memcpy(delay[k]+PS_MAX_DELAY, s[k], numQMFSlots*sizeof(delay[k][0]));

        for (m = 0; m < PS_AP_LINKS; m++) {

            memcpy(ap_delay[k][m],   ap_delay[k][m]+numQMFSlots,           5*sizeof(ap_delay[k][m][0]));

        }

        ps->dsp.decorrelate(out[k], delay[k] + PS_MAX_DELAY - 2, ap_delay[k],

                            phi_fract[is34][k],

                            (const INTFLOAT (*)[2]) Q_fract_allpass[is34][k],

                            transient_gain[b], g_decay_slope, nL - n0);

    }

    for (; k < SHORT_DELAY_BAND[is34]; k++) {

        int i = k_to_i[k];

        memcpy(delay[k], delay[k]+nL, PS_MAX_DELAY*sizeof(delay[k][0]));

        memcpy(delay[k]+PS_MAX_DELAY, s[k], numQMFSlots*sizeof(delay[k][0]));

        //H = delay 14

        ps->dsp.mul_pair_single(out[k], delay[k] + PS_MAX_DELAY - 14,

                                transient_gain[i], nL - n0);

    }

    for (; k < NR_BANDS[is34]; k++) {

        int i = k_to_i[k];

        memcpy(delay[k], delay[k]+nL, PS_MAX_DELAY*sizeof(delay[k][0]));

        memcpy(delay[k]+PS_MAX_DELAY, s[k], numQMFSlots*sizeof(delay[k][0]));

        //H = delay 1

        ps->dsp.mul_pair_single(out[k], delay[k] + PS_MAX_DELAY - 1,

                                transient_gain[i], nL - n0);

    }

}


void tcg_gen_ld8s_i64(TCGv_i64 ret, TCGv_ptr arg2, tcg_target_long offset)

{

    tcg_gen_ld8s_i32(TCGV_LOW(ret), arg2, offset);

    tcg_gen_sari_i32(TCGV_HIGH(ret), TCGV_HIGH(ret), 31);

}


static int load_glyph(AVFilterContext *ctx, Glyph **glyph_ptr, uint32_t code)

{

    DrawTextContext *s = ctx->priv;

    FT_BitmapGlyph bitmapglyph;

    Glyph *glyph;

    struct AVTreeNode *node = NULL;

    int ret;

    /* load glyph into s->face->glyph */

    if (FT_Load_Char(s->face, code, s->ft_load_flags))

        return AVERROR(EINVAL);

    /* save glyph */

    if (!(glyph = av_mallocz(sizeof(*glyph))) ||

        !(glyph->glyph = av_mallocz(sizeof(*glyph->glyph)))) {

        ret = AVERROR(ENOMEM);

        goto error;

    }

    glyph->code  = code;

    if (FT_Get_Glyph(s->face->glyph, glyph->glyph)) {

        ret = AVERROR(EINVAL);

        goto error;

    }

    if (s->borderw) {

        FT_Glyph border_glyph = *glyph->glyph;

        if (FT_Glyph_StrokeBorder(&border_glyph, s->stroker, 0, 0) ||

            FT_Glyph_To_Bitmap(&border_glyph, FT_RENDER_MODE_NORMAL, 0, 1)) {

            ret = AVERROR_EXTERNAL;

            goto error;

        }

        bitmapglyph = (FT_BitmapGlyph) border_glyph;

        glyph->border_bitmap = bitmapglyph->bitmap;

    }

    if (FT_Glyph_To_Bitmap(glyph->glyph, FT_RENDER_MODE_NORMAL, 0, 1)) {

        ret = AVERROR_EXTERNAL;

        goto error;

    }

    bitmapglyph = (FT_BitmapGlyph) *glyph->glyph;

    glyph->bitmap      = bitmapglyph->bitmap;

    glyph->bitmap_left = bitmapglyph->left;

    glyph->bitmap_top  = bitmapglyph->top;

    glyph->advance     = s->face->glyph->advance.x >> 6;

    /* measure text height to calculate text_height (or the maximum text height) */

    FT_Glyph_Get_CBox(*glyph->glyph, ft_glyph_bbox_pixels, &glyph->bbox);

    /* cache the newly created glyph */

    if (!(node = av_tree_node_alloc())) {

        ret = AVERROR(ENOMEM);

        goto error;

    }

    av_tree_insert(&s->glyphs, glyph, glyph_cmp, &node);

    if (glyph_ptr)

        *glyph_ptr = glyph;

    return 0;

error:

    if (glyph)

        av_freep(&glyph->glyph);

    av_freep(&glyph);

    av_freep(&node);

    return ret;

}


QError *qobject_to_qerror(const QObject *obj)

{

    if (qobject_type(obj) != QTYPE_QERROR) {

        return NULL;

    }

    return container_of(obj, QError, base);

}


uint64_t helper_fmul(CPUPPCState *env, uint64_t arg1, uint64_t arg2)

{

    CPU_DoubleU farg1, farg2;

    farg1.ll = arg1;

    farg2.ll = arg2;

    if (unlikely((float64_is_infinity(farg1.d) && float64_is_zero(farg2.d)) ||

                 (float64_is_zero(farg1.d) && float64_is_infinity(farg2.d)))) {

        /* Multiplication of zero by infinity */

        farg1.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXIMZ);

    } else {

        if (unlikely(float64_is_signaling_nan(farg1.d) ||

                     float64_is_signaling_nan(farg2.d))) {

            /* sNaN multiplication */

            fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXSNAN);

        }

        farg1.d = float64_mul(farg1.d, farg2.d, &env->fp_status);

    }

    return farg1.ll;

}


static QObject *parse_value(JSONParserContext *ctxt, va_list *ap)

{

    QObject *token;

    token = parser_context_peek_token(ctxt);

    if (token == NULL) {

        parse_error(ctxt, NULL, "premature EOI");

        return NULL;

    }

    switch (token_get_type(token)) {

    case JSON_LCURLY:

        return parse_object(ctxt, ap);

    case JSON_LSQUARE:

        return parse_array(ctxt, ap);

    case JSON_ESCAPE:

        return parse_escape(ctxt, ap);

    case JSON_INTEGER:

    case JSON_FLOAT:

    case JSON_STRING:

        return parse_literal(ctxt);

    case JSON_KEYWORD:

        return parse_keyword(ctxt);

    default:

        parse_error(ctxt, token, "expecting value");

        return NULL;

    }

}


ssize_t virtio_pdu_vmarshal(V9fsPDU *pdu, size_t offset,

                            const char *fmt, va_list ap)

{

    V9fsState *s = pdu->s;

    V9fsVirtioState *v = container_of(s, V9fsVirtioState, state);

    VirtQueueElement *elem = &v->elems[pdu->idx];

    return v9fs_iov_vmarshal(elem->in_sg, elem->in_num, offset, 1, fmt, ap);

}


static void curl_multi_check_completion(BDRVCURLState *s)

{

    int msgs_in_queue;

    /* Try to find done transfers, so we can free the easy

     * handle again. */

    do {

        CURLMsg *msg;

        msg = curl_multi_info_read(s->multi, &msgs_in_queue);

        if (!msg)

            break;

        if (msg->msg == CURLMSG_NONE)

            break;

        switch (msg->msg) {

            case CURLMSG_DONE:

            {

                CURLState *state = NULL;

                curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE,

                                  (char **)&state);

                /* ACBs for successful messages get completed in curl_read_cb */

                if (msg->data.result != CURLE_OK) {

                    int i;

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

                        CURLAIOCB *acb = state->acb[i];

                        if (acb == NULL) {

                            continue;

                        }

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

                        qemu_aio_release(acb);

                        state->acb[i] = NULL;

                    }

                }

                curl_clean_state(state);

                break;

            }

            default:

                msgs_in_queue = 0;

                break;

        }

    } while(msgs_in_queue);

}


BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,

        const char *backing_file)

{

    char *filename_full = NULL;

    char *backing_file_full = NULL;

    char *filename_tmp = NULL;

    int is_protocol = 0;

    BlockDriverState *curr_bs = NULL;

    BlockDriverState *retval = NULL;

    if (!bs || !bs->drv || !backing_file) {

        return NULL;

    }

    filename_full     = g_malloc(PATH_MAX);

    backing_file_full = g_malloc(PATH_MAX);

    filename_tmp      = g_malloc(PATH_MAX);

    is_protocol = path_has_protocol(backing_file);

    for (curr_bs = bs; curr_bs->backing_hd; curr_bs = curr_bs->backing_hd) {

        /* If either of the filename paths is actually a protocol, then

         * compare unmodified paths; otherwise make paths relative */

        if (is_protocol || path_has_protocol(curr_bs->backing_file)) {

            if (strcmp(backing_file, curr_bs->backing_file) == 0) {

                retval = curr_bs->backing_hd;

                break;

            }

        } else {

            /* If not an absolute filename path, make it relative to the current

             * image's filename path */

            path_combine(filename_tmp, PATH_MAX, curr_bs->filename,

                         backing_file);

            /* We are going to compare absolute pathnames */

            if (!realpath(filename_tmp, filename_full)) {

                continue;

            }

            /* We need to make sure the backing filename we are comparing against

             * is relative to the current image filename (or absolute) */

            path_combine(filename_tmp, PATH_MAX, curr_bs->filename,

                         curr_bs->backing_file);

            if (!realpath(filename_tmp, backing_file_full)) {

                continue;

            }

            if (strcmp(backing_file_full, filename_full) == 0) {

                retval = curr_bs->backing_hd;

                break;

            }

        }

    }

    g_free(filename_full);

    g_free(backing_file_full);

    g_free(filename_tmp);

    return retval;

}


iscsi_set_events(IscsiLun *iscsilun)

{

    struct iscsi_context *iscsi = iscsilun->iscsi;

    int ev;

    /* We always register a read handler.  */

    ev = POLLIN;

    ev |= iscsi_which_events(iscsi);

    if (ev != iscsilun->events) {

        aio_set_fd_handler(iscsilun->aio_context,

                           iscsi_get_fd(iscsi),

                           iscsi_process_read,

                           (ev & POLLOUT) ? iscsi_process_write : NULL,

                           iscsilun);

    }

    iscsilun->events = ev;

}


void s390_program_interrupt(CPUS390XState *env, uint32_t code, int ilen,

                            uintptr_t ra)

{

#ifdef CONFIG_TCG

    S390CPU *cpu = s390_env_get_cpu(env);

    if (tcg_enabled()) {

        cpu_restore_state(CPU(cpu), ra);

    }

#endif

    program_interrupt(env, code, ilen);

}


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

{

    IPMIBmc *b = IPMI_BMC(dev);

    unsigned int i;

    IPMIBmcSim *ibs = IPMI_BMC_SIMULATOR(b);

    qemu_mutex_init(&ibs->lock);

    QTAILQ_INIT(&ibs->rcvbufs);

    ibs->bmc_global_enables = (1 << IPMI_BMC_EVENT_LOG_BIT);

    ibs->device_id = 0x20;

    ibs->ipmi_version = 0x02; /* IPMI 2.0 */

    ibs->restart_cause = 0;

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

        ibs->sel.last_addition[i] = 0xff;

        ibs->sel.last_clear[i] = 0xff;

        ibs->sdr.last_addition[i] = 0xff;

        ibs->sdr.last_clear[i] = 0xff;

    }

    ipmi_sdr_init(ibs);

    ibs->acpi_power_state[0] = 0;

    ibs->acpi_power_state[1] = 0;

    if (qemu_uuid_set) {

        memcpy(&ibs->uuid, qemu_uuid, 16);

    } else {

        memset(&ibs->uuid, 0, 16);

    }

    ipmi_init_sensors_from_sdrs(ibs);

    register_cmds(ibs);

    ibs->timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, ipmi_timeout, ibs);

    vmstate_register(NULL, 0, &vmstate_ipmi_sim, ibs);

}


static void spapr_machine_2_3_class_init(ObjectClass *oc, void *data)

{

    MachineClass *mc = MACHINE_CLASS(oc);

    mc->name = "pseries-2.3";

    mc->desc = "pSeries Logical Partition (PAPR compliant) v2.3";

    mc->alias = "pseries";

    mc->is_default = 1;

}


static int l2_allocate(BlockDriverState *bs, int l1_index, uint64_t **table)

{

    BDRVQcowState *s = bs->opaque;

    uint64_t old_l2_offset;

    uint64_t *l2_table;

    int64_t l2_offset;

    int ret;

    old_l2_offset = s->l1_table[l1_index];

    trace_qcow2_l2_allocate(bs, l1_index);

    /* allocate a new l2 entry */

    l2_offset = qcow2_alloc_clusters(bs, s->l2_size * sizeof(uint64_t));

    if (l2_offset < 0) {

        return l2_offset;

    }

    ret = qcow2_cache_flush(bs, s->refcount_block_cache);

    if (ret < 0) {

        goto fail;

    }

    /* allocate a new entry in the l2 cache */

    trace_qcow2_l2_allocate_get_empty(bs, l1_index);

    ret = qcow2_cache_get_empty(bs, s->l2_table_cache, l2_offset, (void**) table);

    if (ret < 0) {

        return ret;

    }

    l2_table = *table;

    if ((old_l2_offset & L1E_OFFSET_MASK) == 0) {

        /* if there was no old l2 table, clear the new table */

        memset(l2_table, 0, s->l2_size * sizeof(uint64_t));

    } else {

        uint64_t* old_table;

        /* if there was an old l2 table, read it from the disk */

        BLKDBG_EVENT(bs->file, BLKDBG_L2_ALLOC_COW_READ);

        ret = qcow2_cache_get(bs, s->l2_table_cache,

            old_l2_offset & L1E_OFFSET_MASK,

            (void**) &old_table);

        if (ret < 0) {

            goto fail;

        }

        memcpy(l2_table, old_table, s->cluster_size);

        ret = qcow2_cache_put(bs, s->l2_table_cache, (void**) &old_table);

        if (ret < 0) {

            goto fail;

        }

    }

    /* write the l2 table to the file */

    BLKDBG_EVENT(bs->file, BLKDBG_L2_ALLOC_WRITE);

    trace_qcow2_l2_allocate_write_l2(bs, l1_index);

    qcow2_cache_entry_mark_dirty(s->l2_table_cache, l2_table);

    ret = qcow2_cache_flush(bs, s->l2_table_cache);

    if (ret < 0) {

        goto fail;

    }

    /* update the L1 entry */

    trace_qcow2_l2_allocate_write_l1(bs, l1_index);

    s->l1_table[l1_index] = l2_offset | QCOW_OFLAG_COPIED;

    ret = write_l1_entry(bs, l1_index);

    if (ret < 0) {

        goto fail;

    }

    *table = l2_table;

    trace_qcow2_l2_allocate_done(bs, l1_index, 0);

    return 0;

fail:

    trace_qcow2_l2_allocate_done(bs, l1_index, ret);

    qcow2_cache_put(bs, s->l2_table_cache, (void**) table);

    s->l1_table[l1_index] = old_l2_offset;

    return ret;

}


static inline direntry_t* create_short_and_long_name(BDRVVVFATState* s,

	unsigned int directory_start, const char* filename, int is_dot)

{

    int i,j,long_index=s->directory.next;

    direntry_t* entry = NULL;

    direntry_t* entry_long = NULL;

    if(is_dot) {

	entry=array_get_next(&(s->directory));

	memset(entry->name,0x20,11);

	memcpy(entry->name,filename,strlen(filename));

	return entry;

    }

    entry_long=create_long_filename(s,filename);

    i = strlen(filename);

    for(j = i - 1; j>0  && filename[j]!='.';j--);

    if (j > 0)

	i = (j > 8 ? 8 : j);

    else if (i > 8)

	i = 8;

    entry=array_get_next(&(s->directory));

    memset(entry->name,0x20,11);

    memcpy(entry->name, filename, i);

    if(j > 0)

	for (i = 0; i < 3 && filename[j+1+i]; i++)

	    entry->extension[i] = filename[j+1+i];

    /* upcase & remove unwanted characters */

    for(i=10;i>=0;i--) {

	if(i==10 || i==7) for(;i>0 && entry->name[i]==' ';i--);

	if(entry->name[i]<=' ' || entry->name[i]>0x7f

		|| strchr(".*?<>|\":/\\[];,+='",entry->name[i]))

	    entry->name[i]='_';

        else if(entry->name[i]>='a' && entry->name[i]<='z')

            entry->name[i]+='A'-'a';

    }

    /* mangle duplicates */

    while(1) {

	direntry_t* entry1=array_get(&(s->directory),directory_start);

	int j;

	for(;entry1<entry;entry1++)

	    if(!is_long_name(entry1) && !memcmp(entry1->name,entry->name,11))

		break; /* found dupe */

	if(entry1==entry) /* no dupe found */

	    break;

	/* use all 8 characters of name */

	if(entry->name[7]==' ') {

	    int j;

	    for(j=6;j>0 && entry->name[j]==' ';j--)

		entry->name[j]='~';

	}

	/* increment number */

	for(j=7;j>0 && entry->name[j]=='9';j--)

	    entry->name[j]='0';

	if(j>0) {

	    if(entry->name[j]<'0' || entry->name[j]>'9')

	        entry->name[j]='0';

	    else

	        entry->name[j]++;

	}

    }

    /* calculate checksum; propagate to long name */

    if(entry_long) {

        uint8_t chksum=fat_chksum(entry);

	/* calculate anew, because realloc could have taken place */

	entry_long=array_get(&(s->directory),long_index);

	while(entry_long<entry && is_long_name(entry_long)) {

	    entry_long->reserved[1]=chksum;

	    entry_long++;

	}

    }

    return entry;

}


int coroutine_fn bdrv_co_flush(BlockDriverState *bs)

{

    int ret;

    if (!bs || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {

        return 0;

    }

    /* Write back cached data to the OS even with cache=unsafe */

    BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_OS);

    if (bs->drv->bdrv_co_flush_to_os) {

        ret = bs->drv->bdrv_co_flush_to_os(bs);

        if (ret < 0) {

            return ret;

        }

    }

    /* But don't actually force it to the disk with cache=unsafe */

    if (bs->open_flags & BDRV_O_NO_FLUSH) {

        goto flush_parent;

    }

    BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_DISK);

    if (bs->drv->bdrv_co_flush_to_disk) {

        ret = bs->drv->bdrv_co_flush_to_disk(bs);

    } else if (bs->drv->bdrv_aio_flush) {

        BlockAIOCB *acb;

        CoroutineIOCompletion co = {

            .coroutine = qemu_coroutine_self(),

        };

        acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);

        if (acb == NULL) {

            ret = -EIO;

        } else {

            qemu_coroutine_yield();

            ret = co.ret;

        }

    } else {

        /*

         * Some block drivers always operate in either writethrough or unsafe

         * mode and don't support bdrv_flush therefore. Usually qemu doesn't

         * know how the server works (because the behaviour is hardcoded or

         * depends on server-side configuration), so we can't ensure that

         * everything is safe on disk. Returning an error doesn't work because

         * that would break guests even if the server operates in writethrough

         * mode.

         *

         * Let's hope the user knows what he's doing.

         */

        ret = 0;

    }

    if (ret < 0) {

        return ret;

    }

    /* Now flush the underlying protocol.  It will also have BDRV_O_NO_FLUSH

     * in the case of cache=unsafe, so there are no useless flushes.

     */

flush_parent:

    return bdrv_co_flush(bs->file);

}


static void virtio_scsi_push_event(VirtIOSCSI *s, SCSIDevice *dev,

                                   uint32_t event, uint32_t reason)

{

    VirtIOSCSICommon *vs = VIRTIO_SCSI_COMMON(s);

    VirtIOSCSIReq *req;

    VirtIOSCSIEvent *evt;

    VirtIODevice *vdev = VIRTIO_DEVICE(s);

    int in_size;

    if (!(vdev->status & VIRTIO_CONFIG_S_DRIVER_OK)) {

        return;

    }

    req = virtio_scsi_pop_req(s, vs->event_vq);

    if (!req) {

        s->events_dropped = true;

        return;

    }

    if (req->elem.out_num || req->elem.in_num != 1) {

        virtio_scsi_bad_req();

    }

    if (s->events_dropped) {

        event |= VIRTIO_SCSI_T_EVENTS_MISSED;

        s->events_dropped = false;

    }

    in_size = req->elem.in_sg[0].iov_len;

    if (in_size < sizeof(VirtIOSCSIEvent)) {

        virtio_scsi_bad_req();

    }

    evt = req->resp.event;

    memset(evt, 0, sizeof(VirtIOSCSIEvent));

    evt->event = event;

    evt->reason = reason;

    if (!dev) {

        assert(event == VIRTIO_SCSI_T_EVENTS_MISSED);

    } else {

        evt->lun[0] = 1;

        evt->lun[1] = dev->id;

        /* Linux wants us to keep the same encoding we use for REPORT LUNS.  */

        if (dev->lun >= 256) {

            evt->lun[2] = (dev->lun >> 8) | 0x40;

        }

        evt->lun[3] = dev->lun & 0xFF;

    }

    virtio_scsi_complete_req(req);

}


static void gic_thiscpu_write(void *opaque, target_phys_addr_t addr,

                              uint64_t value, unsigned size)

{

    GICState *s = (GICState *)opaque;

    gic_cpu_write(s, gic_get_current_cpu(s), addr, value);

}


static void cmv_process_header(CmvContext *s, const uint8_t *buf, const uint8_t *buf_end)

{

    int pal_start, pal_count, i;

    if(buf_end - buf < 16) {

        av_log(s->avctx, AV_LOG_WARNING, "truncated header\n");

        return;

    }

    s->width  = AV_RL16(&buf[4]);

    s->height = AV_RL16(&buf[6]);

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

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

    s->avctx->time_base.num = 1;

    s->avctx->time_base.den = AV_RL16(&buf[10]);

    pal_start = AV_RL16(&buf[12]);

    pal_count = AV_RL16(&buf[14]);

    buf += 16;

    for (i=pal_start; i<pal_start+pal_count && i<AVPALETTE_COUNT && buf_end - buf >= 3; i++) {

        s->palette[i] = 0xFFU << 24 | AV_RB24(buf);

        buf += 3;

    }

}


FWCfgState *fw_cfg_init_mem(hwaddr ctl_addr, hwaddr data_addr)

{

    DeviceState *dev;

    SysBusDevice *sbd;

    dev = qdev_create(NULL, TYPE_FW_CFG_MEM);

    qdev_prop_set_uint32(dev, "data_width",

                         fw_cfg_data_mem_ops.valid.max_access_size);

    fw_cfg_init1(dev);

    sbd = SYS_BUS_DEVICE(dev);

    sysbus_mmio_map(sbd, 0, ctl_addr);

    sysbus_mmio_map(sbd, 1, data_addr);

    return FW_CFG(dev);

}


static uint32_t mvc_asc(CPUS390XState *env, int64_t l, uint64_t a1,

                        uint64_t mode1, uint64_t a2, uint64_t mode2)

{

    CPUState *cs = CPU(s390_env_get_cpu(env));

    target_ulong src, dest;

    int flags, cc = 0, i;

    if (!l) {

        return 0;

    } else if (l > 256) {

        /* max 256 */

        l = 256;

        cc = 3;

    }

    if (mmu_translate(env, a1, 1, mode1, &dest, &flags, true)) {

        cpu_loop_exit(CPU(s390_env_get_cpu(env)));

    }

    dest |= a1 & ~TARGET_PAGE_MASK;

    if (mmu_translate(env, a2, 0, mode2, &src, &flags, true)) {

        cpu_loop_exit(CPU(s390_env_get_cpu(env)));

    }

    src |= a2 & ~TARGET_PAGE_MASK;

    /* XXX replace w/ memcpy */

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

        /* XXX be more clever */

        if ((((dest + i) & TARGET_PAGE_MASK) != (dest & TARGET_PAGE_MASK)) ||

            (((src + i) & TARGET_PAGE_MASK) != (src & TARGET_PAGE_MASK))) {

            mvc_asc(env, l - i, a1 + i, mode1, a2 + i, mode2);

            break;

        }

        stb_phys(cs->as, dest + i, ldub_phys(cs->as, src + i));

    }

    return cc;

}


static ssize_t qio_channel_file_writev(QIOChannel *ioc,

                                       const struct iovec *iov,

                                       size_t niov,

                                       int *fds,

                                       size_t nfds,

                                       Error **errp)

{

    QIOChannelFile *fioc = QIO_CHANNEL_FILE(ioc);

    ssize_t ret;

 retry:

    ret = writev(fioc->fd, iov, niov);

    if (ret <= 0) {

        if (errno == EAGAIN ||

            errno == EWOULDBLOCK) {

            return QIO_CHANNEL_ERR_BLOCK;

        }

        if (errno == EINTR) {

            goto retry;

        }

        error_setg_errno(errp, errno,

                         "Unable to write to file");

        return -1;

    }

    return ret;

}


static int ac97_initfn (PCIDevice *dev)

{

    AC97LinkState *s = DO_UPCAST (AC97LinkState, dev, dev);

    uint8_t *c = s->dev.config;

    /* TODO: no need to override */

    c[PCI_COMMAND] = 0x00;      /* pcicmd pci command rw, ro */

    c[PCI_COMMAND + 1] = 0x00;

    /* TODO: */

    c[PCI_STATUS] = PCI_STATUS_FAST_BACK;      /* pcists pci status rwc, ro */

    c[PCI_STATUS + 1] = PCI_STATUS_DEVSEL_MEDIUM >> 8;

    c[PCI_CLASS_PROG] = 0x00;      /* pi programming interface ro */

    /* TODO set when bar is registered. no need to override. */

    /* nabmar native audio mixer base address rw */

    c[PCI_BASE_ADDRESS_0] = PCI_BASE_ADDRESS_SPACE_IO;

    c[PCI_BASE_ADDRESS_0 + 1] = 0x00;

    c[PCI_BASE_ADDRESS_0 + 2] = 0x00;

    c[PCI_BASE_ADDRESS_0 + 3] = 0x00;

    /* TODO set when bar is registered. no need to override. */

      /* nabmbar native audio bus mastering base address rw */

    c[PCI_BASE_ADDRESS_0 + 4] = PCI_BASE_ADDRESS_SPACE_IO;

    c[PCI_BASE_ADDRESS_0 + 5] = 0x00;

    c[PCI_BASE_ADDRESS_0 + 6] = 0x00;

    c[PCI_BASE_ADDRESS_0 + 7] = 0x00;

    c[PCI_SUBSYSTEM_VENDOR_ID] = 0x86;      /* svid subsystem vendor id rwo */

    c[PCI_SUBSYSTEM_VENDOR_ID + 1] = 0x80;

    c[PCI_SUBSYSTEM_ID] = 0x00;      /* sid subsystem id rwo */

    c[PCI_SUBSYSTEM_ID + 1] = 0x00;

    c[PCI_INTERRUPT_LINE] = 0x00;      /* intr_ln interrupt line rw */

    c[PCI_INTERRUPT_PIN] = 0x01;      /* intr_pn interrupt pin ro */

    memory_region_init_io (&s->io_nam, &ac97_io_nam_ops, s, "ac97-nam", 1024);

    memory_region_init_io (&s->io_nabm, &ac97_io_nabm_ops, s, "ac97-nabm", 256);

    pci_register_bar (&s->dev, 0, PCI_BASE_ADDRESS_SPACE_IO, &s->io_nam);

    pci_register_bar (&s->dev, 1, PCI_BASE_ADDRESS_SPACE_IO, &s->io_nabm);

    qemu_register_reset (ac97_on_reset, s);

    AUD_register_card ("ac97", &s->card);

    ac97_on_reset (s);

    return 0;

}


static Suite *qjson_suite(void)

{

    Suite *suite;

    TCase *string_literals, *number_literals, *keyword_literals;

    TCase *dicts, *lists, *whitespace, *varargs;

    string_literals = tcase_create("String Literals");

    tcase_add_test(string_literals, simple_string);

    tcase_add_test(string_literals, escaped_string);

    tcase_add_test(string_literals, single_quote_string);

    tcase_add_test(string_literals, vararg_string);

    number_literals = tcase_create("Number Literals");

    tcase_add_test(number_literals, simple_number);

    tcase_add_test(number_literals, float_number);

    tcase_add_test(number_literals, vararg_number);

    keyword_literals = tcase_create("Keywords");

    tcase_add_test(keyword_literals, keyword_literal);

    dicts = tcase_create("Objects");

    tcase_add_test(dicts, simple_dict);

    lists = tcase_create("Lists");

    tcase_add_test(lists, simple_list);

    whitespace = tcase_create("Whitespace");

    tcase_add_test(whitespace, simple_whitespace);

    varargs = tcase_create("Varargs");

    tcase_add_test(varargs, simple_varargs);

    suite = suite_create("QJSON test-suite");

    suite_add_tcase(suite, string_literals);

    suite_add_tcase(suite, number_literals);

    suite_add_tcase(suite, keyword_literals);

    suite_add_tcase(suite, dicts);

    suite_add_tcase(suite, lists);

    suite_add_tcase(suite, whitespace);

    suite_add_tcase(suite, varargs);

    return suite;

}


char_socket_get_addr(Object *obj, Visitor *v, const char *name,

                     void *opaque, Error **errp)

{

    SocketChardev *s = SOCKET_CHARDEV(obj);

    visit_type_SocketAddress(v, name, &s->addr, errp);

}


static void invalidate_and_set_dirty(target_phys_addr_t addr,

                                     target_phys_addr_t length)

{

    if (!cpu_physical_memory_is_dirty(addr)) {

        /* invalidate code */

        tb_invalidate_phys_page_range(addr, addr + length, 0);

        /* set dirty bit */

        cpu_physical_memory_set_dirty_flags(addr, (0xff & ~CODE_DIRTY_FLAG));

    }

    xen_modified_memory(addr, length);

}


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

{

    BDRVRawState *s = bs->opaque;

    struct stat st;

    if (!fstat(s->fd, &st)) {

        if (S_ISBLK(st.st_mode)) {

            int ret = hdev_get_max_transfer_length(s->fd);

            if (ret >= 0) {

                bs->bl.max_transfer_length = ret;

            }

        }

    }

    raw_probe_alignment(bs, s->fd, errp);

    bs->bl.min_mem_alignment = s->buf_align;

    bs->bl.opt_mem_alignment = MAX(s->buf_align, getpagesize());

}


static int cpudef_setfield(const char *name, const char *str, void *opaque)

{

    x86_def_t *def = opaque;

    int err = 0;

    if (!strcmp(name, "name")) {

        def->name = strdup(str);

    } else if (!strcmp(name, "model_id")) {

        strncpy(def->model_id, str, sizeof (def->model_id));

    } else if (!strcmp(name, "level")) {

        setscalar(&def->level, str, &err)

    } else if (!strcmp(name, "vendor")) {

        cpyid(&str[0], &def->vendor1);

        cpyid(&str[4], &def->vendor2);

        cpyid(&str[8], &def->vendor3);

    } else if (!strcmp(name, "family")) {

        setscalar(&def->family, str, &err)

    } else if (!strcmp(name, "model")) {

        setscalar(&def->model, str, &err)

    } else if (!strcmp(name, "stepping")) {

        setscalar(&def->stepping, str, &err)

    } else if (!strcmp(name, "feature_edx")) {

        setfeatures(&def->features, str, feature_name, &err);

    } else if (!strcmp(name, "feature_ecx")) {

        setfeatures(&def->ext_features, str, ext_feature_name, &err);

    } else if (!strcmp(name, "extfeature_edx")) {

        setfeatures(&def->ext2_features, str, ext2_feature_name, &err);

    } else if (!strcmp(name, "extfeature_ecx")) {

        setfeatures(&def->ext3_features, str, ext3_feature_name, &err);

    } else if (!strcmp(name, "xlevel")) {

        setscalar(&def->xlevel, str, &err)

    } else {

        fprintf(stderr, "error: unknown option [%s = %s]\n", name, str);

        return (1);

    }

    if (err) {

        fprintf(stderr, "error: bad option value [%s = %s]\n", name, str);

        return (1);

    }

    return (0);

}


aio_read_f(int argc, char **argv)

{

	int nr_iov, c;

	struct aio_ctx *ctx = calloc(1, sizeof(struct aio_ctx));

	BlockDriverAIOCB *acb;

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

		switch (c) {

		case 'C':

			ctx->Cflag = 1;

			break;

		case 'P':

			ctx->Pflag = 1;

			ctx->pattern = atoi(optarg);

			break;

		case 'q':

			ctx->qflag = 1;

			break;

		case 'v':

			ctx->vflag = 1;

			break;

		default:

			free(ctx);

			return command_usage(&aio_read_cmd);

		}

	}

	if (optind > argc - 2) {

		free(ctx);

		return command_usage(&aio_read_cmd);

	}

	ctx->offset = cvtnum(argv[optind]);

	if (ctx->offset < 0) {

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

		free(ctx);

		return 0;

	}

	optind++;

	if (ctx->offset & 0x1ff) {

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

			(long long)ctx->offset);

		free(ctx);

		return 0;

	}

	nr_iov = argc - optind;

	ctx->buf = create_iovec(&ctx->qiov, &argv[optind], nr_iov, 0xab);

	gettimeofday(&ctx->t1, NULL);

	acb = bdrv_aio_readv(bs, ctx->offset >> 9, &ctx->qiov,

			      ctx->qiov.size >> 9, aio_read_done, ctx);

	if (!acb) {

		free(ctx->buf);

		free(ctx);

		return -EIO;

	}

	return 0;

}


static void nvdimm_build_device_dsm(Aml *dev)

{

    Aml *method;

    method = aml_method("_DSM", 4, AML_NOTSERIALIZED);

    aml_append(method, aml_return(aml_call4(NVDIMM_COMMON_DSM, aml_arg(0),

                                  aml_arg(1), aml_arg(2), aml_arg(3))));

    aml_append(dev, method);

}


void kvm_s390_apply_cpu_model(const S390CPUModel *model, Error **errp)

{

    struct kvm_s390_vm_cpu_processor prop  = {

        .fac_list = { 0 },

    };

    struct kvm_device_attr attr = {

        .group = KVM_S390_VM_CPU_MODEL,

        .attr = KVM_S390_VM_CPU_PROCESSOR,

        .addr = (uint64_t) &prop,

    };

    int rc;

    if (!model) {

        /* compatibility handling if cpu models are disabled */

        if (kvm_s390_cmma_available() && !mem_path) {

            kvm_s390_enable_cmma();

        }

        return;

    }

    if (!kvm_s390_cpu_models_supported()) {

        error_setg(errp, "KVM doesn't support CPU models");

        return;

    }

    prop.cpuid = s390_cpuid_from_cpu_model(model);

    prop.ibc = s390_ibc_from_cpu_model(model);

    /* configure cpu features indicated via STFL(e) */

    s390_fill_feat_block(model->features, S390_FEAT_TYPE_STFL,

                         (uint8_t *) prop.fac_list);

    rc = kvm_vm_ioctl(kvm_state, KVM_SET_DEVICE_ATTR, &attr);

    if (rc) {

        error_setg(errp, "KVM: Error configuring the CPU model: %d", rc);

        return;

    }

    /* configure cpu features indicated e.g. via SCLP */

    rc = configure_cpu_feat(model->features);

    if (rc) {

        error_setg(errp, "KVM: Error configuring CPU features: %d", rc);

        return;

    }

    /* configure cpu subfunctions indicated via query / test bit */

    rc = configure_cpu_subfunc(model->features);

    if (rc) {

        error_setg(errp, "KVM: Error configuring CPU subfunctions: %d", rc);

        return;

    }

    /* enable CMM via CMMA - disable on hugetlbfs */

    if (test_bit(S390_FEAT_CMM, model->features)) {

        if (mem_path) {

            error_report("Warning: CMM will not be enabled because it is not "

                         "compatible to hugetlbfs.");

        } else {

            kvm_s390_enable_cmma();

        }

    }

}


static void qdm2_calculate_fft (QDM2Context *q, int channel, int sub_packet)

{

    const float gain = (q->channels == 1 && q->nb_channels == 2) ? 0.5f : 1.0f;

    int i;

    q->fft.complex[channel][0].re *= 2.0f;

    q->fft.complex[channel][0].im = 0.0f;

    q->rdft_ctx.rdft_calc(&q->rdft_ctx, (FFTSample *)q->fft.complex[channel]);

    /* add samples to output buffer */

    for (i = 0; i < ((q->fft_frame_size + 15) & ~15); i++)

        q->output_buffer[q->channels * i + channel] += ((float *) q->fft.complex[channel])[i] * gain;

}


int sws_init_context(SwsContext *c, SwsFilter *srcFilter, SwsFilter *dstFilter)

{

    int i, j;

    int usesVFilter, usesHFilter;

    int unscaled;

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

    int srcW= c->srcW;

    int srcH= c->srcH;

    int dstW= c->dstW;

    int dstH= c->dstH;

    int dst_stride = FFALIGN(dstW * sizeof(int16_t)+66, 16);

    int flags, cpu_flags;

    enum PixelFormat srcFormat= c->srcFormat;

    enum PixelFormat dstFormat= c->dstFormat;

    cpu_flags = av_get_cpu_flags();

    flags     = c->flags;

    emms_c();

    if (!rgb15to16) sws_rgb2rgb_init();

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

    handle_jpeg(&srcFormat);

    handle_jpeg(&dstFormat);

    if(srcFormat!=c->srcFormat || dstFormat!=c->dstFormat){

        av_log(c, AV_LOG_WARNING, "deprecated pixel format used, make sure you did set range correctly\n");

        c->srcFormat= srcFormat;

        c->dstFormat= dstFormat;

    }

    if (!sws_isSupportedInput(srcFormat)) {

        av_log(c, AV_LOG_ERROR, "%s is not supported as input pixel format\n", av_get_pix_fmt_name(srcFormat));

        return AVERROR(EINVAL);

    }

    if (!sws_isSupportedOutput(dstFormat)) {

        av_log(c, AV_LOG_ERROR, "%s is not supported as output pixel format\n", av_get_pix_fmt_name(dstFormat));

        return AVERROR(EINVAL);

    }

    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(c, AV_LOG_ERROR, "Exactly one scaler algorithm must be chosen\n");

        return AVERROR(EINVAL);

    }

    /* 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(c, AV_LOG_ERROR, "%dx%d -> %dx%d is invalid scaling dimension\n",

               srcW, srcH, dstW, dstH);

        return AVERROR(EINVAL);

    }

    if (!dstFilter) dstFilter= &dummyFilter;

    if (!srcFilter) srcFilter= &dummyFilter;

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

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

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

        if (dstW&1) {

            av_log(c, AV_LOG_DEBUG, "Forcing full internal H chroma due to odd output size\n");

            flags |= SWS_FULL_CHR_H_INT;

            c->flags = flags;

        } else

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

        c->chrSrcHSubSample=1;

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

    /* unscaled special cases */

    if (unscaled && !usesHFilter && !usesVFilter && (c->srcRange == c->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",

                       av_get_pix_fmt_name(srcFormat), av_get_pix_fmt_name(dstFormat));

            return 0;

        }

    }

    c->srcBpc = 1 + av_pix_fmt_descriptors[srcFormat].comp[0].depth_minus1;

    if (c->srcBpc < 8)

        c->srcBpc = 8;

    c->dstBpc = 1 + av_pix_fmt_descriptors[dstFormat].comp[0].depth_minus1;

    if (c->dstBpc < 8)

        c->dstBpc = 8;

    if (isAnyRGB(srcFormat) || srcFormat == PIX_FMT_PAL8)

        c->srcBpc = 16;

    if (c->dstBpc == 16)

        dst_stride <<= 1;

    FF_ALLOC_OR_GOTO(c, c->formatConvBuffer, FFALIGN(srcW*2+78, 16) * 2, fail);

    if (HAVE_MMX2 && cpu_flags & AV_CPU_FLAG_MMX2 && c->srcBpc == 8 && c->dstBpc <= 10) {

        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 || isNBPS(c->srcFormat) || is16BPS(c->srcFormat) || isAnyRGB(c->srcFormat)) 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 (HAVE_MMX && cpu_flags & AV_CPU_FLAG_MMX && c->dstBpc <= 10) {

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

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

        }

    }

    /* precalculate horizontal scaler filter coefficients */

    {

#if HAVE_MMX2

// 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, -1, 0);

            c->chrMmx2FilterCode = mmap(NULL, c->chrMmx2FilterCodeSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 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

#ifdef MAP_ANONYMOUS

            if (c->lumMmx2FilterCode == MAP_FAILED || c->chrMmx2FilterCode == MAP_FAILED)

#else

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

#endif

            {

                av_log(c, AV_LOG_ERROR, "Failed to allocate MMX2FilterCode\n");

                return AVERROR(ENOMEM);

            }

            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, (uint32_t*)c->hLumFilterPos, 8);

            initMMX2HScaler(c->chrDstW, c->chrXInc, c->chrMmx2FilterCode, c->hChrFilter, (uint32_t*)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 /* HAVE_MMX2 */

        {

            const int filterAlign=

                (HAVE_MMX     && cpu_flags & AV_CPU_FLAG_MMX) ? 4 :

                (HAVE_ALTIVEC && cpu_flags & AV_CPU_FLAG_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, cpu_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, cpu_flags,

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

                goto fail;

        }

    } // initialize horizontal stuff

    /* precalculate vertical scaler filter coefficients */

    {

        const int filterAlign=

            (HAVE_MMX     && cpu_flags & AV_CPU_FLAG_MMX) ? 2 :

            (HAVE_ALTIVEC && cpu_flags & AV_CPU_FLAG_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, cpu_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, cpu_flags,

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

            goto fail;

#if 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= (int64_t)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->chrUPixBuf, c->vChrBufSize*2*sizeof(int16_t*), fail);

    FF_ALLOC_OR_GOTO(c, c->chrVPixBuf, 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], dst_stride+16, fail);

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

    }

    // 64 / c->scalingBpp is the same as 16 / sizeof(scaling_intermediate)

    c->uv_off   = (dst_stride>>1) + 64 / (c->dstBpc &~ 7);

    c->uv_offx2 = dst_stride + 16;

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

        FF_ALLOC_OR_GOTO(c, c->chrUPixBuf[i+c->vChrBufSize], dst_stride*2+32, fail);

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

        c->chrVPixBuf[i] = c->chrVPixBuf[i+c->vChrBufSize] = c->chrUPixBuf[i] + (dst_stride >> 1) + 8;

    }

    if (CONFIG_SWSCALE_ALPHA && c->alpPixBuf)

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

            FF_ALLOCZ_OR_GOTO(c, c->alpPixBuf[i+c->vLumBufSize], dst_stride+16, 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++)

        if(av_pix_fmt_descriptors[c->dstFormat].comp[0].depth_minus1 == 15){

            av_assert0(c->dstBpc > 10);

            for(j=0; j<dst_stride/2+1; j++)

                ((int32_t*)(c->chrUPixBuf[i]))[j] = 1<<18;

        } else

            for(j=0; j<dst_stride+1; j++)

                ((int16_t*)(c->chrUPixBuf[i]))[j] = 1<<14;

    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 ",

               av_get_pix_fmt_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

               av_get_pix_fmt_name(dstFormat));

        if      (HAVE_MMX2     && cpu_flags & AV_CPU_FLAG_MMX2)    av_log(c, AV_LOG_INFO, "using MMX2\n");

        else if (HAVE_AMD3DNOW && cpu_flags & AV_CPU_FLAG_3DNOW)   av_log(c, AV_LOG_INFO, "using 3DNOW\n");

        else if (HAVE_MMX      && cpu_flags & AV_CPU_FLAG_MMX)     av_log(c, AV_LOG_INFO, "using MMX\n");

        else if (HAVE_ALTIVEC  && cpu_flags & AV_CPU_FLAG_ALTIVEC) av_log(c, AV_LOG_INFO, "using AltiVec\n");

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

        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 0;

fail: //FIXME replace things by appropriate error codes

    return -1;

}


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

                              int *got_frame_ptr, AVPacket *avpkt)

{

    AVFrame *frame     = data;

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    static const uint8_t sizes[LPC_ORDER] = {6, 5, 5, 4, 4, 3, 3, 3, 3, 2};

    unsigned int refl_rms[NBLOCKS];           // RMS of the reflection coefficients

    uint16_t block_coefs[NBLOCKS][LPC_ORDER]; // LPC coefficients of each sub-block

    unsigned int lpc_refl[LPC_ORDER];         // LPC reflection coefficients of the frame

    int i, j;

    int ret;

    int16_t *samples;

    unsigned int energy;

    RA144Context *ractx = avctx->priv_data;

    GetBitContext gb;

    /* get output buffer */

    frame->nb_samples = NBLOCKS * BLOCKSIZE;

    if ((ret = ff_get_buffer(avctx, frame, 0)) < 0) {

        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");

        return ret;

    }

    samples = (int16_t *)frame->data[0];

    if(buf_size < FRAMESIZE) {

        av_log(avctx, AV_LOG_ERROR,

               "Frame too small (%d bytes). Truncated file?\n", buf_size);

        *got_frame_ptr = 0;

        return buf_size;

    }

    init_get_bits(&gb, buf, FRAMESIZE * 8);

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

        lpc_refl[i] = ff_lpc_refl_cb[i][get_bits(&gb, sizes[i])];

    ff_eval_coefs(ractx->lpc_coef[0], lpc_refl);

    ractx->lpc_refl_rms[0] = ff_rms(lpc_refl);

    energy = ff_energy_tab[get_bits(&gb, 5)];

    refl_rms[0] = ff_interp(ractx, block_coefs[0], 1, 1, ractx->old_energy);

    refl_rms[1] = ff_interp(ractx, block_coefs[1], 2,

                            energy <= ractx->old_energy,

                            ff_t_sqrt(energy*ractx->old_energy) >> 12);

    refl_rms[2] = ff_interp(ractx, block_coefs[2], 3, 0, energy);

    refl_rms[3] = ff_rescale_rms(ractx->lpc_refl_rms[0], energy);

    ff_int_to_int16(block_coefs[3], ractx->lpc_coef[0]);

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

        do_output_subblock(ractx, block_coefs[i], refl_rms[i], &gb);

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

            *samples++ = av_clip_int16(ractx->curr_sblock[j + 10] << 2);

    }

    ractx->old_energy = energy;

    ractx->lpc_refl_rms[1] = ractx->lpc_refl_rms[0];

    FFSWAP(unsigned int *, ractx->lpc_coef[0], ractx->lpc_coef[1]);

    *got_frame_ptr = 1;

    return FRAMESIZE;

}


static TargetFdDataFunc fd_trans_host_to_target_data(int fd)

{

    if (fd < target_fd_max && target_fd_trans[fd]) {

        return target_fd_trans[fd]->host_to_target_data;

    }

    return NULL;

}


static uint64_t arm_sysctl_read(void *opaque, target_phys_addr_t offset,

                                unsigned size)

{

    arm_sysctl_state *s = (arm_sysctl_state *)opaque;

    switch (offset) {

    case 0x00: /* ID */

        return s->sys_id;

    case 0x04: /* SW */

        /* General purpose hardware switches.

           We don't have a useful way of exposing these to the user.  */

        return 0;

    case 0x08: /* LED */

        return s->leds;

    case 0x20: /* LOCK */

        return s->lockval;

    case 0x0c: /* OSC0 */

    case 0x10: /* OSC1 */

    case 0x14: /* OSC2 */

    case 0x18: /* OSC3 */

    case 0x1c: /* OSC4 */

    case 0x24: /* 100HZ */

        /* ??? Implement these.  */

        return 0;

    case 0x28: /* CFGDATA1 */

        return s->cfgdata1;

    case 0x2c: /* CFGDATA2 */

        return s->cfgdata2;

    case 0x30: /* FLAGS */

        return s->flags;

    case 0x38: /* NVFLAGS */

        return s->nvflags;

    case 0x40: /* RESETCTL */

        if (board_id(s) == BOARD_ID_VEXPRESS) {

            /* reserved: RAZ/WI */

            return 0;

        }

        return s->resetlevel;

    case 0x44: /* PCICTL */

        return 1;

    case 0x48: /* MCI */

        return s->sys_mci;

    case 0x4c: /* FLASH */

        return 0;

    case 0x50: /* CLCD */

        return s->sys_clcd;

    case 0x54: /* CLCDSER */

        return 0;

    case 0x58: /* BOOTCS */

        return 0;

    case 0x5c: /* 24MHz */

        return muldiv64(qemu_get_clock_ns(vm_clock), 24000000, get_ticks_per_sec());

    case 0x60: /* MISC */

        return 0;

    case 0x84: /* PROCID0 */

        return s->proc_id;

    case 0x88: /* PROCID1 */

        return 0xff000000;

    case 0x64: /* DMAPSR0 */

    case 0x68: /* DMAPSR1 */

    case 0x6c: /* DMAPSR2 */

    case 0x70: /* IOSEL */

    case 0x74: /* PLDCTL */

    case 0x80: /* BUSID */

    case 0x8c: /* OSCRESET0 */

    case 0x90: /* OSCRESET1 */

    case 0x94: /* OSCRESET2 */

    case 0x98: /* OSCRESET3 */

    case 0x9c: /* OSCRESET4 */

    case 0xc0: /* SYS_TEST_OSC0 */

    case 0xc4: /* SYS_TEST_OSC1 */

    case 0xc8: /* SYS_TEST_OSC2 */

    case 0xcc: /* SYS_TEST_OSC3 */

    case 0xd0: /* SYS_TEST_OSC4 */

        return 0;

    case 0xa0: /* SYS_CFGDATA */

        if (board_id(s) != BOARD_ID_VEXPRESS) {

            goto bad_reg;

        }

        return s->sys_cfgdata;

    case 0xa4: /* SYS_CFGCTRL */

        if (board_id(s) != BOARD_ID_VEXPRESS) {

            goto bad_reg;

        }

        return s->sys_cfgctrl;

    case 0xa8: /* SYS_CFGSTAT */

        if (board_id(s) != BOARD_ID_VEXPRESS) {

            goto bad_reg;

        }

        return s->sys_cfgstat;

    default:

    bad_reg:

        printf ("arm_sysctl_read: Bad register offset 0x%x\n", (int)offset);

        return 0;

    }

}


void virtio_blk_data_plane_stop(VirtIOBlockDataPlane *s)

{

    BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(s->vdev)));

    VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);

    VirtIOBlock *vblk = VIRTIO_BLK(s->vdev);

    unsigned i;

    unsigned nvqs = s->conf->num_queues;

    if (!vblk->dataplane_started || s->stopping) {

        return;

    }

    /* Better luck next time. */

    if (vblk->dataplane_disabled) {

        vblk->dataplane_disabled = false;

        vblk->dataplane_started = false;

        return;

    }

    s->stopping = true;

    trace_virtio_blk_data_plane_stop(s);

    aio_context_acquire(s->ctx);

    /* Stop notifications for new requests from guest */

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

        VirtQueue *vq = virtio_get_queue(s->vdev, i);

        virtio_queue_aio_set_host_notifier_handler(vq, s->ctx, NULL);

    }

    /* Drain and switch bs back to the QEMU main loop */

    blk_set_aio_context(s->conf->conf.blk, qemu_get_aio_context());

    aio_context_release(s->ctx);

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

        virtio_bus_set_host_notifier(VIRTIO_BUS(qbus), i, false);

    }

    /* Clean up guest notifier (irq) */

    k->set_guest_notifiers(qbus->parent, nvqs, false);

    vblk->dataplane_started = false;

    s->stopping = false;

}


static uint32_t scoop_readb(void *opaque, target_phys_addr_t addr)

{

    ScoopInfo *s = (ScoopInfo *) opaque;

    switch (addr) {

    case SCOOP_MCR:

        return s->mcr;

    case SCOOP_CDR:

        return s->cdr;

    case SCOOP_CSR:

        return s->status;

    case SCOOP_CPR:

        return s->power;

    case SCOOP_CCR:

        return s->ccr;

    case SCOOP_IRR_IRM:

        return s->irr;

    case SCOOP_IMR:

        return s->imr;

    case SCOOP_ISR:

        return s->isr;

    case SCOOP_GPCR:

        return s->gpio_dir;

    case SCOOP_GPWR:

    case SCOOP_GPRR:

        return s->gpio_level;

    default:

        zaurus_printf("Bad register offset " REG_FMT "\n", (unsigned long)addr);

    }

    return 0;

}


static void acpi_build_update(void *build_opaque)

{

    AcpiBuildState *build_state = build_opaque;

    AcpiBuildTables tables;

    /* No state to update or already patched? Nothing to do. */

    if (!build_state || build_state->patched) {

        return;

    }

    build_state->patched = 1;

    acpi_build_tables_init(&tables);

    acpi_build(&tables, MACHINE(qdev_get_machine()));

    acpi_ram_update(build_state->table_mr, tables.table_data);

    if (build_state->rsdp) {

        memcpy(build_state->rsdp, tables.rsdp->data, acpi_data_len(tables.rsdp));

    } else {

        acpi_ram_update(build_state->rsdp_mr, tables.rsdp);

    }

    acpi_ram_update(build_state->linker_mr, tables.linker);

    acpi_build_tables_cleanup(&tables, true);

}


static ssize_t nbd_receive_request(QIOChannel *ioc, NBDRequest *request)

{

    uint8_t buf[NBD_REQUEST_SIZE];

    uint32_t magic;

    ssize_t ret;

    ret = read_sync(ioc, buf, sizeof(buf), NULL);

    if (ret < 0) {

        return ret;

    }

    /* Request

       [ 0 ..  3]   magic   (NBD_REQUEST_MAGIC)

       [ 4 ..  5]   flags   (NBD_CMD_FLAG_FUA, ...)

       [ 6 ..  7]   type    (NBD_CMD_READ, ...)

       [ 8 .. 15]   handle

       [16 .. 23]   from

       [24 .. 27]   len

     */

    magic = ldl_be_p(buf);

    request->flags  = lduw_be_p(buf + 4);

    request->type   = lduw_be_p(buf + 6);

    request->handle = ldq_be_p(buf + 8);

    request->from   = ldq_be_p(buf + 16);

    request->len    = ldl_be_p(buf + 24);

    TRACE("Got request: { magic = 0x%" PRIx32 ", .flags = %" PRIx16

          ", .type = %" PRIx16 ", from = %" PRIu64 ", len = %" PRIu32 " }",

          magic, request->flags, request->type, request->from, request->len);

    if (magic != NBD_REQUEST_MAGIC) {

        LOG("invalid magic (got 0x%" PRIx32 ")", magic);

        return -EINVAL;

    }

    return 0;

}


static void change_parent_backing_link(BlockDriverState *from,

                                       BlockDriverState *to)

{

    BdrvChild *c, *next, *to_c;

    QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {

        if (c->role->stay_at_node) {

            continue;

        }

        if (c->role == &child_backing) {

            /* @from is generally not allowed to be a backing file, except for

             * when @to is the overlay. In that case, @from may not be replaced

             * by @to as @to's backing node. */

            QLIST_FOREACH(to_c, &to->children, next) {

                if (to_c == c) {

                    break;

                }

            }

            if (to_c) {

                continue;

            }

        }

        assert(c->role != &child_backing);

        bdrv_ref(to);

        /* FIXME Are we sure that bdrv_replace_child() can't run into

         * &error_abort because of permissions? */

        bdrv_replace_child(c, to, true);

        bdrv_unref(from);

    }

}


static void test_visitor_in_any(TestInputVisitorData *data,

                                const void *unused)

{

    QObject *res = NULL;

    Error *err = NULL;

    Visitor *v;

    QInt *qint;

    QBool *qbool;

    QString *qstring;

    QDict *qdict;

    QObject *qobj;

    v = visitor_input_test_init(data, "-42");

    visit_type_any(v, &res, NULL, &err);

    g_assert(!err);

    qint = qobject_to_qint(res);

    g_assert(qint);

    g_assert_cmpint(qint_get_int(qint), ==, -42);

    qobject_decref(res);

    v = visitor_input_test_init(data, "{ 'integer': -42, 'boolean': true, 'string': 'foo' }");

    visit_type_any(v, &res, NULL, &err);

    g_assert(!err);

    qdict = qobject_to_qdict(res);

    g_assert(qdict && qdict_size(qdict) == 3);

    qobj = qdict_get(qdict, "integer");

    g_assert(qobj);

    qint = qobject_to_qint(qobj);

    g_assert(qint);

    g_assert_cmpint(qint_get_int(qint), ==, -42);

    qobj = qdict_get(qdict, "boolean");

    g_assert(qobj);

    qbool = qobject_to_qbool(qobj);

    g_assert(qbool);

    g_assert(qbool_get_bool(qbool) == true);

    qobj = qdict_get(qdict, "string");

    g_assert(qobj);

    qstring = qobject_to_qstring(qobj);

    g_assert(qstring);

    g_assert_cmpstr(qstring_get_str(qstring), ==, "foo");

    qobject_decref(res);

}


void kvm_remove_all_breakpoints(CPUState *current_env)

{

    struct kvm_sw_breakpoint *bp, *next;

    KVMState *s = current_env->kvm_state;

    CPUState *env;

    QTAILQ_FOREACH_SAFE(bp, &s->kvm_sw_breakpoints, entry, next) {

        if (kvm_arch_remove_sw_breakpoint(current_env, bp) != 0) {

            /* Try harder to find a CPU that currently sees the breakpoint. */

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

                if (kvm_arch_remove_sw_breakpoint(env, bp) == 0)

                    break;

            }

        }

    }

    kvm_arch_remove_all_hw_breakpoints();

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

        kvm_update_guest_debug(env, 0);

}


static void generate_new_codebooks(RoqContext *enc, RoqTempdata *tempData)

{

    int i,j;

    RoqCodebooks *codebooks = &tempData->codebooks;

    int max = enc->width*enc->height/16;

    uint8_t mb2[3*4];

    roq_cell *results4 = av_malloc(sizeof(roq_cell)*MAX_CBS_4x4*4);

    uint8_t *yuvClusters=av_malloc(sizeof(int)*max*6*4);

    int *points = av_malloc(max*6*4*sizeof(int));

    int bias;

    /* Subsample YUV data */

    create_clusters(enc->frame_to_enc, enc->width, enc->height, yuvClusters);

    /* Cast to integer and apply chroma bias */

    for (i=0; i<max*24; i++) {

        bias = ((i%6)<4) ? 1 : CHROMA_BIAS;

        points[i] = bias*yuvClusters[i];

    }

    /* Create 4x4 codebooks */

    generate_codebook(enc, tempData, points, max, results4, 4, MAX_CBS_4x4);

    codebooks->numCB4 = MAX_CBS_4x4;

    tempData->closest_cb2 = av_malloc(max*4*sizeof(int));

    /* Create 2x2 codebooks */

    generate_codebook(enc, tempData, points, max*4, enc->cb2x2, 2, MAX_CBS_2x2);

    codebooks->numCB2 = MAX_CBS_2x2;

    /* Unpack 2x2 codebook clusters */

    for (i=0; i<codebooks->numCB2; i++)

        unpack_roq_cell(enc->cb2x2 + i, codebooks->unpacked_cb2 + i*2*2*3);

    /* Index all 4x4 entries to the 2x2 entries, unpack, and enlarge */

    for (i=0; i<codebooks->numCB4; i++) {

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

            unpack_roq_cell(&results4[4*i + j], mb2);

            index_mb(mb2, codebooks->unpacked_cb2, codebooks->numCB2,

                     &enc->cb4x4[i].idx[j], 2);

        }

        unpack_roq_qcell(codebooks->unpacked_cb2, enc->cb4x4 + i,

                         codebooks->unpacked_cb4 + i*4*4*3);

        enlarge_roq_mb4(codebooks->unpacked_cb4 + i*4*4*3,

                        codebooks->unpacked_cb4_enlarged + i*8*8*3);

    }

    av_free(yuvClusters);

    av_free(points);

    av_free(results4);

}


static void breakpoint_handler(CPUX86State *env)

{

    CPUBreakpoint *bp;

    if (env->watchpoint_hit) {

        if (env->watchpoint_hit->flags & BP_CPU) {

            env->watchpoint_hit = NULL;

            if (check_hw_breakpoints(env, 0))

                raise_exception_env(EXCP01_DB, env);

            else

                cpu_resume_from_signal(env, NULL);

        }

    } else {

        QTAILQ_FOREACH(bp, &env->breakpoints, entry)

            if (bp->pc == env->eip) {

                if (bp->flags & BP_CPU) {

                    check_hw_breakpoints(env, 1);

                    raise_exception_env(EXCP01_DB, env);

                }

                break;

            }

    }

    if (prev_debug_excp_handler)

        prev_debug_excp_handler(env);

}


int usb_desc_msos(const USBDesc *desc,  USBPacket *p,

                  int index, uint8_t *dest, size_t len)

{

    void *buf = g_malloc0(4096);

    int length = 0;

    switch (index) {

    case 0x0004:

        length = usb_desc_msos_compat(desc, buf);

        break;

    case 0x0005:

        length = usb_desc_msos_prop(desc, buf);

        break;

    }

    if (length > len) {

        length = len;

    }

    memcpy(dest, buf, length);

    free(buf);

    p->actual_length = length;

    return 0;

}


static void qemu_chr_parse_udp(QemuOpts *opts, ChardevBackend *backend,

                               Error **errp)

{

    const char *host = qemu_opt_get(opts, "host");

    const char *port = qemu_opt_get(opts, "port");

    const char *localaddr = qemu_opt_get(opts, "localaddr");

    const char *localport = qemu_opt_get(opts, "localport");

    bool has_local = false;

    SocketAddress *addr;

    if (host == NULL || strlen(host) == 0) {

        host = "localhost";

    }

    if (port == NULL || strlen(port) == 0) {

        error_setg(errp, "chardev: udp: remote port not specified");

        return;

    }

    if (localport == NULL || strlen(localport) == 0) {

        localport = "0";

    } else {

        has_local = true;

    }

    if (localaddr == NULL || strlen(localaddr) == 0) {

        localaddr = "";

    } else {

        has_local = true;

    }

    backend->udp = g_new0(ChardevUdp, 1);

    addr = g_new0(SocketAddress, 1);

    addr->kind = SOCKET_ADDRESS_KIND_INET;

    addr->inet = g_new0(InetSocketAddress, 1);

    addr->inet->host = g_strdup(host);

    addr->inet->port = g_strdup(port);

    addr->inet->has_ipv4 = qemu_opt_get(opts, "ipv4");

    addr->inet->ipv4 = qemu_opt_get_bool(opts, "ipv4", 0);

    addr->inet->has_ipv6 = qemu_opt_get(opts, "ipv6");

    addr->inet->ipv6 = qemu_opt_get_bool(opts, "ipv6", 0);

    backend->udp->remote = addr;

    if (has_local) {

        backend->udp->has_local = true;

        addr = g_new0(SocketAddress, 1);

        addr->kind = SOCKET_ADDRESS_KIND_INET;

        addr->inet = g_new0(InetSocketAddress, 1);

        addr->inet->host = g_strdup(localaddr);

        addr->inet->port = g_strdup(localport);

        backend->udp->local = addr;

    }

}


static int read_write_object(int fd, char *buf, uint64_t oid, int copies,

                             unsigned int datalen, uint64_t offset,

                             bool write, bool create, bool cache)

{

    SheepdogObjReq hdr;

    SheepdogObjRsp *rsp = (SheepdogObjRsp *)&hdr;

    unsigned int wlen, rlen;

    int ret;

    memset(&hdr, 0, sizeof(hdr));

    if (write) {

        wlen = datalen;

        rlen = 0;

        hdr.flags = SD_FLAG_CMD_WRITE;

        if (create) {

            hdr.opcode = SD_OP_CREATE_AND_WRITE_OBJ;

        } else {

            hdr.opcode = SD_OP_WRITE_OBJ;

        }

    } else {

        wlen = 0;

        rlen = datalen;

        hdr.opcode = SD_OP_READ_OBJ;

    }

    if (cache) {

        hdr.flags |= SD_FLAG_CMD_CACHE;

    }

    hdr.oid = oid;

    hdr.data_length = datalen;

    hdr.offset = offset;

    hdr.copies = copies;

    ret = do_req(fd, (SheepdogReq *)&hdr, buf, &wlen, &rlen);

    if (ret) {

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

        return ret;

    }

    switch (rsp->result) {

    case SD_RES_SUCCESS:

        return 0;

    default:

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

        return -EIO;

    }

}