restore_sigcontext(CPUMIPSState *regs, struct target_sigcontext *sc)

{

    int err = 0;

    int i;

    __get_user(regs->CP0_EPC, &sc->sc_pc);

    __get_user(regs->active_tc.HI[0], &sc->sc_mdhi);

    __get_user(regs->active_tc.LO[0], &sc->sc_mdlo);

    for (i = 1; i < 32; ++i) {

        __get_user(regs->active_tc.gpr[i], &sc->sc_regs[i]);

    }

    __get_user(regs->active_tc.HI[1], &sc->sc_hi1);

    __get_user(regs->active_tc.HI[2], &sc->sc_hi2);

    __get_user(regs->active_tc.HI[3], &sc->sc_hi3);

    __get_user(regs->active_tc.LO[1], &sc->sc_lo1);

    __get_user(regs->active_tc.LO[2], &sc->sc_lo2);

    __get_user(regs->active_tc.LO[3], &sc->sc_lo3);

    {

        uint32_t dsp;

        __get_user(dsp, &sc->sc_dsp);

        cpu_wrdsp(dsp, 0x3ff, regs);

    }

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

        __get_user(regs->active_fpu.fpr[i].d, &sc->sc_fpregs[i]);

    }

    return err;

}


static void sdhci_write_block_to_card(SDHCIState *s)

{

    int index = 0;

    if (s->prnsts & SDHC_SPACE_AVAILABLE) {

        if (s->norintstsen & SDHC_NISEN_WBUFRDY) {

            s->norintsts |= SDHC_NIS_WBUFRDY;

        }

        sdhci_update_irq(s);

        return;

    }

    if (s->trnmod & SDHC_TRNS_BLK_CNT_EN) {

        if (s->blkcnt == 0) {

            return;

        } else {

            s->blkcnt--;

        }

    }

    for (index = 0; index < (s->blksize & 0x0fff); index++) {

        sd_write_data(s->card, s->fifo_buffer[index]);

    }

    /* Next data can be written through BUFFER DATORT register */

    s->prnsts |= SDHC_SPACE_AVAILABLE;

    /* Finish transfer if that was the last block of data */

    if ((s->trnmod & SDHC_TRNS_MULTI) == 0 ||

            ((s->trnmod & SDHC_TRNS_MULTI) &&

            (s->trnmod & SDHC_TRNS_BLK_CNT_EN) && (s->blkcnt == 0))) {

        SDHCI_GET_CLASS(s)->end_data_transfer(s);

    } else if (s->norintstsen & SDHC_NISEN_WBUFRDY) {

        s->norintsts |= SDHC_NIS_WBUFRDY;

    }

    /* Generate Block Gap Event if requested and if not the last block */

    if (s->stopped_state == sdhc_gap_write && (s->trnmod & SDHC_TRNS_MULTI) &&

            s->blkcnt > 0) {

        s->prnsts &= ~SDHC_DOING_WRITE;

        if (s->norintstsen & SDHC_EISEN_BLKGAP) {

            s->norintsts |= SDHC_EIS_BLKGAP;

        }

        SDHCI_GET_CLASS(s)->end_data_transfer(s);

    }

    sdhci_update_irq(s);

}


static AHCIQState *ahci_boot(void)

{

    AHCIQState *s;

    const char *cli;

    s = g_malloc0(sizeof(AHCIQState));

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

        ",format=qcow2"

        " -M q35 "

        "-device ide-hd,drive=drive0 "

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

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

    alloc_set_flags(s->parent->alloc, ALLOC_LEAK_ASSERT);

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

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

    return s;

}


void address_space_destroy_dispatch(AddressSpace *as)

{

    AddressSpaceDispatch *d = as->dispatch;

    memory_listener_unregister(&d->listener);

    g_free(d);

    as->dispatch = NULL;

}


mst_fpga_readb(void *opaque, target_phys_addr_t addr)

{

	mst_irq_state *s = (mst_irq_state *) opaque;

	switch (addr) {

	case MST_LEDDAT1:

		return s->leddat1;

	case MST_LEDDAT2:

		return s->leddat2;

	case MST_LEDCTRL:

		return s->ledctrl;

	case MST_GPSWR:

		return s->gpswr;

	case MST_MSCWR1:

		return s->mscwr1;

	case MST_MSCWR2:

		return s->mscwr2;

	case MST_MSCWR3:

		return s->mscwr3;

	case MST_MSCRD:

		return s->mscrd;

	case MST_INTMSKENA:

		return s->intmskena;

	case MST_INTSETCLR:

		return s->intsetclr;

	case MST_PCMCIA0:

		return s->pcmcia0;

	case MST_PCMCIA1:

		return s->pcmcia1;

	default:

		printf("Mainstone - mst_fpga_readb: Bad register offset "

			"0x" TARGET_FMT_plx " \n", addr);

	}

	return 0;

}


static int pci_piix_ide_initfn(PCIIDEState *d)

{

    uint8_t *pci_conf = d->dev.config;

    pci_conf[PCI_CLASS_PROG] = 0x80; // legacy ATA mode

    pci_config_set_class(pci_conf, PCI_CLASS_STORAGE_IDE);

    qemu_register_reset(piix3_reset, d);

    pci_register_bar(&d->dev, 4, 0x10, PCI_BASE_ADDRESS_SPACE_IO, bmdma_map);

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

    pci_piix_init_ports(d);

    return 0;

}


static void virtio_net_pci_realize(VirtIOPCIProxy *vpci_dev, Error **errp)

{

    DeviceState *qdev = DEVICE(vpci_dev);

    VirtIONetPCI *dev = VIRTIO_NET_PCI(vpci_dev);

    DeviceState *vdev = DEVICE(&dev->vdev);

    virtio_net_set_config_size(&dev->vdev, vpci_dev->host_features);

    virtio_net_set_netclient_name(&dev->vdev, qdev->id,

                                  object_get_typename(OBJECT(qdev)));

    qdev_set_parent_bus(vdev, BUS(&vpci_dev->bus));

    object_property_set_bool(OBJECT(vdev), true, "realized", errp);

}


static void spapr_nvram_realize(VIOsPAPRDevice *dev, Error **errp)

{

    sPAPRNVRAM *nvram = VIO_SPAPR_NVRAM(dev);

    int ret;

    if (nvram->blk) {

        nvram->size = blk_getlength(nvram->blk);

        ret = blk_set_perm(nvram->blk,

                           BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE,

                           BLK_PERM_ALL, errp);

        if (ret < 0) {

            return;

        }

    } else {

        nvram->size = DEFAULT_NVRAM_SIZE;

    }

    nvram->buf = g_malloc0(nvram->size);

    if ((nvram->size < MIN_NVRAM_SIZE) || (nvram->size > MAX_NVRAM_SIZE)) {

        error_setg(errp, "spapr-nvram must be between %d and %d bytes in size",

                   MIN_NVRAM_SIZE, MAX_NVRAM_SIZE);

        return;

    }

    if (nvram->blk) {

        int alen = blk_pread(nvram->blk, 0, nvram->buf, nvram->size);

        if (alen != nvram->size) {

            error_setg(errp, "can't read spapr-nvram contents");

            return;

        }

    } else if (nb_prom_envs > 0) {

        /* Create a system partition to pass the -prom-env variables */

        chrp_nvram_create_system_partition(nvram->buf, MIN_NVRAM_SIZE / 4);

        chrp_nvram_create_free_partition(&nvram->buf[MIN_NVRAM_SIZE / 4],

                                         nvram->size - MIN_NVRAM_SIZE / 4);

    }

    spapr_rtas_register(RTAS_NVRAM_FETCH, "nvram-fetch", rtas_nvram_fetch);

    spapr_rtas_register(RTAS_NVRAM_STORE, "nvram-store", rtas_nvram_store);

}


static void ehci_free_packet(EHCIPacket *p)

