static void do_token_setup(USBDevice *s, USBPacket *p)

{

    int request, value, index;

    if (p->iov.size != 8) {

        p->status = USB_RET_STALL;

        return;

    }

    usb_packet_copy(p, s->setup_buf, p->iov.size);

    p->actual_length = 0;

    s->setup_len   = (s->setup_buf[7] << 8) | s->setup_buf[6];

    s->setup_index = 0;

    request = (s->setup_buf[0] << 8) | s->setup_buf[1];

    value   = (s->setup_buf[3] << 8) | s->setup_buf[2];

    index   = (s->setup_buf[5] << 8) | s->setup_buf[4];

    if (s->setup_buf[0] & USB_DIR_IN) {

        usb_device_handle_control(s, p, request, value, index,

                                  s->setup_len, s->data_buf);

        if (p->status == USB_RET_ASYNC) {

            s->setup_state = SETUP_STATE_SETUP;

        }

        if (p->status != USB_RET_SUCCESS) {

            return;

        }

        if (p->actual_length < s->setup_len) {

            s->setup_len = p->actual_length;

        }

        s->setup_state = SETUP_STATE_DATA;

    } else {

        if (s->setup_len > sizeof(s->data_buf)) {

            fprintf(stderr,

                "usb_generic_handle_packet: ctrl buffer too small (%d > %zu)\n",

                s->setup_len, sizeof(s->data_buf));

            p->status = USB_RET_STALL;

            return;

        }

        if (s->setup_len == 0)

            s->setup_state = SETUP_STATE_ACK;

        else

            s->setup_state = SETUP_STATE_DATA;

    }

    p->actual_length = 8;

}


static void qfloat_destroy_obj(QObject *obj)

{

    assert(obj != NULL);

    g_free(qobject_to_qfloat(obj));

}


int qcow2_get_refcount(BlockDriverState *bs, int64_t cluster_index,

                       uint64_t *refcount)

{

    BDRVQcowState *s = bs->opaque;

    uint64_t refcount_table_index, block_index;

    int64_t refcount_block_offset;

    int ret;

    void *refcount_block;

    refcount_table_index = cluster_index >> s->refcount_block_bits;

    if (refcount_table_index >= s->refcount_table_size) {

        *refcount = 0;

        return 0;

    }

    refcount_block_offset =

        s->refcount_table[refcount_table_index] & REFT_OFFSET_MASK;

    if (!refcount_block_offset) {

        *refcount = 0;

        return 0;

    }

    if (offset_into_cluster(s, refcount_block_offset)) {

        qcow2_signal_corruption(bs, true, -1, -1, "Refblock offset %#" PRIx64

                                " unaligned (reftable index: %#" PRIx64 ")",

                                refcount_block_offset, refcount_table_index);

        return -EIO;

    }

    ret = qcow2_cache_get(bs, s->refcount_block_cache, refcount_block_offset,

                          &refcount_block);

    if (ret < 0) {

        return ret;

    }

    block_index = cluster_index & (s->refcount_block_size - 1);

    *refcount = s->get_refcount(refcount_block, block_index);

    ret = qcow2_cache_put(bs, s->refcount_block_cache, &refcount_block);

    if (ret < 0) {

        return ret;

    }

    return 0;

}


static void jpeg_prepare_row24(VncState *vs, uint8_t *dst, int x, int y,

                                     int count)

{

    VncDisplay *vd = vs->vd;

    uint32_t *fbptr;

    uint32_t pix;

    fbptr = (uint32_t *)(vd->server->data + y * ds_get_linesize(vs->ds) +

                         x * ds_get_bytes_per_pixel(vs->ds));

    while (count--) {

        pix = *fbptr++;

        *dst++ = (uint8_t)(pix >> vs->ds->surface->pf.rshift);

        *dst++ = (uint8_t)(pix >> vs->ds->surface->pf.gshift);

        *dst++ = (uint8_t)(pix >> vs->ds->surface->pf.bshift);

    }

}


static void unicore_ii_cpu_initfn(Object *obj)

{

    UniCore32CPU *cpu = UNICORE32_CPU(obj);

    CPUUniCore32State *env = &cpu->env;

    env->cp0.c0_cpuid = 0x40010863;

    set_feature(env, UC32_HWCAP_CMOV);

    set_feature(env, UC32_HWCAP_UCF64);

    env->ucf64.xregs[UC32_UCF64_FPSCR] = 0;

    env->cp0.c0_cachetype = 0x1dd20d2;

    env->cp0.c1_sys = 0x00090078;

}


static void draw_slice(AVFilterLink *inlink, int y, int h, int slice_dir)

{

    FadeContext *fade = inlink->dst->priv;

    AVFilterBufferRef *outpic = inlink->cur_buf;

    uint8_t *p;

    int i, j, plane;

    if (fade->factor < 65536) {

        /* luma or rgb plane */

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

            p = outpic->data[0] + (y+i) * outpic->linesize[0];

            for (j = 0; j < inlink->w * fade->bpp; j++) {

                /* fade->factor is using 16 lower-order bits for decimal

                 * places. 32768 = 1 << 15, it is an integer representation

                 * of 0.5 and is for rounding. */

                *p = (*p * fade->factor + 32768) >> 16;

                p++;

            }

        }

        if (outpic->data[0] && outpic->data[1]) {

            /* chroma planes */

            for (plane = 1; plane < 3; plane++) {

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

                    p = outpic->data[plane] + ((y+i) >> fade->vsub) * outpic->linesize[plane];

                    for (j = 0; j < inlink->w >> fade->hsub; j++) {

                        /* 8421367 = ((128 << 1) + 1) << 15. It is an integer

                         * representation of 128.5. The .5 is for rounding

                         * purposes. */

                        *p = ((*p - 128) * fade->factor + 8421367) >> 16;

                        p++;

                    }

                }

            }

        }

    }

    avfilter_draw_slice(inlink->dst->outputs[0], y, h, slice_dir);

}


static uint64_t virtio_blk_get_features(VirtIODevice *vdev, uint64_t features,

                                        Error **errp)

{

    VirtIOBlock *s = VIRTIO_BLK(vdev);

    virtio_add_feature(&features, VIRTIO_BLK_F_SEG_MAX);

    virtio_add_feature(&features, VIRTIO_BLK_F_GEOMETRY);

    virtio_add_feature(&features, VIRTIO_BLK_F_TOPOLOGY);

    virtio_add_feature(&features, VIRTIO_BLK_F_BLK_SIZE);

    if (__virtio_has_feature(features, VIRTIO_F_VERSION_1)) {

        if (s->conf.scsi) {

            error_setg(errp, "Please set scsi=off for virtio-blk devices in order to use virtio 1.0");

            return 0;

        }

    } else {

        virtio_clear_feature(&features, VIRTIO_F_ANY_LAYOUT);

        virtio_add_feature(&features, VIRTIO_BLK_F_SCSI);

    }

    if (s->conf.config_wce) {

        virtio_add_feature(&features, VIRTIO_BLK_F_CONFIG_WCE);

    }

    if (blk_enable_write_cache(s->blk)) {

        virtio_add_feature(&features, VIRTIO_BLK_F_WCE);

    }

    if (blk_is_read_only(s->blk)) {

        virtio_add_feature(&features, VIRTIO_BLK_F_RO);

    }

    return features;

}


static uint32_t memory_region_read_thunk_n(void *_mr,

                                           target_phys_addr_t addr,

                                           unsigned size)

{

    MemoryRegion *mr = _mr;

    uint64_t data = 0;

    if (!memory_region_access_valid(mr, addr, size)) {

        return -1U; /* FIXME: better signalling */

    }

    if (!mr->ops->read) {

        return mr->ops->old_mmio.read[bitops_ffsl(size)](mr->opaque, addr);

    }

    /* FIXME: support unaligned access */

    access_with_adjusted_size(addr + mr->offset, &data, size,

                              mr->ops->impl.min_access_size,

                              mr->ops->impl.max_access_size,

                              memory_region_read_accessor, mr);

    return data;

}


int64_t helper_fstox(CPUSPARCState *env, float32 src)

{

    int64_t ret;

    clear_float_exceptions(env);

    ret = float32_to_int64_round_to_zero(src, &env->fp_status);

    check_ieee_exceptions(env);

    return ret;

}


static sPAPREventLogEntry *rtas_event_log_dequeue(uint32_t event_mask)

{

    sPAPRMachineState *spapr = SPAPR_MACHINE(qdev_get_machine());

    sPAPREventLogEntry *entry = NULL;

    QTAILQ_FOREACH(entry, &spapr->pending_events, next) {

        const sPAPREventSource *source =

            rtas_event_log_to_source(spapr, entry->log_type);

        if (source->mask & event_mask) {

            break;

        }

    }

    if (entry) {

        QTAILQ_REMOVE(&spapr->pending_events, entry, next);

    }

    return entry;

}


static AioHandler *find_aio_handler(int fd)

{

    AioHandler *node;

    LIST_FOREACH(node, &aio_handlers, node) {

        if (node->fd == fd)

            if (!node->deleted)

                return node;

    }

    return NULL;

}


static int raw_open_common(BlockDriverState *bs, QDict *options,

                           int bdrv_flags, int open_flags, Error **errp)

{

    BDRVRawState *s = bs->opaque;

    QemuOpts *opts;

    Error *local_err = NULL;

    const char *filename;

    int fd, ret;

    opts = qemu_opts_create_nofail(&raw_runtime_opts);

    qemu_opts_absorb_qdict(opts, options, &local_err);

    if (error_is_set(&local_err)) {

        error_propagate(errp, local_err);

        ret = -EINVAL;

        goto fail;

    }

    filename = qemu_opt_get(opts, "filename");

    ret = raw_normalize_devicepath(&filename);

    if (ret != 0) {

        error_setg_errno(errp, -ret, "Could not normalize device path");

        goto fail;

    }

    s->open_flags = open_flags;

    raw_parse_flags(bdrv_flags, &s->open_flags);

    s->fd = -1;

    fd = qemu_open(filename, s->open_flags, 0644);

    if (fd < 0) {

        ret = -errno;

        if (ret == -EROFS) {

            ret = -EACCES;

        }

        goto fail;

    }

    s->fd = fd;

#ifdef CONFIG_LINUX_AIO

    if (raw_set_aio(&s->aio_ctx, &s->use_aio, bdrv_flags)) {

        qemu_close(fd);

        ret = -errno;

        error_setg_errno(errp, -ret, "Could not set AIO state");

        goto fail;

    }

#endif

    s->has_discard = 1;

#ifdef CONFIG_XFS

    if (platform_test_xfs_fd(s->fd)) {

        s->is_xfs = 1;

    }

#endif

    ret = 0;

fail:

    qemu_opts_del(opts);

    return ret;

}


static int hash32_bat_601_prot(CPUPPCState *env,

                               target_ulong batu, target_ulong batl)

{

    int key, pp;

    pp = batu & BATU32_601_PP;

    if (msr_pr == 0) {

        key = !!(batu & BATU32_601_KS);

    } else {

        key = !!(batu & BATU32_601_KP);

    }

    return ppc_hash32_pp_check(key, pp, 0);

}


static int decode_block_coeffs(VP56RangeCoder *c, DCTELEM block[16],

                               uint8_t probs[8][3][NUM_DCT_TOKENS-1],

                               int i, int zero_nhood, int16_t qmul[2])

{

    uint8_t *token_prob;

    int nonzero = 0;

    int coeff;

    do {

        token_prob = probs[vp8_coeff_band[i]][zero_nhood];

        if (!vp56_rac_get_prob_branchy(c, token_prob[0]))   // DCT_EOB

            return nonzero;

skip_eob:

        if (!vp56_rac_get_prob_branchy(c, token_prob[1])) { // DCT_0

            zero_nhood = 0;

            token_prob = probs[vp8_coeff_band[++i]][0];

            if (i < 16)

                goto skip_eob;

            return nonzero; // invalid input; blocks should end with EOB

        }

        if (!vp56_rac_get_prob_branchy(c, token_prob[2])) { // DCT_1

            coeff = 1;

            zero_nhood = 1;

        } else {

            zero_nhood = 2;

            if (!vp56_rac_get_prob_branchy(c, token_prob[3])) { // DCT 2,3,4

                coeff = vp56_rac_get_prob(c, token_prob[4]);

                if (coeff)

                    coeff += vp56_rac_get_prob(c, token_prob[5]);

                coeff += 2;

            } else {

                // DCT_CAT*

                if (!vp56_rac_get_prob_branchy(c, token_prob[6])) {

                    if (!vp56_rac_get_prob_branchy(c, token_prob[7])) { // DCT_CAT1

                        coeff  = 5 + vp56_rac_get_prob(c, vp8_dct_cat1_prob[0]);

                    } else {                                    // DCT_CAT2

                        coeff  = 7;

                        coeff += vp56_rac_get_prob(c, vp8_dct_cat2_prob[0]) << 1;

                        coeff += vp56_rac_get_prob(c, vp8_dct_cat2_prob[1]);

                    }

                } else {    // DCT_CAT3 and up

                    int a = vp56_rac_get_prob(c, token_prob[8]);

                    int b = vp56_rac_get_prob(c, token_prob[9+a]);

                    int cat = (a<<1) + b;

                    coeff  = 3 + (8<<cat);

                    coeff += vp8_rac_get_coeff(c, vp8_dct_cat_prob[cat]);

                }

            }

        }

        // todo: full [16] qmat? load into register?

        block[zigzag_scan[i]] = (vp8_rac_get(c) ? -coeff : coeff) * qmul[!!i];

        nonzero = ++i;

    } while (i < 16);

    return nonzero;

}


