static av_cold int split_init(AVFilterContext *ctx)

{

    SplitContext *s = ctx->priv;

    int i;

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

        char name[32];

        AVFilterPad pad = { 0 };

        snprintf(name, sizeof(name), "output%d", i);

        pad.type = ctx->filter->inputs[0].type;

        pad.name = av_strdup(name);

        if (!pad.name)

            return AVERROR(ENOMEM);

        ff_insert_outpad(ctx, i, &pad);

    }

    return 0;

}


static void ide_set_signature(IDEState *s)

{

    s->select &= 0xf0; /* clear head */

    /* put signature */

    s->nsector = 1;

    s->sector = 1;

    if (s->drive_kind == IDE_CD) {

        s->lcyl = 0x14;

        s->hcyl = 0xeb;

    } else if (s->bs) {

        s->lcyl = 0;

        s->hcyl = 0;

    } else {

        s->lcyl = 0xff;

        s->hcyl = 0xff;

    }

}


void isa_mmio_init(target_phys_addr_t base, target_phys_addr_t size)

{

    MemoryRegion *mr = g_malloc(sizeof(*mr));

    isa_mmio_setup(mr, size);

    memory_region_add_subregion(get_system_memory(), base, mr);

}


static int find_allocation(BlockDriverState *bs, off_t start,

                           off_t *data, off_t *hole)

{

    BDRVGlusterState *s = bs->opaque;

    off_t offs;

    if (!s->supports_seek_data) {

        return -ENOTSUP;

    }

    /*

     * SEEK_DATA cases:

     * D1. offs == start: start is in data

     * D2. offs > start: start is in a hole, next data at offs

     * D3. offs < 0, errno = ENXIO: either start is in a trailing hole

     *                              or start is beyond EOF

     *     If the latter happens, the file has been truncated behind

     *     our back since we opened it.  All bets are off then.

     *     Treating like a trailing hole is simplest.

     * D4. offs < 0, errno != ENXIO: we learned nothing

     */

    offs = glfs_lseek(s->fd, start, SEEK_DATA);

    if (offs < 0) {

        return -errno;          /* D3 or D4 */

    }

    assert(offs >= start);

    if (offs > start) {

        /* D2: in hole, next data at offs */

        *hole = start;

        *data = offs;

        return 0;

    }

    /* D1: in data, end not yet known */

    /*

     * SEEK_HOLE cases:

     * H1. offs == start: start is in a hole

     *     If this happens here, a hole has been dug behind our back

     *     since the previous lseek().

     * H2. offs > start: either start is in data, next hole at offs,

     *                   or start is in trailing hole, EOF at offs

     *     Linux treats trailing holes like any other hole: offs ==

     *     start.  Solaris seeks to EOF instead: offs > start (blech).

     *     If that happens here, a hole has been dug behind our back

     *     since the previous lseek().

     * H3. offs < 0, errno = ENXIO: start is beyond EOF

     *     If this happens, the file has been truncated behind our

     *     back since we opened it.  Treat it like a trailing hole.

     * H4. offs < 0, errno != ENXIO: we learned nothing

     *     Pretend we know nothing at all, i.e. "forget" about D1.

     */

    offs = glfs_lseek(s->fd, start, SEEK_HOLE);

    if (offs < 0) {

        return -errno;          /* D1 and (H3 or H4) */

    }

    assert(offs >= start);

    if (offs > start) {

        /*

         * D1 and H2: either in data, next hole at offs, or it was in

         * data but is now in a trailing hole.  In the latter case,

         * all bets are off.  Treating it as if it there was data all

         * the way to EOF is safe, so simply do that.

         */

        *data = start;

        *hole = offs;

        return 0;

    }

    /* D1 and H1 */

    return -EBUSY;

}


static void test_validate_struct_nested(TestInputVisitorData *data,

                                         const void *unused)

{

    UserDefTwo *udp = NULL;

    Visitor *v;

    v = validate_test_init(data, "{ 'string0': 'string0', "

                           "'dict1': { 'string1': 'string1', "

                           "'dict2': { 'userdef': { 'integer': 42, "

                           "'string': 'string' }, 'string': 'string2'}}}");

    visit_type_UserDefTwo(v, NULL, &udp, &error_abort);

    qapi_free_UserDefTwo(udp);

}


void v9fs_device_unrealize_common(V9fsState *s, Error **errp)

{

    g_free(s->ctx.fs_root);

    g_free(s->tag);

}


static int copy_moof(AVFormatContext *s, const char* infile, const char *outfile, int64_t size)

{

    AVIOContext *in, *out;

    int ret = 0;

    if ((ret = avio_open2(&in, infile, AVIO_FLAG_READ, &s->interrupt_callback, NULL)) < 0)

        return ret;

    if ((ret = avio_open2(&out, outfile, AVIO_FLAG_WRITE, &s->interrupt_callback, NULL)) < 0) {

        avio_close(in);

        return ret;

    }

    while (size > 0) {

        uint8_t buf[8192];

        int n = FFMIN(size, sizeof(buf));

        n = avio_read(in, buf, n);

        if (n <= 0) {

            ret = AVERROR(EIO);

            break;

        }

        avio_write(out, buf, n);

        size -= n;

    }

    avio_flush(out);

    avio_close(out);

    avio_close(in);

    return ret;

}


static int get_uint64_as_uint32(QEMUFile *f, void *pv, size_t size,

                                VMStateField *field)

{

    uint64_t *v = pv;

    *v = qemu_get_be32(f);

    return 0;

}


void acpi_memory_plug_cb(HotplugHandler *hotplug_dev, MemHotplugState *mem_st,

                         DeviceState *dev, Error **errp)

{

    MemStatus *mdev;

    DeviceClass *dc = DEVICE_GET_CLASS(dev);

    if (!dc->hotpluggable) {

        return;

    }

    mdev = acpi_memory_slot_status(mem_st, dev, errp);

    if (!mdev) {

        return;

    }

    mdev->dimm = dev;

    mdev->is_enabled = true;

    if (dev->hotplugged) {

        mdev->is_inserting = true;

        acpi_send_event(DEVICE(hotplug_dev), ACPI_MEMORY_HOTPLUG_STATUS);

    }

}


uint8_t *xen_map_cache(hwaddr phys_addr, hwaddr size,

                       uint8_t lock)

{

    MapCacheEntry *entry, *pentry = NULL;

    hwaddr address_index;

    hwaddr address_offset;

    hwaddr cache_size = size;

    hwaddr test_bit_size;

    bool translated = false;

tryagain:

    address_index  = phys_addr >> MCACHE_BUCKET_SHIFT;

    address_offset = phys_addr & (MCACHE_BUCKET_SIZE - 1);

    trace_xen_map_cache(phys_addr);

    /* test_bit_size is always a multiple of XC_PAGE_SIZE */

    if (size) {

        test_bit_size = size + (phys_addr & (XC_PAGE_SIZE - 1));

        if (test_bit_size % XC_PAGE_SIZE) {

            test_bit_size += XC_PAGE_SIZE - (test_bit_size % XC_PAGE_SIZE);

        }

    } else {

        test_bit_size = XC_PAGE_SIZE;

    }

    if (mapcache->last_entry != NULL &&

        mapcache->last_entry->paddr_index == address_index &&

        !lock && !size &&

        test_bits(address_offset >> XC_PAGE_SHIFT,

                  test_bit_size >> XC_PAGE_SHIFT,

                  mapcache->last_entry->valid_mapping)) {

        trace_xen_map_cache_return(mapcache->last_entry->vaddr_base + address_offset);

        return mapcache->last_entry->vaddr_base + address_offset;

    }

    /* size is always a multiple of MCACHE_BUCKET_SIZE */

    if (size) {

        cache_size = size + address_offset;

        if (cache_size % MCACHE_BUCKET_SIZE) {

            cache_size += MCACHE_BUCKET_SIZE - (cache_size % MCACHE_BUCKET_SIZE);

        }

    } else {

        cache_size = MCACHE_BUCKET_SIZE;

    }

    entry = &mapcache->entry[address_index % mapcache->nr_buckets];

    while (entry && entry->lock && entry->vaddr_base &&

            (entry->paddr_index != address_index || entry->size != cache_size ||

             !test_bits(address_offset >> XC_PAGE_SHIFT,

                 test_bit_size >> XC_PAGE_SHIFT,

                 entry->valid_mapping))) {

        pentry = entry;

        entry = entry->next;

    }

    if (!entry) {

        entry = g_malloc0(sizeof (MapCacheEntry));

        pentry->next = entry;

        xen_remap_bucket(entry, cache_size, address_index);

    } else if (!entry->lock) {

        if (!entry->vaddr_base || entry->paddr_index != address_index ||

                entry->size != cache_size ||

                !test_bits(address_offset >> XC_PAGE_SHIFT,

                    test_bit_size >> XC_PAGE_SHIFT,

                    entry->valid_mapping)) {

            xen_remap_bucket(entry, cache_size, address_index);

        }

    }

    if(!test_bits(address_offset >> XC_PAGE_SHIFT,

                test_bit_size >> XC_PAGE_SHIFT,

                entry->valid_mapping)) {

        mapcache->last_entry = NULL;

        if (!translated && mapcache->phys_offset_to_gaddr) {

            phys_addr = mapcache->phys_offset_to_gaddr(phys_addr, size, mapcache->opaque);

            translated = true;

            goto tryagain;

        }

        trace_xen_map_cache_return(NULL);

        return NULL;

    }

    mapcache->last_entry = entry;

    if (lock) {

        MapCacheRev *reventry = g_malloc0(sizeof(MapCacheRev));

        entry->lock++;

        reventry->vaddr_req = mapcache->last_entry->vaddr_base + address_offset;

        reventry->paddr_index = mapcache->last_entry->paddr_index;

        reventry->size = entry->size;

        QTAILQ_INSERT_HEAD(&mapcache->locked_entries, reventry, next);

    }

    trace_xen_map_cache_return(mapcache->last_entry->vaddr_base + address_offset);

    return mapcache->last_entry->vaddr_base + address_offset;

}


static void usb_hid_changed(HIDState *hs)

{

    USBHIDState *us = container_of(hs, USBHIDState, hid);

    us->changed = 1;

    if (us->datain) {

        us->datain(us->datain_opaque);

    }

    usb_wakeup(&us->dev);

}


static int nbd_errno_to_system_errno(int err)

{

    switch (err) {

    case NBD_SUCCESS:

        return 0;

    case NBD_EPERM:

        return EPERM;

    case NBD_EIO:

        return EIO;

    case NBD_ENOMEM:

        return ENOMEM;

    case NBD_ENOSPC:

        return ENOSPC;

    default:

        TRACE("Squashing unexpected error %d to EINVAL", err);

        /* fallthrough */

    case NBD_EINVAL:

        return EINVAL;

    }

}


static int calculate_refcounts(BlockDriverState *bs, BdrvCheckResult *res,

                               BdrvCheckMode fix, uint16_t **refcount_table,

                               int64_t *nb_clusters)

{

    BDRVQcowState *s = bs->opaque;

    int64_t i;

    QCowSnapshot *sn;

    int ret;

    *refcount_table = g_try_new0(uint16_t, *nb_clusters);

    if (*nb_clusters && *refcount_table == NULL) {

        res->check_errors++;

        return -ENOMEM;

    }

    /* header */

    ret = inc_refcounts(bs, res, *refcount_table, *nb_clusters,

                        0, s->cluster_size);

    if (ret < 0) {

        return ret;

    }

    /* current L1 table */

    ret = check_refcounts_l1(bs, res, *refcount_table, *nb_clusters,

                             s->l1_table_offset, s->l1_size, CHECK_FRAG_INFO);

    if (ret < 0) {

        return ret;

    }

    /* snapshots */

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

        sn = s->snapshots + i;

        ret = check_refcounts_l1(bs, res, *refcount_table, *nb_clusters,

                                 sn->l1_table_offset, sn->l1_size, 0);

        if (ret < 0) {

            return ret;

        }

    }

    ret = inc_refcounts(bs, res, *refcount_table, *nb_clusters,

                        s->snapshots_offset, s->snapshots_size);

    if (ret < 0) {

        return ret;

    }

    /* refcount data */

    ret = inc_refcounts(bs, res, *refcount_table, *nb_clusters,

                        s->refcount_table_offset,

                        s->refcount_table_size * sizeof(uint64_t));

    if (ret < 0) {

        return ret;

    }

    return check_refblocks(bs, res, fix, refcount_table, nb_clusters);

}