{

    trace_usb_ehci_packet_action(p->queue, p, "free");

    if (p->async == EHCI_ASYNC_INFLIGHT) {

        usb_cancel_packet(&p->packet);

        usb_packet_unmap(&p->packet, &p->sgl);

        qemu_sglist_destroy(&p->sgl);

    QTAILQ_REMOVE(&p->queue->packets, p, next);

    usb_packet_cleanup(&p->packet);

    g_free(p);


static inline void RENAME(nv12ToUV)(uint8_t *dstU, uint8_t *dstV,

                                    const uint8_t *src1, const uint8_t *src2,

                                    long width, uint32_t *unused)

{

    RENAME(nvXXtoUV)(dstU, dstV, src1, width);

}


int ff_thread_init(AVCodecContext *avctx)

{

    if (avctx->thread_opaque) {

        av_log(avctx, AV_LOG_ERROR, "avcodec_thread_init is ignored after avcodec_open\n");

        return -1;

    }

#if HAVE_W32THREADS

    w32thread_init();

#endif

    if (avctx->codec) {

        validate_thread_parameters(avctx);

        if (avctx->active_thread_type&FF_THREAD_SLICE)

            return thread_init(avctx);

        else if (avctx->active_thread_type&FF_THREAD_FRAME)

            return frame_thread_init(avctx);

    }

    return 0;

}


static inline bool memory_access_is_direct(MemoryRegion *mr, bool is_write)

{

    if (memory_region_is_ram(mr)) {

        return !(is_write && mr->readonly);

    }

    if (memory_region_is_romd(mr)) {

        return !is_write;

    }

    return false;

}


VirtIODevice *virtio_blk_init(DeviceState *dev, VirtIOBlkConf *blk)

{

    VirtIOBlock *s;

    int cylinders, heads, secs;

    static int virtio_blk_id;

    DriveInfo *dinfo;

    if (!blk->conf.bs) {

        error_report("drive property not set");

        return NULL;

    }

    if (!bdrv_is_inserted(blk->conf.bs)) {

        error_report("Device needs media, but drive is empty");

        return NULL;

    }

    if (!blk->serial) {

        /* try to fall back to value set with legacy -drive serial=... */

        dinfo = drive_get_by_blockdev(blk->conf.bs);

        if (*dinfo->serial) {

            blk->serial = strdup(dinfo->serial);

        }

    }

    s = (VirtIOBlock *)virtio_common_init("virtio-blk", VIRTIO_ID_BLOCK,

                                          sizeof(struct virtio_blk_config),

                                          sizeof(VirtIOBlock));

    s->vdev.get_config = virtio_blk_update_config;

    s->vdev.get_features = virtio_blk_get_features;

    s->vdev.reset = virtio_blk_reset;

    s->bs = blk->conf.bs;

    s->conf = &blk->conf;

    s->blk = blk;

    s->rq = NULL;

    s->sector_mask = (s->conf->logical_block_size / BDRV_SECTOR_SIZE) - 1;

    bdrv_guess_geometry(s->bs, &cylinders, &heads, &secs);

    s->vq = virtio_add_queue(&s->vdev, 128, virtio_blk_handle_output);

    qemu_add_vm_change_state_handler(virtio_blk_dma_restart_cb, s);

    s->qdev = dev;

    register_savevm(dev, "virtio-blk", virtio_blk_id++, 2,

                    virtio_blk_save, virtio_blk_load, s);

    bdrv_set_dev_ops(s->bs, &virtio_block_ops, s);

    bdrv_set_buffer_alignment(s->bs, s->conf->logical_block_size);

    bdrv_iostatus_enable(s->bs);

    add_boot_device_path(s->conf->bootindex, dev, "/disk@0,0");

    return &s->vdev;

}


static int pcm_decode_frame(AVCodecContext *avctx,
                            void *data, int *data_size,
                            AVPacket *avpkt)
{
    const uint8_t *buf = avpkt->data;
    int buf_size = avpkt->size;
    PCMDecode *s = avctx->priv_data;
    int sample_size, c, n, i;
    short *samples;
    const uint8_t *src, *src8, *src2[MAX_CHANNELS];
    uint8_t *dstu8;
    int16_t *dst_int16_t;
    int32_t *dst_int32_t;
    int64_t *dst_int64_t;
    uint16_t *dst_uint16_t;
    uint32_t *dst_uint32_t;
    samples = data;
    src = buf;
    if (avctx->sample_fmt!=avctx->codec->sample_fmts[0]) {
        av_log(avctx, AV_LOG_ERROR, "invalid sample_fmt\n");
        return -1;
    if(avctx->channels <= 0 || avctx->channels > MAX_CHANNELS){
        av_log(avctx, AV_LOG_ERROR, "PCM channels out of bounds\n");
        return -1;
    sample_size = av_get_bits_per_sample(avctx->codec_id)/8;
    /* av_get_bits_per_sample returns 0 for CODEC_ID_PCM_DVD */
    if (CODEC_ID_PCM_DVD == avctx->codec_id)
        /* 2 samples are interleaved per block in PCM_DVD */
        sample_size = avctx->bits_per_coded_sample * 2 / 8;
    else if (avctx->codec_id == CODEC_ID_PCM_LXF)
        /* we process 40-bit blocks per channel for LXF */
        sample_size = 5;
    n = avctx->channels * sample_size;
    if(n && buf_size % n){
        if (buf_size < n) {
            av_log(avctx, AV_LOG_ERROR, "invalid PCM packet\n");
            return -1;
        }else
            buf_size -= buf_size % n;
    buf_size= FFMIN(buf_size, *data_size/2);
    *data_size=0;
    n = buf_size/sample_size;
    switch(avctx->codec->id) {
    case CODEC_ID_PCM_U32LE:
        DECODE(uint32_t, le32, src, samples, n, 0, 0x80000000)
        break;
    case CODEC_ID_PCM_U32BE:
        DECODE(uint32_t, be32, src, samples, n, 0, 0x80000000)
        break;
    case CODEC_ID_PCM_S24LE:
        DECODE(int32_t, le24, src, samples, n, 8, 0)
        break;
    case CODEC_ID_PCM_S24BE:
        DECODE(int32_t, be24, src, samples, n, 8, 0)
        break;
    case CODEC_ID_PCM_U24LE:
        DECODE(uint32_t, le24, src, samples, n, 8, 0x800000)
        break;
    case CODEC_ID_PCM_U24BE:
        DECODE(uint32_t, be24, src, samples, n, 8, 0x800000)
        break;
    case CODEC_ID_PCM_S24DAUD:
        for(;n>0;n--) {
          uint32_t v = bytestream_get_be24(&src);
          v >>= 4; // sync flags are here
          *samples++ = av_reverse[(v >> 8) & 0xff] +
                       (av_reverse[v & 0xff] << 8);
        break;
    case CODEC_ID_PCM_S16LE_PLANAR:
        n /= avctx->channels;
        for(c=0;c<avctx->channels;c++)
            src2[c] = &src[c*n*2];
        for(;n>0;n--)
            for(c=0;c<avctx->channels;c++)
                *samples++ = bytestream_get_le16(&src2[c]);
        src = src2[avctx->channels-1];
        break;
    case CODEC_ID_PCM_U16LE:
        DECODE(uint16_t, le16, src, samples, n, 0, 0x8000)
        break;
    case CODEC_ID_PCM_U16BE:
        DECODE(uint16_t, be16, src, samples, n, 0, 0x8000)
        break;
    case CODEC_ID_PCM_S8:
        dstu8= (uint8_t*)samples;
        for(;n>0;n--) {
            *dstu8++ = *src++ + 128;
        samples= (short*)dstu8;
        break;
#if HAVE_BIGENDIAN
    case CODEC_ID_PCM_F64LE:
        DECODE(int64_t, le64, src, samples, n, 0, 0)
        break;
    case CODEC_ID_PCM_S32LE:
    case CODEC_ID_PCM_F32LE:
        DECODE(int32_t, le32, src, samples, n, 0, 0)
        break;
    case CODEC_ID_PCM_S16LE:
        DECODE(int16_t, le16, src, samples, n, 0, 0)
        break;
    case CODEC_ID_PCM_F64BE:
    case CODEC_ID_PCM_F32BE:
    case CODEC_ID_PCM_S32BE:
    case CODEC_ID_PCM_S16BE:
#else
    case CODEC_ID_PCM_F64BE:
        DECODE(int64_t, be64, src, samples, n, 0, 0)
        break;
    case CODEC_ID_PCM_F32BE:
    case CODEC_ID_PCM_S32BE:
        DECODE(int32_t, be32, src, samples, n, 0, 0)
        break;
    case CODEC_ID_PCM_S16BE:
        DECODE(int16_t, be16, src, samples, n, 0, 0)
        break;
    case CODEC_ID_PCM_F64LE:
    case CODEC_ID_PCM_F32LE:
    case CODEC_ID_PCM_S32LE:
    case CODEC_ID_PCM_S16LE:
#endif /* HAVE_BIGENDIAN */
    case CODEC_ID_PCM_U8:
        memcpy(samples, src, n*sample_size);
        src += n*sample_size;
        samples = (short*)((uint8_t*)data + n*sample_size);
        break;
    case CODEC_ID_PCM_ZORK:
        for(;n>0;n--) {
            int x= *src++;
            if(x&128) x-= 128;
            else      x = -x;
            *samples++ = x << 8;
        break;
    case CODEC_ID_PCM_ALAW:
    case CODEC_ID_PCM_MULAW:
        for(;n>0;n--) {
            *samples++ = s->table[*src++];
        break;
    case CODEC_ID_PCM_DVD:
        dst_int32_t = data;
        n /= avctx->channels;
        switch (avctx->bits_per_coded_sample) {
        case 20:
            while (n--) {
                c = avctx->channels;
                src8 = src + 4*c;
                while (c--) {
                    *dst_int32_t++ = (bytestream_get_be16(&src) << 16) + ((*src8   &0xf0) << 8);
                    *dst_int32_t++ = (bytestream_get_be16(&src) << 16) + ((*src8++ &0x0f) << 12);
                src = src8;
            break;
        case 24:
            while (n--) {
                c = avctx->channels;
                src8 = src + 4*c;
                while (c--) {
                    *dst_int32_t++ = (bytestream_get_be16(&src) << 16) + ((*src8++) << 8);
                    *dst_int32_t++ = (bytestream_get_be16(&src) << 16) + ((*src8++) << 8);
                src = src8;
            break;
        default:
            av_log(avctx, AV_LOG_ERROR, "PCM DVD unsupported sample depth\n");
            return -1;
            break;
        samples = (short *) dst_int32_t;
        break;
    case CODEC_ID_PCM_LXF:
        dst_int32_t = data;
        n /= avctx->channels;
        //unpack and de-planerize
        for (i = 0; i < n; i++) {
            for (c = 0, src8 = src + i*5; c < avctx->channels; c++, src8 += n*5) {
                //extract low 20 bits and expand to 32 bits
                *dst_int32_t++ = (src8[2] << 28) | (src8[1] << 20) | (src8[0] << 12) |
                                 ((src8[2] & 0xF) << 8) | src8[1];
            for (c = 0, src8 = src + i*5; c < avctx->channels; c++, src8 += n*5) {
                //extract high 20 bits and expand to 32 bits
                *dst_int32_t++ = (src8[4] << 24) | (src8[3] << 16) |
                                 ((src8[2] & 0xF0) << 8) | (src8[4] << 4) | (src8[3] >> 4);
        src += n * avctx->channels * 5;
        samples = (short *) dst_int32_t;
        break;
    default:
        return -1;
    *data_size = (uint8_t *)samples - (uint8_t *)data;
    return src - buf;


static int arm946_prbs_write(CPUARMState *env, const ARMCPRegInfo *ri,

                             uint64_t value)

{

    if (ri->crm > 8) {

        return EXCP_UDEF;

    }

    env->cp15.c6_region[ri->crm] = value;

    return 0;

}


static int usb_host_open(USBHostDevice *dev, int bus_num,

                         int addr, const char *port,

                         const char *prod_name, int speed)

{

    int fd = -1, ret;

    trace_usb_host_open_started(bus_num, addr);

    if (dev->fd != -1) {

        goto fail;

    }

    fd = usb_host_open_device(bus_num, addr);

    if (fd < 0) {

        goto fail;

    }

    DPRINTF("husb: opened %s\n", buf);

    dev->bus_num = bus_num;

    dev->addr = addr;

    strcpy(dev->port, port);

    dev->fd = fd;

    /* read the device description */

    dev->descr_len = read(fd, dev->descr, sizeof(dev->descr));

    if (dev->descr_len <= 0) {

        perror("husb: reading device data failed");

        goto fail;

    }

#ifdef DEBUG

    {

        int x;

        printf("=== begin dumping device descriptor data ===\n");

        for (x = 0; x < dev->descr_len; x++) {

            printf("%02x ", dev->descr[x]);

        }

        printf("\n=== end dumping device descriptor data ===\n");

    }

#endif

    /* start unconfigured -- we'll wait for the guest to set a configuration */

    if (!usb_host_claim_interfaces(dev, 0)) {

        goto fail;

    }

    usb_ep_init(&dev->dev);

    usb_linux_update_endp_table(dev);

    if (speed == -1) {

        struct usbdevfs_connectinfo ci;

        ret = ioctl(fd, USBDEVFS_CONNECTINFO, &ci);

        if (ret < 0) {

            perror("usb_host_device_open: USBDEVFS_CONNECTINFO");

            goto fail;

        }

        if (ci.slow) {

            speed = USB_SPEED_LOW;

        } else {

            speed = USB_SPEED_HIGH;

        }

    }

    dev->dev.speed = speed;

    dev->dev.speedmask = (1 << speed);

    if (dev->dev.speed == USB_SPEED_HIGH && usb_linux_full_speed_compat(dev)) {

        dev->dev.speedmask |= USB_SPEED_MASK_FULL;

    }

    trace_usb_host_open_success(bus_num, addr);

    if (!prod_name || prod_name[0] == '\0') {

        snprintf(dev->dev.product_desc, sizeof(dev->dev.product_desc),

                 "host:%d.%d", bus_num, addr);

    } else {

        pstrcpy(dev->dev.product_desc, sizeof(dev->dev.product_desc),

                prod_name);

    }

    ret = usb_device_attach(&dev->dev);

    if (ret) {

        goto fail;

    }

    /* USB devio uses 'write' flag to check for async completions */

    qemu_set_fd_handler(dev->fd, NULL, async_complete, dev);

    return 0;

fail:

    trace_usb_host_open_failure(bus_num, addr);

    if (dev->fd != -1) {

        close(dev->fd);

        dev->fd = -1;

    }

    return -1;

}


static int esp_pci_scsi_init(PCIDevice *dev)

{

    PCIESPState *pci = PCI_ESP(dev);

    DeviceState *d = DEVICE(dev);

    ESPState *s = &pci->esp;

    uint8_t *pci_conf;

    Error *err = NULL;

    pci_conf = dev->config;

    /* Interrupt pin A */

    pci_conf[PCI_INTERRUPT_PIN] = 0x01;

    s->dma_memory_read = esp_pci_dma_memory_read;

    s->dma_memory_write = esp_pci_dma_memory_write;

    s->dma_opaque = pci;

    s->chip_id = TCHI_AM53C974;

    memory_region_init_io(&pci->io, OBJECT(pci), &esp_pci_io_ops, pci,

                          "esp-io", 0x80);

    pci_register_bar(dev, 0, PCI_BASE_ADDRESS_SPACE_IO, &pci->io);

    s->irq = pci_allocate_irq(dev);

    scsi_bus_new(&s->bus, sizeof(s->bus), d, &esp_pci_scsi_info, NULL);

    if (!d->hotplugged) {

        scsi_bus_legacy_handle_cmdline(&s->bus, &err);

        if (err != NULL) {

            error_free(err);

            return -1;

        }

    }

    return 0;

}


static void copy_frame(Jpeg2000EncoderContext *s)

{

    int tileno, compno, i, y, x;

    uint8_t *line;

    for (tileno = 0; tileno < s->numXtiles * s->numYtiles; tileno++){

        Jpeg2000Tile *tile = s->tile + tileno;

        if (s->planar){

            for (compno = 0; compno < s->ncomponents; compno++){

                Jpeg2000Component *comp = tile->comp + compno;

                int *dst = comp->data;

                line = s->picture.data[compno]

                       + comp->coord[1][0] * s->picture.linesize[compno]

                       + comp->coord[0][0];

                for (y = comp->coord[1][0]; y < comp->coord[1][1]; y++){

                    uint8_t *ptr = line;

                    for (x = comp->coord[0][0]; x < comp->coord[0][1]; x++)

                        *dst++ = *ptr++ - (1 << 7);

                    line += s->picture.linesize[compno];

                }

            }

        } else{

            line = s->picture.data[0] + tile->comp[0].coord[1][0] * s->picture.linesize[0]

                   + tile->comp[0].coord[0][0] * s->ncomponents;

            i = 0;

            for (y = tile->comp[0].coord[1][0]; y < tile->comp[0].coord[1][1]; y++){

                uint8_t *ptr = line;

                for (x = tile->comp[0].coord[0][0]; x < tile->comp[0].coord[0][1]; x++, i++){

                    for (compno = 0; compno < s->ncomponents; compno++){

                        tile->comp[compno].data[i] = *ptr++  - (1 << 7);

                    }

                }

                line += s->picture.linesize[0];

            }

        }

    }

}


static off_t proxy_telldir(FsContext *ctx, V9fsFidOpenState *fs)

{

    return telldir(fs->dir);

}


static int filter_samples(AVFilterLink *inlink, AVFilterBufferRef *insamplesref)

{

    AResampleContext *aresample = inlink->dst->priv;

    const int n_in  = insamplesref->audio->nb_samples;

    int n_out       = FFMAX(n_in * aresample->ratio * 2, 1);

    AVFilterLink *const outlink = inlink->dst->outputs[0];

    AVFilterBufferRef *outsamplesref = ff_get_audio_buffer(outlink, AV_PERM_WRITE, n_out);

    int ret;

    if(!outsamplesref)

        return AVERROR(ENOMEM);

    avfilter_copy_buffer_ref_props(outsamplesref, insamplesref);

    outsamplesref->format                = outlink->format;

    outsamplesref->audio->channel_layout = outlink->channel_layout;

    outsamplesref->audio->sample_rate    = outlink->sample_rate;

    if(insamplesref->pts != AV_NOPTS_VALUE) {

        int64_t inpts = av_rescale(insamplesref->pts, inlink->time_base.num * (int64_t)outlink->sample_rate * inlink->sample_rate, inlink->time_base.den);

        int64_t outpts= swr_next_pts(aresample->swr, inpts);

        aresample->next_pts =

        outsamplesref->pts  = (outpts + inlink->sample_rate/2) / inlink->sample_rate;

    } else {

        outsamplesref->pts  = AV_NOPTS_VALUE;

    }

    n_out = swr_convert(aresample->swr, outsamplesref->extended_data, n_out,

                                 (void *)insamplesref->extended_data, n_in);

    if (n_out <= 0) {

        avfilter_unref_buffer(outsamplesref);

        avfilter_unref_buffer(insamplesref);

        return 0;

    }

    outsamplesref->audio->nb_samples  = n_out;

    ret = ff_filter_samples(outlink, outsamplesref);

    aresample->req_fullfilled= 1;

    avfilter_unref_buffer(insamplesref);

    return ret;

}


static int mov_read_ctts(MOVContext *c, ByteIOContext *pb, MOV_atom_t atom)

{

    AVStream *st = c->fc->streams[c->fc->nb_streams-1];

    MOVStreamContext *sc = st->priv_data;

    unsigned int i, entries;

    get_byte(pb); /* version */

    get_be24(pb); /* flags */

    entries = get_be32(pb);

    if(entries >= UINT_MAX / sizeof(MOV_stts_t))

        return -1;

    sc->ctts_count = entries;

    sc->ctts_data = av_malloc(entries * sizeof(MOV_stts_t));

    if (!sc->ctts_data)

        return -1;

    dprintf(c->fc, "track[%i].ctts.entries = %i\n", c->fc->nb_streams-1, entries);

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

        int count    =get_be32(pb);

        int duration =get_be32(pb);

        if (duration < 0) {

            av_log(c->fc, AV_LOG_ERROR, "negative ctts, ignoring\n");

            sc->ctts_count = 0;

            url_fskip(pb, 8 * (entries - i - 1));

            break;

        }

        sc->ctts_data[i].count   = count;

        sc->ctts_data[i].duration= duration;

        sc->time_rate= ff_gcd(sc->time_rate, duration);

    }

    return 0;

}


int64_t av_get_int(void *obj, const char *name, const AVOption **o_out)

{

    int64_t intnum=1;

    double num=1;

    int den=1;

    av_get_number(obj, name, o_out, &num, &den, &intnum);

    return num*intnum/den;

}


void commit_active_start(BlockDriverState *bs, BlockDriverState *base,

                         int64_t speed,

                         BlockdevOnError on_error,

                         BlockDriverCompletionFunc *cb,

                         void *opaque, Error **errp)

{

    int64_t length, base_length;

    int orig_base_flags;

    orig_base_flags = bdrv_get_flags(base);

    if (bdrv_reopen(base, bs->open_flags, errp)) {

        return;

    }

    length = bdrv_getlength(bs);

    if (length < 0) {

        error_setg(errp, "Unable to determine length of %s", bs->filename);

        goto error_restore_flags;

    }

    base_length = bdrv_getlength(base);

    if (base_length < 0) {

        error_setg(errp, "Unable to determine length of %s", base->filename);

        goto error_restore_flags;

    }

    if (length > base_length) {

        if (bdrv_truncate(base, length) < 0) {

            error_setg(errp, "Top image %s is larger than base image %s, and "

                             "resize of base image failed",

                             bs->filename, base->filename);

            goto error_restore_flags;

        }

    }

    bdrv_ref(base);

    mirror_start_job(bs, base, speed, 0, 0,

                     on_error, on_error, cb, opaque, errp,

                     &commit_active_job_driver, false, base);

    if (error_is_set(errp)) {

        goto error_restore_flags;

    }

    return;

error_restore_flags:

    /* ignore error and errp for bdrv_reopen, because we want to propagate

     * the original error */

    bdrv_reopen(base, orig_base_flags, NULL);

    return;

}


static int matroska_decode_buffer(uint8_t** buf, int* buf_size,
                                  MatroskaTrack *track)
{
    MatroskaTrackEncoding *encodings = track->encodings.elem;
    uint8_t* data = *buf;
    int isize = *buf_size;
    uint8_t* pkt_data = NULL;
    int pkt_size = isize;
    int result = 0;
    int olen;
    switch (encodings[0].compression.algo) {
    case MATROSKA_TRACK_ENCODING_COMP_HEADERSTRIP:
        return encodings[0].compression.settings.size;
    case MATROSKA_TRACK_ENCODING_COMP_LZO:
        do {
            olen = pkt_size *= 3;
            pkt_data = av_realloc(pkt_data, pkt_size+AV_LZO_OUTPUT_PADDING);
            result = av_lzo1x_decode(pkt_data, &olen, data, &isize);
        } while (result==AV_LZO_OUTPUT_FULL && pkt_size<10000000);
        if (result)
            goto failed;
        pkt_size -= olen;
        break;
#if CONFIG_ZLIB
    case MATROSKA_TRACK_ENCODING_COMP_ZLIB: {
        z_stream zstream = {0};
        if (inflateInit(&zstream) != Z_OK)
        zstream.next_in = data;
        zstream.avail_in = isize;
        do {
            pkt_size *= 3;
            pkt_data = av_realloc(pkt_data, pkt_size);
            zstream.avail_out = pkt_size - zstream.total_out;
            zstream.next_out = pkt_data + zstream.total_out;
            result = inflate(&zstream, Z_NO_FLUSH);
        } while (result==Z_OK && pkt_size<10000000);
        pkt_size = zstream.total_out;
        inflateEnd(&zstream);
        if (result != Z_STREAM_END)
            goto failed;
        break;
    }
#endif
#if CONFIG_BZLIB
    case MATROSKA_TRACK_ENCODING_COMP_BZLIB: {
        bz_stream bzstream = {0};
        if (BZ2_bzDecompressInit(&bzstream, 0, 0) != BZ_OK)
        bzstream.next_in = data;
        bzstream.avail_in = isize;
        do {
            pkt_size *= 3;
            pkt_data = av_realloc(pkt_data, pkt_size);
            bzstream.avail_out = pkt_size - bzstream.total_out_lo32;
            bzstream.next_out = pkt_data + bzstream.total_out_lo32;
            result = BZ2_bzDecompress(&bzstream);
        } while (result==BZ_OK && pkt_size<10000000);
        pkt_size = bzstream.total_out_lo32;
        BZ2_bzDecompressEnd(&bzstream);
        if (result != BZ_STREAM_END)
            goto failed;
        break;
    }
#endif
    default:
    }
    *buf = pkt_data;
    *buf_size = pkt_size;
    return 0;
 failed:
    av_free(pkt_data);
}


void alpha_cpu_unassigned_access(CPUState *cs, hwaddr addr,

                                 bool is_write, bool is_exec, int unused,

                                 unsigned size)

{

    AlphaCPU *cpu = ALPHA_CPU(cs);

    CPUAlphaState *env = &cpu->env;

    env->trap_arg0 = addr;

    env->trap_arg1 = is_write ? 1 : 0;

    dynamic_excp(env, 0, EXCP_MCHK, 0);

}


static int virtio_serial_init_pci(PCIDevice *pci_dev)

{

    VirtIOPCIProxy *proxy = DO_UPCAST(VirtIOPCIProxy, pci_dev, pci_dev);

    VirtIODevice *vdev;

    if (proxy->class_code != PCI_CLASS_COMMUNICATION_OTHER &&

        proxy->class_code != PCI_CLASS_DISPLAY_OTHER && /* qemu 0.10 */

        proxy->class_code != PCI_CLASS_OTHERS)          /* qemu-kvm  */

        proxy->class_code = PCI_CLASS_COMMUNICATION_OTHER;

    vdev = virtio_serial_init(&pci_dev->qdev, &proxy->serial);

    if (!vdev) {

        return -1;

    }

    vdev->nvectors = proxy->nvectors == DEV_NVECTORS_UNSPECIFIED

                                        ? proxy->serial.max_virtserial_ports + 1

                                        : proxy->nvectors;

    virtio_init_pci(proxy, vdev,

                    PCI_VENDOR_ID_REDHAT_QUMRANET,

                    PCI_DEVICE_ID_VIRTIO_CONSOLE,

                    proxy->class_code, 0x00);

    proxy->nvectors = vdev->nvectors;

    return 0;

}


static CharDriverState *qmp_chardev_open_serial(const char *id,

                                                ChardevBackend *backend,

                                                ChardevReturn *ret,

                                                Error **errp)

{

    ChardevHostdev *serial = backend->serial;

    int fd;

    fd = qmp_chardev_open_file_source(serial->device, O_RDWR, errp);

    if (fd < 0) {

        return NULL;

    }

    qemu_set_nonblock(fd);

    return qemu_chr_open_tty_fd(fd);

}


void alpha_pci_vga_setup(PCIBus *pci_bus)

{

    switch (vga_interface_type) {

#ifdef CONFIG_SPICE

    case VGA_QXL:

        pci_create_simple(pci_bus, -1, "qxl-vga");

        return;

#endif

    case VGA_CIRRUS:

        pci_cirrus_vga_init(pci_bus);

        return;

    case VGA_VMWARE:

        if (pci_vmsvga_init(pci_bus)) {

            return;

        }

        break;

    }

    /* If VGA is enabled at all, and one of the above didn't work, then

       fallback to Standard VGA.  */

    if (vga_interface_type != VGA_NONE) {

        pci_vga_init(pci_bus);

    }

}


struct omap_uart_s *omap2_uart_init(struct omap_target_agent_s *ta,

                qemu_irq irq, omap_clk fclk, omap_clk iclk,

                qemu_irq txdma, qemu_irq rxdma, CharDriverState *chr)

{

    target_phys_addr_t base = omap_l4_attach(ta, 0, 0);

    struct omap_uart_s *s = omap_uart_init(base, irq,

                    fclk, iclk, txdma, rxdma, chr);

    int iomemtype = cpu_register_io_memory(0, omap_uart_readfn,

                    omap_uart_writefn, s);

    s->ta = ta;

    s->base = base;

    cpu_register_physical_memory(s->base + 0x20, 0x100, iomemtype);

    return s;

}


static void QEMU_NORETURN help(void)

{

    const char *help_msg =

           QEMU_IMG_VERSION

           "usage: qemu-img [standard options] command [command options]\n"

           "QEMU disk image utility\n"

           "\n"

           "    '-h', '--help'       display this help and exit\n"

           "    '-V', '--version'    output version information and exit\n"

           "    '-T', '--trace'      [[enable=]<pattern>][,events=<file>][,file=<file>]\n"

           "                         specify tracing options\n"

           "\n"

           "Command syntax:\n"

#define DEF(option, callback, arg_string)        \

           "  " arg_string "\n"

#include "qemu-img-cmds.h"

#undef DEF

#undef GEN_DOCS

           "\n"

           "Command parameters:\n"

           "  'filename' is a disk image filename\n"

           "  'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"

           "    manual page for a description of the object properties. The most common\n"

           "    object type is a 'secret', which is used to supply passwords and/or\n"

           "    encryption keys.\n"

           "  'fmt' is the disk image format. It is guessed automatically in most cases\n"

           "  'cache' is the cache mode used to write the output disk image, the valid\n"

           "    options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"

           "    'directsync' and 'unsafe' (default for convert)\n"

           "  'src_cache' is the cache mode used to read input disk images, the valid\n"

           "    options are the same as for the 'cache' option\n"

           "  'size' is the disk image size in bytes. Optional suffixes\n"

           "    'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"

           "    'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P)  are\n"

           "    supported. 'b' is ignored.\n"

           "  'output_filename' is the destination disk image filename\n"

           "  'output_fmt' is the destination format\n"

           "  'options' is a comma separated list of format specific options in a\n"

           "    name=value format. Use -o ? for an overview of the options supported by the\n"

           "    used format\n"

           "  'snapshot_param' is param used for internal snapshot, format\n"

           "    is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"

           "    '[ID_OR_NAME]'\n"

           "  'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"

           "    instead\n"

           "  '-c' indicates that target image must be compressed (qcow format only)\n"

           "  '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"

           "       match exactly. The image doesn't need a working backing file before\n"

           "       rebasing in this case (useful for renaming the backing file)\n"

           "  '-h' with or without a command shows this help and lists the supported formats\n"

           "  '-p' show progress of command (only certain commands)\n"

           "  '-q' use Quiet mode - do not print any output (except errors)\n"

           "  '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"

           "       contain only zeros for qemu-img to create a sparse image during\n"

           "       conversion. If the number of bytes is 0, the source will not be scanned for\n"

           "       unallocated or zero sectors, and the destination image will always be\n"

           "       fully allocated\n"

           "  '--output' takes the format in which the output must be done (human or json)\n"

           "  '-n' skips the target volume creation (useful if the volume is created\n"

           "       prior to running qemu-img)\n"

           "\n"

           "Parameters to check subcommand:\n"

           "  '-r' tries to repair any inconsistencies that are found during the check.\n"

           "       '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"

           "       kinds of errors, with a higher risk of choosing the wrong fix or\n"

           "       hiding corruption that has already occurred.\n"

           "\n"

           "Parameters to convert subcommand:\n"

           "  '-m' specifies how many coroutines work in parallel during the convert\n"

           "       process (defaults to 8)\n"

           "  '-W' allow to write to the target out of order rather than sequential\n"

           "\n"

           "Parameters to snapshot subcommand:\n"

           "  'snapshot' is the name of the snapshot to create, apply or delete\n"

           "  '-a' applies a snapshot (revert disk to saved state)\n"

           "  '-c' creates a snapshot\n"

           "  '-d' deletes a snapshot\n"

           "  '-l' lists all snapshots in the given image\n"

           "\n"

           "Parameters to compare subcommand:\n"

           "  '-f' first image format\n"

           "  '-F' second image format\n"

           "  '-s' run in Strict mode - fail on different image size or sector allocation\n"

           "\n"

           "Parameters to dd subcommand:\n"

           "  'bs=BYTES' read and write up to BYTES bytes at a time "

           "(default: 512)\n"

           "  'count=N' copy only N input blocks\n"

           "  'if=FILE' read from FILE\n"

           "  'of=FILE' write to FILE\n"

           "  'skip=N' skip N bs-sized blocks at the start of input\n";

    printf("%s\nSupported formats:", help_msg);

    bdrv_iterate_format(format_print, NULL);

    printf("\n");

    exit(EXIT_SUCCESS);

}


static void coroutine_fn bdrv_create_co_entry(void *opaque)

{

    Error *local_err = NULL;

    int ret;

    CreateCo *cco = opaque;

    assert(cco->drv);

    ret = cco->drv->bdrv_create(cco->filename, cco->opts, &local_err);

    if (local_err) {

        error_propagate(&cco->err, local_err);

    }

    cco->ret = ret;

}


void helper_mtc0_entryhi(CPUMIPSState *env, target_ulong arg1)

{

    target_ulong old, val, mask;

    mask = (TARGET_PAGE_MASK << 1) | env->CP0_EntryHi_ASID_mask;

    if (((env->CP0_Config4 >> CP0C4_IE) & 0x3) >= 2) {

        mask |= 1 << CP0EnHi_EHINV;

    }

    /* 1k pages not implemented */

#if defined(TARGET_MIPS64)

    if (env->insn_flags & ISA_MIPS32R6) {

        int entryhi_r = extract64(arg1, 62, 2);

        int config0_at = extract32(env->CP0_Config0, 13, 2);

        bool no_supervisor = (env->CP0_Status_rw_bitmask & 0x8) == 0;

        if ((entryhi_r == 2) ||

            (entryhi_r == 1 && (no_supervisor || config0_at == 1))) {

            /* skip EntryHi.R field if new value is reserved */

            mask &= ~(0x3ull << 62);

        }

    }

    mask &= env->SEGMask;

#endif

    old = env->CP0_EntryHi;

    val = (arg1 & mask) | (old & ~mask);

    env->CP0_EntryHi = val;

    if (env->CP0_Config3 & (1 << CP0C3_MT)) {

        sync_c0_entryhi(env, env->current_tc);

    }

    /* If the ASID changes, flush qemu's TLB.  */

    if ((old & env->CP0_EntryHi_ASID_mask) !=

        (val & env->CP0_EntryHi_ASID_mask)) {

        cpu_mips_tlb_flush(env);

    }

}


static bool vmxnet3_verify_driver_magic(hwaddr dshmem)

{

    return (VMXNET3_READ_DRV_SHARED32(dshmem, magic) == VMXNET3_REV1_MAGIC);

}


ram_addr_t qemu_ram_addr_from_host_nofail(void *ptr)

{

    ram_addr_t ram_addr;

    if (qemu_ram_addr_from_host(ptr, &ram_addr)) {

        fprintf(stderr, "Bad ram pointer %p\n", ptr);

        abort();

    }

    return ram_addr;

}


static int decode_format80(VqaContext *s, int src_size,

    unsigned char *dest, int dest_size, int check_size) {

    int dest_index = 0;

    int count, opcode, start;

    int src_pos;

    unsigned char color;

    int i;

    start = bytestream2_tell(&s->gb);

    while (bytestream2_tell(&s->gb) - start < src_size) {

        opcode = bytestream2_get_byte(&s->gb);

        av_dlog(s->avctx, "opcode %02X: ", opcode);

        /* 0x80 means that frame is finished */

        if (opcode == 0x80)

            break;

        if (dest_index >= dest_size) {

            av_log(s->avctx, AV_LOG_ERROR, "decode_format80 problem: dest_index (%d) exceeded dest_size (%d)\n",

                dest_index, dest_size);

            return AVERROR_INVALIDDATA;

        }

        if (opcode == 0xFF) {

            count   = bytestream2_get_le16(&s->gb);

            src_pos = bytestream2_get_le16(&s->gb);

            av_dlog(s->avctx, "(1) copy %X bytes from absolute pos %X\n", count, src_pos);

            CHECK_COUNT();

            CHECK_COPY(src_pos);

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

                dest[dest_index + i] = dest[src_pos + i];

            dest_index += count;

        } else if (opcode == 0xFE) {

            count = bytestream2_get_le16(&s->gb);

            color = bytestream2_get_byte(&s->gb);

            av_dlog(s->avctx, "(2) set %X bytes to %02X\n", count, color);

            CHECK_COUNT();

            memset(&dest[dest_index], color, count);

            dest_index += count;

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

            count = (opcode & 0x3F) + 3;

            src_pos = bytestream2_get_le16(&s->gb);

            av_dlog(s->avctx, "(3) copy %X bytes from absolute pos %X\n", count, src_pos);

            CHECK_COUNT();

            CHECK_COPY(src_pos);

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

                dest[dest_index + i] = dest[src_pos + i];

            dest_index += count;

        } else if (opcode > 0x80) {

            count = opcode & 0x3F;

            av_dlog(s->avctx, "(4) copy %X bytes from source to dest\n", count);

            CHECK_COUNT();

            bytestream2_get_buffer(&s->gb, &dest[dest_index], count);

            dest_index += count;

        } else {

            count = ((opcode & 0x70) >> 4) + 3;

            src_pos = bytestream2_get_byte(&s->gb) | ((opcode & 0x0F) << 8);

            av_dlog(s->avctx, "(5) copy %X bytes from relpos %X\n", count, src_pos);

            CHECK_COUNT();

            CHECK_COPY(dest_index - src_pos);

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

                dest[dest_index + i] = dest[dest_index - src_pos + i];

            dest_index += count;

        }

    }

    /* validate that the entire destination buffer was filled; this is

     * important for decoding frame maps since each vector needs to have a

     * codebook entry; it is not important for compressed codebooks because

     * not every entry needs to be filled */

    if (check_size)

        if (dest_index < dest_size)

            av_log(s->avctx, AV_LOG_ERROR, "decode_format80 problem: decode finished with dest_index (%d) < dest_size (%d)\n",

                dest_index, dest_size);

    return 0; // let's display what we decoded anyway

}


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

                                int *got_frame, AVPacket *avpkt)

{

    int line = 0, ret;

    const int width = avctx->width;

    AVFrame *pic = data;

    uint16_t *y, *u, *v;

    const uint8_t *line_end, *src = avpkt->data;

    int stride = avctx->width * 8 / 3;

    if (width == 1) {

        av_log(avctx, AV_LOG_ERROR, "Width 1 not supported.\n");

        return AVERROR_INVALIDDATA;

    }

    if (   avctx->codec_tag == MKTAG('0', '1', '2', 'v')

        && avpkt->size % avctx->height == 0

        && avpkt->size / avctx->height * 3 >= width * 8)

        stride = avpkt->size / avctx->height;

    if (avpkt->size < avctx->height * stride) {

        av_log(avctx, AV_LOG_ERROR, "Packet too small: %d instead of %d\n",

               avpkt->size, avctx->height * stride);

        return AVERROR_INVALIDDATA;

    }

    if ((ret = ff_get_buffer(avctx, pic, 0)) < 0)

        return ret;

    pic->pict_type = AV_PICTURE_TYPE_I;

    pic->key_frame = 1;

    y = (uint16_t *)pic->data[0];

    u = (uint16_t *)pic->data[1];

    v = (uint16_t *)pic->data[2];

    line_end = avpkt->data + stride;

    while (line++ < avctx->height) {

        while (1) {

            uint32_t t = AV_RL32(src);

            src += 4;

            *u++ = t <<  6 & 0xFFC0;

            *y++ = t >>  4 & 0xFFC0;

            *v++ = t >> 14 & 0xFFC0;

            if (src >= line_end - 1) {

                *y = 0x80;

                src++;

                line_end += stride;

                y = (uint16_t *)(pic->data[0] + line * pic->linesize[0]);

                u = (uint16_t *)(pic->data[1] + line * pic->linesize[1]);

                v = (uint16_t *)(pic->data[2] + line * pic->linesize[2]);

                break;

            }

            t = AV_RL32(src);

            src += 4;

            *y++ = t <<  6 & 0xFFC0;

            *u++ = t >>  4 & 0xFFC0;

            *y++ = t >> 14 & 0xFFC0;

            if (src >= line_end - 2) {

                if (!(width & 1)) {

                    *y = 0x80;

                    src += 2;

                }

                line_end += stride;

                y = (uint16_t *)(pic->data[0] + line * pic->linesize[0]);

                u = (uint16_t *)(pic->data[1] + line * pic->linesize[1]);

                v = (uint16_t *)(pic->data[2] + line * pic->linesize[2]);

                break;

            }

            t = AV_RL32(src);

            src += 4;

            *v++ = t <<  6 & 0xFFC0;

            *y++ = t >>  4 & 0xFFC0;

            *u++ = t >> 14 & 0xFFC0;

            if (src >= line_end - 1) {

                *y = 0x80;

                src++;

                line_end += stride;

                y = (uint16_t *)(pic->data[0] + line * pic->linesize[0]);

                u = (uint16_t *)(pic->data[1] + line * pic->linesize[1]);

                v = (uint16_t *)(pic->data[2] + line * pic->linesize[2]);

                break;

            }

            t = AV_RL32(src);

            src += 4;

            *y++ = t <<  6 & 0xFFC0;

            *v++ = t >>  4 & 0xFFC0;

            *y++ = t >> 14 & 0xFFC0;

            if (src >= line_end - 2) {

                if (width & 1) {

                    *y = 0x80;

                    src += 2;

                }

                line_end += stride;

                y = (uint16_t *)(pic->data[0] + line * pic->linesize[0]);

                u = (uint16_t *)(pic->data[1] + line * pic->linesize[1]);

                v = (uint16_t *)(pic->data[2] + line * pic->linesize[2]);

                break;

            }

        }

    }

    *got_frame = 1;

    return avpkt->size;

}


static inline int test_bit(uint32_t *field, int bit)

{

    return (field[bit >> 5] & 1 << (bit & 0x1F)) != 0;

}


static void test_qemu_strtoul_decimal(void)

{

    const char *str = "0123";

    char f = 'X';

    const char *endptr = &f;

    unsigned long res = 999;

    int err;

    err = qemu_strtoul(str, &endptr, 10, &res);

    g_assert_cmpint(err, ==, 0);

    g_assert_cmpint(res, ==, 123);

    g_assert(endptr == str + strlen(str));

    str = "123";

    res = 999;

    endptr = &f;

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

    g_assert_cmpint(err, ==, 0);

    g_assert_cmpint(res, ==, 123);

    g_assert(endptr == str + strlen(str));

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);

    dc->desc        = "ISA bridge";

    dc->vmsd        = &vmstate_piix3;

    dc->no_user     = 1,

    k->no_hotplug   = 1;

    k->init         = piix3_initfn;

    k->config_write = piix3_write_config;

    k->vendor_id    = PCI_VENDOR_ID_INTEL;

    /* 82371SB PIIX3 PCI-to-ISA bridge (Step A1) */

    k->device_id    = PCI_DEVICE_ID_INTEL_82371SB_0;

    k->class_id     = PCI_CLASS_BRIDGE_ISA;

}


qio_channel_websock_source_dispatch(GSource *source,

                                    GSourceFunc callback,

                                    gpointer user_data)

{

    QIOChannelFunc func = (QIOChannelFunc)callback;

    QIOChannelWebsockSource *wsource = (QIOChannelWebsockSource *)source;

    GIOCondition cond = 0;

    if (wsource->wioc->rawinput.offset) {

        cond |= G_IO_IN;

    }

    if (wsource->wioc->rawoutput.offset < QIO_CHANNEL_WEBSOCK_MAX_BUFFER) {

        cond |= G_IO_OUT;

    }

    return (*func)(QIO_CHANNEL(wsource->wioc),

                   (cond & wsource->condition),

                   user_data);

}


static void acpi_dsdt_add_pci(Aml *scope, const MemMapEntry *memmap,

                              uint32_t irq, bool use_highmem)

{

    Aml *method, *crs, *ifctx, *UUID, *ifctx1, *elsectx, *buf;

    int i, bus_no;

    hwaddr base_mmio = memmap[VIRT_PCIE_MMIO].base;

    hwaddr size_mmio = memmap[VIRT_PCIE_MMIO].size;

    hwaddr base_pio = memmap[VIRT_PCIE_PIO].base;

    hwaddr size_pio = memmap[VIRT_PCIE_PIO].size;

    hwaddr base_ecam = memmap[VIRT_PCIE_ECAM].base;

    hwaddr size_ecam = memmap[VIRT_PCIE_ECAM].size;

    int nr_pcie_buses = size_ecam / PCIE_MMCFG_SIZE_MIN;

    Aml *dev = aml_device("%s", "PCI0");

    aml_append(dev, aml_name_decl("_HID", aml_string("PNP0A08")));

    aml_append(dev, aml_name_decl("_CID", aml_string("PNP0A03")));

    aml_append(dev, aml_name_decl("_SEG", aml_int(0)));

    aml_append(dev, aml_name_decl("_BBN", aml_int(0)));

    aml_append(dev, aml_name_decl("_ADR", aml_int(0)));

    aml_append(dev, aml_name_decl("_UID", aml_string("PCI0")));

    aml_append(dev, aml_name_decl("_STR", aml_unicode("PCIe 0 Device")));

    aml_append(dev, aml_name_decl("_CCA", aml_int(1)));

    /* Declare the PCI Routing Table. */

    Aml *rt_pkg = aml_package(nr_pcie_buses * PCI_NUM_PINS);

    for (bus_no = 0; bus_no < nr_pcie_buses; bus_no++) {

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

            int gsi = (i + bus_no) % PCI_NUM_PINS;

            Aml *pkg = aml_package(4);

            aml_append(pkg, aml_int((bus_no << 16) | 0xFFFF));

            aml_append(pkg, aml_int(i));

            aml_append(pkg, aml_name("GSI%d", gsi));

            aml_append(pkg, aml_int(0));

            aml_append(rt_pkg, pkg);

        }

    }

    aml_append(dev, aml_name_decl("_PRT", rt_pkg));

    /* Create GSI link device */

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

        uint32_t irqs =  irq + i;

        Aml *dev_gsi = aml_device("GSI%d", i);

        aml_append(dev_gsi, aml_name_decl("_HID", aml_string("PNP0C0F")));

        aml_append(dev_gsi, aml_name_decl("_UID", aml_int(0)));

        crs = aml_resource_template();

        aml_append(crs,

                   aml_interrupt(AML_CONSUMER, AML_LEVEL, AML_ACTIVE_HIGH,

                                 AML_EXCLUSIVE, &irqs, 1));

        aml_append(dev_gsi, aml_name_decl("_PRS", crs));

        crs = aml_resource_template();

        aml_append(crs,

                   aml_interrupt(AML_CONSUMER, AML_LEVEL, AML_ACTIVE_HIGH,

                                 AML_EXCLUSIVE, &irqs, 1));

        aml_append(dev_gsi, aml_name_decl("_CRS", crs));

        method = aml_method("_SRS", 1, AML_NOTSERIALIZED);

        aml_append(dev_gsi, method);

        aml_append(dev, dev_gsi);

    }

    method = aml_method("_CBA", 0, AML_NOTSERIALIZED);

    aml_append(method, aml_return(aml_int(base_ecam)));

    aml_append(dev, method);

    method = aml_method("_CRS", 0, AML_NOTSERIALIZED);

    Aml *rbuf = aml_resource_template();

    aml_append(rbuf,

        aml_word_bus_number(AML_MIN_FIXED, AML_MAX_FIXED, AML_POS_DECODE,

                            0x0000, 0x0000, nr_pcie_buses - 1, 0x0000,

                            nr_pcie_buses));

    aml_append(rbuf,

        aml_dword_memory(AML_POS_DECODE, AML_MIN_FIXED, AML_MAX_FIXED,

                         AML_NON_CACHEABLE, AML_READ_WRITE, 0x0000, base_mmio,

                         base_mmio + size_mmio - 1, 0x0000, size_mmio));

    aml_append(rbuf,

        aml_dword_io(AML_MIN_FIXED, AML_MAX_FIXED, AML_POS_DECODE,

                     AML_ENTIRE_RANGE, 0x0000, 0x0000, size_pio - 1, base_pio,

                     size_pio));

    if (use_highmem) {

        hwaddr base_mmio_high = memmap[VIRT_PCIE_MMIO_HIGH].base;

        hwaddr size_mmio_high = memmap[VIRT_PCIE_MMIO_HIGH].size;

        aml_append(rbuf,

            aml_qword_memory(AML_POS_DECODE, AML_MIN_FIXED, AML_MAX_FIXED,

                             AML_NON_CACHEABLE, AML_READ_WRITE, 0x0000,

                             base_mmio_high, base_mmio_high, 0x0000,

                             size_mmio_high));

    }

    aml_append(method, aml_name_decl("RBUF", rbuf));

    aml_append(method, aml_return(rbuf));

    aml_append(dev, method);

    /* Declare an _OSC (OS Control Handoff) method */

    aml_append(dev, aml_name_decl("SUPP", aml_int(0)));

    aml_append(dev, aml_name_decl("CTRL", aml_int(0)));

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

    aml_append(method,

        aml_create_dword_field(aml_arg(3), aml_int(0), "CDW1"));

    /* PCI Firmware Specification 3.0

     * 4.5.1. _OSC Interface for PCI Host Bridge Devices

     * The _OSC interface for a PCI/PCI-X/PCI Express hierarchy is

     * identified by the Universal Unique IDentifier (UUID)

     * 33DB4D5B-1FF7-401C-9657-7441C03DD766

     */

    UUID = aml_touuid("33DB4D5B-1FF7-401C-9657-7441C03DD766");

    ifctx = aml_if(aml_equal(aml_arg(0), UUID));

    aml_append(ifctx,

        aml_create_dword_field(aml_arg(3), aml_int(4), "CDW2"));

    aml_append(ifctx,

        aml_create_dword_field(aml_arg(3), aml_int(8), "CDW3"));

    aml_append(ifctx, aml_store(aml_name("CDW2"), aml_name("SUPP")));

    aml_append(ifctx, aml_store(aml_name("CDW3"), aml_name("CTRL")));

    aml_append(ifctx, aml_store(aml_and(aml_name("CTRL"), aml_int(0x1D), NULL),

                                aml_name("CTRL")));

    ifctx1 = aml_if(aml_lnot(aml_equal(aml_arg(1), aml_int(0x1))));

    aml_append(ifctx1, aml_store(aml_or(aml_name("CDW1"), aml_int(0x08), NULL),

                                 aml_name("CDW1")));

    aml_append(ifctx, ifctx1);

    ifctx1 = aml_if(aml_lnot(aml_equal(aml_name("CDW3"), aml_name("CTRL"))));

    aml_append(ifctx1, aml_store(aml_or(aml_name("CDW1"), aml_int(0x10), NULL),

                                 aml_name("CDW1")));

    aml_append(ifctx, ifctx1);

    aml_append(ifctx, aml_store(aml_name("CTRL"), aml_name("CDW3")));

    aml_append(ifctx, aml_return(aml_arg(3)));

    aml_append(method, ifctx);

    elsectx = aml_else();

    aml_append(elsectx, aml_store(aml_or(aml_name("CDW1"), aml_int(4), NULL),

                                  aml_name("CDW1")));

    aml_append(elsectx, aml_return(aml_arg(3)));

    aml_append(method, elsectx);

    aml_append(dev, method);

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

    /* PCI Firmware Specification 3.0

     * 4.6.1. _DSM for PCI Express Slot Information

     * The UUID in _DSM in this context is

     * {E5C937D0-3553-4D7A-9117-EA4D19C3434D}

     */

    UUID = aml_touuid("E5C937D0-3553-4D7A-9117-EA4D19C3434D");

    ifctx = aml_if(aml_equal(aml_arg(0), UUID));

    ifctx1 = aml_if(aml_equal(aml_arg(2), aml_int(0)));

    uint8_t byte_list[1] = {1};

    buf = aml_buffer(1, byte_list);

    aml_append(ifctx1, aml_return(buf));

    aml_append(ifctx, ifctx1);

    aml_append(method, ifctx);

    byte_list[0] = 0;

    buf = aml_buffer(1, byte_list);

    aml_append(method, aml_return(buf));

    aml_append(dev, method);

    Aml *dev_rp0 = aml_device("%s", "RP0");

    aml_append(dev_rp0, aml_name_decl("_ADR", aml_int(0)));

    aml_append(dev, dev_rp0);

    aml_append(scope, dev);

}


static int vmdk_parent_open(BlockDriverState *bs)

{

    char *p_name;

    char desc[DESC_SIZE + 1];

    BDRVVmdkState *s = bs->opaque;

    desc[DESC_SIZE] = '\0';

    if (bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE) != DESC_SIZE) {

        return -1;

    }

    if ((p_name = strstr(desc,"parentFileNameHint")) != NULL) {

        char *end_name;

        p_name += sizeof("parentFileNameHint") + 1;

        if ((end_name = strchr(p_name,'\"')) == NULL)

            return -1;

        if ((end_name - p_name) > sizeof (bs->backing_file) - 1)

            return -1;

        pstrcpy(bs->backing_file, end_name - p_name + 1, p_name);

    }

    return 0;

}


static MemoryRegionSection address_space_do_translate(AddressSpace *as,

                                                      hwaddr addr,

                                                      hwaddr *xlat,

                                                      hwaddr *plen,

                                                      bool is_write,

                                                      bool is_mmio)

{

    IOMMUTLBEntry iotlb;

    MemoryRegionSection *section;

    MemoryRegion *mr;

    for (;;) {

        AddressSpaceDispatch *d = atomic_rcu_read(&as->dispatch);

        section = address_space_translate_internal(d, addr, &addr, plen, is_mmio);

        mr = section->mr;

        if (!mr->iommu_ops) {

            break;

        }

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

        addr = ((iotlb.translated_addr & ~iotlb.addr_mask)

                | (addr & iotlb.addr_mask));

        *plen = MIN(*plen, (addr | iotlb.addr_mask) - addr + 1);

        if (!(iotlb.perm & (1 << is_write))) {

            goto translate_fail;

        }

        as = iotlb.target_as;

    }

    *xlat = addr;

    return *section;

translate_fail:

    return (MemoryRegionSection) { .mr = &io_mem_unassigned };

}


static void read_guest_mem(void)

{

    uint32_t *guest_mem;

    gint64 end_time;

    int i, j;

    size_t size;

    g_mutex_lock(data_mutex);

    end_time = g_get_monotonic_time() + 5 * G_TIME_SPAN_SECOND;

    while (!fds_num) {

        if (!_cond_wait_until(data_cond, data_mutex, end_time)) {

            /* timeout has passed */

            g_assert(fds_num);

            break;

        }

    }

    /* check for sanity */

    g_assert_cmpint(fds_num, >, 0);

    g_assert_cmpint(fds_num, ==, memory.nregions);

    /* iterate all regions */

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

        /* We'll check only the region statring at 0x0*/

        if (memory.regions[i].guest_phys_addr != 0x0) {

            continue;

        }

        g_assert_cmpint(memory.regions[i].memory_size, >, 1024);

        size =  memory.regions[i].memory_size + memory.regions[i].mmap_offset;

        guest_mem = mmap(0, size, PROT_READ | PROT_WRITE,

                         MAP_SHARED, fds[i], 0);

        g_assert(guest_mem != MAP_FAILED);

        guest_mem += (memory.regions[i].mmap_offset / sizeof(*guest_mem));

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

            uint32_t a = readl(memory.regions[i].guest_phys_addr + j*4);

            uint32_t b = guest_mem[j];

            g_assert_cmpint(a, ==, b);

        }

        munmap(guest_mem, memory.regions[i].memory_size);

    }

    g_assert_cmpint(1, ==, 1);

    g_mutex_unlock(data_mutex);

}


static uint64_t qemu_rdma_poll(RDMAContext *rdma, uint64_t *wr_id_out,

                               uint32_t *byte_len)

{

    int ret;

    struct ibv_wc wc;

    uint64_t wr_id;

    ret = ibv_poll_cq(rdma->cq, 1, &wc);

    if (!ret) {

        *wr_id_out = RDMA_WRID_NONE;

        return 0;

    }

    if (ret < 0) {

        fprintf(stderr, "ibv_poll_cq return %d!\n", ret);

        return ret;

    }

    wr_id = wc.wr_id & RDMA_WRID_TYPE_MASK;

    if (wc.status != IBV_WC_SUCCESS) {

        fprintf(stderr, "ibv_poll_cq wc.status=%d %s!\n",

                        wc.status, ibv_wc_status_str(wc.status));

        fprintf(stderr, "ibv_poll_cq wrid=%s!\n", wrid_desc[wr_id]);

        return -1;

    }

    if (rdma->control_ready_expected &&

        (wr_id >= RDMA_WRID_RECV_CONTROL)) {

        DDDPRINTF("completion %s #%" PRId64 " received (%" PRId64 ")"

                  " left %d\n", wrid_desc[RDMA_WRID_RECV_CONTROL],

                  wr_id - RDMA_WRID_RECV_CONTROL, wr_id, rdma->nb_sent);

        rdma->control_ready_expected = 0;

    }

    if (wr_id == RDMA_WRID_RDMA_WRITE) {

        uint64_t chunk =

            (wc.wr_id & RDMA_WRID_CHUNK_MASK) >> RDMA_WRID_CHUNK_SHIFT;

        uint64_t index =

            (wc.wr_id & RDMA_WRID_BLOCK_MASK) >> RDMA_WRID_BLOCK_SHIFT;

        RDMALocalBlock *block = &(rdma->local_ram_blocks.block[index]);

        DDDPRINTF("completions %s (%" PRId64 ") left %d, "

                 "block %" PRIu64 ", chunk: %" PRIu64 " %p %p\n",

                 print_wrid(wr_id), wr_id, rdma->nb_sent, index, chunk,

                 block->local_host_addr, (void *)block->remote_host_addr);

        clear_bit(chunk, block->transit_bitmap);

        if (rdma->nb_sent > 0) {

            rdma->nb_sent--;

        }

        if (!rdma->pin_all) {

            /*

             * FYI: If one wanted to signal a specific chunk to be unregistered

             * using LRU or workload-specific information, this is the function

             * you would call to do so. That chunk would then get asynchronously

             * unregistered later.

             */

#ifdef RDMA_UNREGISTRATION_EXAMPLE

            qemu_rdma_signal_unregister(rdma, index, chunk, wc.wr_id);

#endif

        }

    } else {

        DDDPRINTF("other completion %s (%" PRId64 ") received left %d\n",

            print_wrid(wr_id), wr_id, rdma->nb_sent);

    }

    *wr_id_out = wc.wr_id;

    if (byte_len) {

        *byte_len = wc.byte_len;

    }

    return  0;

}


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

{

    uint32_t minor_ver;

    int comp_brand_size;

    char minor_ver_str[11]; /* 32 bit integer -> 10 digits + null */

    char* comp_brands_str;

    uint8_t type[5] = {0};

    avio_read(pb, type, 4);

    if (strcmp(type, "qt  "))

        c->isom = 1;

    av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type);

    av_dict_set(&c->fc->metadata, "major_brand", type, 0);

    minor_ver = avio_rb32(pb); /* minor version */

    snprintf(minor_ver_str, sizeof(minor_ver_str), "%"PRIu32"", minor_ver);

    av_dict_set(&c->fc->metadata, "minor_version", minor_ver_str, 0);

    comp_brand_size = atom.size - 8;

    if (comp_brand_size < 0)

        return AVERROR_INVALIDDATA;

    comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */

    if (!comp_brands_str)

        return AVERROR(ENOMEM);

    avio_read(pb, comp_brands_str, comp_brand_size);

    comp_brands_str[comp_brand_size] = 0;

    av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0);

    av_freep(&comp_brands_str);

    return 0;

}


static void qpci_pc_config_writew(QPCIBus *bus, int devfn, uint8_t offset, uint16_t value)

{

    outl(0xcf8, (1 << 31) | (devfn << 8) | offset);

    outw(0xcfc, value);

}


static int decode_stream_header(NUTContext *nut){

    AVFormatContext *s= nut->avf;

    ByteIOContext *bc = &s->pb;

    StreamContext *stc;

    int class, stream_id;

    uint64_t tmp, end;

    AVStream *st;

    end= get_packetheader(nut, bc, 1);

    end += url_ftell(bc);

    GET_V(stream_id, tmp < s->nb_streams && !nut->stream[tmp].time_base);

    stc= &nut->stream[stream_id];

    st = s->streams[stream_id];

    if (!st)

        return AVERROR(ENOMEM);

    class = get_v(bc);

    tmp = get_fourcc(bc);

    st->codec->codec_tag= tmp;

    switch(class)

    {

        case 0:

            st->codec->codec_type = CODEC_TYPE_VIDEO;

            st->codec->codec_id = codec_get_id(codec_bmp_tags, tmp);

            if (st->codec->codec_id == CODEC_ID_NONE)

                av_log(s, AV_LOG_ERROR, "Unknown codec?!\n");

            break;

        case 1:

            st->codec->codec_type = CODEC_TYPE_AUDIO;

            st->codec->codec_id = codec_get_id(codec_wav_tags, tmp);

            if (st->codec->codec_id == CODEC_ID_NONE)

                av_log(s, AV_LOG_ERROR, "Unknown codec?!\n");

            break;

        case 2:

//            st->codec->codec_type = CODEC_TYPE_TEXT;

//            break;

        case 3:

            st->codec->codec_type = CODEC_TYPE_DATA;

            break;

        default:

            av_log(s, AV_LOG_ERROR, "Unknown stream class (%d)\n", class);

            return -1;

    }

    GET_V(stc->time_base_id    , tmp < nut->time_base_count);

    GET_V(stc->msb_pts_shift   , tmp < 16);

    stc->max_pts_distance= get_v(bc);

    GET_V(stc->decode_delay    , tmp < 1000); //sanity limit, raise this if moors law is true

    st->codec->has_b_frames= stc->decode_delay;

    get_v(bc); //stream flags

    GET_V(st->codec->extradata_size, tmp < (1<<30));

    if(st->codec->extradata_size){

        st->codec->extradata= av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);

        get_buffer(bc, st->codec->extradata, st->codec->extradata_size);

    }

    if (st->codec->codec_type == CODEC_TYPE_VIDEO){

        GET_V(st->codec->width , tmp > 0)

        GET_V(st->codec->height, tmp > 0)

        st->codec->sample_aspect_ratio.num= get_v(bc);

        st->codec->sample_aspect_ratio.den= get_v(bc);

        if((!st->codec->sample_aspect_ratio.num) != (!st->codec->sample_aspect_ratio.den)){

            av_log(s, AV_LOG_ERROR, "invalid aspect ratio\n");

            return -1;

        }

        get_v(bc); /* csp type */

    }else if (st->codec->codec_type == CODEC_TYPE_AUDIO){

        GET_V(st->codec->sample_rate , tmp > 0)

        tmp= get_v(bc); // samplerate_den

        if(tmp > st->codec->sample_rate){

            av_log(s, AV_LOG_ERROR, "bleh, libnut muxed this ;)\n");

            st->codec->sample_rate= tmp;

        }

        GET_V(st->codec->channels, tmp > 0)

    }

    if(skip_reserved(bc, end) || get_checksum(bc)){

        av_log(s, AV_LOG_ERROR, "Stream header %d checksum mismatch\n", stream_id);

        return -1;

    }

    stc->time_base= &nut->time_base[stc->time_base_id];

    av_set_pts_info(s->streams[stream_id], 63, stc->time_base->num, stc->time_base->den);

    return 0;

}


static void lz_unpack(const unsigned char *src, unsigned char *dest, int dest_len)

{

    const unsigned char *s;

    unsigned char *d;

    unsigned char *d_end;

    unsigned char queue[QUEUE_SIZE];

    unsigned int qpos;

    unsigned int dataleft;

    unsigned int chainofs;

    unsigned int chainlen;

    unsigned int speclen;

    unsigned char tag;

    unsigned int i, j;

    s = src;

    d = dest;

    d_end = d + dest_len;

    dataleft = AV_RL32(s);

    s += 4;

    memset(queue, 0x20, QUEUE_SIZE);

    if (AV_RL32(s) == 0x56781234) {

        s += 4;

        qpos = 0x111;

        speclen = 0xF + 3;

    } else {

        qpos = 0xFEE;

        speclen = 100;  /* no speclen */

    }

    while (dataleft > 0) {

        tag = *s++;

        if ((tag == 0xFF) && (dataleft > 8)) {

            if (d + 8 > d_end)

                return;

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

                queue[qpos++] = *d++ = *s++;

                qpos &= QUEUE_MASK;

            }

            dataleft -= 8;

        } else {

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

                if (dataleft == 0)

                    break;

                if (tag & 0x01) {

                    if (d + 1 > d_end)

                        return;

                    queue[qpos++] = *d++ = *s++;

                    qpos &= QUEUE_MASK;

                    dataleft--;

                } else {

                    chainofs = *s++;

                    chainofs |= ((*s & 0xF0) << 4);

                    chainlen = (*s++ & 0x0F) + 3;

                    if (chainlen == speclen)

                        chainlen = *s++ + 0xF + 3;

                    if (d + chainlen > d_end)

                        return;

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

                        *d = queue[chainofs++ & QUEUE_MASK];

                        queue[qpos++] = *d++;

                        qpos &= QUEUE_MASK;

                    }

                    dataleft -= chainlen;

                }

                tag >>= 1;

            }

        }

    }

}


void scsi_req_cancel(SCSIRequest *req)

{

    trace_scsi_req_cancel(req->dev->id, req->lun, req->tag);

    if (!req->enqueued) {

        return;

    }

    scsi_req_ref(req);

    scsi_req_dequeue(req);

    req->io_canceled = true;

    if (req->aiocb) {

        blk_aio_cancel(req->aiocb);

    } else {

        scsi_req_cancel_complete(req);

    }

}


static void gen_exception_return(DisasContext *s, TCGv_i32 pc)

{

    TCGv_i32 tmp;

    store_reg(s, 15, pc);

    tmp = load_cpu_field(spsr);

    gen_set_cpsr(tmp, CPSR_ERET_MASK);

    tcg_temp_free_i32(tmp);

    s->is_jmp = DISAS_UPDATE;

}


static void qio_channel_websock_write_close(QIOChannelWebsock *ioc,

                                            uint16_t code, const char *reason)

{

    struct iovec iov;

    buffer_reserve(&ioc->rawoutput, 2 + (reason ? strlen(reason) : 0));

    *(uint16_t *)(ioc->rawoutput.buffer + ioc->rawoutput.offset) =

        cpu_to_be16(code);

    ioc->rawoutput.offset += 2;

    if (reason) {

        buffer_append(&ioc->rawoutput, reason, strlen(reason));

    }

    iov.iov_base = ioc->rawoutput.buffer;

    iov.iov_len = ioc->rawoutput.offset;

    qio_channel_websock_encode(ioc, QIO_CHANNEL_WEBSOCK_OPCODE_CLOSE,

                               &iov, 1, iov.iov_len);

    buffer_reset(&ioc->rawoutput);

    qio_channel_websock_write_wire(ioc, NULL);

    qio_channel_shutdown(ioc->master, QIO_CHANNEL_SHUTDOWN_BOTH, NULL);

}


static void fadt_setup(AcpiFadtDescriptorRev1 *fadt, AcpiPmInfo *pm)

{

    fadt->model = 1;

    fadt->reserved1 = 0;

    fadt->sci_int = cpu_to_le16(pm->sci_int);

    fadt->smi_cmd = cpu_to_le32(ACPI_PORT_SMI_CMD);

    fadt->acpi_enable = pm->acpi_enable_cmd;

    fadt->acpi_disable = pm->acpi_disable_cmd;

    /* EVT, CNT, TMR offset matches hw/acpi/core.c */

    fadt->pm1a_evt_blk = cpu_to_le32(pm->io_base);

    fadt->pm1a_cnt_blk = cpu_to_le32(pm->io_base + 0x04);

    fadt->pm_tmr_blk = cpu_to_le32(pm->io_base + 0x08);

    fadt->gpe0_blk = cpu_to_le32(pm->gpe0_blk);

    /* EVT, CNT, TMR length matches hw/acpi/core.c */

    fadt->pm1_evt_len = 4;

    fadt->pm1_cnt_len = 2;

    fadt->pm_tmr_len = 4;

    fadt->gpe0_blk_len = pm->gpe0_blk_len;

    fadt->plvl2_lat = cpu_to_le16(0xfff); /* C2 state not supported */

    fadt->plvl3_lat = cpu_to_le16(0xfff); /* C3 state not supported */

    fadt->flags = cpu_to_le32((1 << ACPI_FADT_F_WBINVD) |

                              (1 << ACPI_FADT_F_PROC_C1) |

                              (1 << ACPI_FADT_F_SLP_BUTTON) |

                              (1 << ACPI_FADT_F_RTC_S4));

    fadt->flags |= cpu_to_le32(1 << ACPI_FADT_F_USE_PLATFORM_CLOCK);

    /* APIC destination mode ("Flat Logical") has an upper limit of 8 CPUs

     * For more than 8 CPUs, "Clustered Logical" mode has to be used

     */

    if (max_cpus > 8) {

        fadt->flags |= cpu_to_le32(1 << ACPI_FADT_F_FORCE_APIC_CLUSTER_MODEL);

    }

    fadt->century = RTC_CENTURY;

}


void acpi_pm1_cnt_write(ACPIREGS *ar, uint16_t val)

{

    ar->pm1.cnt.cnt = val & ~(ACPI_BITMASK_SLEEP_ENABLE);

    if (val & ACPI_BITMASK_SLEEP_ENABLE) {

        /* change suspend type */

        uint16_t sus_typ = (val >> 10) & 7;

        switch(sus_typ) {

        case 0: /* soft power off */

            qemu_system_shutdown_request();

            break;

        case 1:

            /* ACPI_BITMASK_WAKE_STATUS should be set on resume.

               Pretend that resume was caused by power button */

            ar->pm1.evt.sts |=

                (ACPI_BITMASK_WAKE_STATUS | ACPI_BITMASK_POWER_BUTTON_STATUS);

            qemu_system_reset_request();

            qemu_irq_raise(ar->pm1.cnt.cmos_s3);

        default:

            break;

        }

    }

}


static void win32_rearm_timer(struct qemu_alarm_timer *t)

{

    struct qemu_alarm_win32 *data = t->priv;

    uint64_t nearest_delta_us;

    if (!active_timers[QEMU_TIMER_REALTIME] &&

                !active_timers[QEMU_TIMER_VIRTUAL])

        return;

    nearest_delta_us = qemu_next_deadline_dyntick();

    nearest_delta_us /= 1000;

    timeKillEvent(data->timerId);

    data->timerId = timeSetEvent(1,

                        data->period,

                        host_alarm_handler,

                        (DWORD)t,

                        TIME_ONESHOT | TIME_PERIODIC);

    if (!data->timerId) {

        fprintf(stderr, "Failed to re-arm win32 alarm timer %ld\n",

                GetLastError());

        timeEndPeriod(data->period);

        exit(1);

    }

}


static void qapi_dealloc_end_struct(Visitor *v, Error **errp)

{

    QapiDeallocVisitor *qov = to_qov(v);

    void **obj = qapi_dealloc_pop(qov);

    if (obj) {

        g_free(*obj);

    }

}


static void file_completion(const char *input)

{

    DIR *ffs;

    struct dirent *d;

    char path[1024];

    char file[1024], file_prefix[1024];

    int input_path_len;

    const char *p;

    p = strrchr(input, '/');

    if (!p) {

        input_path_len = 0;

        pstrcpy(file_prefix, sizeof(file_prefix), input);

        pstrcpy(path, sizeof(path), ".");

    } else {

        input_path_len = p - input + 1;

        memcpy(path, input, input_path_len);

        if (input_path_len > sizeof(path) - 1)

            input_path_len = sizeof(path) - 1;

        path[input_path_len] = '\0';

        pstrcpy(file_prefix, sizeof(file_prefix), p + 1);

    }

#ifdef DEBUG_COMPLETION

    monitor_printf(cur_mon, "input='%s' path='%s' prefix='%s'\n",

                   input, path, file_prefix);

#endif

    ffs = opendir(path);

    if (!ffs)

        return;

    for(;;) {

        struct stat sb;

        d = readdir(ffs);

        if (!d)

            break;

        if (strcmp(d->d_name, ".") == 0 || strcmp(d->d_name, "..") == 0) {

            continue;

        }

        if (strstart(d->d_name, file_prefix, NULL)) {

            memcpy(file, input, input_path_len);

            if (input_path_len < sizeof(file))

                pstrcpy(file + input_path_len, sizeof(file) - input_path_len,

                        d->d_name);

            /* stat the file to find out if it's a directory.

             * In that case add a slash to speed up typing long paths

             */

            stat(file, &sb);

            if(S_ISDIR(sb.st_mode))

                pstrcat(file, sizeof(file), "/");

            readline_add_completion(cur_mon->rs, file);

        }

    }

    closedir(ffs);

}


static void set_int8(Object *obj, Visitor *v, void *opaque,

                     const char *name, Error **errp)

{

    DeviceState *dev = DEVICE(obj);

    Property *prop = opaque;

    int8_t *ptr = qdev_get_prop_ptr(dev, prop);

    Error *local_err = NULL;

    int64_t value;

    if (dev->state != DEV_STATE_CREATED) {

        error_set(errp, QERR_PERMISSION_DENIED);

        return;

    }

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

    if (local_err) {

        error_propagate(errp, local_err);

        return;

    }

    if (value > prop->info->min && value <= prop->info->max) {

        *ptr = value;

    } else {

        error_set(errp, QERR_PROPERTY_VALUE_OUT_OF_RANGE,

                  dev->id?:"", name, value, prop->info->min,

                  prop->info->max);

    }

}


static void enter_migration_coroutine(void *opaque)

{

    Coroutine *co = opaque;

    qemu_coroutine_enter(co, NULL);

}


static int decode_channel_residues(WmallDecodeCtx *s, int ch, int tile_size)

{

    int i = 0;

    unsigned int ave_mean;

    s->transient[ch] = get_bits1(&s->gb);

    if (s->transient[ch]) {

        s->transient_pos[ch] = get_bits(&s->gb, av_log2(tile_size));

        if (s->transient_pos[ch])

            s->transient[ch] = 0;

        s->channel[ch].transient_counter =

            FFMAX(s->channel[ch].transient_counter, s->samples_per_frame / 2);

    } else if (s->channel[ch].transient_counter)

        s->transient[ch] = 1;

    if (s->seekable_tile) {

        ave_mean = get_bits(&s->gb, s->bits_per_sample);

        s->ave_sum[ch] = ave_mean << (s->movave_scaling + 1);

    }

    if (s->seekable_tile) {

        if (s->do_inter_ch_decorr)

            s->channel_residues[ch][0] = get_sbits(&s->gb, s->bits_per_sample + 1);

        else

            s->channel_residues[ch][0] = get_sbits(&s->gb, s->bits_per_sample);

        i++;

    }

    for (; i < tile_size; i++) {

        int quo = 0, rem, rem_bits, residue;

        while(get_bits1(&s->gb)) {

            quo++;

            if (get_bits_left(&s->gb) <= 0)

                return -1;

        }

        if (quo >= 32)

            quo += get_bits_long(&s->gb, get_bits(&s->gb, 5) + 1);

        ave_mean = (s->ave_sum[ch] + (1 << s->movave_scaling)) >> (s->movave_scaling + 1);

        if (ave_mean <= 1)

            residue = quo;

        else {

            rem_bits = av_ceil_log2(ave_mean);

            rem      = rem_bits ? get_bits(&s->gb, rem_bits) : 0;

            residue  = (quo << rem_bits) + rem;

        }

        s->ave_sum[ch] = residue + s->ave_sum[ch] -

                         (s->ave_sum[ch] >> s->movave_scaling);

        if (residue & 1)

            residue = -(residue >> 1) - 1;

        else

            residue = residue >> 1;

        s->channel_residues[ch][i] = residue;

    }

    return 0;

}


static int cinaudio_decode_frame(AVCodecContext *avctx,

                                 void *data, int *data_size,

                                 AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    CinAudioContext *cin = avctx->priv_data;

    const uint8_t *src = buf;

    int16_t *samples = data;

    int delta;

    buf_size = FFMIN(buf_size, *data_size/2);

    delta = cin->delta;

    if (cin->initial_decode_frame) {

        cin->initial_decode_frame = 0;

        delta = (int16_t)AV_RL16(src); src += 2;

        *samples++ = delta;

        buf_size -= 2;

    }

    while (buf_size > 0) {

        delta += cinaudio_delta16_table[*src++];

        delta = av_clip_int16(delta);

        *samples++ = delta;

        --buf_size;

    }

    cin->delta = delta;

    *data_size = (uint8_t *)samples - (uint8_t *)data;

    return src - buf;

}


static void rv34_pred_mv_rv3(RV34DecContext *r, int block_type, int dir)

{

    MpegEncContext *s = &r->s;

    int mv_pos = s->mb_x * 2 + s->mb_y * 2 * s->b8_stride;

    int A[2] = {0}, B[2], C[2];

    int i, j, k;

    int mx, my;

    int avail_index = avail_indexes[0];

    if(r->avail_cache[avail_index - 1]){

        A[0] = s->current_picture_ptr->f.motion_val[0][mv_pos - 1][0];

        A[1] = s->current_picture_ptr->f.motion_val[0][mv_pos - 1][1];

    }

    if(r->avail_cache[avail_index - 4]){

        B[0] = s->current_picture_ptr->f.motion_val[0][mv_pos - s->b8_stride][0];

        B[1] = s->current_picture_ptr->f.motion_val[0][mv_pos - s->b8_stride][1];

    }else{

        B[0] = A[0];

        B[1] = A[1];

    }

    if(!r->avail_cache[avail_index - 4 + 2]){

        if(r->avail_cache[avail_index - 4] && (r->avail_cache[avail_index - 1])){

            C[0] = s->current_picture_ptr->f.motion_val[0][mv_pos - s->b8_stride - 1][0];

            C[1] = s->current_picture_ptr->f.motion_val[0][mv_pos - s->b8_stride - 1][1];

        }else{

            C[0] = A[0];

            C[1] = A[1];

        }

    }else{

        C[0] = s->current_picture_ptr->f.motion_val[0][mv_pos - s->b8_stride + 2][0];

        C[1] = s->current_picture_ptr->f.motion_val[0][mv_pos - s->b8_stride + 2][1];

    }

    mx = mid_pred(A[0], B[0], C[0]);

    my = mid_pred(A[1], B[1], C[1]);

    mx += r->dmv[0][0];

    my += r->dmv[0][1];

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

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

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

                s->current_picture_ptr->f.motion_val[k][mv_pos + i + j*s->b8_stride][0] = mx;

                s->current_picture_ptr->f.motion_val[k][mv_pos + i + j*s->b8_stride][1] = my;

            }

        }

    }

}


int qemu_paio_init(struct qemu_paioinit *aioinit)

{

    int ret;

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

    return 0;

}


dprint(int level, const char *fmt, ...)

{

    va_list args;

    if (level <= debug) {

        va_start(args, fmt);

        vfprintf(stderr, fmt, args);

        va_end(args);

    }

}


static void s390_pcihost_hot_plug(HotplugHandler *hotplug_dev,

                                  DeviceState *dev, Error **errp)

{

    PCIDevice *pci_dev = PCI_DEVICE(dev);

    S390PCIBusDevice *pbdev;

    S390pciState *s = S390_PCI_HOST_BRIDGE(pci_device_root_bus(pci_dev)

                                           ->qbus.parent);

    pbdev = &s->pbdev[PCI_SLOT(pci_dev->devfn)];

    pbdev->fid = s390_pci_get_pfid(pci_dev);

    pbdev->pdev = pci_dev;

    pbdev->configured = true;

    pbdev->fh = s390_pci_get_pfh(pci_dev);

    s390_pcihost_setup_msix(pbdev);

    if (dev->hotplugged) {

        s390_pci_generate_plug_event(HP_EVENT_RESERVED_TO_STANDBY,

                                     pbdev->fh, pbdev->fid);

        s390_pci_generate_plug_event(HP_EVENT_TO_CONFIGURED,

                                     pbdev->fh, pbdev->fid);

    }

}


static uint64_t pxa2xx_mm_read(void *opaque, hwaddr addr,

                               unsigned size)

{

    PXA2xxState *s = (PXA2xxState *) opaque;

    switch (addr) {

    case MDCNFG ... SA1110:

        if ((addr & 3) == 0)

            return s->mm_regs[addr >> 2];

    default:

        printf("%s: Bad register " REG_FMT "\n", __FUNCTION__, addr);

        break;

    }

    return 0;

}


static int vhost_verify_ring_mappings(struct vhost_dev *dev,

                                      uint64_t start_addr,

                                      uint64_t size)

{

    int i, j;

    int r = 0;

    const char *part_name[] = {

        "descriptor table",

        "available ring",

        "used ring"

    };

    for (i = 0; i < dev->nvqs; ++i) {

        struct vhost_virtqueue *vq = dev->vqs + i;

        j = 0;

        r = vhost_verify_ring_part_mapping(vq->desc, vq->desc_phys,

                                           vq->desc_size, start_addr, size);

        if (!r) {

            break;

        }

        j++;

        r = vhost_verify_ring_part_mapping(vq->avail, vq->avail_phys,

                                           vq->avail_size, start_addr, size);

        if (!r) {

            break;

        }

        j++;

        r = vhost_verify_ring_part_mapping(vq->used, vq->used_phys,

                                           vq->used_size, start_addr, size);

        if (!r) {

            break;

        }

    }

    if (r == -ENOMEM) {

        error_report("Unable to map %s for ring %d", part_name[j], i);

    } else if (r == -EBUSY) {

        error_report("%s relocated for ring %d", part_name[j], i);

    }

    return r;

}


void qemu_ram_remap(ram_addr_t addr, ram_addr_t length)

{

    RAMBlock *block;

    ram_addr_t offset;

    int flags;

    void *area, *vaddr;

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

        offset = addr - block->offset;

        if (offset < block->length) {

            vaddr = block->host + offset;

            if (block->flags & RAM_PREALLOC_MASK) {

                ;

            } else if (xen_enabled()) {

                abort();

            } else {

                flags = MAP_FIXED;

                munmap(vaddr, length);

                if (mem_path) {

#if defined(__linux__) && !defined(TARGET_S390X)

                    if (block->fd) {

#ifdef MAP_POPULATE

                        flags |= mem_prealloc ? MAP_POPULATE | MAP_SHARED :

                            MAP_PRIVATE;

#else

                        flags |= MAP_PRIVATE;

#endif

                        area = mmap(vaddr, length, PROT_READ | PROT_WRITE,

                                    flags, block->fd, offset);

                    } else {

                        flags |= MAP_PRIVATE | MAP_ANONYMOUS;

                        area = mmap(vaddr, length, PROT_READ | PROT_WRITE,

                                    flags, -1, 0);

                    }

#else

                    abort();

#endif

                } else {

#if defined(TARGET_S390X) && defined(CONFIG_KVM)

                    flags |= MAP_SHARED | MAP_ANONYMOUS;

                    area = mmap(vaddr, length, PROT_EXEC|PROT_READ|PROT_WRITE,

                                flags, -1, 0);

#else

                    flags |= MAP_PRIVATE | MAP_ANONYMOUS;

                    area = mmap(vaddr, length, PROT_READ | PROT_WRITE,

                                flags, -1, 0);

#endif

                }

                if (area != vaddr) {

                    fprintf(stderr, "Could not remap addr: "

                            RAM_ADDR_FMT "@" RAM_ADDR_FMT "\n",

                            length, addr);

                    exit(1);

                }

                memory_try_enable_merging(vaddr, length);

                qemu_ram_setup_dump(vaddr, length);

            }

            return;

        }

    }

}


const char *object_get_typename(Object *obj)

{

    return obj->class->type->name;

}


static int vaapi_build_decoder_config(VAAPIDecoderContext *ctx,

                                      AVCodecContext *avctx,

                                      int fallback_allowed)

{

    AVVAAPIDeviceContext *hwctx = ctx->device->hwctx;

    AVVAAPIHWConfig *hwconfig = NULL;

    AVHWFramesConstraints *constraints = NULL;

    VAStatus vas;

    int err, i, j;

    int loglevel = fallback_allowed ? AV_LOG_VERBOSE : AV_LOG_ERROR;

    const AVCodecDescriptor *codec_desc;

    const AVPixFmtDescriptor *pix_desc;

    enum AVPixelFormat pix_fmt;

    VAProfile profile, *profile_list = NULL;

    int profile_count, exact_match, alt_profile;

    codec_desc = avcodec_descriptor_get(avctx->codec_id);

    if (!codec_desc) {

        err = AVERROR(EINVAL);

        goto fail;

    }

    profile_count = vaMaxNumProfiles(hwctx->display);

    profile_list = av_malloc(profile_count * sizeof(VAProfile));

    if (!profile_list) {

        err = AVERROR(ENOMEM);

        goto fail;

    }

    vas = vaQueryConfigProfiles(hwctx->display,

                                profile_list, &profile_count);

    if (vas != VA_STATUS_SUCCESS) {

        av_log(ctx, loglevel, "Failed to query profiles: %d (%s).\n",

               vas, vaErrorStr(vas));

        err = AVERROR(EIO);

        goto fail;

    }

    profile = VAProfileNone;

    exact_match = 0;

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

        int profile_match = 0;

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

            continue;

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

            profile_match = 1;

        profile = vaapi_profile_map[i].va_profile;

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

            if (profile == profile_list[j]) {

                exact_match = profile_match;

                break;

            }

        }

        if (j < profile_count) {

            if (exact_match)

                break;

            alt_profile = vaapi_profile_map[i].codec_profile;

        }

    }

    av_freep(&profile_list);

    if (profile == VAProfileNone) {

        av_log(ctx, loglevel, "No VAAPI support for codec %s.\n",

               codec_desc->name);

        err = AVERROR(ENOSYS);

        goto fail;

    }

    if (!exact_match) {

        if (fallback_allowed || !hwaccel_lax_profile_check) {

            av_log(ctx, loglevel, "No VAAPI support for codec %s "

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

            if (!fallback_allowed) {

                av_log(ctx, AV_LOG_WARNING, "If you want attempt decoding "

                       "anyway with a possibly-incompatible profile, add "

                       "the option -hwaccel_lax_profile_check.\n");

            }

            err = AVERROR(EINVAL);

            goto fail;

        } else {

            av_log(ctx, AV_LOG_WARNING, "No VAAPI support for codec %s "

                   "profile %d: trying instead with profile %d.\n",

                   codec_desc->name, avctx->profile, alt_profile);

            av_log(ctx, AV_LOG_WARNING, "This may fail or give "

                   "incorrect results, depending on your hardware.\n");

        }

    }

    ctx->va_profile = profile;

    ctx->va_entrypoint = VAEntrypointVLD;

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

                         ctx->va_entrypoint, 0, 0, &ctx->va_config);

    if (vas != VA_STATUS_SUCCESS) {

        av_log(ctx, AV_LOG_ERROR, "Failed to create decode pipeline "

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

        err = AVERROR(EIO);

        goto fail;

    }

    hwconfig = av_hwdevice_hwconfig_alloc(ctx->device_ref);

    if (!hwconfig) {

        err = AVERROR(ENOMEM);

        goto fail;

    }

    hwconfig->config_id = ctx->va_config;

    constraints = av_hwdevice_get_hwframe_constraints(ctx->device_ref,

                                                      hwconfig);

    if (!constraints)

        goto fail;

    // Decide on the decoder target format.

    // If the user specified something with -hwaccel_output_format then

    // try to use that to minimise conversions later.

    ctx->decode_format = AV_PIX_FMT_NONE;

    if (ctx->output_format != AV_PIX_FMT_NONE &&

        ctx->output_format != AV_PIX_FMT_VAAPI) {

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

            if (constraints->valid_sw_formats[i] == ctx->decode_format) {

                ctx->decode_format = ctx->output_format;

                av_log(ctx, AV_LOG_DEBUG, "Using decode format %s (output "

                       "format).\n", av_get_pix_fmt_name(ctx->decode_format));

                break;

            }

        }

    }

    // Otherwise, we would like to try to choose something which matches the

    // decoder output, but there isn't enough information available here to

    // do so.  Assume for now that we are always dealing with YUV 4:2:0, so

    // pick a format which does that.

    if (ctx->decode_format == AV_PIX_FMT_NONE) {

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

            pix_fmt  = constraints->valid_sw_formats[i];

            pix_desc = av_pix_fmt_desc_get(pix_fmt);

            if (pix_desc->nb_components == 3 &&

                pix_desc->log2_chroma_w == 1 &&

                pix_desc->log2_chroma_h == 1) {

                ctx->decode_format = pix_fmt;

                av_log(ctx, AV_LOG_DEBUG, "Using decode format %s (format "

                       "matched).\n", av_get_pix_fmt_name(ctx->decode_format));

                break;

            }

        }

    }

    // Otherwise pick the first in the list and hope for the best.

    if (ctx->decode_format == AV_PIX_FMT_NONE) {

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

        av_log(ctx, AV_LOG_DEBUG, "Using decode format %s (first in list).\n",

               av_get_pix_fmt_name(ctx->decode_format));

        if (i > 1) {

            // There was a choice, and we picked randomly.  Warn the user

            // that they might want to choose intelligently instead.

            av_log(ctx, AV_LOG_WARNING, "Using randomly chosen decode "

                   "format %s.\n", av_get_pix_fmt_name(ctx->decode_format));

        }

    }

    // Ensure the picture size is supported by the hardware.

    ctx->decode_width  = avctx->coded_width;

    ctx->decode_height = avctx->coded_height;

    if (ctx->decode_width  < constraints->min_width  ||

        ctx->decode_height < constraints->min_height ||

        ctx->decode_width  > constraints->max_width  ||

        ctx->decode_height >constraints->max_height) {

        av_log(ctx, AV_LOG_ERROR, "VAAPI hardware does not support image "

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

               ctx->decode_width, ctx->decode_height,

               constraints->min_width,  constraints->max_width,

               constraints->min_height, constraints->max_height);

        err = AVERROR(EINVAL);

        goto fail;

    }

    av_hwframe_constraints_free(&constraints);

    av_freep(&hwconfig);

    // Decide how many reference frames we need.  This might be doable more

    // nicely based on the codec and input stream?

    ctx->decode_surfaces = DEFAULT_SURFACES;

    // For frame-threaded decoding, one additional surfaces is needed for

    // each thread.

    if (avctx->active_thread_type & FF_THREAD_FRAME)

        ctx->decode_surfaces += avctx->thread_count;

    return 0;