InputEvent *qemu_input_event_new_move(InputEventKind kind,

                                      InputAxis axis, int value)

{

    InputEvent *evt = g_new0(InputEvent, 1);

    InputMoveEvent *move = g_new0(InputMoveEvent, 1);

    evt->type = kind;

    evt->u.rel = move; /* evt->u.rel is the same as evt->u.abs */

    move->axis = axis;

    move->value = value;

    return evt;

}


static void load_symbols(struct elfhdr *hdr, int fd)

{

    unsigned int i, nsyms;

    struct elf_shdr sechdr, symtab, strtab;

    char *strings;

    struct syminfo *s;

    struct elf_sym *syms;

    lseek(fd, hdr->e_shoff, SEEK_SET);

    for (i = 0; i < hdr->e_shnum; i++) {

        if (read(fd, &sechdr, sizeof(sechdr)) != sizeof(sechdr))

            return;

#ifdef BSWAP_NEEDED

        bswap_shdr(&sechdr);

#endif

        if (sechdr.sh_type == SHT_SYMTAB) {

            symtab = sechdr;

            lseek(fd, hdr->e_shoff

                  + sizeof(sechdr) * sechdr.sh_link, SEEK_SET);

            if (read(fd, &strtab, sizeof(strtab))

                != sizeof(strtab))

                return;

#ifdef BSWAP_NEEDED

            bswap_shdr(&strtab);

#endif

            goto found;

        }

    }

    return; /* Shouldn't happen... */

 found:

    /* Now know where the strtab and symtab are.  Snarf them. */

    s = malloc(sizeof(*s));

    syms = malloc(symtab.sh_size);

    if (!syms)

        return;

    s->disas_strtab = strings = malloc(strtab.sh_size);

    if (!s->disas_strtab)

        return;

    lseek(fd, symtab.sh_offset, SEEK_SET);

    if (read(fd, syms, symtab.sh_size) != symtab.sh_size)

        return;

    nsyms = symtab.sh_size / sizeof(struct elf_sym);

    i = 0;

    while (i < nsyms) {

#ifdef BSWAP_NEEDED

        bswap_sym(syms + i);

#endif

        // Throw away entries which we do not need.

        if (syms[i].st_shndx == SHN_UNDEF ||

            syms[i].st_shndx >= SHN_LORESERVE ||

            ELF_ST_TYPE(syms[i].st_info) != STT_FUNC) {

            nsyms--;

            if (i < nsyms) {

                syms[i] = syms[nsyms];

            }

            continue;

        }

#if defined(TARGET_ARM) || defined (TARGET_MIPS)

        /* The bottom address bit marks a Thumb or MIPS16 symbol.  */

        syms[i].st_value &= ~(target_ulong)1;

#endif

        i++;

    }

    syms = realloc(syms, nsyms * sizeof(*syms));

    qsort(syms, nsyms, sizeof(*syms), symcmp);

    lseek(fd, strtab.sh_offset, SEEK_SET);

    if (read(fd, strings, strtab.sh_size) != strtab.sh_size)

        return;

    s->disas_num_syms = nsyms;

#if ELF_CLASS == ELFCLASS32

    s->disas_symtab.elf32 = syms;

    s->lookup_symbol = lookup_symbolxx;

#else

    s->disas_symtab.elf64 = syms;

    s->lookup_symbol = lookup_symbolxx;

#endif

    s->next = syminfos;

    syminfos = s;

}


static void xlnx_ep108_init(MachineState *machine)

{

    XlnxEP108 *s = g_new0(XlnxEP108, 1);

    int i;

    uint64_t ram_size = machine->ram_size;

    /* Create the memory region to pass to the SoC */

    if (ram_size > XLNX_ZYNQMP_MAX_RAM_SIZE) {

        error_report("ERROR: RAM size 0x%" PRIx64 " above max supported of "

                     "0x%llx", ram_size,

                     XLNX_ZYNQMP_MAX_RAM_SIZE);

        exit(1);

    }

    if (ram_size < 0x08000000) {

        qemu_log("WARNING: RAM size 0x%" PRIx64 " is small for EP108",

                 ram_size);

    }

    memory_region_allocate_system_memory(&s->ddr_ram, NULL, "ddr-ram",

                                         ram_size);

    object_initialize(&s->soc, sizeof(s->soc), TYPE_XLNX_ZYNQMP);

    object_property_add_child(OBJECT(machine), "soc", OBJECT(&s->soc),

                              &error_abort);

    object_property_set_link(OBJECT(&s->soc), OBJECT(&s->ddr_ram),

                         "ddr-ram", &error_abort);

    object_property_set_bool(OBJECT(&s->soc), true, "realized", &error_fatal);

    /* Create and plug in the SD cards */

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

        BusState *bus;

        DriveInfo *di = drive_get_next(IF_SD);

        BlockBackend *blk = di ? blk_by_legacy_dinfo(di) : NULL;

        DeviceState *carddev;

        char *bus_name;

        bus_name = g_strdup_printf("sd-bus%d", i);

        bus = qdev_get_child_bus(DEVICE(&s->soc), bus_name);

        g_free(bus_name);

        if (!bus) {

            error_report("No SD bus found for SD card %d", i);

            exit(1);

        }

        carddev = qdev_create(bus, TYPE_SD_CARD);

        qdev_prop_set_drive(carddev, "drive", blk, &error_fatal);

        object_property_set_bool(OBJECT(carddev), true, "realized",

                                 &error_fatal);

    }

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

        SSIBus *spi_bus;

        DeviceState *flash_dev;

        qemu_irq cs_line;

        DriveInfo *dinfo = drive_get_next(IF_MTD);

        gchar *bus_name = g_strdup_printf("spi%d", i);

        spi_bus = (SSIBus *)qdev_get_child_bus(DEVICE(&s->soc), bus_name);

        g_free(bus_name);

        flash_dev = ssi_create_slave_no_init(spi_bus, "sst25wf080");

        if (dinfo) {

            qdev_prop_set_drive(flash_dev, "drive", blk_by_legacy_dinfo(dinfo),

                                &error_fatal);

        }

        qdev_init_nofail(flash_dev);

        cs_line = qdev_get_gpio_in_named(flash_dev, SSI_GPIO_CS, 0);

        sysbus_connect_irq(SYS_BUS_DEVICE(&s->soc.spi[i]), 1, cs_line);

    }

    /* TODO create and connect IDE devices for ide_drive_get() */

    xlnx_ep108_binfo.ram_size = ram_size;

    xlnx_ep108_binfo.kernel_filename = machine->kernel_filename;

    xlnx_ep108_binfo.kernel_cmdline = machine->kernel_cmdline;

    xlnx_ep108_binfo.initrd_filename = machine->initrd_filename;

    xlnx_ep108_binfo.loader_start = 0;

    arm_load_kernel(s->soc.boot_cpu_ptr, &xlnx_ep108_binfo);

}


void address_space_rw(AddressSpace *as, hwaddr addr, uint8_t *buf,

                      int len, bool is_write)

{

    AddressSpaceDispatch *d = as->dispatch;

    int l;

    uint8_t *ptr;

    uint32_t val;

    hwaddr page;

    MemoryRegionSection *section;

    while (len > 0) {

        page = addr & TARGET_PAGE_MASK;

        l = (page + TARGET_PAGE_SIZE) - addr;

        if (l > len)

            l = len;

        section = phys_page_find(d, page >> TARGET_PAGE_BITS);

        if (is_write) {

            if (!memory_region_is_ram(section->mr)) {

                hwaddr addr1;

                addr1 = memory_region_section_addr(section, addr);

                /* XXX: could force cpu_single_env to NULL to avoid

                   potential bugs */

                if (l >= 4 && ((addr1 & 3) == 0)) {

                    /* 32 bit write access */

                    val = ldl_p(buf);

                    io_mem_write(section->mr, addr1, val, 4);

                    l = 4;

                } else if (l >= 2 && ((addr1 & 1) == 0)) {

                    /* 16 bit write access */

                    val = lduw_p(buf);

                    io_mem_write(section->mr, addr1, val, 2);

                    l = 2;

                } else {

                    /* 8 bit write access */

                    val = ldub_p(buf);

                    io_mem_write(section->mr, addr1, val, 1);

                    l = 1;

                }

            } else if (!section->readonly) {

                ram_addr_t addr1;

                addr1 = memory_region_get_ram_addr(section->mr)

                    + memory_region_section_addr(section, addr);

                /* RAM case */

                ptr = qemu_get_ram_ptr(addr1);

                memcpy(ptr, buf, l);

                invalidate_and_set_dirty(addr1, l);

            }

        } else {

            if (!(memory_region_is_ram(section->mr) ||

                  memory_region_is_romd(section->mr))) {

                hwaddr addr1;

                /* I/O case */

                addr1 = memory_region_section_addr(section, addr);

                if (l >= 4 && ((addr1 & 3) == 0)) {

                    /* 32 bit read access */

                    val = io_mem_read(section->mr, addr1, 4);

                    stl_p(buf, val);

                    l = 4;

                } else if (l >= 2 && ((addr1 & 1) == 0)) {

                    /* 16 bit read access */

                    val = io_mem_read(section->mr, addr1, 2);

                    stw_p(buf, val);

                    l = 2;

                } else {

                    /* 8 bit read access */

                    val = io_mem_read(section->mr, addr1, 1);

                    stb_p(buf, val);

                    l = 1;

                }

            } else {

                /* RAM case */

                ptr = qemu_get_ram_ptr(section->mr->ram_addr

                                       + memory_region_section_addr(section,

                                                                    addr));

                memcpy(buf, ptr, l);

            }

        }

        len -= l;

        buf += l;

        addr += l;

    }

}


static int parse_numa(void *opaque, QemuOpts *opts, Error **errp)

{

    NumaOptions *object = NULL;

    Error *err = NULL;

    {

        OptsVisitor *ov = opts_visitor_new(opts);

        visit_type_NumaOptions(opts_get_visitor(ov), NULL, &object, &err);

        opts_visitor_cleanup(ov);

    }

    if (err) {

        goto error;

    }

    switch (object->type) {

    case NUMA_OPTIONS_KIND_NODE:

        numa_node_parse(object->u.node, opts, &err);

        if (err) {

            goto error;

        }

        nb_numa_nodes++;

        break;

    default:

        abort();

    }

    return 0;

error:

    error_report_err(err);

    qapi_free_NumaOptions(object);

    return -1;

}


void qmp_migrate_set_capabilities(MigrationCapabilityStatusList *params,

                                  Error **errp)

{

    MigrationState *s = migrate_get_current();

    MigrationCapabilityStatusList *cap;

    bool old_postcopy_cap = migrate_postcopy_ram();

    if (migration_is_setup_or_active(s->state)) {

        error_setg(errp, QERR_MIGRATION_ACTIVE);

        return;

    }

    for (cap = params; cap; cap = cap->next) {

#ifndef CONFIG_LIVE_BLOCK_MIGRATION

        if (cap->value->capability == MIGRATION_CAPABILITY_BLOCK

            && cap->value->state) {

            error_setg(errp, "QEMU compiled without old-style (blk/-b, inc/-i) "

                       "block migration");

            error_append_hint(errp, "Use drive_mirror+NBD instead.\n");

            continue;

        }

#endif

        s->enabled_capabilities[cap->value->capability] = cap->value->state;

    }

    if (migrate_postcopy_ram()) {

        if (migrate_use_compression()) {

            /* The decompression threads asynchronously write into RAM

             * rather than use the atomic copies needed to avoid

             * userfaulting.  It should be possible to fix the decompression

             * threads for compatibility in future.

             */

            error_report("Postcopy is not currently compatible with "

                         "compression");

            s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_RAM] =

                false;

        }

        /* This check is reasonably expensive, so only when it's being

         * set the first time, also it's only the destination that needs

         * special support.

         */

        if (!old_postcopy_cap && runstate_check(RUN_STATE_INMIGRATE) &&

            !postcopy_ram_supported_by_host()) {

            /* postcopy_ram_supported_by_host will have emitted a more

             * detailed message

             */

            error_report("Postcopy is not supported");

            s->enabled_capabilities[MIGRATION_CAPABILITY_POSTCOPY_RAM] =

                false;

        }

    }

}


void vga_hw_screen_dump(const char *filename)

{

    TextConsole *previous_active_console;

    previous_active_console = active_console;

    active_console = consoles[0];

    /* There is currently no way of specifying which screen we want to dump,

       so always dump the first one.  */

    if (consoles[0]->hw_screen_dump)

        consoles[0]->hw_screen_dump(consoles[0]->hw, filename);

    active_console = previous_active_console;

}