void aio_context_setup(AioContext *ctx)

{

}


static uint64_t timer_read(void *opaque, target_phys_addr_t addr, unsigned size)

{

    LM32TimerState *s = opaque;

    uint32_t r = 0;

    addr >>= 2;

    switch (addr) {

    case R_SR:

    case R_CR:

    case R_PERIOD:

        r = s->regs[addr];

        break;

    case R_SNAPSHOT:

        r = (uint32_t)ptimer_get_count(s->ptimer);

        break;

    default:

        error_report("lm32_timer: read access to unknown register 0x"

                TARGET_FMT_plx, addr << 2);

        break;

    }

    trace_lm32_timer_memory_read(addr << 2, r);

    return r;

}


void virtio_scsi_handle_cmd_req_submit(VirtIOSCSI *s, VirtIOSCSIReq *req)

{

    SCSIRequest *sreq = req->sreq;

    if (scsi_req_enqueue(sreq)) {

        scsi_req_continue(sreq);

    }

    bdrv_io_unplug(sreq->dev->conf.bs);

    scsi_req_unref(sreq);

}


static int truespeech_decode_frame(AVCodecContext *avctx,

                void *data, int *data_size,

                AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    TSContext *c = avctx->priv_data;

    int i, j;

    short *samples = data;

    int consumed = 0;

    int16_t out_buf[240];

    int iterations;

    if (!buf_size)

        return 0;

    if (buf_size < 32) {

        av_log(avctx, AV_LOG_ERROR,

               "Too small input buffer (%d bytes), need at least 32 bytes\n", buf_size);

        return -1;

    }

    iterations = FFMIN(buf_size / 32, *data_size / 480);

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

        truespeech_read_frame(c, buf + consumed);

        consumed += 32;

        truespeech_correlate_filter(c);

        truespeech_filters_merge(c);

        memset(out_buf, 0, 240 * 2);

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

            truespeech_apply_twopoint_filter(c, i);

            truespeech_place_pulses(c, out_buf + i * 60, i);

            truespeech_update_filters(c, out_buf + i * 60, i);

            truespeech_synth(c, out_buf + i * 60, i);

        }

        truespeech_save_prevvec(c);

        /* finally output decoded frame */

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

            *samples++ = out_buf[i];

    }

    *data_size = consumed * 15;

    return consumed;

}


static int cirrus_bitblt_common_patterncopy(CirrusVGAState * s,

					    const uint8_t * src)

{

    uint8_t *dst;

    dst = s->vga.vram_ptr + (s->cirrus_blt_dstaddr & s->cirrus_addr_mask);

    if (blit_is_unsafe(s, false))

        return 0;

    (*s->cirrus_rop) (s, dst, src,

                      s->cirrus_blt_dstpitch, 0,

                      s->cirrus_blt_width, s->cirrus_blt_height);

    cirrus_invalidate_region(s, s->cirrus_blt_dstaddr,

                             s->cirrus_blt_dstpitch, s->cirrus_blt_width,

                             s->cirrus_blt_height);

    return 1;

}


static int qcow2_read_extensions(BlockDriverState *bs, uint64_t start_offset,

                                 uint64_t end_offset, void **p_feature_table,

                                 int flags, Error **errp)

{

    BDRVQcow2State *s = bs->opaque;

    QCowExtension ext;

    uint64_t offset;

    int ret;

#ifdef DEBUG_EXT

    printf("qcow2_read_extensions: start=%ld end=%ld\n", start_offset, end_offset);

#endif

    offset = start_offset;

    while (offset < end_offset) {

#ifdef DEBUG_EXT

        /* Sanity check */

        if (offset > s->cluster_size)

            printf("qcow2_read_extension: suspicious offset %lu\n", offset);

        printf("attempting to read extended header in offset %lu\n", offset);

#endif

        ret = bdrv_pread(bs->file, offset, &ext, sizeof(ext));

        if (ret < 0) {

            error_setg_errno(errp, -ret, "qcow2_read_extension: ERROR: "

                             "pread fail from offset %" PRIu64, offset);

            return 1;

        }

        be32_to_cpus(&ext.magic);

        be32_to_cpus(&ext.len);

        offset += sizeof(ext);

#ifdef DEBUG_EXT

        printf("ext.magic = 0x%x\n", ext.magic);

#endif

        if (offset > end_offset || ext.len > end_offset - offset) {

            error_setg(errp, "Header extension too large");

            return -EINVAL;

        }

        switch (ext.magic) {

        case QCOW2_EXT_MAGIC_END:

            return 0;

        case QCOW2_EXT_MAGIC_BACKING_FORMAT:

            if (ext.len >= sizeof(bs->backing_format)) {

                error_setg(errp, "ERROR: ext_backing_format: len=%" PRIu32

                           " too large (>=%zu)", ext.len,

                           sizeof(bs->backing_format));

                return 2;

            }

            ret = bdrv_pread(bs->file, offset, bs->backing_format, ext.len);

            if (ret < 0) {

                error_setg_errno(errp, -ret, "ERROR: ext_backing_format: "

                                 "Could not read format name");

                return 3;

            }

            bs->backing_format[ext.len] = '\0';

            s->image_backing_format = g_strdup(bs->backing_format);

#ifdef DEBUG_EXT

            printf("Qcow2: Got format extension %s\n", bs->backing_format);

#endif

            break;

        case QCOW2_EXT_MAGIC_FEATURE_TABLE:

            if (p_feature_table != NULL) {

                void* feature_table = g_malloc0(ext.len + 2 * sizeof(Qcow2Feature));

                ret = bdrv_pread(bs->file, offset , feature_table, ext.len);

                if (ret < 0) {

                    error_setg_errno(errp, -ret, "ERROR: ext_feature_table: "

                                     "Could not read table");

                    return ret;

                }

                *p_feature_table = feature_table;

            }

            break;

        case QCOW2_EXT_MAGIC_CRYPTO_HEADER: {

            unsigned int cflags = 0;

            if (s->crypt_method_header != QCOW_CRYPT_LUKS) {

                error_setg(errp, "CRYPTO header extension only "

                           "expected with LUKS encryption method");

                return -EINVAL;

            }

            if (ext.len != sizeof(Qcow2CryptoHeaderExtension)) {

                error_setg(errp, "CRYPTO header extension size %u, "

                           "but expected size %zu", ext.len,

                           sizeof(Qcow2CryptoHeaderExtension));

                return -EINVAL;

            }

            ret = bdrv_pread(bs->file, offset, &s->crypto_header, ext.len);

            if (ret < 0) {

                error_setg_errno(errp, -ret,

                                 "Unable to read CRYPTO header extension");

                return ret;

            }

            be64_to_cpus(&s->crypto_header.offset);

            be64_to_cpus(&s->crypto_header.length);

            if ((s->crypto_header.offset % s->cluster_size) != 0) {

                error_setg(errp, "Encryption header offset '%" PRIu64 "' is "

                           "not a multiple of cluster size '%u'",

                           s->crypto_header.offset, s->cluster_size);

                return -EINVAL;

            }

            if (flags & BDRV_O_NO_IO) {

                cflags |= QCRYPTO_BLOCK_OPEN_NO_IO;

            }

            s->crypto = qcrypto_block_open(s->crypto_opts, "encrypt.",

                                           qcow2_crypto_hdr_read_func,

                                           bs, cflags, errp);

            if (!s->crypto) {

                return -EINVAL;

            }

        }   break;

        default:

            /* unknown magic - save it in case we need to rewrite the header */

            {

                Qcow2UnknownHeaderExtension *uext;

                uext = g_malloc0(sizeof(*uext)  + ext.len);

                uext->magic = ext.magic;

                uext->len = ext.len;

                QLIST_INSERT_HEAD(&s->unknown_header_ext, uext, next);

                ret = bdrv_pread(bs->file, offset , uext->data, uext->len);

                if (ret < 0) {

                    error_setg_errno(errp, -ret, "ERROR: unknown extension: "

                                     "Could not read data");

                    return ret;

                }

            }

            break;

        }

        offset += ((ext.len + 7) & ~7);

    }

    return 0;

}


static void listener_add_address_space(MemoryListener *listener,

                                       AddressSpace *as)

{

    FlatView *view;

    FlatRange *fr;

    if (listener->address_space_filter

        && listener->address_space_filter != as) {

        return;

    }

    if (global_dirty_log) {

        if (listener->log_global_start) {

            listener->log_global_start(listener);

        }

    }

    view = as->current_map;

    FOR_EACH_FLAT_RANGE(fr, view) {

        MemoryRegionSection section = {

            .mr = fr->mr,

            .address_space = as,

            .offset_within_region = fr->offset_in_region,

            .size = fr->addr.size,

            .offset_within_address_space = int128_get64(fr->addr.start),

            .readonly = fr->readonly,

        };

        if (listener->region_add) {

            listener->region_add(listener, &section);

        }

    }

}


long do_sigreturn(CPUM68KState *env)

{

    struct target_sigframe *frame;

    abi_ulong frame_addr = env->aregs[7] - 4;

    target_sigset_t target_set;

    sigset_t set;

    int d0, i;

    if (!lock_user_struct(VERIFY_READ, frame, frame_addr, 1))

        goto badframe;

    /* set blocked signals */

    if (__get_user(target_set.sig[0], &frame->sc.sc_mask))

        goto badframe;

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

        if (__get_user(target_set.sig[i], &frame->extramask[i - 1]))

            goto badframe;

    }

    target_to_host_sigset_internal(&set, &target_set);

    sigprocmask(SIG_SETMASK, &set, NULL);

    /* restore registers */

    if (restore_sigcontext(env, &frame->sc, &d0))

        goto badframe;

    unlock_user_struct(frame, frame_addr, 0);

    return d0;

badframe:

    unlock_user_struct(frame, frame_addr, 0);

    force_sig(TARGET_SIGSEGV);

    return 0;

}


static int tcg_match_cmpi(TCGType type, tcg_target_long val)

{

    if (facilities & FACILITY_EXT_IMM) {

        /* The COMPARE IMMEDIATE instruction is available.  */

        if (type == TCG_TYPE_I32) {

            /* We have a 32-bit immediate and can compare against anything.  */

            return 1;

        } else {

            /* ??? We have no insight here into whether the comparison is

               signed or unsigned.  The COMPARE IMMEDIATE insn uses a 32-bit

               signed immediate, and the COMPARE LOGICAL IMMEDIATE insn uses

               a 32-bit unsigned immediate.  If we were to use the (semi)

               obvious "val == (int32_t)val" we would be enabling unsigned

               comparisons vs very large numbers.  The only solution is to

               take the intersection of the ranges.  */

            /* ??? Another possible solution is to simply lie and allow all

               constants here and force the out-of-range values into a temp

               register in tgen_cmp when we have knowledge of the actual

               comparison code in use.  */

            return val >= 0 && val <= 0x7fffffff;

        }

    } else {

        /* Only the LOAD AND TEST instruction is available.  */

        return val == 0;

    }

}


static inline bool vhost_needs_vring_endian(VirtIODevice *vdev)

{

    if (virtio_vdev_has_feature(vdev, VIRTIO_F_VERSION_1)) {

        return false;

    }

#ifdef TARGET_IS_BIENDIAN

#ifdef HOST_WORDS_BIGENDIAN

    return !virtio_is_big_endian(vdev);

#else

    return virtio_is_big_endian(vdev);

#endif

#else

    return false;

#endif

}


int qxl_render_cursor(PCIQXLDevice *qxl, QXLCommandExt *ext)