fail:

    av_hwframe_constraints_free(&constraints);

    av_freep(&hwconfig);

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

    av_freep(&profile_list);

    return err;

}


static int parse(AVCodecParserContext *ctx,

                 AVCodecContext *avctx,

                 const uint8_t **out_data, int *out_size,

                 const uint8_t *data, int size)

{

    VP9ParseContext *s = ctx->priv_data;

    int marker;

    if (size <= 0) {

        *out_size = 0;

        *out_data = data;

        return 0;

    }

    if (s->n_frames > 0) {

        *out_data = data;

        *out_size = s->size[--s->n_frames];

        parse_frame(ctx, *out_data, *out_size);

        return s->n_frames > 0 ? *out_size : size /* i.e. include idx tail */;

    }

    marker = data[size - 1];

    if ((marker & 0xe0) == 0xc0) {

        int nbytes = 1 + ((marker >> 3) & 0x3);

        int n_frames = 1 + (marker & 0x7), idx_sz = 2 + n_frames * nbytes;

        if (size >= idx_sz && data[size - idx_sz] == marker) {

            const uint8_t *idx = data + size + 1 - idx_sz;

            int first = 1;

            switch (nbytes) {

#define case_n(a, rd) \

            case a: \

                while (n_frames--) { \

                    int sz = rd; \

                    idx += a; \

                    if (sz > size) { \

                        s->n_frames = 0; \

                        av_log(avctx, AV_LOG_ERROR, \

                               "Superframe packet size too big: %d > %d\n", \

                               sz, size); \

                        return AVERROR_INVALIDDATA; \

                    } \

                    if (first) { \

                        first = 0; \

                        *out_data = data; \

                        *out_size = sz; \

                        s->n_frames = n_frames; \

                    } else { \

                        s->size[n_frames] = sz; \

                    } \

                    data += sz; \

                    size -= sz; \

                } \

                parse_frame(ctx, *out_data, *out_size); \

                return *out_size

                case_n(1, *idx);

                case_n(2, AV_RL16(idx));

                case_n(3, AV_RL24(idx));

                case_n(4, AV_RL32(idx));

            }

        }

    }

    *out_data = data;

    *out_size = size;

    parse_frame(ctx, data, size);

    return size;

}