static void fill_mbaff_ref_list(H264Context *h){

    int list, i, j;

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

        for(i=0; i<h->ref_count[list]; i++){

            Picture *frame = &h->ref_list[list][i];

            Picture *field = &h->ref_list[list][16+2*i];

            field[0] = *frame;

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

                field[0].linesize[j] <<= 1;

            field[1] = field[0];

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

                field[1].data[j] += frame->linesize[j];

            h->luma_weight[list][16+2*i] = h->luma_weight[list][16+2*i+1] = h->luma_weight[list][i];

            h->luma_offset[list][16+2*i] = h->luma_offset[list][16+2*i+1] = h->luma_offset[list][i];

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

                h->chroma_weight[list][16+2*i][j] = h->chroma_weight[list][16+2*i+1][j] = h->chroma_weight[list][i][j];

                h->chroma_offset[list][16+2*i][j] = h->chroma_offset[list][16+2*i+1][j] = h->chroma_offset[list][i][j];

            }

        }

    }

    for(j=0; j<h->ref_count[1]; j++){

        for(i=0; i<h->ref_count[0]; i++)

            h->implicit_weight[j][16+2*i] = h->implicit_weight[j][16+2*i+1] = h->implicit_weight[j][i];

        memcpy(h->implicit_weight[16+2*j],   h->implicit_weight[j], sizeof(*h->implicit_weight));

        memcpy(h->implicit_weight[16+2*j+1], h->implicit_weight[j], sizeof(*h->implicit_weight));

    }

}


void configure_icount(QemuOpts *opts, Error **errp)

{

    const char *option;

    char *rem_str = NULL;

    option = qemu_opt_get(opts, "shift");

    if (!option) {

        if (qemu_opt_get(opts, "align") != NULL) {

            error_setg(errp, "Please specify shift option when using align");

        }

        return;

    }

    icount_sleep = qemu_opt_get_bool(opts, "sleep", true);

    if (icount_sleep) {

        icount_warp_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL_RT,

                                         icount_dummy_timer, NULL);

    }

    icount_align_option = qemu_opt_get_bool(opts, "align", false);

    if (icount_align_option && !icount_sleep) {

        error_setg(errp, "align=on and sleep=off are incompatible");

    }

    if (strcmp(option, "auto") != 0) {

        errno = 0;

        icount_time_shift = strtol(option, &rem_str, 0);

        if (errno != 0 || *rem_str != '\0' || !strlen(option)) {

            error_setg(errp, "icount: Invalid shift value");

        }

        use_icount = 1;

        return;

    } else if (icount_align_option) {

        error_setg(errp, "shift=auto and align=on are incompatible");

    } else if (!icount_sleep) {

        error_setg(errp, "shift=auto and sleep=off are incompatible");

    }

    use_icount = 2;

    /* 125MIPS seems a reasonable initial guess at the guest speed.

       It will be corrected fairly quickly anyway.  */

    icount_time_shift = 3;

    /* Have both realtime and virtual time triggers for speed adjustment.

       The realtime trigger catches emulated time passing too slowly,

       the virtual time trigger catches emulated time passing too fast.

       Realtime triggers occur even when idle, so use them less frequently

       than VM triggers.  */

    icount_rt_timer = timer_new_ms(QEMU_CLOCK_VIRTUAL_RT,

                                   icount_adjust_rt, NULL);

    timer_mod(icount_rt_timer,

                   qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL_RT) + 1000);

    icount_vm_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL,

                                        icount_adjust_vm, NULL);

    timer_mod(icount_vm_timer,

                   qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +

                   get_ticks_per_sec() / 10);

}


static void handle_port_status_write(EHCIState *s, int port, uint32_t val)

{

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

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

    /* Clear rwc bits */

    *portsc &= ~(val & PORTSC_RWC_MASK);

    /* The guest may clear, but not set the PED bit */

    *portsc &= val | ~PORTSC_PED;

    /* POWNER is masked out by RO_MASK as it is RO when we've no companion */

    handle_port_owner_write(s, port, val);

    /* And finally apply RO_MASK */

    val &= PORTSC_RO_MASK;

    if ((val & PORTSC_PRESET) && !(*portsc & PORTSC_PRESET)) {

        trace_usb_ehci_port_reset(port, 1);

    }

    if (!(val & PORTSC_PRESET) &&(*portsc & PORTSC_PRESET)) {

        trace_usb_ehci_port_reset(port, 0);

        if (dev) {

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

            usb_send_msg(dev, USB_MSG_RESET);

            *portsc &= ~PORTSC_CSC;

        }

        /*

         *  Table 2.16 Set the enable bit(and enable bit change) to indicate

         *  to SW that this port has a high speed device attached

         */

        if (dev && (dev->speedmask & USB_SPEED_MASK_HIGH)) {

            val |= PORTSC_PED;

        }

    }

    *portsc &= ~PORTSC_RO_MASK;

    *portsc |= val;

}


static uint64_t omap_rtc_read(void *opaque, target_phys_addr_t addr,

                              unsigned size)

{

    struct omap_rtc_s *s = (struct omap_rtc_s *) opaque;

    int offset = addr & OMAP_MPUI_REG_MASK;

    uint8_t i;

    if (size != 1) {

        return omap_badwidth_read8(opaque, addr);

    }

    switch (offset) {

    case 0x00:	/* SECONDS_REG */

        return to_bcd(s->current_tm.tm_sec);

    case 0x04:	/* MINUTES_REG */

        return to_bcd(s->current_tm.tm_min);

    case 0x08:	/* HOURS_REG */

        if (s->pm_am)

            return ((s->current_tm.tm_hour > 11) << 7) |

                    to_bcd(((s->current_tm.tm_hour - 1) % 12) + 1);

        else

            return to_bcd(s->current_tm.tm_hour);

    case 0x0c:	/* DAYS_REG */

        return to_bcd(s->current_tm.tm_mday);

    case 0x10:	/* MONTHS_REG */

        return to_bcd(s->current_tm.tm_mon + 1);

    case 0x14:	/* YEARS_REG */

        return to_bcd(s->current_tm.tm_year % 100);

    case 0x18:	/* WEEK_REG */

        return s->current_tm.tm_wday;

    case 0x20:	/* ALARM_SECONDS_REG */

        return to_bcd(s->alarm_tm.tm_sec);

    case 0x24:	/* ALARM_MINUTES_REG */

        return to_bcd(s->alarm_tm.tm_min);

    case 0x28:	/* ALARM_HOURS_REG */

        if (s->pm_am)

            return ((s->alarm_tm.tm_hour > 11) << 7) |

                    to_bcd(((s->alarm_tm.tm_hour - 1) % 12) + 1);

        else

            return to_bcd(s->alarm_tm.tm_hour);

    case 0x2c:	/* ALARM_DAYS_REG */

        return to_bcd(s->alarm_tm.tm_mday);

    case 0x30:	/* ALARM_MONTHS_REG */

        return to_bcd(s->alarm_tm.tm_mon + 1);

    case 0x34:	/* ALARM_YEARS_REG */

        return to_bcd(s->alarm_tm.tm_year % 100);

    case 0x40:	/* RTC_CTRL_REG */

        return (s->pm_am << 3) | (s->auto_comp << 2) |

                (s->round << 1) | s->running;

    case 0x44:	/* RTC_STATUS_REG */

        i = s->status;

        s->status &= ~0x3d;

        return i;

    case 0x48:	/* RTC_INTERRUPTS_REG */

        return s->interrupts;

    case 0x4c:	/* RTC_COMP_LSB_REG */

        return ((uint16_t) s->comp_reg) & 0xff;

    case 0x50:	/* RTC_COMP_MSB_REG */

        return ((uint16_t) s->comp_reg) >> 8;

    }

    OMAP_BAD_REG(addr);

    return 0;

}


cac_applet_pki_process_apdu(VCard *card, VCardAPDU *apdu,

                            VCardResponse **response)

{

    CACPKIAppletData *pki_applet = NULL;

    VCardAppletPrivate *applet_private = NULL;

    int size, next;

    unsigned char *sign_buffer;

    vcard_7816_status_t status;

    VCardStatus ret = VCARD_FAIL;

    applet_private = vcard_get_current_applet_private(card, apdu->a_channel);

    assert(applet_private);

    pki_applet = &(applet_private->u.pki_data);

    switch (apdu->a_ins) {

    case CAC_UPDATE_BUFFER:

        *response = vcard_make_response(

            VCARD7816_STATUS_ERROR_CONDITION_NOT_SATISFIED);

        ret = VCARD_DONE;

        break;

    case CAC_GET_CERTIFICATE:

        if ((apdu->a_p2 != 0) || (apdu->a_p1 != 0)) {

            *response = vcard_make_response(

                             VCARD7816_STATUS_ERROR_P1_P2_INCORRECT);

            break;

        }

        assert(pki_applet->cert != NULL);

        size = apdu->a_Le;

        if (pki_applet->cert_buffer == NULL) {

            pki_applet->cert_buffer = pki_applet->cert;

            pki_applet->cert_buffer_len = pki_applet->cert_len;

        }

        size = MIN(size, pki_applet->cert_buffer_len);

        next = MIN(255, pki_applet->cert_buffer_len - size);

        *response = vcard_response_new_bytes(

                        card, pki_applet->cert_buffer, size,

                        apdu->a_Le, next ?

                        VCARD7816_SW1_WARNING_CHANGE :

                        VCARD7816_SW1_SUCCESS,

                        next);

        pki_applet->cert_buffer += size;

        pki_applet->cert_buffer_len -= size;

        if ((*response == NULL) || (next == 0)) {

            pki_applet->cert_buffer = NULL;

        }

        if (*response == NULL) {

            *response = vcard_make_response(

                            VCARD7816_STATUS_EXC_ERROR_MEMORY_FAILURE);

        }

        ret = VCARD_DONE;

        break;

    case CAC_SIGN_DECRYPT:

        if (apdu->a_p2 != 0) {

            *response = vcard_make_response(

                             VCARD7816_STATUS_ERROR_P1_P2_INCORRECT);

            break;

        }

        size = apdu->a_Lc;

        sign_buffer = g_realloc(pki_applet->sign_buffer,

                                pki_applet->sign_buffer_len + size);

        memcpy(sign_buffer+pki_applet->sign_buffer_len, apdu->a_body, size);

        size += pki_applet->sign_buffer_len;

        switch (apdu->a_p1) {

        case  0x80:

            /* p1 == 0x80 means we haven't yet sent the whole buffer, wait for

             * the rest */

            pki_applet->sign_buffer = sign_buffer;

            pki_applet->sign_buffer_len = size;

            *response = vcard_make_response(VCARD7816_STATUS_SUCCESS);

            break;

        case 0x00:

            /* we now have the whole buffer, do the operation, result will be

             * in the sign_buffer */

            status = vcard_emul_rsa_op(card, pki_applet->key,

                                       sign_buffer, size);

            if (status != VCARD7816_STATUS_SUCCESS) {

                *response = vcard_make_response(status);

                break;

            }

            *response = vcard_response_new(card, sign_buffer, size, apdu->a_Le,

                                                     VCARD7816_STATUS_SUCCESS);

            if (*response == NULL) {

                *response = vcard_make_response(

                                VCARD7816_STATUS_EXC_ERROR_MEMORY_FAILURE);

            }

            break;

        default:

           *response = vcard_make_response(

                                VCARD7816_STATUS_ERROR_P1_P2_INCORRECT);

            break;

        }

        g_free(sign_buffer);

        pki_applet->sign_buffer = NULL;

        pki_applet->sign_buffer_len = 0;

        ret = VCARD_DONE;

        break;

    case CAC_READ_BUFFER:

        /* new CAC call, go ahead and use the old version for now */

        /* TODO: implement */

        *response = vcard_make_response(

                                VCARD7816_STATUS_ERROR_COMMAND_NOT_SUPPORTED);

        ret = VCARD_DONE;

        break;

    default:

        ret = cac_common_process_apdu(card, apdu, response);

        break;

    }

    return ret;

}


int qcow2_encrypt_sectors(BDRVQcow2State *s, int64_t sector_num,

                          uint8_t *buf, int nb_sectors, bool enc,

                          Error **errp)

{

    union {

        uint64_t ll[2];

        uint8_t b[16];

    } ivec;

    int i;

    int ret;

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

        ivec.ll[0] = cpu_to_le64(sector_num);

        ivec.ll[1] = 0;

        if (qcrypto_cipher_setiv(s->cipher,

                                 ivec.b, G_N_ELEMENTS(ivec.b),

                                 errp) < 0) {

            return -1;

        }

        if (enc) {

            ret = qcrypto_cipher_encrypt(s->cipher,

                                         buf, buf,

                                         512,

                                         errp);

        } else {

            ret = qcrypto_cipher_decrypt(s->cipher,

                                         buf, buf,

                                         512,

                                         errp);

        }

        if (ret < 0) {

            return -1;

        }

        sector_num++;

        buf += 512;

    }

    return 0;

}


void qemu_system_shutdown_request(void)

{

    trace_qemu_system_shutdown_request();

    replay_shutdown_request();

    /* TODO - add a parameter to allow callers to specify reason */

    shutdown_requested = SHUTDOWN_CAUSE_HOST_ERROR;

    qemu_notify_event();

}