{

    QXLCursorCmd *cmd = qxl_phys2virt(qxl, ext->cmd.data, ext->group_id);

    QXLCursor *cursor;

    QEMUCursor *c;

    if (!cmd) {

        return 1;

    }

    if (!dpy_cursor_define_supported(qxl->vga.con)) {

        return 0;

    }

    if (qxl->debug > 1 && cmd->type != QXL_CURSOR_MOVE) {

        fprintf(stderr, "%s", __FUNCTION__);

        qxl_log_cmd_cursor(qxl, cmd, ext->group_id);

        fprintf(stderr, "\n");

    }

    switch (cmd->type) {

    case QXL_CURSOR_SET:

        cursor = qxl_phys2virt(qxl, cmd->u.set.shape, ext->group_id);

        if (!cursor) {

            return 1;

        }

        c = qxl_cursor(qxl, cursor, ext->group_id);

        if (c == NULL) {

            c = cursor_builtin_left_ptr();

        }

        qemu_mutex_lock(&qxl->ssd.lock);

        if (qxl->ssd.cursor) {

            cursor_put(qxl->ssd.cursor);

        }

        qxl->ssd.cursor = c;

        qxl->ssd.mouse_x = cmd->u.set.position.x;

        qxl->ssd.mouse_y = cmd->u.set.position.y;

        qemu_mutex_unlock(&qxl->ssd.lock);

        qemu_bh_schedule(qxl->ssd.cursor_bh);

        break;

    case QXL_CURSOR_MOVE:

        qemu_mutex_lock(&qxl->ssd.lock);

        qxl->ssd.mouse_x = cmd->u.position.x;

        qxl->ssd.mouse_y = cmd->u.position.y;

        qemu_mutex_unlock(&qxl->ssd.lock);

        qemu_bh_schedule(qxl->ssd.cursor_bh);

        break;

    }

    return 0;

}


static int decode_tile(Jpeg2000DecoderContext *s, Jpeg2000Tile *tile)

{

    int compno, reslevelno, bandno;

    int x, y, *src[4];

    uint8_t *line;

    Jpeg2000T1Context t1;

    /* Loop on tile components */

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

        Jpeg2000Component *comp     = tile->comp + compno;

        Jpeg2000CodingStyle *codsty = tile->codsty + compno;

        /* Loop on resolution levels */

        for (reslevelno = 0; reslevelno < codsty->nreslevels2decode; reslevelno++) {

            Jpeg2000ResLevel *rlevel = comp->reslevel + reslevelno;

            /* Loop on bands */

            for (bandno = 0; bandno < rlevel->nbands; bandno++) {

                int nb_precincts, precno;

                Jpeg2000Band *band = rlevel->band + bandno;

                int cblkx, cblky, cblkno=0, bandpos;

                bandpos = bandno + (reslevelno > 0);

                if (band->coord[0][0] == band->coord[0][1] || band->coord[1][0] == band->coord[1][1])

                    continue;

                nb_precincts = rlevel->num_precincts_x * rlevel->num_precincts_y;

                /* Loop on precincts */

                for (precno = 0; precno < nb_precincts; precno++) {

                    Jpeg2000Prec *prec = band->prec + precno;

                    /* Loop on codeblocks */

                    for (cblkno = 0; cblkno < prec->nb_codeblocks_width * prec->nb_codeblocks_height; cblkno++) {

                        int x, y;

                        int i, j;

                        Jpeg2000Cblk *cblk = prec->cblk + cblkno;

                        decode_cblk(s, codsty, &t1, cblk,

                                    cblk->coord[0][1] - cblk->coord[0][0],

                                    cblk->coord[1][1] - cblk->coord[1][0],

                                    bandpos);

                        /* Manage band offsets */

                        x = cblk->coord[0][0];

                        y = cblk->coord[1][0];

                        dequantization_int(x, y, cblk, comp, &t1, band);

                   } /* end cblk */

                } /*end prec */

            } /* end band */

        } /* end reslevel */

        ff_dwt_decode(&comp->dwt, comp->data);

        src[compno] = comp->data;

    } /*end comp */

    /* inverse MCT transformation */

    if (tile->codsty[0].mct)

        mct_decode(s, tile);

    if (s->precision <= 8) {

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

            y = tile->comp[compno].coord[1][0] - s->image_offset_y;

            line = s->picture->data[0] + y * s->picture->linesize[0];

            for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {

                uint8_t *dst;

                x   = tile->comp[compno].coord[0][0] - s->image_offset_x;

                dst = line + x * s->ncomponents + compno;

                for (; x < tile->comp[compno].coord[0][1] - s->image_offset_x; x += s->cdx[compno]) {

                    int val = *src[compno]++ << (8 - s->cbps[compno]);

                    val += 1 << 7;

                    val = av_clip(val, 0, (1 << 8) - 1);

                    *dst = val;

                    dst += s->ncomponents;

                }

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

            }

        }

    } else {

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

            y = tile->comp[compno].coord[1][0] - s->image_offset_y;

            line = s->picture->data[0] + y * s->picture->linesize[0];

            for (; y < tile->comp[compno].coord[1][1] - s->image_offset_y; y += s->cdy[compno]) {

                uint16_t *dst;

                x = tile->comp[compno].coord[0][0] - s->image_offset_x;

                dst = (uint16_t *)(line + (x * s->ncomponents + compno) * 2);

                for (; x < tile->comp[compno].coord[0][1] - s->image_offset_x; x += s-> cdx[compno]) {

                    int32_t val;

                    val = *src[compno]++ << (16 - s->cbps[compno]);

                    val += 1 << 15;

                    val = av_clip(val, 0, (1 << 16) - 1);

                    *dst = val;

                    dst += s->ncomponents;

                }

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

            }

        }

    }

    return 0;

}


static void omap_pwl_init(target_phys_addr_t base, struct omap_mpu_state_s *s,

                omap_clk clk)

{

    int iomemtype;

    s->pwl.base = base;

    omap_pwl_reset(s);

    iomemtype = cpu_register_io_memory(0, omap_pwl_readfn,

                    omap_pwl_writefn, s);

    cpu_register_physical_memory(s->pwl.base, 0x800, iomemtype);

    omap_clk_adduser(clk, qemu_allocate_irqs(omap_pwl_clk_update, s, 1)[0]);

}


static void virt_acpi_build_update(void *build_opaque)

{

    AcpiBuildState *build_state = build_opaque;

    AcpiBuildTables tables;

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

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

        return;

    }

    build_state->patched = true;

    acpi_build_tables_init(&tables);

    virt_acpi_build(build_state->guest_info, &tables);

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

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

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

    acpi_build_tables_cleanup(&tables, true);

}


static void uart_rx_reset(UartState *s)

{

    s->rx_wpos = 0;

    s->rx_count = 0;

    qemu_chr_accept_input(s->chr);

    s->r[R_SR] |= UART_SR_INTR_REMPTY;

    s->r[R_SR] &= ~UART_SR_INTR_RFUL;

}


static int rndis_set_response(USBNetState *s,

                rndis_set_msg_type *buf, unsigned int length)

{

    rndis_set_cmplt_type *resp =

            rndis_queue_response(s, sizeof(rndis_set_cmplt_type));

    uint32_t bufoffs, buflen;

    int ret;

    if (!resp)

        return USB_RET_STALL;

    bufoffs = le32_to_cpu(buf->InformationBufferOffset) + 8;

    buflen = le32_to_cpu(buf->InformationBufferLength);

    if (bufoffs + buflen > length)

        return USB_RET_STALL;

    ret = ndis_set(s, le32_to_cpu(buf->OID),

                    bufoffs + (uint8_t *) buf, buflen);

    resp->MessageType = cpu_to_le32(RNDIS_SET_CMPLT);

    resp->RequestID = buf->RequestID; /* Still LE in msg buffer */

    resp->MessageLength = cpu_to_le32(sizeof(rndis_set_cmplt_type));

    if (ret < 0) {

        /* OID not supported */

        resp->Status = cpu_to_le32(RNDIS_STATUS_NOT_SUPPORTED);

        return 0;

    }

    resp->Status = cpu_to_le32(RNDIS_STATUS_SUCCESS);

    return 0;

}


SwsContext *sws_alloc_context(void)

{

    SwsContext *c = av_mallocz(sizeof(SwsContext));

    c->av_class = &sws_context_class;

    av_opt_set_defaults(c);

    return c;

}


static i2c_interface *musicpal_audio_init(qemu_irq irq)

{

    AudioState *audio;

    musicpal_audio_state *s;

    i2c_interface *i2c;

    int iomemtype;

    audio = AUD_init();

    if (!audio) {

        AUD_log(audio_name, "No audio state\n");

        return NULL;

    }

    s = qemu_mallocz(sizeof(musicpal_audio_state));

    s->irq = irq;

    i2c = qemu_mallocz(sizeof(i2c_interface));

    i2c->bus = i2c_init_bus();

    i2c->current_addr = -1;

    s->wm = wm8750_init(i2c->bus, audio);

    if (!s->wm)

        return NULL;

    i2c_set_slave_address(s->wm, MP_WM_ADDR);

    wm8750_data_req_set(s->wm, audio_callback, s);

    iomemtype = cpu_register_io_memory(0, musicpal_audio_readfn,

                       musicpal_audio_writefn, s);

    cpu_register_physical_memory(MP_AUDIO_BASE, MP_AUDIO_SIZE, iomemtype);

    qemu_register_reset(musicpal_audio_reset, s);

    return i2c;

}


void bdrv_error_action(BlockDriverState *bs, BlockErrorAction action,

                       bool is_read, int error)

{

    assert(error >= 0);

    bdrv_emit_qmp_error_event(bs, QEVENT_BLOCK_IO_ERROR, action, is_read);

    if (action == BDRV_ACTION_STOP) {

        vm_stop(RUN_STATE_IO_ERROR);

        bdrv_iostatus_set_err(bs, error);

    }

}


static void ram_init(target_phys_addr_t addr, ram_addr_t RAM_size,

                     uint64_t max_mem)

{

    DeviceState *dev;

    SysBusDevice *s;

    RamDevice *d;

    /* allocate RAM */

    if ((uint64_t)RAM_size > max_mem) {

        fprintf(stderr,

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

                (unsigned int)(RAM_size / (1024 * 1024)),

                (unsigned int)(max_mem / (1024 * 1024)));

        exit(1);

    }

    dev = qdev_create(NULL, "memory");

    s = sysbus_from_qdev(dev);

    d = FROM_SYSBUS(RamDevice, s);

    d->size = RAM_size;

    qdev_init(dev);

    sysbus_mmio_map(s, 0, addr);

}


int xics_alloc_block(XICSState *icp, int src, int num, bool lsi, bool align)

{

    int i, first = -1;

    ICSState *ics = &icp->ics[src];

    assert(src == 0);

    /*

     * MSIMesage::data is used for storing VIRQ so

     * it has to be aligned to num to support multiple

     * MSI vectors. MSI-X is not affected by this.

     * The hint is used for the first IRQ, the rest should

     * be allocated continuously.

     */

    if (align) {

        assert((num == 1) || (num == 2) || (num == 4) ||

               (num == 8) || (num == 16) || (num == 32));

        first = ics_find_free_block(ics, num, num);

    } else {

        first = ics_find_free_block(ics, num, 1);

    }

    if (first >= 0) {

        for (i = first; i < first + num; ++i) {

            ics_set_irq_type(ics, i, lsi);

        }

    }

    first += ics->offset;

    trace_xics_alloc_block(src, first, num, lsi, align);

    return first;

}


void object_property_get_uint16List(Object *obj, const char *name,

                                    uint16List **list, Error **errp)

{

    StringOutputVisitor *ov;

    StringInputVisitor *iv;

    ov = string_output_visitor_new(false);

    object_property_get(obj, string_output_get_visitor(ov),

                        name, errp);

    iv = string_input_visitor_new(string_output_get_string(ov));

    visit_type_uint16List(string_input_get_visitor(iv),

                          list, NULL, errp);

    string_output_visitor_cleanup(ov);

    string_input_visitor_cleanup(iv);

}


static int raw_create(const char *filename, QEMUOptionParameter *options)