static int ram_init1(SysBusDevice *dev)

{

    RamDevice *d = SUN4U_RAM(dev);

    memory_region_init_ram(&d->ram, OBJECT(d), "sun4u.ram", d->size,

                           &error_abort);

    vmstate_register_ram_global(&d->ram);

    sysbus_init_mmio(dev, &d->ram);

    return 0;

}


static void stop_tco(const TestData *d)

{

    uint32_t val;

    val = qpci_io_readw(d->dev, d->tco_io_base + TCO1_CNT);

    val |= TCO_TMR_HLT;

    qpci_io_writew(d->dev, d->tco_io_base + TCO1_CNT, val);

}


void qemu_put_be32(QEMUFile *f, unsigned int v)

{

    qemu_put_byte(f, v >> 24);

    qemu_put_byte(f, v >> 16);

    qemu_put_byte(f, v >> 8);

    qemu_put_byte(f, v);

}


static const unsigned char *seq_unpack_rle_block(const unsigned char *src, unsigned char *dst, int dst_size)

{

    int i, len, sz;

    GetBitContext gb;

    int code_table[64];

    /* get the rle codes (at most 64 bytes) */

    init_get_bits(&gb, src, 64 * 8);

    for (i = 0, sz = 0; i < 64 && sz < dst_size; i++) {

        code_table[i] = get_sbits(&gb, 4);

        sz += FFABS(code_table[i]);

    }

    src += (get_bits_count(&gb) + 7) / 8;

    /* do the rle unpacking */

    for (i = 0; i < 64 && dst_size > 0; i++) {

        len = code_table[i];

        if (len < 0) {

            len = -len;

            memset(dst, *src++, FFMIN(len, dst_size));

        } else {

            memcpy(dst, src, FFMIN(len, dst_size));

            src += len;

        }

        dst += len;

        dst_size -= len;

    }

    return src;

}