static void virtio_s390_notify(DeviceState *d, uint16_t vector)

{

    VirtIOS390Device *dev = to_virtio_s390_device_fast(d);

    uint64_t token = s390_virtio_device_vq_token(dev, vector);

    S390CPU *cpu = s390_cpu_addr2state(0);

    s390_virtio_irq(cpu, 0, token);

}


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

{

    int l1, l2, prot, last_prot;

    uint32_t pgd, pde, pte;

    target_phys_addr_t start, end;

    pgd = env->cr[3] & ~0xfff;

    last_prot = 0;

    start = -1;

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

        cpu_physical_memory_read(pgd + l1 * 4, &pde, 4);

        pde = le32_to_cpu(pde);

        end = l1 << 22;

        if (pde & PG_PRESENT_MASK) {

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

                prot = pde & (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);

                mem_print(mon, &start, &last_prot, end, prot);

            } else {

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

                    cpu_physical_memory_read((pde & ~0xfff) + l2 * 4, &pte, 4);

                    pte = le32_to_cpu(pte);

                    end = (l1 << 22) + (l2 << 12);

                    if (pte & PG_PRESENT_MASK) {

                        prot = pte & (PG_USER_MASK | PG_RW_MASK | PG_PRESENT_MASK);

                    } else {

                        prot = 0;

                    }

                    mem_print(mon, &start, &last_prot, end, prot);

                }

            }

        } else {

            prot = 0;

            mem_print(mon, &start, &last_prot, end, prot);

        }

    }

}


int av_opt_set_sample_fmt(void *obj, const char *name, enum AVSampleFormat fmt, int search_flags)

{

    return set_format(obj, name, fmt, search_flags, AV_OPT_TYPE_SAMPLE_FMT, "sample", AV_SAMPLE_FMT_NB-1);

}


static void do_stop(int argc, const char **argv)

{

    vm_stop(EXCP_INTERRUPT);

}


static void RENAME(yuyvtoyuv422)(uint8_t *ydst, uint8_t *udst, uint8_t *vdst, const uint8_t *src,

                                      long width, long height,

                                      long lumStride, long chromStride, long srcStride)

{

    long y;

    const long chromWidth= -((-width)>>1);

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

        RENAME(extract_even)(src, ydst, width);

        RENAME(extract_odd2)(src, udst, vdst, chromWidth);

        src += srcStride;

        ydst+= lumStride;

        udst+= chromStride;

        vdst+= chromStride;

    }

#if COMPILE_TEMPLATE_MMX

    __asm__(

            EMMS"       \n\t"

            SFENCE"     \n\t"

            ::: "memory"

        );

#endif

}


void ff_lag_rac_init(lag_rac *l, GetBitContext *gb, int length)

{

    int i, j, left;

    /* According to reference decoder "1st byte is garbage",

     * however, it gets skipped by the call to align_get_bits()

     */

    align_get_bits(gb);

    left                = get_bits_left(gb) >> 3;

    l->bytestream_start =

    l->bytestream       = gb->buffer + get_bits_count(gb) / 8;

    l->bytestream_end   = l->bytestream_start + left;

    l->range        = 0x80;

    l->low          = *l->bytestream >> 1;

    l->hash_shift   = FFMAX(l->scale - 8, 0);

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

        unsigned r = i << l->hash_shift;

        while (l->prob[j + 1] <= r)

            j++;

        l->range_hash[i] = j;

    }

    /* Add conversion factor to hash_shift so we don't have to in lag_get_rac. */

    l->hash_shift += 23;

}


static inline void xan_wc3_copy_pixel_run(XanContext *s, AVFrame *frame,

                                          int x, int y,

                                          int pixel_count, int motion_x,

                                          int motion_y)

{

    int stride;

    int line_inc;

    int curframe_index, prevframe_index;

    int curframe_x, prevframe_x;

    int width = s->avctx->width;

    uint8_t *palette_plane, *prev_palette_plane;

    if (y + motion_y < 0 || y + motion_y >= s->avctx->height ||

        x + motion_x < 0 || x + motion_x >= s->avctx->width)

        return;

    palette_plane = frame->data[0];

    prev_palette_plane = s->last_frame->data[0];

    if (!prev_palette_plane)

        prev_palette_plane = palette_plane;

    stride = frame->linesize[0];

    line_inc = stride - width;

    curframe_index = y * stride + x;

    curframe_x = x;

    prevframe_index = (y + motion_y) * stride + x + motion_x;

    prevframe_x = x + motion_x;

    if (prev_palette_plane == palette_plane && FFABS(curframe_index - prevframe_index) < pixel_count) {

         avpriv_request_sample(s->avctx, "Overlapping copy");

         return ;

    }

    while (pixel_count &&

           curframe_index  < s->frame_size &&

           prevframe_index < s->frame_size) {

        int count = FFMIN3(pixel_count, width - curframe_x,

                           width - prevframe_x);

        memcpy(palette_plane + curframe_index,

               prev_palette_plane + prevframe_index, count);

        pixel_count     -= count;

        curframe_index  += count;

        prevframe_index += count;

        curframe_x      += count;

        prevframe_x     += count;

        if (curframe_x >= width) {

            curframe_index += line_inc;

            curframe_x = 0;

        }

        if (prevframe_x >= width) {

            prevframe_index += line_inc;

            prevframe_x = 0;

        }

    }

}


static av_cold int on2avc_decode_init(AVCodecContext *avctx)