{

    int fd;

    int64_t total_size = 0;

    /* Read out options */

    while (options && options->name) {

        if (!strcmp(options->name, BLOCK_OPT_SIZE)) {

            total_size = options->value.n / 512;

        }

        options++;

    }

    fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY,

              0644);

    if (fd < 0)

        return -EIO;

    ftruncate(fd, total_size * 512);

    close(fd);

    return 0;

}


static inline void RENAME(rgb24ToUV_half)(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1, const uint8_t *src2, int width, uint32_t *unused)

{

    int i;

    assert(src1==src2);

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

        int r= src1[6*i + 0] + src1[6*i + 3];

        int g= src1[6*i + 1] + src1[6*i + 4];

        int b= src1[6*i + 2] + src1[6*i + 5];

        dstU[i]= (RU*r + GU*g + BU*b + (257<<RGB2YUV_SHIFT))>>(RGB2YUV_SHIFT+1);

        dstV[i]= (RV*r + GV*g + BV*b + (257<<RGB2YUV_SHIFT))>>(RGB2YUV_SHIFT+1);

    }

}


uint64_t qcow2_alloc_cluster_offset(BlockDriverState *bs,

                                    uint64_t offset,

                                    int n_start, int n_end,

                                    int *num, QCowL2Meta *m)

{

    BDRVQcowState *s = bs->opaque;

    int l2_index, ret;

    uint64_t l2_offset, *l2_table, cluster_offset;

    int nb_clusters, i = 0;

    QCowL2Meta *old_alloc;

    ret = get_cluster_table(bs, offset, &l2_table, &l2_offset, &l2_index);

    if (ret == 0)

        return 0;

    nb_clusters = size_to_clusters(s, n_end << 9);

    nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);

    cluster_offset = be64_to_cpu(l2_table[l2_index]);

    /* We keep all QCOW_OFLAG_COPIED clusters */

    if (cluster_offset & QCOW_OFLAG_COPIED) {

        nb_clusters = count_contiguous_clusters(nb_clusters, s->cluster_size,

                &l2_table[l2_index], 0, 0);

        cluster_offset &= ~QCOW_OFLAG_COPIED;

        m->nb_clusters = 0;

        goto out;

    }

    /* for the moment, multiple compressed clusters are not managed */

    if (cluster_offset & QCOW_OFLAG_COMPRESSED)

        nb_clusters = 1;

    /* how many available clusters ? */

    while (i < nb_clusters) {

        i += count_contiguous_clusters(nb_clusters - i, s->cluster_size,

                &l2_table[l2_index], i, 0);

        if(be64_to_cpu(l2_table[l2_index + i]))

            break;

        i += count_contiguous_free_clusters(nb_clusters - i,

                &l2_table[l2_index + i]);

        cluster_offset = be64_to_cpu(l2_table[l2_index + i]);

        if ((cluster_offset & QCOW_OFLAG_COPIED) ||

                (cluster_offset & QCOW_OFLAG_COMPRESSED))

            break;

    }

    nb_clusters = i;

    /*

     * Check if there already is an AIO write request in flight which allocates

     * the same cluster. In this case we need to wait until the previous

     * request has completed and updated the L2 table accordingly.

     */

    QLIST_FOREACH(old_alloc, &s->cluster_allocs, next_in_flight) {

        uint64_t end_offset = offset + nb_clusters * s->cluster_size;

        uint64_t old_offset = old_alloc->offset;

        uint64_t old_end_offset = old_alloc->offset +

            old_alloc->nb_clusters * s->cluster_size;

        if (end_offset < old_offset || offset > old_end_offset) {

            /* No intersection */

        } else {

            if (offset < old_offset) {

                /* Stop at the start of a running allocation */

                nb_clusters = (old_offset - offset) >> s->cluster_bits;

            } else {

                nb_clusters = 0;

            }

            if (nb_clusters == 0) {

                /* Set dependency and wait for a callback */

                m->depends_on = old_alloc;

                m->nb_clusters = 0;

                *num = 0;

                return 0;

            }

        }

    }

    if (!nb_clusters) {

        abort();

    }

    QLIST_INSERT_HEAD(&s->cluster_allocs, m, next_in_flight);

    /* allocate a new cluster */

    cluster_offset = qcow2_alloc_clusters(bs, nb_clusters * s->cluster_size);

    /* save info needed for meta data update */

    m->offset = offset;

    m->n_start = n_start;

    m->nb_clusters = nb_clusters;

out:

    m->nb_available = MIN(nb_clusters << (s->cluster_bits - 9), n_end);

    *num = m->nb_available - n_start;

    return cluster_offset;

}


void ff_xvmc_init_block(MpegEncContext *s)

{

    struct xvmc_render_state *render = (struct xvmc_render_state*)s->current_picture.data[2];

    assert(render);

    if (!render || render->magic != AV_XVMC_RENDER_MAGIC) {

        assert(0);

        return; // make sure that this is a render packet

    }

    s->block = (DCTELEM *)(render->data_blocks + render->next_free_data_block_num * 64);

}


void do_adde (void)

{

    T2 = T0;

    T0 += T1 + xer_ca;

    if (likely(!(T0 < T2 || (xer_ca == 1 && T0 == T2)))) {

        xer_ca = 0;

    } else {

        xer_ca = 1;

    }

}


static uint32_t ecc_mem_readl(void *opaque, target_phys_addr_t addr)

{

    ECCState *s = opaque;

    uint32_t ret = 0;

    switch (addr & ECC_ADDR_MASK) {

    case ECC_MER:

        ret = s->regs[0];

        DPRINTF("Read memory enable %08x\n", ret);

        break;

    case ECC_MDR:

        ret = s->regs[1];

        DPRINTF("Read memory delay %08x\n", ret);

        break;

    case ECC_MFSR:

        ret = s->regs[2];

        DPRINTF("Read memory fault status %08x\n", ret);

        break;

    case ECC_VCR:

        ret = s->regs[3];

        DPRINTF("Read slot configuration %08x\n", ret);

        break;

    case ECC_MFAR0:

        ret = s->regs[4];

        DPRINTF("Read memory fault address 0 %08x\n", ret);

        break;

    case ECC_MFAR1:

        ret = s->regs[5];

        DPRINTF("Read memory fault address 1 %08x\n", ret);

        break;

    case ECC_DR:

        ret = s->regs[6];

        DPRINTF("Read diagnostic %08x\n", ret);

        break;

    case ECC_ECR0:

        ret = s->regs[7];

        DPRINTF("Read event count 1 %08x\n", ret);

        break;

    case ECC_ECR1:

        ret = s->regs[7];

        DPRINTF("Read event count 2 %08x\n", ret);

        break;

    }

    return ret;

}