bool bdrv_is_first_non_filter(BlockDriverState *candidate)

{

    BlockDriverState *bs;

    BdrvNextIterator *it = NULL;

    /* walk down the bs forest recursively */

    while ((it = bdrv_next(it, &bs)) != NULL) {

        bool perm;

        /* try to recurse in this top level bs */

        perm = bdrv_recurse_is_first_non_filter(bs, candidate);

        /* candidate is the first non filter */

        if (perm) {

            return true;

        }

    }

    return false;

}


static int vhost_user_set_mem_table(struct vhost_dev *dev,

                                    struct vhost_memory *mem)

{

    int fds[VHOST_MEMORY_MAX_NREGIONS];

    int i, fd;

    size_t fd_num = 0;

    bool reply_supported = virtio_has_feature(dev->protocol_features,

                                              VHOST_USER_PROTOCOL_F_REPLY_ACK);

    VhostUserMsg msg = {

        .hdr.request = VHOST_USER_SET_MEM_TABLE,

        .hdr.flags = VHOST_USER_VERSION,

    };

    if (reply_supported) {

        msg.hdr.flags |= VHOST_USER_NEED_REPLY_MASK;

    }

    for (i = 0; i < dev->mem->nregions; ++i) {

        struct vhost_memory_region *reg = dev->mem->regions + i;

        ram_addr_t offset;

        MemoryRegion *mr;

        assert((uintptr_t)reg->userspace_addr == reg->userspace_addr);

        mr = memory_region_from_host((void *)(uintptr_t)reg->userspace_addr,

                                     &offset);

        fd = memory_region_get_fd(mr);

        if (fd > 0) {

            msg.payload.memory.regions[fd_num].userspace_addr = reg->userspace_addr;

            msg.payload.memory.regions[fd_num].memory_size  = reg->memory_size;

            msg.payload.memory.regions[fd_num].guest_phys_addr = reg->guest_phys_addr;

            msg.payload.memory.regions[fd_num].mmap_offset = offset;

            assert(fd_num < VHOST_MEMORY_MAX_NREGIONS);

            fds[fd_num++] = fd;

        }

    }

    msg.payload.memory.nregions = fd_num;

    if (!fd_num) {

        error_report("Failed initializing vhost-user memory map, "

                     "consider using -object memory-backend-file share=on");

        return -1;

    }

    msg.hdr.size = sizeof(msg.payload.memory.nregions);

    msg.hdr.size += sizeof(msg.payload.memory.padding);

    msg.hdr.size += fd_num * sizeof(VhostUserMemoryRegion);

    if (vhost_user_write(dev, &msg, fds, fd_num) < 0) {

        return -1;

    }

    if (reply_supported) {

        return process_message_reply(dev, &msg);

    }

    return 0;

}