{

    On2AVCContext *c = avctx->priv_data;

    int i;

    c->avctx = avctx;

    avctx->sample_fmt     = AV_SAMPLE_FMT_FLTP;

    avctx->channel_layout = (avctx->channels == 2) ? AV_CH_LAYOUT_STEREO

                                                   : AV_CH_LAYOUT_MONO;

    c->is_av500 = (avctx->codec_tag == 0x500);

    if (c->is_av500 && avctx->channels == 2) {

        av_log(avctx, AV_LOG_ERROR, "0x500 version should be mono\n");

        return AVERROR_INVALIDDATA;

    if (avctx->channels == 2)

        av_log(avctx, AV_LOG_WARNING,

               "Stereo mode support is not good, patch is welcome\n");

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

        c->scale_tab[i] = ceil(pow(10.0, i * 0.1) * 16) / 32;

    for (; i < 128; i++)

        c->scale_tab[i] = ceil(pow(10.0, i * 0.1) * 0.5);

    if (avctx->sample_rate < 32000 || avctx->channels == 1)

        memcpy(c->long_win, ff_on2avc_window_long_24000,

               1024 * sizeof(*c->long_win));

    else

        memcpy(c->long_win, ff_on2avc_window_long_32000,

               1024 * sizeof(*c->long_win));

    memcpy(c->short_win, ff_on2avc_window_short, 128 * sizeof(*c->short_win));

    c->modes = (avctx->sample_rate <= 40000) ? ff_on2avc_modes_40

                                             : ff_on2avc_modes_44;

    c->wtf   = (avctx->sample_rate <= 40000) ? wtf_40

                                             : wtf_44;

    ff_mdct_init(&c->mdct,       11, 1, 1.0 / (32768.0 * 1024.0));

    ff_mdct_init(&c->mdct_half,  10, 1, 1.0 / (32768.0 * 512.0));

    ff_mdct_init(&c->mdct_small,  8, 1, 1.0 / (32768.0 * 128.0));

    ff_fft_init(&c->fft128,  6, 0);

    ff_fft_init(&c->fft256,  7, 0);

    ff_fft_init(&c->fft512,  8, 1);

    ff_fft_init(&c->fft1024, 9, 1);

    avpriv_float_dsp_init(&c->fdsp, avctx->flags & CODEC_FLAG_BITEXACT);

    if (init_vlc(&c->scale_diff, 9, ON2AVC_SCALE_DIFFS,

                 ff_on2avc_scale_diff_bits,  1, 1,

                 ff_on2avc_scale_diff_codes, 4, 4, 0)) {

        av_log(avctx, AV_LOG_ERROR, "Cannot init VLC\n");

        return AVERROR(ENOMEM);

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

        int idx = i - 1;

        if (ff_init_vlc_sparse(&c->cb_vlc[i], 9, ff_on2avc_quad_cb_elems[idx],

                               ff_on2avc_quad_cb_bits[idx],  1, 1,

                               ff_on2avc_quad_cb_codes[idx], 4, 4,

                               ff_on2avc_quad_cb_syms[idx],  2, 2, 0)) {

            av_log(avctx, AV_LOG_ERROR, "Cannot init VLC\n");

            on2avc_free_vlcs(c);

            return AVERROR(ENOMEM);

    for (i = 9; i < 16; i++) {

        int idx = i - 9;

        if (ff_init_vlc_sparse(&c->cb_vlc[i], 9, ff_on2avc_pair_cb_elems[idx],

                               ff_on2avc_pair_cb_bits[idx],  1, 1,

                               ff_on2avc_pair_cb_codes[idx], 2, 2,

                               ff_on2avc_pair_cb_syms[idx],  2, 2, 0)) {

            av_log(avctx, AV_LOG_ERROR, "Cannot init VLC\n");

            on2avc_free_vlcs(c);

            return AVERROR(ENOMEM);

    return 0;


static uint64_t ahci_alloc(AHCIQState *ahci, size_t bytes)

{

    return qmalloc(ahci->parent, bytes);

}


static int ea_probe(AVProbeData *p)

{

    switch (AV_RL32(&p->buf[0])) {

    case ISNh_TAG:

    case SCHl_TAG:

    case SEAD_TAG:

    case SHEN_TAG:

    case kVGT_TAG:

    case MADk_TAG:

    case MPCh_TAG:

    case MVhd_TAG:

    case MVIh_TAG:

        break;

    default:

        return 0;

    }

    if (AV_RL32(&p->buf[4]) > 0xfffff && AV_RB32(&p->buf[4]) > 0xfffff)

        return 0;

    return AVPROBE_SCORE_MAX;

}


static int ulti_decode_frame(AVCodecContext *avctx,

                             void *data, int *data_size,

                             AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    UltimotionDecodeContext *s=avctx->priv_data;

    int modifier = 0;

    int uniq = 0;

    int mode = 0;

    int blocks = 0;

    int done = 0;

    int x = 0, y = 0;

    int i;

    int skip;

    int tmp;

    s->frame.reference = 1;

    s->frame.buffer_hints = FF_BUFFER_HINTS_VALID | FF_BUFFER_HINTS_PRESERVE | FF_BUFFER_HINTS_REUSABLE;

    if (avctx->reget_buffer(avctx, &s->frame) < 0) {

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

        return -1;

    }

    while(!done) {

        int idx;

        if(blocks >= s->blocks || y >= s->height)

            break;//all blocks decoded

        idx = *buf++;

        if((idx & 0xF8) == 0x70) {

            switch(idx) {

            case 0x70: //change modifier

                modifier = *buf++;

                if(modifier>1)

                    av_log(avctx, AV_LOG_INFO, "warning: modifier must be 0 or 1, got %i\n", modifier);

                break;

            case 0x71: // set uniq flag

                uniq = 1;

                break;

            case 0x72: //toggle mode

                mode = !mode;

                break;

            case 0x73: //end-of-frame

                done = 1;

                break;

            case 0x74: //skip some blocks

                skip = *buf++;

                if ((blocks + skip) >= s->blocks)

                    break;

                blocks += skip;

                x += skip * 8;

                while(x >= s->width) {

                    x -= s->width;

                    y += 8;

                }

                break;

            default:

                av_log(avctx, AV_LOG_INFO, "warning: unknown escape 0x%02X\n", idx);

            }

        } else { //handle one block

            int code;

            int cf;

            int angle = 0;

            uint8_t Y[4]; // luma samples of block

            int tx = 0, ty = 0; //coords of subblock

            int chroma = 0;

            if (mode || uniq) {

                uniq = 0;

                cf = 1;

                chroma = 0;

            } else {

                cf = 0;

                if (idx)

                    chroma = *buf++;

            }

            for (i = 0; i < 4; i++) { // for every subblock

                code = (idx >> (6 - i*2)) & 3; //extract 2 bits

                if(!code) //skip subblock

                    continue;

                if(cf)

                    chroma = *buf++;

                tx = x + block_coords[i * 2];

                ty = y + block_coords[(i * 2) + 1];

                switch(code) {

                case 1:

                    tmp = *buf++;

                    angle = angle_by_index[(tmp >> 6) & 0x3];

                    Y[0] = tmp & 0x3F;

                    Y[1] = Y[0];

                    if (angle) {

                        Y[2] = Y[0]+1;

                        if (Y[2] > 0x3F)

                            Y[2] = 0x3F;

                        Y[3] = Y[2];

                    } else {

                        Y[2] = Y[0];

                        Y[3] = Y[0];

                    }

                    break;

                case 2:

                    if (modifier) { // unpack four luma samples

                        tmp = bytestream_get_be24(&buf);

                        Y[0] = (tmp >> 18) & 0x3F;

                        Y[1] = (tmp >> 12) & 0x3F;

                        Y[2] = (tmp >> 6) & 0x3F;

                        Y[3] = tmp & 0x3F;

                        angle = 16;

                    } else { // retrieve luma samples from codebook

                        tmp = bytestream_get_be16(&buf);

                        angle = (tmp >> 12) & 0xF;

                        tmp &= 0xFFF;

                        tmp <<= 2;

                        Y[0] = s->ulti_codebook[tmp];

                        Y[1] = s->ulti_codebook[tmp + 1];

                        Y[2] = s->ulti_codebook[tmp + 2];

                        Y[3] = s->ulti_codebook[tmp + 3];

                    }

                    break;

                case 3:

                    if (modifier) { // all 16 luma samples

                        uint8_t Luma[16];

                        tmp = bytestream_get_be24(&buf);

                        Luma[0] = (tmp >> 18) & 0x3F;

                        Luma[1] = (tmp >> 12) & 0x3F;

                        Luma[2] = (tmp >> 6) & 0x3F;

                        Luma[3] = tmp & 0x3F;

                        tmp = bytestream_get_be24(&buf);

                        Luma[4] = (tmp >> 18) & 0x3F;

                        Luma[5] = (tmp >> 12) & 0x3F;

                        Luma[6] = (tmp >> 6) & 0x3F;

                        Luma[7] = tmp & 0x3F;

                        tmp = bytestream_get_be24(&buf);

                        Luma[8] = (tmp >> 18) & 0x3F;

                        Luma[9] = (tmp >> 12) & 0x3F;

                        Luma[10] = (tmp >> 6) & 0x3F;

                        Luma[11] = tmp & 0x3F;

                        tmp = bytestream_get_be24(&buf);

                        Luma[12] = (tmp >> 18) & 0x3F;

                        Luma[13] = (tmp >> 12) & 0x3F;

                        Luma[14] = (tmp >> 6) & 0x3F;

                        Luma[15] = tmp & 0x3F;

                        ulti_convert_yuv(&s->frame, tx, ty, Luma, chroma);

                    } else {

                        tmp = *buf++;

                        if(tmp & 0x80) {

                            angle = (tmp >> 4) & 0x7;

                            tmp = (tmp << 8) + *buf++;

                            Y[0] = (tmp >> 6) & 0x3F;

                            Y[1] = tmp & 0x3F;

                            Y[2] = (*buf++) & 0x3F;

                            Y[3] = (*buf++) & 0x3F;

                            ulti_grad(&s->frame, tx, ty, Y, chroma, angle); //draw block

                        } else { // some patterns

                            int f0, f1;

                            f0 = *buf++;

                            f1 = tmp;

                            Y[0] = (*buf++) & 0x3F;

                            Y[1] = (*buf++) & 0x3F;

                            ulti_pattern(&s->frame, tx, ty, f1, f0, Y[0], Y[1], chroma);

                        }

                    }

                    break;

                }

                if(code != 3)

                    ulti_grad(&s->frame, tx, ty, Y, chroma, angle); // draw block

            }

            blocks++;

                x += 8;

            if(x >= s->width) {

                x = 0;

                y += 8;

            }

        }

    }

    *data_size=sizeof(AVFrame);

    *(AVFrame*)data= s->frame;

    return buf_size;

}


int locate_option(int argc, char **argv, const OptionDef *options,

                  const char *optname)

{

    const OptionDef *po;

    int i;

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

        const char *cur_opt = argv[i];

        if (*cur_opt++ != '-')

            continue;

        po = find_option(options, cur_opt);

        if (!po->name && cur_opt[0] == 'n' && cur_opt[1] == 'o')

            po = find_option(options, cur_opt + 2);

        if ((!po->name && !strcmp(cur_opt, optname)) ||

             (po->name && !strcmp(optname, po->name)))

            return i;

        if (!po || po->flags & HAS_ARG)

            i++;

    }

    return 0;

}


iscsi_set_events(IscsiLun *iscsilun)

{

    struct iscsi_context *iscsi = iscsilun->iscsi;

    int ev = iscsi_which_events(iscsi);

    if (ev != iscsilun->events) {

        aio_set_fd_handler(iscsilun->aio_context,

                           iscsi_get_fd(iscsi),

                           (ev & POLLIN) ? iscsi_process_read : NULL,

                           (ev & POLLOUT) ? iscsi_process_write : NULL,

                           iscsilun);

        iscsilun->events = ev;

    }

    /* newer versions of libiscsi may return zero events. In this

     * case start a timer to ensure we are able to return to service

     * once this situation changes. */

    if (!ev) {

        timer_mod(iscsilun->event_timer,

                  qemu_clock_get_ms(QEMU_CLOCK_REALTIME) + EVENT_INTERVAL);

    }

}


static struct omap_watchdog_timer_s *omap_wd_timer_init(MemoryRegion *memory,

                hwaddr base,

                qemu_irq irq, omap_clk clk)

{

    struct omap_watchdog_timer_s *s = (struct omap_watchdog_timer_s *)

            g_malloc0(sizeof(struct omap_watchdog_timer_s));

    s->timer.irq = irq;

    s->timer.clk = clk;

    s->timer.timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, omap_timer_tick, &s->timer);

    omap_wd_timer_reset(s);

    omap_timer_clk_setup(&s->timer);

    memory_region_init_io(&s->iomem, NULL, &omap_wd_timer_ops, s,

                          "omap-wd-timer", 0x100);

    memory_region_add_subregion(memory, base, &s->iomem);

    return s;

}


static target_ulong h_enter(PowerPCCPU *cpu, sPAPREnvironment *spapr,

                            target_ulong opcode, target_ulong *args)

{

    CPUPPCState *env = &cpu->env;

    target_ulong flags = args[0];

    target_ulong pte_index = args[1];

    target_ulong pteh = args[2];

    target_ulong ptel = args[3];

    target_ulong page_shift = 12;

    target_ulong raddr;

    target_ulong i;

    hwaddr hpte;

    /* only handle 4k and 16M pages for now */

    if (pteh & HPTE64_V_LARGE) {

#if 0 /* We don't support 64k pages yet */

        if ((ptel & 0xf000) == 0x1000) {

            /* 64k page */

        } else

#endif

        if ((ptel & 0xff000) == 0) {

            /* 16M page */

            page_shift = 24;

            /* lowest AVA bit must be 0 for 16M pages */

            if (pteh & 0x80) {

                return H_PARAMETER;

            }

        } else {

            return H_PARAMETER;

        }

    }

    raddr = (ptel & HPTE64_R_RPN) & ~((1ULL << page_shift) - 1);

    if (raddr < spapr->ram_limit) {

        /* Regular RAM - should have WIMG=0010 */

        if ((ptel & HPTE64_R_WIMG) != HPTE64_R_M) {

            return H_PARAMETER;

        }

    } else {

        /* Looks like an IO address */

        /* FIXME: What WIMG combinations could be sensible for IO?

         * For now we allow WIMG=010x, but are there others? */

        /* FIXME: Should we check against registered IO addresses? */

        if ((ptel & (HPTE64_R_W | HPTE64_R_I | HPTE64_R_M)) != HPTE64_R_I) {

            return H_PARAMETER;

        }

    }

    pteh &= ~0x60ULL;

    if ((pte_index * HASH_PTE_SIZE_64) & ~env->htab_mask) {

        return H_PARAMETER;

    }

    if (likely((flags & H_EXACT) == 0)) {

        pte_index &= ~7ULL;

        hpte = pte_index * HASH_PTE_SIZE_64;

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

            if (i == 8) {

                return H_PTEG_FULL;

            }

            if ((ppc_hash64_load_hpte0(env, hpte) & HPTE64_V_VALID) == 0) {

                break;

            }

            hpte += HASH_PTE_SIZE_64;

        }

    } else {

        i = 0;

        hpte = pte_index * HASH_PTE_SIZE_64;

        if (ppc_hash64_load_hpte0(env, hpte) & HPTE64_V_VALID) {

            return H_PTEG_FULL;

        }

    }

    ppc_hash64_store_hpte1(env, hpte, ptel);

    /* eieio();  FIXME: need some sort of barrier for smp? */

    ppc_hash64_store_hpte0(env, hpte, pteh | HPTE64_V_HPTE_DIRTY);

    args[0] = pte_index + i;

    return H_SUCCESS;

}


static inline int asym_quant(int c, int e, int qbits)

{

    int m;

    c = (((c << e) >> (24 - qbits)) + 1) >> 1;

    m = (1 << (qbits-1));

    if (c >= m)

        c = m - 1;

    av_assert2(c >= -m);

    return c;

}


void virtqueue_get_avail_bytes(VirtQueue *vq, unsigned int *in_bytes,

                               unsigned int *out_bytes,

                               unsigned max_in_bytes, unsigned max_out_bytes)

{

    VirtIODevice *vdev = vq->vdev;

    unsigned int max, idx;

    unsigned int total_bufs, in_total, out_total;

    VRingMemoryRegionCaches *caches;

    MemoryRegionCache indirect_desc_cache = MEMORY_REGION_CACHE_INVALID;

    int64_t len = 0;

    int rc;

    if (unlikely(!vq->vring.desc)) {

        if (in_bytes) {

            *in_bytes = 0;

        }

        if (out_bytes) {

            *out_bytes = 0;

        }

        return;

    }

    rcu_read_lock();

    idx = vq->last_avail_idx;

    total_bufs = in_total = out_total = 0;

    max = vq->vring.num;

    caches = atomic_rcu_read(&vq->vring.caches);

    if (caches->desc.len < max * sizeof(VRingDesc)) {

        virtio_error(vdev, "Cannot map descriptor ring");

        goto err;

    }

    while ((rc = virtqueue_num_heads(vq, idx)) > 0) {

        MemoryRegionCache *desc_cache = &caches->desc;

        unsigned int num_bufs;

        VRingDesc desc;

        unsigned int i;

        num_bufs = total_bufs;

        if (!virtqueue_get_head(vq, idx++, &i)) {

            goto err;

        }

        vring_desc_read(vdev, &desc, desc_cache, i);

        if (desc.flags & VRING_DESC_F_INDIRECT) {

            if (desc.len % sizeof(VRingDesc)) {

                virtio_error(vdev, "Invalid size for indirect buffer table");

                goto err;

            }

            /* If we've got too many, that implies a descriptor loop. */

            if (num_bufs >= max) {

                virtio_error(vdev, "Looped descriptor");

                goto err;

            }

            /* loop over the indirect descriptor table */

            len = address_space_cache_init(&indirect_desc_cache,

                                           vdev->dma_as,

                                           desc.addr, desc.len, false);

            desc_cache = &indirect_desc_cache;

            if (len < desc.len) {

                virtio_error(vdev, "Cannot map indirect buffer");

                goto err;

            }

            max = desc.len / sizeof(VRingDesc);

            num_bufs = i = 0;

            vring_desc_read(vdev, &desc, desc_cache, i);

        }

        do {

            /* If we've got too many, that implies a descriptor loop. */

            if (++num_bufs > max) {

                virtio_error(vdev, "Looped descriptor");

                goto err;

            }

            if (desc.flags & VRING_DESC_F_WRITE) {

                in_total += desc.len;

            } else {

                out_total += desc.len;

            }

            if (in_total >= max_in_bytes && out_total >= max_out_bytes) {

                goto done;

            }

            rc = virtqueue_read_next_desc(vdev, &desc, desc_cache, max, &i);

        } while (rc == VIRTQUEUE_READ_DESC_MORE);

        if (rc == VIRTQUEUE_READ_DESC_ERROR) {

            goto err;

        }

        if (desc_cache == &indirect_desc_cache) {

            address_space_cache_destroy(&indirect_desc_cache);

            total_bufs++;

        } else {

            total_bufs = num_bufs;

        }

    }

    if (rc < 0) {

        goto err;

    }

done:

    address_space_cache_destroy(&indirect_desc_cache);

    if (in_bytes) {

        *in_bytes = in_total;

    }

    if (out_bytes) {

        *out_bytes = out_total;

    }

    rcu_read_unlock();

    return;

err:

    in_total = out_total = 0;

    goto done;

}


static inline int compress_coef(int *coefs, int num)

{

    int i, res = 0;

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

        res += coef_test_compression(coefs[i]);

    return res == num ? 1 : 0;

}


static char *sysbus_get_fw_dev_path(DeviceState *dev)

{

    SysBusDevice *s = SYS_BUS_DEVICE(dev);

    char path[40];

    int off;

    off = snprintf(path, sizeof(path), "%s", qdev_fw_name(dev));

    if (s->num_mmio) {

        snprintf(path + off, sizeof(path) - off, "@"TARGET_FMT_plx,

                 s->mmio[0].addr);

    } else if (s->num_pio) {

        snprintf(path + off, sizeof(path) - off, "@i%04x", s->pio[0]);

    }

    return g_strdup(path);

}


static void init_pipe_signaling(PCIQXLDevice *d)

{

   if (pipe(d->pipe) < 0) {

       dprint(d, 1, "%s: pipe creation failed\n", __FUNCTION__);

       return;

   }

#ifdef CONFIG_IOTHREAD

   fcntl(d->pipe[0], F_SETFL, O_NONBLOCK);

#else

   fcntl(d->pipe[0], F_SETFL, O_NONBLOCK /* | O_ASYNC */);

#endif

   fcntl(d->pipe[1], F_SETFL, O_NONBLOCK);

   fcntl(d->pipe[0], F_SETOWN, getpid());

   d->main = pthread_self();

   qemu_set_fd_handler(d->pipe[0], pipe_read, NULL, d);

}


void ff_simple_idct248_put(uint8_t *dest, int line_size, DCTELEM *block)

{

    int i;

    DCTELEM *ptr;

    /* butterfly */

    ptr = block;

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

        BF(0);

        BF(1);

        BF(2);

        BF(3);

        BF(4);

        BF(5);

        BF(6);

        BF(7);

        ptr += 2 * 8;

    }

    /* IDCT8 on each line */

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

        idctRowCondDC_8(block + i*8);

    }

    /* IDCT4 and store */

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

        idct4col_put(dest + i, 2 * line_size, block + i);

        idct4col_put(dest + line_size + i, 2 * line_size, block + 8 + i);

    }

}