int avcodec_decode_subtitle2(AVCodecContext *avctx, AVSubtitle *sub,
                             int *got_sub_ptr,
                             AVPacket *avpkt)
{
    int i, ret = 0;
    if (!avpkt->data && avpkt->size) {
        av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");
        return AVERROR(EINVAL);
    if (!avctx->codec)
        return AVERROR(EINVAL);
    if (avctx->codec->type != AVMEDIA_TYPE_SUBTITLE) {
        av_log(avctx, AV_LOG_ERROR, "Invalid media type for subtitles\n");
        return AVERROR(EINVAL);
    *got_sub_ptr = 0;
    avcodec_get_subtitle_defaults(sub);
    if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size) {
        AVPacket pkt_recoded;
        AVPacket tmp = *avpkt;
        int did_split = av_packet_split_side_data(&tmp);
        //apply_param_change(avctx, &tmp);
        pkt_recoded = tmp;
        ret = recode_subtitle(avctx, &pkt_recoded, &tmp);
        if (ret < 0) {
            *got_sub_ptr = 0;
        } else {
            avctx->internal->pkt = &pkt_recoded;
            if (avctx->pkt_timebase.den && avpkt->pts != AV_NOPTS_VALUE)
                sub->pts = av_rescale_q(avpkt->pts,
                                        avctx->pkt_timebase, AV_TIME_BASE_Q);
            ret = avctx->codec->decode(avctx, sub, got_sub_ptr, &pkt_recoded);
            av_assert1((ret >= 0) >= !!*got_sub_ptr &&
                       !!*got_sub_ptr >= !!sub->num_rects);
            if (sub->num_rects && !sub->end_display_time && avpkt->duration &&
                avctx->pkt_timebase.num) {
                AVRational ms = { 1, 1000 };
                sub->end_display_time = av_rescale_q(avpkt->duration,
                                                     avctx->pkt_timebase, ms);
            for (i = 0; i < sub->num_rects; i++) {
                if (sub->rects[i]->ass && !utf8_check(sub->rects[i]->ass)) {
                    av_log(avctx, AV_LOG_ERROR,
                           "Invalid UTF-8 in decoded subtitles text; "
                           "maybe missing -sub_charenc option\n");
                    avsubtitle_free(sub);
                    return AVERROR_INVALIDDATA;
            if (tmp.data != pkt_recoded.data) { // did we recode?
                /* prevent from destroying side data from original packet */
                pkt_recoded.side_data = NULL;
                pkt_recoded.side_data_elems = 0;
                av_free_packet(&pkt_recoded);
            if (avctx->codec_descriptor->props & AV_CODEC_PROP_BITMAP_SUB)
                sub->format = 0;
            else if (avctx->codec_descriptor->props & AV_CODEC_PROP_TEXT_SUB)
                sub->format = 1;
            avctx->internal->pkt = NULL;
            av_packet_free_side_data(&tmp);
            if(ret == tmp.size)
                ret = avpkt->size;
        if (*got_sub_ptr)
            avctx->frame_number++;
    return ret;


static int mp_decode_frame(MPADecodeContext *s,

                           short *samples)

{

    int i, nb_frames, ch;

    short *samples_ptr;

    init_get_bits(&s->gb, s->inbuf + HEADER_SIZE,

                  s->inbuf_ptr - s->inbuf - HEADER_SIZE);

    /* skip error protection field */

    if (s->error_protection)

        get_bits(&s->gb, 16);

    dprintf("frame %d:\n", s->frame_count);

    switch(s->layer) {

    case 1:

        nb_frames = mp_decode_layer1(s);

        break;

    case 2:

        nb_frames = mp_decode_layer2(s);

        break;

    case 3:

    default:

        nb_frames = mp_decode_layer3(s);

        break;

    }

#if defined(DEBUG)

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

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

            int j;

            printf("%d-%d:", i, ch);

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

                printf(" %0.6f", (double)s->sb_samples[ch][i][j] / FRAC_ONE);

            printf("\n");

        }

    }

#endif

    /* apply the synthesis filter */

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

        samples_ptr = samples + ch;

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

            synth_filter(s, ch, samples_ptr, s->nb_channels,

                         s->sb_samples[ch][i]);

            samples_ptr += 32 * s->nb_channels;

        }

    }

#ifdef DEBUG

    s->frame_count++;

#endif

    return nb_frames * 32 * sizeof(short) * s->nb_channels;

}


static int pcm_decode_frame(AVCodecContext *avctx,

                            void *data, int *data_size,

                            const uint8_t *buf, int buf_size)

{

    PCMDecode *s = avctx->priv_data;

    int sample_size, c, n;

    short *samples;

    const uint8_t *src, *src8, *src2[MAX_CHANNELS];

    uint8_t *dstu8;

    int16_t *dst_int16_t;

    int32_t *dst_int32_t;

    int64_t *dst_int64_t;

    uint16_t *dst_uint16_t;

    uint32_t *dst_uint32_t;

    samples = data;

    src = buf;

    if (avctx->sample_fmt!=avctx->codec->sample_fmts[0]) {

        av_log(avctx, AV_LOG_ERROR, "invalid sample_fmt\n");

        return -1;

    }

    if(avctx->channels <= 0 || avctx->channels > MAX_CHANNELS){

        av_log(avctx, AV_LOG_ERROR, "PCM channels out of bounds\n");

        return -1;

    }

    sample_size = av_get_bits_per_sample(avctx->codec_id)/8;

    /* av_get_bits_per_sample returns 0 for CODEC_ID_PCM_DVD */

    if (CODEC_ID_PCM_DVD == avctx->codec_id)

        /* 2 samples are interleaved per block in PCM_DVD */

        sample_size = avctx->bits_per_coded_sample * 2 / 8;

    n = avctx->channels * sample_size;

    if(n && buf_size % n){

        av_log(avctx, AV_LOG_ERROR, "invalid PCM packet\n");

        return -1;

    }

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

    *data_size=0;

    n = buf_size/sample_size;

    switch(avctx->codec->id) {

    case CODEC_ID_PCM_U32LE:

        DECODE(uint32_t, le32, src, samples, n, 0, 0x80000000)

        break;

    case CODEC_ID_PCM_U32BE:

        DECODE(uint32_t, be32, src, samples, n, 0, 0x80000000)

        break;

    case CODEC_ID_PCM_S24LE:

        DECODE(int32_t, le24, src, samples, n, 8, 0)

        break;

    case CODEC_ID_PCM_S24BE:

        DECODE(int32_t, be24, src, samples, n, 8, 0)

        break;

    case CODEC_ID_PCM_U24LE:

        DECODE(uint32_t, le24, src, samples, n, 8, 0x800000)

        break;

    case CODEC_ID_PCM_U24BE:

        DECODE(uint32_t, be24, src, samples, n, 8, 0x800000)

        break;

    case CODEC_ID_PCM_S24DAUD:

        for(;n>0;n--) {

          uint32_t v = bytestream_get_be24(&src);

          v >>= 4; // sync flags are here

          *samples++ = ff_reverse[(v >> 8) & 0xff] +

                       (ff_reverse[v & 0xff] << 8);

        }

        break;

    case CODEC_ID_PCM_S16LE_PLANAR:

        n /= avctx->channels;

        for(c=0;c<avctx->channels;c++)

            src2[c] = &src[c*n*2];

        for(;n>0;n--)

            for(c=0;c<avctx->channels;c++)

                *samples++ = bytestream_get_le16(&src2[c]);

        src = src2[avctx->channels-1];

        break;

    case CODEC_ID_PCM_U16LE:

        DECODE(uint16_t, le16, src, samples, n, 0, 0x8000)

        break;

    case CODEC_ID_PCM_U16BE:

        DECODE(uint16_t, be16, src, samples, n, 0, 0x8000)

        break;

    case CODEC_ID_PCM_S8:

        dstu8= (uint8_t*)samples;

        for(;n>0;n--) {

            *dstu8++ = *src++ + 128;

        }

        samples= (short*)dstu8;

        break;

#if WORDS_BIGENDIAN

    case CODEC_ID_PCM_F64LE:

        DECODE(int64_t, le64, src, samples, n, 0, 0)

        break;

    case CODEC_ID_PCM_S32LE:

    case CODEC_ID_PCM_F32LE:

        DECODE(int32_t, le32, src, samples, n, 0, 0)

        break;

    case CODEC_ID_PCM_S16LE:

        DECODE(int16_t, le16, src, samples, n, 0, 0)

        break;

    case CODEC_ID_PCM_F64BE:

    case CODEC_ID_PCM_F32BE:

    case CODEC_ID_PCM_S32BE:

    case CODEC_ID_PCM_S16BE:

#else

    case CODEC_ID_PCM_F64BE:

        DECODE(int64_t, be64, src, samples, n, 0, 0)

        break;

    case CODEC_ID_PCM_F32BE:

    case CODEC_ID_PCM_S32BE:

        DECODE(int32_t, be32, src, samples, n, 0, 0)

        break;

    case CODEC_ID_PCM_S16BE:

        DECODE(int16_t, be16, src, samples, n, 0, 0)

        break;

    case CODEC_ID_PCM_F64LE:

    case CODEC_ID_PCM_F32LE:

    case CODEC_ID_PCM_S32LE:

    case CODEC_ID_PCM_S16LE:

#endif /* WORDS_BIGENDIAN */

    case CODEC_ID_PCM_U8:

        memcpy(samples, src, n*sample_size);

        src += n*sample_size;

        samples = (short*)((uint8_t*)data + n*sample_size);

        break;

    case CODEC_ID_PCM_ZORK:

        for(;n>0;n--) {

            int x= *src++;

            if(x&128) x-= 128;

            else      x = -x;

            *samples++ = x << 8;

        }

        break;

    case CODEC_ID_PCM_ALAW:

    case CODEC_ID_PCM_MULAW:

        for(;n>0;n--) {

            *samples++ = s->table[*src++];

        }

        break;

    case CODEC_ID_PCM_DVD:

        dst_int32_t = data;

        n /= avctx->channels;

        switch (avctx->bits_per_coded_sample) {

        case 20:

            while (n--) {

                c = avctx->channels;

                src8 = src + 4*c;

                while (c--) {

                    *dst_int32_t++ = (bytestream_get_be16(&src) << 16) + ((*src8   &0xf0) << 8);

                    *dst_int32_t++ = (bytestream_get_be16(&src) << 16) + ((*src8++ &0x0f) << 12);

                }

                src = src8;

            }

            break;

        case 24:

            while (n--) {

                c = avctx->channels;

                src8 = src + 4*c;

                while (c--) {

                    *dst_int32_t++ = (bytestream_get_be16(&src) << 16) + ((*src8++) << 8);

                    *dst_int32_t++ = (bytestream_get_be16(&src) << 16) + ((*src8++) << 8);

                }

                src = src8;

            }

            break;

        default:

            av_log(avctx, AV_LOG_ERROR, "PCM DVD unsupported sample depth\n");

            return -1;

            break;

        }

        samples = (short *) dst_int32_t;

        break;

    default:

        return -1;

    }

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

    return src - buf;

}


static int write_trailer(AVFormatContext *s)

{

    WVMuxContext *wc = s->priv_data;

    AVIOContext *pb = s->pb;

    ff_ape_write(s);

    if (pb->seekable) {

        avio_seek(pb, 12, SEEK_SET);

        avio_wl32(pb, wc->duration);

        avio_flush(pb);

    }

    return 0;

}


void virtio_queue_set_align(VirtIODevice *vdev, int n, int align)

{

    BusState *qbus = qdev_get_parent_bus(DEVICE(vdev));

    VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);

    /* virtio-1 compliant devices cannot change the alignment */

    if (virtio_has_feature(vdev, VIRTIO_F_VERSION_1)) {

        error_report("tried to modify queue alignment for virtio-1 device");

        return;

    }

    /* Check that the transport told us it was going to do this

     * (so a buggy transport will immediately assert rather than

     * silently failing to migrate this state)

     */

    assert(k->has_variable_vring_alignment);

    vdev->vq[n].vring.align = align;

    virtio_queue_update_rings(vdev, n);

}


static inline void RENAME(yuvPlanartouyvy)(const uint8_t *ysrc, const uint8_t *usrc, const uint8_t *vsrc, uint8_t *dst,

                                           long width, long height,

                                           long lumStride, long chromStride, long dstStride, long vertLumPerChroma)

{

    long y;

    const x86_reg chromWidth= width>>1;

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

#if COMPILE_TEMPLATE_MMX

        //FIXME handle 2 lines at once (fewer prefetches, reuse some chroma, but very likely memory-limited anyway)

        __asm__ volatile(

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

            ".p2align                   4               \n\t"

            "1:                                         \n\t"

            PREFETCH"   32(%1, %%"REG_a", 2)            \n\t"

            PREFETCH"   32(%2, %%"REG_a")               \n\t"

            PREFETCH"   32(%3, %%"REG_a")               \n\t"

            "movq         (%2, %%"REG_a"), %%mm0        \n\t" // U(0)

            "movq                   %%mm0, %%mm2        \n\t" // U(0)

            "movq         (%3, %%"REG_a"), %%mm1        \n\t" // V(0)

            "punpcklbw              %%mm1, %%mm0        \n\t" // UVUV UVUV(0)

            "punpckhbw              %%mm1, %%mm2        \n\t" // UVUV UVUV(8)

            "movq       (%1, %%"REG_a",2), %%mm3        \n\t" // Y(0)

            "movq      8(%1, %%"REG_a",2), %%mm5        \n\t" // Y(8)

            "movq                   %%mm0, %%mm4        \n\t" // Y(0)

            "movq                   %%mm2, %%mm6        \n\t" // Y(8)

            "punpcklbw              %%mm3, %%mm0        \n\t" // YUYV YUYV(0)

            "punpckhbw              %%mm3, %%mm4        \n\t" // YUYV YUYV(4)

            "punpcklbw              %%mm5, %%mm2        \n\t" // YUYV YUYV(8)

            "punpckhbw              %%mm5, %%mm6        \n\t" // YUYV YUYV(12)

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

            MOVNTQ"                 %%mm4,  8(%0, %%"REG_a", 4)     \n\t"

            MOVNTQ"                 %%mm2, 16(%0, %%"REG_a", 4)     \n\t"

            MOVNTQ"                 %%mm6, 24(%0, %%"REG_a", 4)     \n\t"

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

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

            " jb                       1b               \n\t"

            ::"r"(dst), "r"(ysrc), "r"(usrc), "r"(vsrc), "g" (chromWidth)

            : "%"REG_a

        );

#else

//FIXME adapt the Alpha ASM code from yv12->yuy2

#if HAVE_FAST_64BIT

        int i;

        uint64_t *ldst = (uint64_t *) dst;

        const uint8_t *yc = ysrc, *uc = usrc, *vc = vsrc;

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

            uint64_t k, l;

            k = uc[0] + (yc[0] << 8) +

                (vc[0] << 16) + (yc[1] << 24);

            l = uc[1] + (yc[2] << 8) +

                (vc[1] << 16) + (yc[3] << 24);

            *ldst++ = k + (l << 32);

            yc += 4;

            uc += 2;

            vc += 2;

        }

#else

        int i, *idst = (int32_t *) dst;

        const uint8_t *yc = ysrc, *uc = usrc, *vc = vsrc;

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

#if HAVE_BIGENDIAN

            *idst++ = (uc[0] << 24)+ (yc[0] << 16) +

                (vc[0] << 8) + (yc[1] << 0);

#else

            *idst++ = uc[0] + (yc[0] << 8) +

               (vc[0] << 16) + (yc[1] << 24);

#endif

            yc += 2;

            uc++;

            vc++;

        }

#endif

#endif

        if ((y&(vertLumPerChroma-1)) == vertLumPerChroma-1) {

            usrc += chromStride;

            vsrc += chromStride;

        }

        ysrc += lumStride;

        dst += dstStride;

    }

#if COMPILE_TEMPLATE_MMX

    __asm__(EMMS"       \n\t"

            SFENCE"     \n\t"

            :::"memory");

#endif

}


int qcrypto_init(Error **errp)

{

    int ret;

    ret = gnutls_global_init();

    if (ret < 0) {

        error_setg(errp,

                   "Unable to initialize GNUTLS library: %s",

                   gnutls_strerror(ret));

        return -1;

    }

#ifdef DEBUG_GNUTLS

    gnutls_global_set_log_level(10);

    gnutls_global_set_log_function(qcrypto_gnutls_log);

#endif

#ifdef CONFIG_GNUTLS_GCRYPT

    if (!gcry_check_version(GCRYPT_VERSION)) {

        error_setg(errp, "Unable to initialize gcrypt");

        return -1;

    }

#ifdef QCRYPTO_INIT_GCRYPT_THREADS

    gcry_control(GCRYCTL_SET_THREAD_CBS, &qcrypto_gcrypt_thread_impl);

#endif /* QCRYPTO_INIT_GCRYPT_THREADS */

    gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);

#endif

    return 0;

}


static void read_vec_element_i32(DisasContext *s, TCGv_i32 tcg_dest, int srcidx,

                                 int element, TCGMemOp memop)