static int vc1_decode_intra_block(VC1Context *v, int16_t block[64], int n,

                                  int coded, int mquant, int codingset)

{

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

    MpegEncContext *s = &v->s;

    int dc_pred_dir = 0; /* Direction of the DC prediction used */

    int i;

    int16_t *dc_val;

    int16_t *ac_val, *ac_val2;

    int dcdiff;

    int mb_pos = s->mb_x + s->mb_y * s->mb_stride;

    int a_avail = v->a_avail, c_avail = v->c_avail;

    int use_pred = s->ac_pred;

    int scale;

    int q1, q2 = 0;

    s->dsp.clear_block(block);

    /* XXX: Guard against dumb values of mquant */

    mquant = (mquant < 1) ? 0 : ((mquant > 31) ? 31 : mquant);

    /* Set DC scale - y and c use the same */

    s->y_dc_scale = s->y_dc_scale_table[mquant];

    s->c_dc_scale = s->c_dc_scale_table[mquant];

    /* Get DC differential */

    if (n < 4) {

        dcdiff = get_vlc2(&s->gb, ff_msmp4_dc_luma_vlc[s->dc_table_index].table, DC_VLC_BITS, 3);

    } else {

        dcdiff = get_vlc2(&s->gb, ff_msmp4_dc_chroma_vlc[s->dc_table_index].table, DC_VLC_BITS, 3);

    }

    if (dcdiff < 0) {

        av_log(s->avctx, AV_LOG_ERROR, "Illegal DC VLC\n");

        return -1;

    }

    if (dcdiff) {

        if (dcdiff == 119 /* ESC index value */) {

            /* TODO: Optimize */

            if (mquant == 1)      dcdiff = get_bits(gb, 10);

            else if (mquant == 2) dcdiff = get_bits(gb, 9);

            else                  dcdiff = get_bits(gb, 8);

        } else {

            if (mquant == 1)

                dcdiff = (dcdiff << 2) + get_bits(gb, 2) - 3;

            else if (mquant == 2)

                dcdiff = (dcdiff << 1) + get_bits1(gb)   - 1;

        }

        if (get_bits1(gb))

            dcdiff = -dcdiff;

    }

    /* Prediction */

    dcdiff += vc1_pred_dc(&v->s, v->overlap, mquant, n, a_avail, c_avail, &dc_val, &dc_pred_dir);

    *dc_val = dcdiff;

    /* Store the quantized DC coeff, used for prediction */

    if (n < 4) {

        block[0] = dcdiff * s->y_dc_scale;

    } else {

        block[0] = dcdiff * s->c_dc_scale;

    }

    //AC Decoding

    i = 1;

    /* check if AC is needed at all and adjust direction if needed */

    if (!a_avail) dc_pred_dir = 1;

    if (!c_avail) dc_pred_dir = 0;

    if (!a_avail && !c_avail) use_pred = 0;

    ac_val = s->ac_val[0][0] + s->block_index[n] * 16;

    ac_val2 = ac_val;

    scale = mquant * 2 + v->halfpq;

    if (dc_pred_dir) //left

        ac_val -= 16;

    else //top

        ac_val -= 16 * s->block_wrap[n];

    q1 = s->current_picture.f.qscale_table[mb_pos];

    if (dc_pred_dir && c_avail && mb_pos)

        q2 = s->current_picture.f.qscale_table[mb_pos - 1];

    if (!dc_pred_dir && a_avail && mb_pos >= s->mb_stride)

        q2 = s->current_picture.f.qscale_table[mb_pos - s->mb_stride];

    if ( dc_pred_dir && n == 1)

        q2 = q1;

    if (!dc_pred_dir && n == 2)

        q2 = q1;

    if (n == 3) q2 = q1;

    if (coded) {

        int last = 0, skip, value;

        int k;

        while (!last) {

            vc1_decode_ac_coeff(v, &last, &skip, &value, codingset);

            i += skip;

            if (i > 63)

                break;

            if (v->fcm == PROGRESSIVE)

                block[v->zz_8x8[0][i++]] = value;

            else {

                if (use_pred && (v->fcm == ILACE_FRAME)) {

                    if (!dc_pred_dir) // top

                        block[v->zz_8x8[2][i++]] = value;

                    else // left

                        block[v->zz_8x8[3][i++]] = value;

                } else {

                    block[v->zzi_8x8[i++]] = value;

                }

            }

        }

        /* apply AC prediction if needed */

        if (use_pred) {

            /* scale predictors if needed*/

            if (q2 && q1 != q2) {

                q1 = q1 * 2 + ((q1 == v->pq) ? v->halfpq : 0) - 1;

                q2 = q2 * 2 + ((q2 == v->pq) ? v->halfpq : 0) - 1;

                if (q1 < 1)

                    return AVERROR_INVALIDDATA;

                if (dc_pred_dir) { // left

                    for (k = 1; k < 8; k++)

                        block[k << v->left_blk_sh] += (ac_val[k] * q2 * ff_vc1_dqscale[q1 - 1] + 0x20000) >> 18;

                } else { //top

                    for (k = 1; k < 8; k++)

                        block[k << v->top_blk_sh] += (ac_val[k + 8] * q2 * ff_vc1_dqscale[q1 - 1] + 0x20000) >> 18;

                }

            } else {

                if (dc_pred_dir) { // left

                    for (k = 1; k < 8; k++)

                        block[k << v->left_blk_sh] += ac_val[k];

                } else { // top

                    for (k = 1; k < 8; k++)

                        block[k << v->top_blk_sh] += ac_val[k + 8];

                }

            }

        }

        /* save AC coeffs for further prediction */

        for (k = 1; k < 8; k++) {

            ac_val2[k    ] = block[k << v->left_blk_sh];

            ac_val2[k + 8] = block[k << v->top_blk_sh];

        }

        /* scale AC coeffs */

        for (k = 1; k < 64; k++)

            if (block[k]) {

                block[k] *= scale;

                if (!v->pquantizer)

                    block[k] += (block[k] < 0) ? -mquant : mquant;

            }

        if (use_pred) i = 63;

    } else { // no AC coeffs

        int k;

        memset(ac_val2, 0, 16 * 2);

        if (dc_pred_dir) { // left

            if (use_pred) {

                memcpy(ac_val2, ac_val, 8 * 2);

                if (q2 && q1 != q2) {

                    q1 = q1 * 2 + ((q1 == v->pq) ? v->halfpq : 0) - 1;

                    q2 = q2 * 2 + ((q2 == v->pq) ? v->halfpq : 0) - 1;

                    if (q1 < 1)

                        return AVERROR_INVALIDDATA;

                    for (k = 1; k < 8; k++)

                        ac_val2[k] = (ac_val2[k] * q2 * ff_vc1_dqscale[q1 - 1] + 0x20000) >> 18;

                }

            }

        } else { // top

            if (use_pred) {

                memcpy(ac_val2 + 8, ac_val + 8, 8 * 2);

                if (q2 && q1 != q2) {

                    q1 = q1 * 2 + ((q1 == v->pq) ? v->halfpq : 0) - 1;

                    q2 = q2 * 2 + ((q2 == v->pq) ? v->halfpq : 0) - 1;

                    if (q1 < 1)

                        return AVERROR_INVALIDDATA;

                    for (k = 1; k < 8; k++)

                        ac_val2[k + 8] = (ac_val2[k + 8] * q2 * ff_vc1_dqscale[q1 - 1] + 0x20000) >> 18;

                }

            }

        }

        /* apply AC prediction if needed */

        if (use_pred) {

            if (dc_pred_dir) { // left

                for (k = 1; k < 8; k++) {

                    block[k << v->left_blk_sh] = ac_val2[k] * scale;

                    if (!v->pquantizer && block[k << v->left_blk_sh])

                        block[k << v->left_blk_sh] += (block[k << v->left_blk_sh] < 0) ? -mquant : mquant;

                }

            } else { // top

                for (k = 1; k < 8; k++) {

                    block[k << v->top_blk_sh] = ac_val2[k + 8] * scale;

                    if (!v->pquantizer && block[k << v->top_blk_sh])

                        block[k << v->top_blk_sh] += (block[k << v->top_blk_sh] < 0) ? -mquant : mquant;

                }

            }

            i = 63;

        }

    }

    s->block_last_index[n] = i;

    return 0;

}


static int64_t coroutine_fn vvfat_co_get_block_status(BlockDriverState *bs,

	int64_t sector_num, int nb_sectors, int *n, BlockDriverState **file)

{

    BDRVVVFATState* s = bs->opaque;

    *n = s->sector_count - sector_num;

    if (*n > nb_sectors) {

        *n = nb_sectors;

    } else if (*n < 0) {

        return 0;

    }

    return BDRV_BLOCK_DATA;

}


static void gen_rot_rm_T1(DisasContext *s, int ot, int op1, int is_right)

{

    target_ulong mask = (ot == OT_QUAD ? 0x3f : 0x1f);

    TCGv_i32 t0, t1;

    /* load */

    if (op1 == OR_TMP0) {

        gen_op_ld_T0_A0(ot + s->mem_index);

    } else {

        gen_op_mov_TN_reg(ot, 0, op1);

    }

    tcg_gen_andi_tl(cpu_T[1], cpu_T[1], mask);

    switch (ot) {

    case OT_BYTE:

        /* Replicate the 8-bit input so that a 32-bit rotate works.  */

        tcg_gen_ext8u_tl(cpu_T[0], cpu_T[0]);

        tcg_gen_muli_tl(cpu_T[0], cpu_T[0], 0x01010101);

        goto do_long;

    case OT_WORD:

        /* Replicate the 16-bit input so that a 32-bit rotate works.  */

        tcg_gen_deposit_tl(cpu_T[0], cpu_T[0], cpu_T[0], 16, 16);

        goto do_long;

    do_long:

#ifdef TARGET_X86_64

    case OT_LONG:

        tcg_gen_trunc_tl_i32(cpu_tmp2_i32, cpu_T[0]);

        tcg_gen_trunc_tl_i32(cpu_tmp3_i32, cpu_T[1]);

        if (is_right) {

            tcg_gen_rotr_i32(cpu_tmp2_i32, cpu_tmp2_i32, cpu_tmp3_i32);

        } else {

            tcg_gen_rotl_i32(cpu_tmp2_i32, cpu_tmp2_i32, cpu_tmp3_i32);

        }

        tcg_gen_extu_i32_tl(cpu_T[0], cpu_tmp2_i32);

        break;

#endif

    default:

        if (is_right) {

            tcg_gen_rotr_tl(cpu_T[0], cpu_T[0], cpu_T[1]);

        } else {

            tcg_gen_rotl_tl(cpu_T[0], cpu_T[0], cpu_T[1]);

        }

        break;

    }

    /* store */

    if (op1 == OR_TMP0) {

        gen_op_st_T0_A0(ot + s->mem_index);

    } else {

        gen_op_mov_reg_T0(ot, op1);

    }

    /* We'll need the flags computed into CC_SRC.  */

    gen_compute_eflags(s);

    /* The value that was "rotated out" is now present at the other end

       of the word.  Compute C into CC_DST and O into CC_SRC2.  Note that

       since we've computed the flags into CC_SRC, these variables are

       currently dead.  */

    if (is_right) {

        tcg_gen_shri_tl(cpu_cc_src2, cpu_T[0], mask - 1);

        tcg_gen_shri_tl(cpu_cc_dst, cpu_T[0], mask);

    } else {

        tcg_gen_shri_tl(cpu_cc_src2, cpu_T[0], mask);

        tcg_gen_andi_tl(cpu_cc_dst, cpu_T[0], 1);

    }

    tcg_gen_andi_tl(cpu_cc_src2, cpu_cc_src2, 1);

    tcg_gen_xor_tl(cpu_cc_src2, cpu_cc_src2, cpu_cc_dst);

    /* Now conditionally store the new CC_OP value.  If the shift count

       is 0 we keep the CC_OP_EFLAGS setting so that only CC_SRC is live.

       Otherwise reuse CC_OP_ADCOX which have the C and O flags split out

       exactly as we computed above.  */

    t0 = tcg_const_i32(0);

    t1 = tcg_temp_new_i32();

    tcg_gen_trunc_tl_i32(t1, cpu_T[1]);

    tcg_gen_movi_i32(cpu_tmp2_i32, CC_OP_ADCOX);

    tcg_gen_movi_i32(cpu_tmp3_i32, CC_OP_EFLAGS);

    tcg_gen_movcond_i32(TCG_COND_NE, cpu_cc_op, t1, t0,

                        cpu_tmp2_i32, cpu_tmp3_i32);

    tcg_temp_free_i32(t0);

    tcg_temp_free_i32(t1);

    /* The CC_OP value is no longer predictable.  */

    set_cc_op(s, CC_OP_DYNAMIC);

}


int rtjpeg_decode_frame_yuv420(RTJpegContext *c, AVFrame *f,

                               const uint8_t *buf, int buf_size) {

    GetBitContext gb;

    int w = c->w / 16, h = c->h / 16;

    int x, y;

    uint8_t *y1 = f->data[0], *y2 = f->data[0] + 8 * f->linesize[0];

    uint8_t *u = f->data[1], *v = f->data[2];

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

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

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

            DCTELEM *block = c->block;

            if (get_block(&gb, block, c->scan, c->lquant) > 0)

                c->dsp->idct_put(y1, f->linesize[0], block);

            y1 += 8;

            if (get_block(&gb, block, c->scan, c->lquant) > 0)

                c->dsp->idct_put(y1, f->linesize[0], block);

            y1 += 8;

            if (get_block(&gb, block, c->scan, c->lquant) > 0)

                c->dsp->idct_put(y2, f->linesize[0], block);

            y2 += 8;

            if (get_block(&gb, block, c->scan, c->lquant) > 0)

                c->dsp->idct_put(y2, f->linesize[0], block);

            y2 += 8;

            if (get_block(&gb, block, c->scan, c->cquant) > 0)

                c->dsp->idct_put(u, f->linesize[1], block);

            u += 8;

            if (get_block(&gb, block, c->scan, c->cquant) > 0)

                c->dsp->idct_put(v, f->linesize[2], block);

            v += 8;

        }

        y1 += 2 * 8 * (f->linesize[0] - w);

        y2 += 2 * 8 * (f->linesize[0] - w);

        u += 8 * (f->linesize[1] - w);

        v += 8 * (f->linesize[2] - w);

    }

    return get_bits_count(&gb) / 8;

}


static void virgl_resource_attach_backing(VirtIOGPU *g,

                                          struct virtio_gpu_ctrl_command *cmd)

{

    struct virtio_gpu_resource_attach_backing att_rb;

    struct iovec *res_iovs;

    int ret;

    VIRTIO_GPU_FILL_CMD(att_rb);

    trace_virtio_gpu_cmd_res_back_attach(att_rb.resource_id);

    ret = virtio_gpu_create_mapping_iov(&att_rb, cmd, NULL, &res_iovs);

    if (ret != 0) {

        cmd->error = VIRTIO_GPU_RESP_ERR_UNSPEC;

        return;

    }

    virgl_renderer_resource_attach_iov(att_rb.resource_id,

                                       res_iovs, att_rb.nr_entries);

}


static int dvbsub_probe(AVProbeData *p)

{

    int i, j, k;

    const uint8_t *end = p->buf + p->buf_size;

    int type, len;

    int max_score = 0;

    for(i=0; i<p->buf_size; i++){

        if (p->buf[i] == 0x0f) {

            const uint8_t *ptr = p->buf + i;

            uint8_t histogram[6] = {0};

            int min = 255;

            for(j=0; ptr + 6 < end; j++) {

                if (*ptr != 0x0f)

                    break;

                type    = ptr[1];

                //page_id = AV_RB16(ptr + 2);

                len     = AV_RB16(ptr + 4);

                if (type == 0x80) {

                    ;

                } else if (type >= 0x10 && type <= 0x14) {

                    histogram[type - 0x10] ++;

                } else

                    break;

                ptr += 6 + len;

            }

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

                min = FFMIN(min, histogram[k]);

            }

            if (min && j > max_score)

                max_score = j;

        }

    }

    if (max_score > 5)

        return AVPROBE_SCORE_EXTENSION;

    return 0;

}


static void gen_hrfid(DisasContext *ctx)

{

#if defined(CONFIG_USER_ONLY)

    gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

#else

    /* Restore CPU state */

    if (unlikely(ctx->pr || !ctx->hv)) {

        gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

        return;

    }

    gen_helper_hrfid(cpu_env);

    gen_sync_exception(ctx);

#endif

}


static void coroutine_fn v9fs_write(void *opaque)

{

    ssize_t err;

    int32_t fid;

    uint64_t off;

    uint32_t count;

    int32_t len = 0;

    int32_t total = 0;

    size_t offset = 7;

    V9fsFidState *fidp;

    V9fsPDU *pdu = opaque;

    V9fsState *s = pdu->s;

    QEMUIOVector qiov_full;

    QEMUIOVector qiov;

    err = pdu_unmarshal(pdu, offset, "dqd", &fid, &off, &count);

    if (err < 0) {

        pdu_complete(pdu, err);

        return;

    }

    offset += err;

    v9fs_init_qiov_from_pdu(&qiov_full, pdu, offset, count, true);

    trace_v9fs_write(pdu->tag, pdu->id, fid, off, count, qiov_full.niov);

    fidp = get_fid(pdu, fid);

    if (fidp == NULL) {

        err = -EINVAL;

        goto out_nofid;

    }

    if (fidp->fid_type == P9_FID_FILE) {

        if (fidp->fs.fd == -1) {

            err = -EINVAL;

            goto out;

        }

    } else if (fidp->fid_type == P9_FID_XATTR) {

        /*

         * setxattr operation

         */

        err = v9fs_xattr_write(s, pdu, fidp, off, count,

                               qiov_full.iov, qiov_full.niov);

        goto out;

    } else {

        err = -EINVAL;

        goto out;

    }

    qemu_iovec_init(&qiov, qiov_full.niov);

    do {

        qemu_iovec_reset(&qiov);

        qemu_iovec_concat(&qiov, &qiov_full, total, qiov_full.size - total);

        if (0) {

            print_sg(qiov.iov, qiov.niov);

        }

        /* Loop in case of EINTR */

        do {

            len = v9fs_co_pwritev(pdu, fidp, qiov.iov, qiov.niov, off);

            if (len >= 0) {

                off   += len;

                total += len;

            }

        } while (len == -EINTR && !pdu->cancelled);

        if (len < 0) {

            /* IO error return the error */

            err = len;

            goto out_qiov;

        }

    } while (total < count && len > 0);

    offset = 7;

    err = pdu_marshal(pdu, offset, "d", total);

    if (err < 0) {

        goto out;

    }

    err += offset;

    trace_v9fs_write_return(pdu->tag, pdu->id, total, err);

out_qiov:

    qemu_iovec_destroy(&qiov);

out:

    put_fid(pdu, fidp);

out_nofid:

    qemu_iovec_destroy(&qiov_full);

    pdu_complete(pdu, err);

}


Qcow2Cache *qcow2_cache_create(BlockDriverState *bs, int num_tables)

{

    BDRVQcowState *s = bs->opaque;

    Qcow2Cache *c;

    int i;

    c = g_malloc0(sizeof(*c));

    c->size = num_tables;

    c->entries = g_malloc0(sizeof(*c->entries) * num_tables);

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

        c->entries[i].table = qemu_try_blockalign(bs->file, s->cluster_size);

        if (c->entries[i].table == NULL) {

            goto fail;

        }

    }

    return c;

fail:

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

        qemu_vfree(c->entries[i].table);

    }

    g_free(c->entries);

    g_free(c);

    return NULL;

}


int bdrv_commit(BlockDriverState *bs)

{

    BlockDriver *drv = bs->drv;

    int64_t sector, total_sectors;

    int n, ro, open_flags;

    int ret = 0;

    uint8_t *buf;

    char filename[1024];

    if (!drv)

        return -ENOMEDIUM;

    if (!bs->backing_hd) {

        return -ENOTSUP;

    }

    if (bdrv_in_use(bs) || bdrv_in_use(bs->backing_hd)) {

        return -EBUSY;

    }

    ro = bs->backing_hd->read_only;

    strncpy(filename, bs->backing_hd->filename, sizeof(filename));

    open_flags =  bs->backing_hd->open_flags;

    if (ro) {

        if (bdrv_reopen(bs->backing_hd, open_flags | BDRV_O_RDWR, NULL)) {

            return -EACCES;

        }

    }

    total_sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;

    buf = g_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);

    for (sector = 0; sector < total_sectors; sector += n) {

        if (bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n)) {

            if (bdrv_read(bs, sector, buf, n) != 0) {

                ret = -EIO;

                goto ro_cleanup;

            }

            if (bdrv_write(bs->backing_hd, sector, buf, n) != 0) {

                ret = -EIO;

                goto ro_cleanup;

            }

        }

    }

    if (drv->bdrv_make_empty) {

        ret = drv->bdrv_make_empty(bs);

        bdrv_flush(bs);

    }

    /*

     * Make sure all data we wrote to the backing device is actually

     * stable on disk.

     */

    if (bs->backing_hd)

        bdrv_flush(bs->backing_hd);

ro_cleanup:

    g_free(buf);

    if (ro) {

        /* ignoring error return here */

        bdrv_reopen(bs->backing_hd, open_flags & ~BDRV_O_RDWR, NULL);

    }

    return ret;

}


static int cinepak_decode (CinepakContext *s)

{

    const uint8_t  *eod = (s->data + s->size);

    int           i, result, strip_size, frame_flags, num_strips;

    int           y0 = 0;

    int           encoded_buf_size;

    if (s->size < 10)

        return -1;

    frame_flags = s->data[0];

    num_strips  = AV_RB16 (&s->data[8]);

    encoded_buf_size = ((s->data[1] << 16) | AV_RB16 (&s->data[2]));

    /* if this is the first frame, check for deviant Sega FILM data */

    if (s->sega_film_skip_bytes == -1) {

        if (encoded_buf_size != s->size) {

            /* If the encoded frame size differs from the frame size as indicated

             * by the container file, this data likely comes from a Sega FILM/CPK file.

             * If the frame header is followed by the bytes FE 00 00 06 00 00 then

             * this is probably one of the two known files that have 6 extra bytes

             * after the frame header. Else, assume 2 extra bytes. */

            if ((s->data[10] == 0xFE) &&

                (s->data[11] == 0x00) &&

                (s->data[12] == 0x00) &&

                (s->data[13] == 0x06) &&

                (s->data[14] == 0x00) &&

                (s->data[15] == 0x00))

                s->sega_film_skip_bytes = 6;

            else

                s->sega_film_skip_bytes = 2;

        } else

            s->sega_film_skip_bytes = 0;

    }

    s->data += 10 + s->sega_film_skip_bytes;

    if (num_strips > MAX_STRIPS)

        num_strips = MAX_STRIPS;

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

        if ((s->data + 12) > eod)

            return -1;

        s->strips[i].id = s->data[0];

        s->strips[i].y1 = y0;

        s->strips[i].x1 = 0;

        s->strips[i].y2 = y0 + AV_RB16 (&s->data[8]);

        s->strips[i].x2 = s->avctx->width;

        strip_size = AV_RB24 (&s->data[1]) - 12;

        s->data   += 12;

        strip_size = ((s->data + strip_size) > eod) ? (eod - s->data) : strip_size;

        if ((i > 0) && !(frame_flags & 0x01)) {

            memcpy (s->strips[i].v4_codebook, s->strips[i-1].v4_codebook,

                sizeof(s->strips[i].v4_codebook));

            memcpy (s->strips[i].v1_codebook, s->strips[i-1].v1_codebook,

                sizeof(s->strips[i].v1_codebook));

        }

        result = cinepak_decode_strip (s, &s->strips[i], s->data, strip_size);

        if (result != 0)

            return result;

        s->data += strip_size;

        y0    = s->strips[i].y2;

    }

    return 0;

}


int ff_mpeg1_find_frame_end(ParseContext *pc, const uint8_t *buf, int buf_size, AVCodecParserContext *s)

{

    int i;

    uint32_t state = pc->state;

    /* EOF considered as end of frame */

    if (buf_size == 0)

        return 0;

/*

 0  frame start         -> 1/4

 1  first_SEQEXT        -> 0/2

 2  first field start   -> 3/0

 3  second_SEQEXT       -> 2/0

 4  searching end

*/

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

        av_assert1(pc->frame_start_found >= 0 && pc->frame_start_found <= 4);

        if (pc->frame_start_found & 1) {

            if (state == EXT_START_CODE && (buf[i] & 0xF0) != 0x80)

                pc->frame_start_found--;

            else if (state == EXT_START_CODE + 2) {

                if ((buf[i] & 3) == 3)

                    pc->frame_start_found = 0;

                else

                    pc->frame_start_found = (pc->frame_start_found + 1) & 3;

            }

            state++;

        } else {

            i = avpriv_find_start_code(buf + i, buf + buf_size, &state) - buf - 1;

            if (pc->frame_start_found == 0 && state >= SLICE_MIN_START_CODE && state <= SLICE_MAX_START_CODE) {

                i++;

                pc->frame_start_found = 4;

            }

            if (state == SEQ_END_CODE) {

                pc->frame_start_found = 0;

                pc->state=-1;

                return i+1;

            }

            if (pc->frame_start_found == 2 && state == SEQ_START_CODE)

                pc->frame_start_found = 0;

            if (pc->frame_start_found  < 4 && state == EXT_START_CODE)

                pc->frame_start_found++;

            if (pc->frame_start_found == 4 && (state & 0xFFFFFF00) == 0x100) {

                if (state < SLICE_MIN_START_CODE || state > SLICE_MAX_START_CODE) {

                    pc->frame_start_found = 0;

                    pc->state             = -1;

                    return i - 3;

                }

            }

            if (pc->frame_start_found == 0 && s && state == PICTURE_START_CODE) {

                ff_fetch_timestamp(s, i - 3, 1);

            }

        }

    }

    pc->state = state;

    return END_NOT_FOUND;

}