{

    int vect_off = vec_reg_offset(srcidx, element, memop & MO_SIZE);

    switch (memop) {

    case MO_8:

        tcg_gen_ld8u_i32(tcg_dest, cpu_env, vect_off);

        break;

    case MO_16:

        tcg_gen_ld16u_i32(tcg_dest, cpu_env, vect_off);

        break;

    case MO_8|MO_SIGN:

        tcg_gen_ld8s_i32(tcg_dest, cpu_env, vect_off);

        break;

    case MO_16|MO_SIGN:

        tcg_gen_ld16s_i32(tcg_dest, cpu_env, vect_off);

        break;

    case MO_32:

    case MO_32|MO_SIGN:

        tcg_gen_ld_i32(tcg_dest, cpu_env, vect_off);

        break;

    default:

        g_assert_not_reached();

    }

}


static void vring_desc_read(VirtIODevice *vdev, VRingDesc *desc,

                            hwaddr desc_pa, int i)

{

    address_space_read(&address_space_memory, desc_pa + i * sizeof(VRingDesc),

                       MEMTXATTRS_UNSPECIFIED, (void *)desc, sizeof(VRingDesc));

    virtio_tswap64s(vdev, &desc->addr);

    virtio_tswap32s(vdev, &desc->len);

    virtio_tswap16s(vdev, &desc->flags);

    virtio_tswap16s(vdev, &desc->next);

}


static AddressSpace *q35_host_dma_iommu(PCIBus *bus, void *opaque, int devfn)

{

    IntelIOMMUState *s = opaque;

    VTDAddressSpace **pvtd_as;

    int bus_num = pci_bus_num(bus);

    assert(0 <= bus_num && bus_num <= VTD_PCI_BUS_MAX);

    assert(0 <= devfn && devfn <= VTD_PCI_DEVFN_MAX);

    pvtd_as = s->address_spaces[bus_num];

    if (!pvtd_as) {

        /* No corresponding free() */

        pvtd_as = g_malloc0(sizeof(VTDAddressSpace *) * VTD_PCI_DEVFN_MAX);

        s->address_spaces[bus_num] = pvtd_as;

    }

    if (!pvtd_as[devfn]) {

        pvtd_as[devfn] = g_malloc0(sizeof(VTDAddressSpace));

        pvtd_as[devfn]->bus_num = (uint8_t)bus_num;

        pvtd_as[devfn]->devfn = (uint8_t)devfn;

        pvtd_as[devfn]->iommu_state = s;

        pvtd_as[devfn]->context_cache_entry.context_cache_gen = 0;

        memory_region_init_iommu(&pvtd_as[devfn]->iommu, OBJECT(s),

                                 &s->iommu_ops, "intel_iommu", UINT64_MAX);

        address_space_init(&pvtd_as[devfn]->as,

                           &pvtd_as[devfn]->iommu, "intel_iommu");

    }

    return &pvtd_as[devfn]->as;

}


static inline uint64_t vmdk_find_offset_in_cluster(VmdkExtent *extent,

                                                   int64_t offset)

{

    uint64_t offset_in_cluster, extent_begin_offset, extent_relative_offset;

    uint64_t cluster_size = extent->cluster_sectors * BDRV_SECTOR_SIZE;

    extent_begin_offset =

        (extent->end_sector - extent->sectors) * BDRV_SECTOR_SIZE;

    extent_relative_offset = offset - extent_begin_offset;

    offset_in_cluster = extent_relative_offset % cluster_size;

    return offset_in_cluster;

}


static unsigned int dec_move_pr(DisasContext *dc)

{

	TCGv t0;

	DIS(fprintf (logfile, "move $p%u, $r%u\n", dc->op1, dc->op2));

	cris_cc_mask(dc, 0);

	if (dc->op2 == PR_CCS)

		cris_evaluate_flags(dc);

	t0 = tcg_temp_new(TCG_TYPE_TL);

	t_gen_mov_TN_preg(t0, dc->op2);

	cris_alu(dc, CC_OP_MOVE,

		 cpu_R[dc->op1], cpu_R[dc->op1], t0, preg_sizes[dc->op2]);

	tcg_temp_free(t0);

	return 2;

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);

    k->init = virtio_balloon_init_pci;

    k->exit = virtio_balloon_exit_pci;

    k->vendor_id = PCI_VENDOR_ID_REDHAT_QUMRANET;

    k->device_id = PCI_DEVICE_ID_VIRTIO_BALLOON;

    k->revision = VIRTIO_PCI_ABI_VERSION;

    k->class_id = PCI_CLASS_MEMORY_RAM;

    dc->alias = "virtio-balloon";

    dc->reset = virtio_pci_reset;

    dc->props = virtio_balloon_properties;

}


static int fetch_active_ports_list(QEMUFile *f,

                                   VirtIOSerial *s, uint32_t nr_active_ports)

{

    uint32_t i;

    s->post_load = g_malloc0(sizeof(*s->post_load));

    s->post_load->nr_active_ports = nr_active_ports;

    s->post_load->connected =

        g_malloc0(sizeof(*s->post_load->connected) * nr_active_ports);

    s->post_load->timer = timer_new_ns(QEMU_CLOCK_VIRTUAL,

                                            virtio_serial_post_load_timer_cb,

                                            s);

    /* Items in struct VirtIOSerialPort */

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

        VirtIOSerialPort *port;

        uint32_t elem_popped;

        uint32_t id;

        id = qemu_get_be32(f);

        port = find_port_by_id(s, id);

        if (!port) {

            return -EINVAL;

        }

        port->guest_connected = qemu_get_byte(f);

        s->post_load->connected[i].port = port;

        s->post_load->connected[i].host_connected = qemu_get_byte(f);

        qemu_get_be32s(f, &elem_popped);

        if (elem_popped) {

            qemu_get_be32s(f, &port->iov_idx);

            qemu_get_be64s(f, &port->iov_offset);

            port->elem =

                qemu_get_virtqueue_element(f, sizeof(VirtQueueElement));

            /*

             *  Port was throttled on source machine.  Let's

             *  unthrottle it here so data starts flowing again.

             */

            virtio_serial_throttle_port(port, false);

        }

    }

    timer_mod(s->post_load->timer, 1);

    return 0;

}


void HELPER(ucf64_cmps)(float32 a, float32 b, uint32_t c, CPUUniCore32State *env)

{

    int flag;

    flag = float32_compare_quiet(a, b, &env->ucf64.fp_status);

    env->CF = 0;

    switch (c & 0x7) {

    case 0: /* F */

        break;

    case 1: /* UN */

        if (flag == 2) {

            env->CF = 1;

        }

        break;

    case 2: /* EQ */

        if (flag == 0) {

            env->CF = 1;

        }

        break;

    case 3: /* UEQ */

        if ((flag == 0) || (flag == 2)) {

            env->CF = 1;

        }

        break;

    case 4: /* OLT */

        if (flag == -1) {

            env->CF = 1;

        }

        break;

    case 5: /* ULT */

        if ((flag == -1) || (flag == 2)) {

            env->CF = 1;

        }

        break;

    case 6: /* OLE */

        if ((flag == -1) || (flag == 0)) {

            env->CF = 1;

        }

        break;

    case 7: /* ULE */

        if (flag != 1) {

            env->CF = 1;

        }

        break;

    }

    env->ucf64.xregs[UC32_UCF64_FPSCR] = (env->CF << 29)

                    | (env->ucf64.xregs[UC32_UCF64_FPSCR] & 0x0fffffff);

}


static void RENAME(yuv2yuyv422_2)(SwsContext *c, const uint16_t *buf0,

                                  const uint16_t *buf1, const uint16_t *ubuf0,

                                  const uint16_t *ubuf1, const uint16_t *vbuf0,

                                  const uint16_t *vbuf1, const uint16_t *abuf0,

                                  const uint16_t *abuf1, uint8_t *dest,

                                  int dstW, int yalpha, int uvalpha, int y)

{

    //Note 8280 == DSTW_OFFSET but the preprocessor can't handle that there :(

    __asm__ volatile(

        "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"

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

        "push %%"REG_BP"                        \n\t"

        YSCALEYUV2PACKED(%%REGBP, %5)

        WRITEYUY2(%%REGb, 8280(%5), %%REGBP)

        "pop %%"REG_BP"                         \n\t"

        "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"

        :: "c" (buf0), "d" (buf1), "S" (ubuf0), "D" (ubuf1), "m" (dest),

           "a" (&c->redDither)

    );

}


static int scsi_disk_emulate_start_stop(SCSIDiskReq *r)

{

    SCSIRequest *req = &r->req;

    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, req->dev);

    bool start = req->cmd.buf[4] & 1;

    bool loej = req->cmd.buf[4] & 2; /* load on start, eject on !start */

    if (s->qdev.type == TYPE_ROM && loej) {

        if (!start && !s->tray_open && s->tray_locked) {

            scsi_check_condition(r,

                                 bdrv_is_inserted(s->qdev.conf.bs)

                                 ? SENSE_CODE(ILLEGAL_REQ_REMOVAL_PREVENTED)

                                 : SENSE_CODE(NOT_READY_REMOVAL_PREVENTED));

            return -1;

        }

        if (s->tray_open != !start) {

            bdrv_eject(s->qdev.conf.bs, !start);

            s->tray_open = !start;

        }

    }

    return 0;

}


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

{

    printf("ECC: Unsupported write 0x" TARGET_FMT_plx " %04x\n",

           addr, val & 0xffff);

}


int kvm_arch_debug(struct kvm_debug_exit_arch *arch_info)

{

    int handle = 0;

    int n;

    if (arch_info->exception == 1) {

        if (arch_info->dr6 & (1 << 14)) {

            if (cpu_single_env->singlestep_enabled)

                handle = 1;

        } else {

            for (n = 0; n < 4; n++)

                if (arch_info->dr6 & (1 << n))

                    switch ((arch_info->dr7 >> (16 + n*4)) & 0x3) {

                    case 0x0:

                        handle = 1;

                        break;

                    case 0x1:

                        handle = 1;

                        cpu_single_env->watchpoint_hit = &hw_watchpoint;

                        hw_watchpoint.vaddr = hw_breakpoint[n].addr;

                        hw_watchpoint.flags = BP_MEM_WRITE;

                        break;

                    case 0x3:

                        handle = 1;

                        cpu_single_env->watchpoint_hit = &hw_watchpoint;

                        hw_watchpoint.vaddr = hw_breakpoint[n].addr;

                        hw_watchpoint.flags = BP_MEM_ACCESS;

                        break;

                    }

        }

    } else if (kvm_find_sw_breakpoint(cpu_single_env, arch_info->pc))

        handle = 1;

    if (!handle) {

        cpu_synchronize_state(cpu_single_env);

        assert(cpu_single_env->exception_injected == -1);

        cpu_single_env->exception_injected = arch_info->exception;

        cpu_single_env->has_error_code = 0;

    }

    return handle;

}


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

                                 Error **errp)

{

    ChardevStdio *stdio;

    stdio = backend->u.stdio = g_new0(ChardevStdio, 1);

    qemu_chr_parse_common(opts, qapi_ChardevStdio_base(stdio));

    stdio->has_signal = true;

    stdio->signal = qemu_opt_get_bool(opts, "signal", true);

}


static void mirror_complete(BlockJob *job, Error **errp)

{

    MirrorBlockJob *s = container_of(job, MirrorBlockJob, common);

    Error *local_err = NULL;

    int ret;

    ret = bdrv_open_backing_file(s->target, NULL, &local_err);

    if (ret < 0) {

        error_propagate(errp, local_err);

        return;

    }

    if (!s->synced) {

        error_setg(errp, QERR_BLOCK_JOB_NOT_READY,

                   bdrv_get_device_name(job->bs));

        return;

    }

    /* check the target bs is not blocked and block all operations on it */

    if (s->replaces) {

        AioContext *replace_aio_context;

        s->to_replace = check_to_replace_node(s->replaces, &local_err);

        if (!s->to_replace) {

            error_propagate(errp, local_err);

            return;

        }

        replace_aio_context = bdrv_get_aio_context(s->to_replace);

        aio_context_acquire(replace_aio_context);

        error_setg(&s->replace_blocker,

                   "block device is in use by block-job-complete");

        bdrv_op_block_all(s->to_replace, s->replace_blocker);

        bdrv_ref(s->to_replace);

        aio_context_release(replace_aio_context);

    }

    s->should_complete = true;

    block_job_enter(&s->common);

}