static void dec_barrel(DisasContext *dc)

{

    TCGv t0;

    bool s, t;

    if ((dc->tb_flags & MSR_EE_FLAG)

          && (dc->cpu->env.pvr.regs[2] & PVR2_ILL_OPCODE_EXC_MASK)

          && !dc->cpu->cfg.use_barrel) {

        tcg_gen_movi_tl(cpu_SR[SR_ESR], ESR_EC_ILLEGAL_OP);

        t_gen_raise_exception(dc, EXCP_HW_EXCP);

        return;

    }

    s = extract32(dc->imm, 10, 1);

    t = extract32(dc->imm, 9, 1);

    LOG_DIS("bs%s%s r%d r%d r%d\n",

            s ? "l" : "r", t ? "a" : "l", dc->rd, dc->ra, dc->rb);

    t0 = tcg_temp_new();

    tcg_gen_mov_tl(t0, *(dec_alu_op_b(dc)));

    tcg_gen_andi_tl(t0, t0, 31);

    if (s) {

        tcg_gen_shl_tl(cpu_R[dc->rd], cpu_R[dc->ra], t0);

    } else {

        if (t) {

            tcg_gen_sar_tl(cpu_R[dc->rd], cpu_R[dc->ra], t0);

        } else {

            tcg_gen_shr_tl(cpu_R[dc->rd], cpu_R[dc->ra], t0);

        }

    }

}


static int hwmap_config_output(AVFilterLink *outlink)

{

    AVFilterContext *avctx = outlink->src;

    HWMapContext      *ctx = avctx->priv;

    AVFilterLink   *inlink = avctx->inputs[0];

    AVHWFramesContext *hwfc;

    AVBufferRef *device;

    const AVPixFmtDescriptor *desc;

    int err;

    av_log(avctx, AV_LOG_DEBUG, "Configure hwmap %s -> %s.\n",

           av_get_pix_fmt_name(inlink->format),

           av_get_pix_fmt_name(outlink->format));

    av_buffer_unref(&ctx->hwframes_ref);

    device = avctx->hw_device_ctx;

    if (inlink->hw_frames_ctx) {

        hwfc = (AVHWFramesContext*)inlink->hw_frames_ctx->data;

        if (ctx->derive_device_type) {

            enum AVHWDeviceType type;

            type = av_hwdevice_find_type_by_name(ctx->derive_device_type);

            if (type == AV_HWDEVICE_TYPE_NONE) {

                av_log(avctx, AV_LOG_ERROR, "Invalid device type.\n");

                goto fail;

            }

            err = av_hwdevice_ctx_create_derived(&device, type,

                                                 hwfc->device_ref, 0);

            if (err < 0) {

                av_log(avctx, AV_LOG_ERROR, "Failed to created derived "

                       "device context: %d.\n", err);

                goto fail;

            }

        }

        desc = av_pix_fmt_desc_get(outlink->format);

        if (!desc) {

            err = AVERROR(EINVAL);

            goto fail;

        }

        if (inlink->format == hwfc->format &&

            (desc->flags & AV_PIX_FMT_FLAG_HWACCEL)) {

            // Map between two hardware formats (including the case of

            // undoing an existing mapping).

            if (!device) {

                av_log(avctx, AV_LOG_ERROR, "A device reference is "

                       "required to map to a hardware format.\n");

                err = AVERROR(EINVAL);

                goto fail;

            }

            err = av_hwframe_ctx_create_derived(&ctx->hwframes_ref,

                                                outlink->format,

                                                device,

                                                inlink->hw_frames_ctx, 0);

            if (err < 0) {

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

                       "frames context: %d.\n", err);

                goto fail;

            }

        } else if ((outlink->format == hwfc->format &&

                    inlink->format  == hwfc->sw_format) ||

                   inlink->format == hwfc->format) {

            // Map from a hardware format to a software format, or

            // undo an existing such mapping.

            ctx->hwframes_ref = av_buffer_ref(inlink->hw_frames_ctx);

            if (!ctx->hwframes_ref) {

                err = AVERROR(ENOMEM);

                goto fail;

            }

        } else {

            // Non-matching formats - not supported.

            av_log(avctx, AV_LOG_ERROR, "Unsupported formats for "

                   "hwmap: from %s (%s) to %s.\n",

                   av_get_pix_fmt_name(inlink->format),

                   av_get_pix_fmt_name(hwfc->format),

                   av_get_pix_fmt_name(outlink->format));

            err = AVERROR(EINVAL);

            goto fail;

        }

    } else if (avctx->hw_device_ctx) {

        // Map from a software format to a hardware format.  This

        // creates a new hwframe context like hwupload, but then

        // returns frames mapped from that to the previous link in

        // order to fill them without an additional copy.

        if (!device) {

            av_log(avctx, AV_LOG_ERROR, "A device reference is "

                   "required to create new frames with backwards "

                   "mapping.\n");

            err = AVERROR(EINVAL);

            goto fail;

        }

        ctx->map_backwards = 1;

        ctx->hwframes_ref = av_hwframe_ctx_alloc(device);

        if (!ctx->hwframes_ref) {

            err = AVERROR(ENOMEM);

            goto fail;

        }

        hwfc = (AVHWFramesContext*)ctx->hwframes_ref->data;

        hwfc->format    = outlink->format;

        hwfc->sw_format = inlink->format;

        hwfc->width     = inlink->w;

        hwfc->height    = inlink->h;

        err = av_hwframe_ctx_init(ctx->hwframes_ref);

        if (err < 0) {

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

                   "context for backward mapping: %d.\n", err);

            goto fail;

        }

    } else {

        av_log(avctx, AV_LOG_ERROR, "Mapping requires a hardware "

               "context (a device, or frames on input).\n");

        return AVERROR(EINVAL);

    }

    outlink->hw_frames_ctx = av_buffer_ref(ctx->hwframes_ref);

    if (!outlink->hw_frames_ctx) {

        err = AVERROR(ENOMEM);

        goto fail;

    }

    outlink->w = inlink->w;

    outlink->h = inlink->h;

    return 0;

fail:

    av_buffer_unref(&ctx->hwframes_ref);

    return err;

}


static int ram_find_and_save_block(RAMState *rs, bool last_stage)

{

    PageSearchStatus pss;

    int pages = 0;

    bool again, found;

    ram_addr_t dirty_ram_abs; /* Address of the start of the dirty page in

                                 ram_addr_t space */

    /* No dirty page as there is zero RAM */

    if (!ram_bytes_total()) {

        return pages;

    }

    pss.block = rs->last_seen_block;

    pss.offset = rs->last_offset;

    pss.complete_round = false;

    if (!pss.block) {

        pss.block = QLIST_FIRST_RCU(&ram_list.blocks);

    }

    do {

        again = true;

        found = get_queued_page(rs, &pss, &dirty_ram_abs);

        if (!found) {

            /* priority queue empty, so just search for something dirty */

            found = find_dirty_block(rs, &pss, &again, &dirty_ram_abs);

        }

        if (found) {

            pages = ram_save_host_page(rs, &pss, last_stage, dirty_ram_abs);

        }

    } while (!pages && again);

    rs->last_seen_block = pss.block;

    rs->last_offset = pss.offset;

    return pages;

}


int msix_init(struct PCIDevice *dev, unsigned short nentries,

              MemoryRegion *table_bar, uint8_t table_bar_nr,

              unsigned table_offset, MemoryRegion *pba_bar,

              uint8_t pba_bar_nr, unsigned pba_offset, uint8_t cap_pos)

{

    int cap;

    unsigned table_size, pba_size;

    uint8_t *config;

    /* Nothing to do if MSI is not supported by interrupt controller */

    if (!msi_nonbroken) {

        return -ENOTSUP;

    }

    if (nentries < 1 || nentries > PCI_MSIX_FLAGS_QSIZE + 1) {

        return -EINVAL;

    }

    table_size = nentries * PCI_MSIX_ENTRY_SIZE;

    pba_size = QEMU_ALIGN_UP(nentries, 64) / 8;

    /* Sanity test: table & pba don't overlap, fit within BARs, min aligned */

    if ((table_bar_nr == pba_bar_nr &&

         ranges_overlap(table_offset, table_size, pba_offset, pba_size)) ||

        table_offset + table_size > memory_region_size(table_bar) ||

        pba_offset + pba_size > memory_region_size(pba_bar) ||

        (table_offset | pba_offset) & PCI_MSIX_FLAGS_BIRMASK) {

        return -EINVAL;

    }

    cap = pci_add_capability(dev, PCI_CAP_ID_MSIX, cap_pos, MSIX_CAP_LENGTH);

    if (cap < 0) {

        return cap;

    }

    dev->msix_cap = cap;

    dev->cap_present |= QEMU_PCI_CAP_MSIX;

    config = dev->config + cap;

    pci_set_word(config + PCI_MSIX_FLAGS, nentries - 1);

    dev->msix_entries_nr = nentries;

    dev->msix_function_masked = true;

    pci_set_long(config + PCI_MSIX_TABLE, table_offset | table_bar_nr);

    pci_set_long(config + PCI_MSIX_PBA, pba_offset | pba_bar_nr);

    /* Make flags bit writable. */

    dev->wmask[cap + MSIX_CONTROL_OFFSET] |= MSIX_ENABLE_MASK |

                                             MSIX_MASKALL_MASK;

    dev->msix_table = g_malloc0(table_size);

    dev->msix_pba = g_malloc0(pba_size);

    dev->msix_entry_used = g_malloc0(nentries * sizeof *dev->msix_entry_used);

    msix_mask_all(dev, nentries);

    memory_region_init_io(&dev->msix_table_mmio, OBJECT(dev), &msix_table_mmio_ops, dev,

                          "msix-table", table_size);

    memory_region_add_subregion(table_bar, table_offset, &dev->msix_table_mmio);

    memory_region_init_io(&dev->msix_pba_mmio, OBJECT(dev), &msix_pba_mmio_ops, dev,

                          "msix-pba", pba_size);

    memory_region_add_subregion(pba_bar, pba_offset, &dev->msix_pba_mmio);

    return 0;

}


static bool gen_wsr_ccount(DisasContext *dc, uint32_t sr, TCGv_i32 v)

{

    if (dc->tb->cflags & CF_USE_ICOUNT) {

        gen_io_start();

    }

    gen_helper_wsr_ccount(cpu_env, v);

    if (dc->tb->cflags & CF_USE_ICOUNT) {

        gen_io_end();

        gen_jumpi_check_loop_end(dc, 0);

        return true;

    }

    return false;

}


static void common_unbind(struct common *c)

{

    xen_be_unbind_evtchn(&c->xendev);

    if (c->page) {

	munmap(c->page, XC_PAGE_SIZE);

	c->page = NULL;

    }

}


static int ape_tag_read_field(AVFormatContext *s)

{

    AVIOContext *pb = s->pb;

    uint8_t key[1024], *value;

    uint32_t size, flags;

    int i, c;

    size = avio_rl32(pb);  /* field size */

    flags = avio_rl32(pb); /* field flags */

    for (i = 0; i < sizeof(key) - 1; i++) {

        c = avio_r8(pb);

        if (c < 0x20 || c > 0x7E)

            break;

        else

            key[i] = c;

    }

    key[i] = 0;

    if (c != 0) {

        av_log(s, AV_LOG_WARNING, "Invalid APE tag key '%s'.\n", key);

        return -1;

    }

    if (size >= UINT_MAX)

        return -1;

    if (flags & APE_TAG_FLAG_IS_BINARY) {

        uint8_t filename[1024];

        AVStream *st = avformat_new_stream(s, NULL);

        if (!st)

            return AVERROR(ENOMEM);

        avio_get_str(pb, INT_MAX, filename, sizeof(filename));

        st->codec->extradata = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);

        if (!st->codec->extradata)

            return AVERROR(ENOMEM);

        if (avio_read(pb, st->codec->extradata, size) != size) {

            av_freep(&st->codec->extradata);

            return AVERROR(EIO);

        }

        st->codec->extradata_size = size;

        av_dict_set(&st->metadata, key, filename, 0);

        st->codec->codec_type = AVMEDIA_TYPE_ATTACHMENT;

    } else {

        value = av_malloc(size+1);

        if (!value)

            return AVERROR(ENOMEM);

        c = avio_read(pb, value, size);

        if (c < 0)

            return c;

        value[c] = 0;

        av_dict_set(&s->metadata, key, value, AV_DICT_DONT_STRDUP_VAL);

    }

    return 0;

}