static bool scsi_target_emulate_inquiry(SCSITargetReq *r)

{

    assert(r->req.dev->lun != r->req.lun);

    scsi_target_alloc_buf(&r->req, SCSI_INQUIRY_LEN);

    if (r->req.cmd.buf[1] & 0x2) {

        /* Command support data - optional, not implemented */

        return false;

    }

    if (r->req.cmd.buf[1] & 0x1) {

        /* Vital product data */

        uint8_t page_code = r->req.cmd.buf[2];

        r->buf[r->len++] = page_code ; /* this page */

        r->buf[r->len++] = 0x00;

        switch (page_code) {

        case 0x00: /* Supported page codes, mandatory */

        {

            int pages;

            pages = r->len++;

            r->buf[r->len++] = 0x00; /* list of supported pages (this page) */

            r->buf[pages] = r->len - pages - 1; /* number of pages */

            break;

        }

        default:

            return false;

        }

        /* done with EVPD */

        assert(r->len < r->buf_len);

        r->len = MIN(r->req.cmd.xfer, r->len);

        return true;

    }

    /* Standard INQUIRY data */

    if (r->req.cmd.buf[2] != 0) {

        return false;

    }

    /* PAGE CODE == 0 */

    r->len = MIN(r->req.cmd.xfer, SCSI_INQUIRY_LEN);

    memset(r->buf, 0, r->len);

    if (r->req.lun != 0) {

        r->buf[0] = TYPE_NO_LUN;

    } else {

        r->buf[0] = TYPE_NOT_PRESENT | TYPE_INACTIVE;

        r->buf[2] = 5; /* Version */

        r->buf[3] = 2 | 0x10; /* HiSup, response data format */

        r->buf[4] = r->len - 5; /* Additional Length = (Len - 1) - 4 */

        r->buf[7] = 0x10 | (r->req.bus->info->tcq ? 0x02 : 0); /* Sync, TCQ.  */

        memcpy(&r->buf[8], "QEMU    ", 8);

        memcpy(&r->buf[16], "QEMU TARGET     ", 16);

        pstrcpy((char *) &r->buf[32], 4, qemu_get_version());

    }

    return true;

}


void OPPROTO op_movl_npc_T0(void)

{

    env->npc = T0;

}


void ff_aac_search_for_tns(AACEncContext *s, SingleChannelElement *sce)

{

    TemporalNoiseShaping *tns = &sce->tns;

    int w, g, order, sfb_start, sfb_len, coef_start, shift[MAX_LPC_ORDER], count = 0;

    const int is8 = sce->ics.window_sequence[0] == EIGHT_SHORT_SEQUENCE;

    const int tns_max_order = is8 ? 7 : s->profile == FF_PROFILE_AAC_LOW ? 12 : TNS_MAX_ORDER;

    const float freq_mult = mpeg4audio_sample_rates[s->samplerate_index]/(1024.0f/sce->ics.num_windows)/2.0f;

    float max_coef = 0.0f;

    sce->tns.present = 0;

    return;

    for (coef_start = 0; coef_start < 1024; coef_start++)

        max_coef = FFMAX(max_coef, sce->pcoeffs[coef_start]);

    for (w = 0; w < sce->ics.num_windows; w++) {

        int filters = 1, start = 0, coef_len = 0;

        int32_t conv_coeff[1024] = {0};

        int32_t coefs_t[MAX_LPC_ORDER][MAX_LPC_ORDER] = {{0}};

        /* Determine start sfb + coef - excludes anything below threshold */

        for (g = 0;  g < sce->ics.num_swb; g++) {

            if (start*freq_mult > TNS_LOW_LIMIT) {

                sfb_start = w*16+g;

                sfb_len   = (w+1)*16 + g - sfb_start;

                coef_start = sce->ics.swb_offset[sfb_start];

                coef_len  = sce->ics.swb_offset[sfb_start + sfb_len] - coef_start;

                break;

            }

            start += sce->ics.swb_sizes[g];

        }

        if (coef_len <= 0)

            continue;

        conv_to_int32(conv_coeff, &sce->pcoeffs[coef_start], coef_len, max_coef);

        /* LPC */

        order = ff_lpc_calc_coefs(&s->lpc, conv_coeff, coef_len,

                                  TNS_MIN_PRED_ORDER, tns_max_order,

                                  32, coefs_t, shift,

                                  FF_LPC_TYPE_LEVINSON, 10,

                                  ORDER_METHOD_EST, MAX_LPC_SHIFT, 0) - 1;

        /* Works surprisingly well, remember to tweak MAX_LPC_SHIFT if you want to play around with this */

        if (shift[order] > 3) {

            int direction = 0;

            float tns_coefs_raw[TNS_MAX_ORDER];

            tns->n_filt[w] = filters++;

            conv_to_float(tns_coefs_raw, coefs_t[order], order);

            for (g = 0; g < tns->n_filt[w]; g++) {

                process_tns_coeffs(tns, tns_coefs_raw, order, w, g);

                apply_tns_filter(&sce->coeffs[coef_start], sce->pcoeffs, order, direction, tns->coef[w][g],

                                 sce->ics.ltp.present, w, g, coef_start, coef_len);

                tns->order[w][g]     = order;

                tns->length[w][g]    = sfb_len;

                tns->direction[w][g] = direction;

            }

            count++;

        }

    }

    sce->tns.present = !!count;

}


int ff_lock_avcodec(AVCodecContext *log_ctx, const AVCodec *codec)

{

    _Bool exp = 0;

    if (codec->caps_internal & FF_CODEC_CAP_INIT_THREADSAFE || !codec->init)

        return 0;

    if (lockmgr_cb) {

        if ((*lockmgr_cb)(&codec_mutex, AV_LOCK_OBTAIN))

            return -1;

    }

    if (atomic_fetch_add(&entangled_thread_counter, 1)) {

        av_log(log_ctx, AV_LOG_ERROR,

               "Insufficient thread locking. At least %d threads are "

               "calling avcodec_open2() at the same time right now.\n",

               atomic_load(&entangled_thread_counter));

        if (!lockmgr_cb)

            av_log(log_ctx, AV_LOG_ERROR, "No lock manager is set, please see av_lockmgr_register()\n");

        atomic_store(&ff_avcodec_locked, 1);

        ff_unlock_avcodec(codec);

        return AVERROR(EINVAL);

    }

    av_assert0(atomic_compare_exchange_strong(&ff_avcodec_locked, &exp, 1));

    return 0;

}


void FUNCC(ff_h264_idct_add)(uint8_t *_dst, int16_t *_block, int stride)

{

    int i;

    pixel *dst = (pixel*)_dst;

    dctcoef *block = (dctcoef*)_block;

    stride >>= sizeof(pixel)-1;

    block[0] += 1 << 5;

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

        const int z0=  block[i + 4*0]     +  block[i + 4*2];

        const int z1=  block[i + 4*0]     -  block[i + 4*2];

        const int z2= (block[i + 4*1]>>1) -  block[i + 4*3];

        const int z3=  block[i + 4*1]     + (block[i + 4*3]>>1);

        block[i + 4*0]= z0 + z3;

        block[i + 4*1]= z1 + z2;

        block[i + 4*2]= z1 - z2;

        block[i + 4*3]= z0 - z3;

    }

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

        const int z0=  block[0 + 4*i]     +  block[2 + 4*i];

        const int z1=  block[0 + 4*i]     -  block[2 + 4*i];

        const int z2= (block[1 + 4*i]>>1) -  block[3 + 4*i];

        const int z3=  block[1 + 4*i]     + (block[3 + 4*i]>>1);

        dst[i + 0*stride]= av_clip_pixel(dst[i + 0*stride] + ((z0 + z3) >> 6));

        dst[i + 1*stride]= av_clip_pixel(dst[i + 1*stride] + ((z1 + z2) >> 6));

        dst[i + 2*stride]= av_clip_pixel(dst[i + 2*stride] + ((z1 - z2) >> 6));

        dst[i + 3*stride]= av_clip_pixel(dst[i + 3*stride] + ((z0 - z3) >> 6));

    }

    memset(block, 0, 16 * sizeof(dctcoef));

}


static int qemu_rdma_registration_handle(QEMUFile *f, void *opaque,

                                         uint64_t flags)

{

    RDMAControlHeader reg_resp = { .len = sizeof(RDMARegisterResult),

                               .type = RDMA_CONTROL_REGISTER_RESULT,

                               .repeat = 0,

                             };

    RDMAControlHeader unreg_resp = { .len = 0,

                               .type = RDMA_CONTROL_UNREGISTER_FINISHED,

                               .repeat = 0,

                             };

    RDMAControlHeader blocks = { .type = RDMA_CONTROL_RAM_BLOCKS_RESULT,

                                 .repeat = 1 };

    QEMUFileRDMA *rfile = opaque;

    RDMAContext *rdma = rfile->rdma;

    RDMALocalBlocks *local = &rdma->local_ram_blocks;

    RDMAControlHeader head;

    RDMARegister *reg, *registers;

    RDMACompress *comp;

    RDMARegisterResult *reg_result;

    static RDMARegisterResult results[RDMA_CONTROL_MAX_COMMANDS_PER_MESSAGE];

    RDMALocalBlock *block;

    void *host_addr;

    int ret = 0;

    int idx = 0;

    int count = 0;

    int i = 0;

    CHECK_ERROR_STATE();

    do {

        DDDPRINTF("Waiting for next request %" PRIu64 "...\n", flags);

        ret = qemu_rdma_exchange_recv(rdma, &head, RDMA_CONTROL_NONE);

        if (ret < 0) {

            break;

        }

        if (head.repeat > RDMA_CONTROL_MAX_COMMANDS_PER_MESSAGE) {

            fprintf(stderr, "rdma: Too many requests in this message (%d)."

                            "Bailing.\n", head.repeat);

            ret = -EIO;

            break;

        }

        switch (head.type) {

        case RDMA_CONTROL_COMPRESS:

            comp = (RDMACompress *) rdma->wr_data[idx].control_curr;

            network_to_compress(comp);

            DDPRINTF("Zapping zero chunk: %" PRId64

                    " bytes, index %d, offset %" PRId64 "\n",

                    comp->length, comp->block_idx, comp->offset);

            block = &(rdma->local_ram_blocks.block[comp->block_idx]);

            host_addr = block->local_host_addr +

                            (comp->offset - block->offset);

            ram_handle_compressed(host_addr, comp->value, comp->length);

            break;

        case RDMA_CONTROL_REGISTER_FINISHED:

            DDDPRINTF("Current registrations complete.\n");

            goto out;

        case RDMA_CONTROL_RAM_BLOCKS_REQUEST:

            DPRINTF("Initial setup info requested.\n");

            if (rdma->pin_all) {

                ret = qemu_rdma_reg_whole_ram_blocks(rdma);

                if (ret) {

                    fprintf(stderr, "rdma migration: error dest "

                                    "registering ram blocks!\n");

                    goto out;

                }

            }

            /*

             * Dest uses this to prepare to transmit the RAMBlock descriptions

             * to the source VM after connection setup.

             * Both sides use the "remote" structure to communicate and update

             * their "local" descriptions with what was sent.

             */

            for (i = 0; i < local->nb_blocks; i++) {

                rdma->block[i].remote_host_addr =

                    (uint64_t)(local->block[i].local_host_addr);

                if (rdma->pin_all) {

                    rdma->block[i].remote_rkey = local->block[i].mr->rkey;

                }

                rdma->block[i].offset = local->block[i].offset;

                rdma->block[i].length = local->block[i].length;

                remote_block_to_network(&rdma->block[i]);

            }

            blocks.len = rdma->local_ram_blocks.nb_blocks

                                                * sizeof(RDMARemoteBlock);

            ret = qemu_rdma_post_send_control(rdma,

                                        (uint8_t *) rdma->block, &blocks);

            if (ret < 0) {

                fprintf(stderr, "rdma migration: error sending remote info!\n");

                goto out;

            }

            break;

        case RDMA_CONTROL_REGISTER_REQUEST:

            DDPRINTF("There are %d registration requests\n", head.repeat);

            reg_resp.repeat = head.repeat;

            registers = (RDMARegister *) rdma->wr_data[idx].control_curr;

            for (count = 0; count < head.repeat; count++) {

                uint64_t chunk;

                uint8_t *chunk_start, *chunk_end;

                reg = &registers[count];

                network_to_register(reg);

                reg_result = &results[count];

                DDPRINTF("Registration request (%d): index %d, current_addr %"

                         PRIu64 " chunks: %" PRIu64 "\n", count,

                         reg->current_index, reg->key.current_addr, reg->chunks);

                block = &(rdma->local_ram_blocks.block[reg->current_index]);

                if (block->is_ram_block) {

                    host_addr = (block->local_host_addr +

                                (reg->key.current_addr - block->offset));

                    chunk = ram_chunk_index(block->local_host_addr,

                                            (uint8_t *) host_addr);

                } else {

                    chunk = reg->key.chunk;

                    host_addr = block->local_host_addr +

                        (reg->key.chunk * (1UL << RDMA_REG_CHUNK_SHIFT));

                }

                chunk_start = ram_chunk_start(block, chunk);

                chunk_end = ram_chunk_end(block, chunk + reg->chunks);

                if (qemu_rdma_register_and_get_keys(rdma, block,

                            (uint8_t *)host_addr, NULL, &reg_result->rkey,

                            chunk, chunk_start, chunk_end)) {

                    fprintf(stderr, "cannot get rkey!\n");

                    ret = -EINVAL;

                    goto out;

                }

                reg_result->host_addr = (uint64_t) block->local_host_addr;

                DDPRINTF("Registered rkey for this request: %x\n",

                                reg_result->rkey);

                result_to_network(reg_result);

            }

            ret = qemu_rdma_post_send_control(rdma,

                            (uint8_t *) results, &reg_resp);

            if (ret < 0) {

                fprintf(stderr, "Failed to send control buffer!\n");

                goto out;

            }

            break;

        case RDMA_CONTROL_UNREGISTER_REQUEST:

            DDPRINTF("There are %d unregistration requests\n", head.repeat);

            unreg_resp.repeat = head.repeat;

            registers = (RDMARegister *) rdma->wr_data[idx].control_curr;

            for (count = 0; count < head.repeat; count++) {

                reg = &registers[count];

                network_to_register(reg);

                DDPRINTF("Unregistration request (%d): "

                         " index %d, chunk %" PRIu64 "\n",

                         count, reg->current_index, reg->key.chunk);

                block = &(rdma->local_ram_blocks.block[reg->current_index]);

                ret = ibv_dereg_mr(block->pmr[reg->key.chunk]);

                block->pmr[reg->key.chunk] = NULL;

                if (ret != 0) {

                    perror("rdma unregistration chunk failed");

                    ret = -ret;

                    goto out;

                }

                rdma->total_registrations--;

                DDPRINTF("Unregistered chunk %" PRIu64 " successfully.\n",

                            reg->key.chunk);

            }

            ret = qemu_rdma_post_send_control(rdma, NULL, &unreg_resp);

            if (ret < 0) {

                fprintf(stderr, "Failed to send control buffer!\n");

                goto out;

            }

            break;

        case RDMA_CONTROL_REGISTER_RESULT:

            fprintf(stderr, "Invalid RESULT message at dest.\n");

            ret = -EIO;

            goto out;

        default:

            fprintf(stderr, "Unknown control message %s\n",

                                control_desc[head.type]);

            ret = -EIO;

            goto out;

        }

    } while (1);

out:

    if (ret < 0) {

        rdma->error_state = ret;

    }

    return ret;

}


static int read_data(void *opaque, uint8_t *buf, int buf_size)

{

    struct playlist *v = opaque;

    HLSContext *c = v->parent->priv_data;

    int ret, i;

    int just_opened = 0;

restart:

    if (!v->needed)

        return AVERROR_EOF;

    if (!v->input) {

        int64_t reload_interval;

        struct segment *seg;

        /* Check that the playlist is still needed before opening a new

         * segment. */

        if (v->ctx && v->ctx->nb_streams) {

            v->needed = 0;

            for (i = 0; i < v->n_main_streams; i++) {

                if (v->main_streams[i]->discard < AVDISCARD_ALL) {

                    v->needed = 1;

                    break;

                }

            }

        }

        if (!v->needed) {

            av_log(v->parent, AV_LOG_INFO, "No longer receiving playlist %d\n",

                v->index);

            return AVERROR_EOF;

        }

        /* If this is a live stream and the reload interval has elapsed since

         * the last playlist reload, reload the playlists now. */

        reload_interval = default_reload_interval(v);

reload:

        reload_count++;

        if (reload_count > c->max_reload)

            return AVERROR_EOF;

        if (!v->finished &&

            av_gettime_relative() - v->last_load_time >= reload_interval) {

            if ((ret = parse_playlist(c, v->url, v, NULL)) < 0) {

                av_log(v->parent, AV_LOG_WARNING, "Failed to reload playlist %d\n",

                       v->index);

                return ret;

            }

            /* If we need to reload the playlist again below (if

             * there's still no more segments), switch to a reload

             * interval of half the target duration. */

            reload_interval = v->target_duration / 2;

        }

        if (v->cur_seq_no < v->start_seq_no) {

            av_log(NULL, AV_LOG_WARNING,

                   "skipping %d segments ahead, expired from playlists\n",

                   v->start_seq_no - v->cur_seq_no);

            v->cur_seq_no = v->start_seq_no;

        }

        if (v->cur_seq_no >= v->start_seq_no + v->n_segments) {

            if (v->finished)

                return AVERROR_EOF;

            while (av_gettime_relative() - v->last_load_time < reload_interval) {

                if (ff_check_interrupt(c->interrupt_callback))

                    return AVERROR_EXIT;

                av_usleep(100*1000);

            }

            /* Enough time has elapsed since the last reload */

            goto reload;

        }

        seg = current_segment(v);

        /* load/update Media Initialization Section, if any */

        ret = update_init_section(v, seg);

        if (ret)

            return ret;

        ret = open_input(c, v, seg);

        if (ret < 0) {

            if (ff_check_interrupt(c->interrupt_callback))

                return AVERROR_EXIT;

            av_log(v->parent, AV_LOG_WARNING, "Failed to open segment of playlist %d\n",

                   v->index);

            v->cur_seq_no += 1;

            goto reload;

        }

        just_opened = 1;

    }

    if (v->init_sec_buf_read_offset < v->init_sec_data_len) {

        /* Push init section out first before first actual segment */

        int copy_size = FFMIN(v->init_sec_data_len - v->init_sec_buf_read_offset, buf_size);

        memcpy(buf, v->init_sec_buf, copy_size);

        v->init_sec_buf_read_offset += copy_size;

        return copy_size;

    }

    ret = read_from_url(v, current_segment(v), buf, buf_size, READ_NORMAL);

    if (ret > 0) {

        if (just_opened && v->is_id3_timestamped != 0) {

            /* Intercept ID3 tags here, elementary audio streams are required

             * to convey timestamps using them in the beginning of each segment. */

            intercept_id3(v, buf, buf_size, &ret);

        }

        return ret;

    }

    ff_format_io_close(v->parent, &v->input);

    v->cur_seq_no++;

    c->cur_seq_no = v->cur_seq_no;

    goto restart;

}


static void put_swf_matrix(ByteIOContext *pb,

                           int a, int b, int c, int d, int tx, int ty)

{

    PutBitContext p;

    uint8_t buf[256];

    init_put_bits(&p, buf, sizeof(buf));

    put_bits(&p, 1, 1); /* a, d present */

    put_bits(&p, 5, 20); /* nb bits */

    put_bits(&p, 20, a);

    put_bits(&p, 20, d);

    put_bits(&p, 1, 1); /* b, c present */

    put_bits(&p, 5, 20); /* nb bits */

    put_bits(&p, 20, c);

    put_bits(&p, 20, b);

    put_bits(&p, 5, 20); /* nb bits */

    put_bits(&p, 20, tx);

    put_bits(&p, 20, ty);

    flush_put_bits(&p);

    put_buffer(pb, buf, pbBufPtr(&p) - p.buf);

}


int ff_nvdec_start_frame(AVCodecContext *avctx, AVFrame *frame)

{

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

    FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;

    NVDECFrame *cf = NULL;

    int ret;

    ctx->bitstream_len = 0;

    ctx->nb_slices     = 0;

    if (fdd->hwaccel_priv)

        return 0;

    cf = av_mallocz(sizeof(*cf));

    if (!cf)

        return AVERROR(ENOMEM);

    cf->decoder_ref = av_buffer_ref(ctx->decoder_ref);

    if (!cf->decoder_ref)

        goto fail;

    cf->idx_ref = av_buffer_pool_get(ctx->decoder_pool);

    if (!cf->idx_ref) {

        av_log(avctx, AV_LOG_ERROR, "No decoder surfaces left\n");

        ret = AVERROR(ENOMEM);

        goto fail;

    }

    cf->idx = *(unsigned int*)cf->idx_ref->data;

    fdd->hwaccel_priv      = cf;

    fdd->hwaccel_priv_free = nvdec_fdd_priv_free;

    fdd->post_process      = nvdec_retrieve_data;

    return 0;

fail:

    nvdec_fdd_priv_free(cf);

    return ret;

}


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

{

    MOVFragment *frag = &c->fragment;

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

    MOVStreamContext *sc = st->priv_data;

    uint64_t offset;

    int64_t dts;

    int data_offset = 0;

    unsigned entries, first_sample_flags = frag->flags;

    int flags, distance, i;

    if (sc->pseudo_stream_id+1 != frag->stsd_id)

        return 0;

    if (!st->nb_index_entries)

        return -1;

    get_byte(pb); /* version */

    flags = get_be24(pb);

    entries = get_be32(pb);

    dprintf(c->fc, "flags 0x%x entries %d\n", flags, entries);

    if (flags & 0x001) data_offset        = get_be32(pb);

    if (flags & 0x004) first_sample_flags = get_be32(pb);

    if (flags & 0x800) {

        if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data))

            return -1;

        sc->ctts_data = av_realloc(sc->ctts_data,

                                   (entries+sc->ctts_count)*sizeof(*sc->ctts_data));

        if (!sc->ctts_data)

            return AVERROR(ENOMEM);

    }

    dts = st->duration;

    offset = frag->base_data_offset + data_offset;

    distance = 0;

    dprintf(c->fc, "first sample flags 0x%x\n", first_sample_flags);

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

        unsigned sample_size = frag->size;

        int sample_flags = i ? frag->flags : first_sample_flags;

        unsigned sample_duration = frag->duration;

        int keyframe;

        if (flags & 0x100) sample_duration = get_be32(pb);

        if (flags & 0x200) sample_size     = get_be32(pb);

        if (flags & 0x400) sample_flags    = get_be32(pb);

        if (flags & 0x800) {

            sc->ctts_data[sc->ctts_count].count = 1;

            sc->ctts_data[sc->ctts_count].duration = get_be32(pb);

            sc->ctts_count++;

        }

        if ((keyframe = st->codec->codec_type == CODEC_TYPE_AUDIO ||

             (flags & 0x004 && !i && !sample_flags) || sample_flags & 0x2000000))

            distance = 0;

        av_add_index_entry(st, offset, dts, sample_size, distance,

                           keyframe ? AVINDEX_KEYFRAME : 0);

        dprintf(c->fc, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", "

                "size %d, distance %d, keyframe %d\n", st->index, sc->sample_count+i,

                offset, dts, sample_size, distance, keyframe);

        distance++;

        assert(sample_duration % sc->time_rate == 0);

        dts += sample_duration / sc->time_rate;

        offset += sample_size;

    }

    frag->moof_offset = offset;

    sc->sample_count = st->nb_index_entries;

    st->duration = dts;

    return 0;

}