static int http_connect(URLContext *h, const char *path, const char *local_path,

                        const char *hoststr, const char *auth,

                        const char *proxyauth, int *new_location)

{

    HTTPContext *s = h->priv_data;

    int post, err;

    char headers[1024] = "";

    char *authstr = NULL, *proxyauthstr = NULL;

    int64_t off = s->off;

    int len = 0;

    const char *method;

    /* send http header */

    post = h->flags & AVIO_FLAG_WRITE;

    if (s->post_data) {

        /* force POST method and disable chunked encoding when

         * custom HTTP post data is set */

        post = 1;

        s->chunked_post = 0;

    }

    method = post ? "POST" : "GET";

    authstr = ff_http_auth_create_response(&s->auth_state, auth, local_path,

                                           method);

    proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,

                                                local_path, method);

    /* set default headers if needed */

    if (!has_header(s->headers, "\r\nUser-Agent: "))

       len += av_strlcatf(headers + len, sizeof(headers) - len,

                          "User-Agent: %s\r\n", LIBAVFORMAT_IDENT);

    if (!has_header(s->headers, "\r\nAccept: "))

        len += av_strlcpy(headers + len, "Accept: */*\r\n",

                          sizeof(headers) - len);

    if (!has_header(s->headers, "\r\nRange: ") && !post)

        len += av_strlcatf(headers + len, sizeof(headers) - len,

                           "Range: bytes=%"PRId64"-\r\n", s->off);

    if (!has_header(s->headers, "\r\nConnection: ")) {

        if (s->multiple_requests) {

            len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",

                              sizeof(headers) - len);

        } else {

            len += av_strlcpy(headers + len, "Connection: close\r\n",

                              sizeof(headers) - len);

        }

    }

    if (!has_header(s->headers, "\r\nHost: "))

        len += av_strlcatf(headers + len, sizeof(headers) - len,

                           "Host: %s\r\n", hoststr);

    if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)

        len += av_strlcatf(headers + len, sizeof(headers) - len,

                           "Content-Length: %d\r\n", s->post_datalen);

    /* now add in custom headers */

    if (s->headers)

        av_strlcpy(headers + len, s->headers, sizeof(headers) - len);

    snprintf(s->buffer, sizeof(s->buffer),

             "%s %s HTTP/1.1\r\n"

             "%s"

             "%s"

             "%s"

             "%s%s"

             "\r\n",

             method,

             path,

             post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",

             headers,

             authstr ? authstr : "",

             proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");

    av_freep(&authstr);

    av_freep(&proxyauthstr);

    if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)

        return err;

    if (s->post_data)

        if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)

            return err;

    /* init input buffer */

    s->buf_ptr = s->buffer;

    s->buf_end = s->buffer;

    s->line_count = 0;

    s->off = 0;

    s->filesize = -1;

    s->willclose = 0;

    s->end_chunked_post = 0;

    s->end_header = 0;

    if (post && !s->post_data) {

        /* Pretend that it did work. We didn't read any header yet, since

         * we've still to send the POST data, but the code calling this

         * function will check http_code after we return. */

        s->http_code = 200;

        return 0;

    }

    /* wait for header */

    err = http_read_header(h, new_location);

    if (err < 0)

        return err;

    return (off == s->off) ? 0 : -1;

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);

    dc->exit = virtio_serial_device_exit;

    dc->props = virtio_serial_properties;

    set_bit(DEVICE_CATEGORY_INPUT, dc->categories);

    vdc->init = virtio_serial_device_init;

    vdc->get_features = get_features;

    vdc->get_config = get_config;

    vdc->set_config = set_config;

    vdc->set_status = set_status;

    vdc->reset = vser_reset;

}


static uint64_t get_channel_layout_single(const char *name, int name_len)

{

    int i;

    char *end;

    int64_t layout;

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

        if (strlen(channel_layout_map[i].name) == name_len &&

            !memcmp(channel_layout_map[i].name, name, name_len))

            return channel_layout_map[i].layout;

    }

    for (i = 0; i < FF_ARRAY_ELEMS(channel_names); i++)

        if (channel_names[i].name &&

            strlen(channel_names[i].name) == name_len &&

            !memcmp(channel_names[i].name, name, name_len))

            return (int64_t)1 << i;

    i = strtol(name, &end, 10);

    if ((end + 1 - name == name_len && *end  == 'c'))

        return av_get_default_channel_layout(i);

    layout = strtoll(name, &end, 0);

    if (end - name == name_len)

        return FFMAX(layout, 0);

    return 0;

}


static void get_offset_range(hwaddr phys_addr,

                             ram_addr_t mapping_length,

                             DumpState *s,

                             hwaddr *p_offset,

                             hwaddr *p_filesz)

{

    RAMBlock *block;

    hwaddr offset = s->memory_offset;

    int64_t size_in_block, start;

    /* When the memory is not stored into vmcore, offset will be -1 */

    *p_offset = -1;

    *p_filesz = 0;

    if (s->has_filter) {

        if (phys_addr < s->begin || phys_addr >= s->begin + s->length) {

            return;

        }

    }

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

        if (s->has_filter) {

            if (block->offset >= s->begin + s->length ||

                block->offset + block->length <= s->begin) {

                /* This block is out of the range */

                continue;

            }

            if (s->begin <= block->offset) {

                start = block->offset;

            } else {

                start = s->begin;

            }

            size_in_block = block->length - (start - block->offset);

            if (s->begin + s->length < block->offset + block->length) {

                size_in_block -= block->offset + block->length -

                                 (s->begin + s->length);

            }

        } else {

            start = block->offset;

            size_in_block = block->length;

        }

        if (phys_addr >= start && phys_addr < start + size_in_block) {

            *p_offset = phys_addr - start + offset;

            /* The offset range mapped from the vmcore file must not spill over

             * the RAMBlock, clamp it. The rest of the mapping will be

             * zero-filled in memory at load time; see

             * <http://refspecs.linuxbase.org/elf/gabi4+/ch5.pheader.html>.

             */

            *p_filesz = phys_addr + mapping_length <= start + size_in_block ?

                        mapping_length :

                        size_in_block - (phys_addr - start);

            return;

        }

        offset += size_in_block;

    }

}


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

                                int flags, Error **errp)

{

    BDRVQcow2State *s = bs->opaque;

    QemuOpts *opts = NULL;

    const char *opt_overlap_check, *opt_overlap_check_template;

    int overlap_check_template = 0;

    uint64_t l2_cache_size, refcount_cache_size;

    Qcow2Cache *l2_table_cache;

    Qcow2Cache *refcount_block_cache;

    uint64_t cache_clean_interval;

    bool use_lazy_refcounts;

    int i;

    Error *local_err = NULL;

    int ret;

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

    qemu_opts_absorb_qdict(opts, options, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        ret = -EINVAL;

        goto fail;

    }

    /* get L2 table/refcount block cache size from command line options */

    read_cache_sizes(bs, opts, &l2_cache_size, &refcount_cache_size,

                     &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        ret = -EINVAL;

        goto fail;

    }

    l2_cache_size /= s->cluster_size;

    if (l2_cache_size < MIN_L2_CACHE_SIZE) {

        l2_cache_size = MIN_L2_CACHE_SIZE;

    }

    if (l2_cache_size > INT_MAX) {

        error_setg(errp, "L2 cache size too big");

        ret = -EINVAL;

        goto fail;

    }

    refcount_cache_size /= s->cluster_size;

    if (refcount_cache_size < MIN_REFCOUNT_CACHE_SIZE) {

        refcount_cache_size = MIN_REFCOUNT_CACHE_SIZE;

    }

    if (refcount_cache_size > INT_MAX) {

        error_setg(errp, "Refcount cache size too big");

        ret = -EINVAL;

        goto fail;

    }

    /* alloc L2 table/refcount block cache */

    l2_table_cache = qcow2_cache_create(bs, l2_cache_size);

    refcount_block_cache = qcow2_cache_create(bs, refcount_cache_size);

    if (l2_table_cache == NULL || refcount_block_cache == NULL) {

        error_setg(errp, "Could not allocate metadata caches");

        ret = -ENOMEM;

        goto fail;

    }

    /* New interval for cache cleanup timer */

    cache_clean_interval =

        qemu_opt_get_number(opts, QCOW2_OPT_CACHE_CLEAN_INTERVAL, 0);

    if (cache_clean_interval > UINT_MAX) {

        error_setg(errp, "Cache clean interval too big");

        ret = -EINVAL;

        goto fail;

    }

    /* Enable lazy_refcounts according to image and command line options */

    use_lazy_refcounts = qemu_opt_get_bool(opts, QCOW2_OPT_LAZY_REFCOUNTS,

        (s->compatible_features & QCOW2_COMPAT_LAZY_REFCOUNTS));

    if (use_lazy_refcounts && s->qcow_version < 3) {

        error_setg(errp, "Lazy refcounts require a qcow2 image with at least "

                   "qemu 1.1 compatibility level");

        ret = -EINVAL;

        goto fail;

    }

    /* Overlap check options */

    opt_overlap_check = qemu_opt_get(opts, QCOW2_OPT_OVERLAP);

    opt_overlap_check_template = qemu_opt_get(opts, QCOW2_OPT_OVERLAP_TEMPLATE);

    if (opt_overlap_check_template && opt_overlap_check &&

        strcmp(opt_overlap_check_template, opt_overlap_check))

    {

        error_setg(errp, "Conflicting values for qcow2 options '"

                   QCOW2_OPT_OVERLAP "' ('%s') and '" QCOW2_OPT_OVERLAP_TEMPLATE

                   "' ('%s')", opt_overlap_check, opt_overlap_check_template);

        ret = -EINVAL;

        goto fail;

    }

    if (!opt_overlap_check) {

        opt_overlap_check = opt_overlap_check_template ?: "cached";

    }

    if (!strcmp(opt_overlap_check, "none")) {

        overlap_check_template = 0;

    } else if (!strcmp(opt_overlap_check, "constant")) {

        overlap_check_template = QCOW2_OL_CONSTANT;

    } else if (!strcmp(opt_overlap_check, "cached")) {

        overlap_check_template = QCOW2_OL_CACHED;

    } else if (!strcmp(opt_overlap_check, "all")) {

        overlap_check_template = QCOW2_OL_ALL;

    } else {

        error_setg(errp, "Unsupported value '%s' for qcow2 option "

                   "'overlap-check'. Allowed are any of the following: "

                   "none, constant, cached, all", opt_overlap_check);

        ret = -EINVAL;

        goto fail;

    }

    /*

     * Start updating fields in BDRVQcow2State.

     * After this point no failure is allowed any more.

     */

    s->overlap_check = 0;

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

        /* overlap-check defines a template bitmask, but every flag may be

         * overwritten through the associated boolean option */

        s->overlap_check |=

            qemu_opt_get_bool(opts, overlap_bool_option_names[i],

                              overlap_check_template & (1 << i)) << i;

    }

    s->l2_table_cache = l2_table_cache;

    s->refcount_block_cache = refcount_block_cache;

    s->use_lazy_refcounts = use_lazy_refcounts;

    s->discard_passthrough[QCOW2_DISCARD_NEVER] = false;

    s->discard_passthrough[QCOW2_DISCARD_ALWAYS] = true;

    s->discard_passthrough[QCOW2_DISCARD_REQUEST] =

        qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_REQUEST,

                          flags & BDRV_O_UNMAP);

    s->discard_passthrough[QCOW2_DISCARD_SNAPSHOT] =

        qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_SNAPSHOT, true);

    s->discard_passthrough[QCOW2_DISCARD_OTHER] =

        qemu_opt_get_bool(opts, QCOW2_OPT_DISCARD_OTHER, false);

    s->cache_clean_interval = cache_clean_interval;

    cache_clean_timer_init(bs, bdrv_get_aio_context(bs));

    ret = 0;

fail:

    qemu_opts_del(opts);

    opts = NULL;

    return ret;

}


vu_message_read(VuDev *dev, int conn_fd, VhostUserMsg *vmsg)

{

    char control[CMSG_SPACE(VHOST_MEMORY_MAX_NREGIONS * sizeof(int))] = { };

    struct iovec iov = {

        .iov_base = (char *)vmsg,

        .iov_len = VHOST_USER_HDR_SIZE,

    };

    struct msghdr msg = {

        .msg_iov = &iov,

        .msg_iovlen = 1,

        .msg_control = control,

        .msg_controllen = sizeof(control),

    };

    size_t fd_size;

    struct cmsghdr *cmsg;

    int rc;

    do {

        rc = recvmsg(conn_fd, &msg, 0);

    } while (rc < 0 && (errno == EINTR || errno == EAGAIN));

    if (rc <= 0) {

        vu_panic(dev, "Error while recvmsg: %s", strerror(errno));

        return false;

    }

    vmsg->fd_num = 0;

    for (cmsg = CMSG_FIRSTHDR(&msg);

         cmsg != NULL;

         cmsg = CMSG_NXTHDR(&msg, cmsg))

    {

        if (cmsg->cmsg_level == SOL_SOCKET && cmsg->cmsg_type == SCM_RIGHTS) {

            fd_size = cmsg->cmsg_len - CMSG_LEN(0);

            vmsg->fd_num = fd_size / sizeof(int);

            memcpy(vmsg->fds, CMSG_DATA(cmsg), fd_size);

            break;

        }

    }

    if (vmsg->size > sizeof(vmsg->payload)) {

        vu_panic(dev,

                 "Error: too big message request: %d, size: vmsg->size: %u, "

                 "while sizeof(vmsg->payload) = %zu\n",

                 vmsg->request, vmsg->size, sizeof(vmsg->payload));

        goto fail;

    }

    if (vmsg->size) {

        do {

            rc = read(conn_fd, &vmsg->payload, vmsg->size);

        } while (rc < 0 && (errno == EINTR || errno == EAGAIN));

        if (rc <= 0) {

            vu_panic(dev, "Error while reading: %s", strerror(errno));

            goto fail;

        }

        assert(rc == vmsg->size);

    }

    return true;

fail:

    vmsg_close_fds(vmsg);

    return false;

}


static void entropy_available(void *opaque)

{

    RndRandom *s = RNG_RANDOM(opaque);

    uint8_t buffer[s->size];

    ssize_t len;

    len = read(s->fd, buffer, s->size);

    g_assert(len != -1);

    s->receive_func(s->opaque, buffer, len);

    s->receive_func = NULL;

    qemu_set_fd_handler(s->fd, NULL, NULL, NULL);


static float32 addFloat32Sigs( float32 a, float32 b, flag zSign STATUS_PARAM)

{

    int16 aExp, bExp, zExp;

    uint32_t aSig, bSig, zSig;

    int16 expDiff;

    aSig = extractFloat32Frac( a );

    aExp = extractFloat32Exp( a );

    bSig = extractFloat32Frac( b );

    bExp = extractFloat32Exp( b );

    expDiff = aExp - bExp;

    aSig <<= 6;

    bSig <<= 6;

    if ( 0 < expDiff ) {

        if ( aExp == 0xFF ) {

            if ( aSig ) return propagateFloat32NaN( a, b STATUS_VAR );

            return a;

        }

        if ( bExp == 0 ) {

            --expDiff;

        }

        else {

            bSig |= 0x20000000;

        }

        shift32RightJamming( bSig, expDiff, &bSig );

        zExp = aExp;

    }

    else if ( expDiff < 0 ) {

        if ( bExp == 0xFF ) {

            if ( bSig ) return propagateFloat32NaN( a, b STATUS_VAR );

            return packFloat32( zSign, 0xFF, 0 );

        }

        if ( aExp == 0 ) {

            ++expDiff;

        }

        else {

            aSig |= 0x20000000;

        }

        shift32RightJamming( aSig, - expDiff, &aSig );

        zExp = bExp;

    }

    else {

        if ( aExp == 0xFF ) {

            if ( aSig | bSig ) return propagateFloat32NaN( a, b STATUS_VAR );

            return a;

        }

        if ( aExp == 0 ) {

            if ( STATUS(flush_to_zero) ) return packFloat32( zSign, 0, 0 );

            return packFloat32( zSign, 0, ( aSig + bSig )>>6 );

        }

        zSig = 0x40000000 + aSig + bSig;

        zExp = aExp;

        goto roundAndPack;

    }

    aSig |= 0x20000000;

    zSig = ( aSig + bSig )<<1;

    --zExp;

    if ( (int32_t) zSig < 0 ) {

        zSig = aSig + bSig;

        ++zExp;

    }

 roundAndPack:

    return roundAndPackFloat32( zSign, zExp, zSig STATUS_VAR );

}


static void rc4030_write(void *opaque, hwaddr addr, uint64_t data,

                         unsigned int size)

{

    rc4030State *s = opaque;

    uint32_t val = data;

    addr &= 0x3fff;

    trace_rc4030_write(addr, val);

    switch (addr & ~0x3) {

    /* Global config register */

    case 0x0000:

        s->config = val;

        break;

    /* DMA transl. table base */

    case 0x0018:

        rc4030_dma_tt_update(s, val, s->dma_tl_limit);

        break;

    /* DMA transl. table limit */

    case 0x0020:

        rc4030_dma_tt_update(s, s->dma_tl_base, val);

        break;

    /* DMA transl. table invalidated */

    case 0x0028:

        break;

    /* Cache Maintenance */

    case 0x0030:

        s->cache_maint = val;

        break;

    /* I/O Cache Physical Tag */

    case 0x0048:

        s->cache_ptag = val;

        break;

    /* I/O Cache Logical Tag */

    case 0x0050:

        s->cache_ltag = val;

        break;

    /* I/O Cache Byte Mask */

    case 0x0058:

        s->cache_bmask |= val; /* HACK */

        break;

    /* I/O Cache Buffer Window */

    case 0x0060:

        /* HACK */

        if (s->cache_ltag == 0x80000001 && s->cache_bmask == 0xf0f0f0f) {

            hwaddr dest = s->cache_ptag & ~0x1;

            dest += (s->cache_maint & 0x3) << 3;

            cpu_physical_memory_write(dest, &val, 4);

        }

        break;

    /* Remote Speed Registers */

    case 0x0070:

    case 0x0078:

    case 0x0080:

    case 0x0088:

    case 0x0090:

    case 0x0098:

    case 0x00a0:

    case 0x00a8:

    case 0x00b0:

    case 0x00b8:

    case 0x00c0:

    case 0x00c8:

    case 0x00d0:

    case 0x00d8:

    case 0x00e0:

    case 0x00e8:

        s->rem_speed[(addr - 0x0070) >> 3] = val;

        break;

    /* DMA channel base address */

    case 0x0100:

    case 0x0108:

    case 0x0110:

    case 0x0118:

    case 0x0120:

    case 0x0128:

    case 0x0130:

    case 0x0138:

    case 0x0140:

    case 0x0148:

    case 0x0150:

    case 0x0158:

    case 0x0160:

    case 0x0168:

    case 0x0170:

    case 0x0178:

    case 0x0180:

    case 0x0188:

    case 0x0190:

    case 0x0198:

    case 0x01a0:

    case 0x01a8:

    case 0x01b0:

    case 0x01b8:

    case 0x01c0:

    case 0x01c8:

    case 0x01d0:

    case 0x01d8:

    case 0x01e0:

    case 0x01e8:

    case 0x01f0:

    case 0x01f8:

        {

            int entry = (addr - 0x0100) >> 5;

            int idx = (addr & 0x1f) >> 3;

            s->dma_regs[entry][idx] = val;

        }

        break;

    /* Memory refresh rate */

    case 0x0210:

        s->memory_refresh_rate = val;

        break;

    /* Interval timer reload */

    case 0x0228:

        s->itr = val;

        qemu_irq_lower(s->timer_irq);

        set_next_tick(s);

        break;

    /* EISA interrupt */

    case 0x0238:

        break;

    default:

        qemu_log_mask(LOG_GUEST_ERROR,

                      "rc4030: invalid write of 0x%02x at 0x%x",

                      val, (int)addr);

        break;

    }

}


int qcow2_grow_l1_table(BlockDriverState *bs, int min_size, bool exact_size)

{

    BDRVQcowState *s = bs->opaque;

    int new_l1_size, new_l1_size2, ret, i;

    uint64_t *new_l1_table;

    int64_t new_l1_table_offset;

    uint8_t data[12];

    if (min_size <= s->l1_size)

        return 0;

    if (exact_size) {

        new_l1_size = min_size;

    } else {

        /* Bump size up to reduce the number of times we have to grow */

        new_l1_size = s->l1_size;

        if (new_l1_size == 0) {

            new_l1_size = 1;

        }

        while (min_size > new_l1_size) {

            new_l1_size = (new_l1_size * 3 + 1) / 2;

        }

    }

#ifdef DEBUG_ALLOC2

    fprintf(stderr, "grow l1_table from %d to %d\n", s->l1_size, new_l1_size);

#endif

    new_l1_size2 = sizeof(uint64_t) * new_l1_size;

    new_l1_table = g_malloc0(align_offset(new_l1_size2, 512));

    memcpy(new_l1_table, s->l1_table, s->l1_size * sizeof(uint64_t));

    /* write new table (align to cluster) */

    BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_ALLOC_TABLE);

    new_l1_table_offset = qcow2_alloc_clusters(bs, new_l1_size2);

    if (new_l1_table_offset < 0) {

        g_free(new_l1_table);

        return new_l1_table_offset;

    }

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

    if (ret < 0) {

        goto fail;

    }

    BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_WRITE_TABLE);

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

        new_l1_table[i] = cpu_to_be64(new_l1_table[i]);

    ret = bdrv_pwrite_sync(bs->file, new_l1_table_offset, new_l1_table, new_l1_size2);

    if (ret < 0)

        goto fail;

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

        new_l1_table[i] = be64_to_cpu(new_l1_table[i]);

    /* set new table */

    BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_ACTIVATE_TABLE);

    cpu_to_be32w((uint32_t*)data, new_l1_size);

    cpu_to_be64wu((uint64_t*)(data + 4), new_l1_table_offset);

    ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_size), data,sizeof(data));

    if (ret < 0) {

        goto fail;

    }

    g_free(s->l1_table);

    qcow2_free_clusters(bs, s->l1_table_offset, s->l1_size * sizeof(uint64_t));

    s->l1_table_offset = new_l1_table_offset;

    s->l1_table = new_l1_table;

    s->l1_size = new_l1_size;

    return 0;

 fail:

    g_free(new_l1_table);

    qcow2_free_clusters(bs, new_l1_table_offset, new_l1_size2);

    return ret;

}


static bool qemu_vmstop_requested(RunState *r)

{

    if (vmstop_requested < RUN_STATE_MAX) {

        *r = vmstop_requested;

        vmstop_requested = RUN_STATE_MAX;

        return true;

    }

    return false;

}


int kvm_irqchip_add_adapter_route(KVMState *s, AdapterInfo *adapter)

{

    struct kvm_irq_routing_entry kroute;

    int virq;

    if (!kvm_gsi_routing_enabled()) {

        return -ENOSYS;

    }

    virq = kvm_irqchip_get_virq(s);

    if (virq < 0) {

        return virq;

    }

    kroute.gsi = virq;

    kroute.type = KVM_IRQ_ROUTING_S390_ADAPTER;

    kroute.flags = 0;

    kroute.u.adapter.summary_addr = adapter->summary_addr;

    kroute.u.adapter.ind_addr = adapter->ind_addr;

    kroute.u.adapter.summary_offset = adapter->summary_offset;

    kroute.u.adapter.ind_offset = adapter->ind_offset;

    kroute.u.adapter.adapter_id = adapter->adapter_id;

    kvm_add_routing_entry(s, &kroute);

    kvm_irqchip_commit_routes(s);

    return virq;

}


static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *buf)

{

    AVFilterContext *ctx = inlink->dst;

    AlphaMergeContext *merge = ctx->priv;

    int is_alpha = (inlink == ctx->inputs[1]);

    struct FFBufQueue *queue =

        (is_alpha ? &merge->queue_alpha : &merge->queue_main);

    ff_bufqueue_add(ctx, queue, buf);

    while (1) {

        AVFilterBufferRef *main_buf, *alpha_buf;

        if (!ff_bufqueue_peek(&merge->queue_main, 0) ||

            !ff_bufqueue_peek(&merge->queue_alpha, 0)) break;

        main_buf = ff_bufqueue_get(&merge->queue_main);

        alpha_buf = ff_bufqueue_get(&merge->queue_alpha);

        merge->frame_requested = 0;

        draw_frame(ctx, main_buf, alpha_buf);

        ff_filter_frame(ctx->outputs[0], avfilter_ref_buffer(main_buf, ~0));

        avfilter_unref_buffer(alpha_buf);

    }

    return 0;

}


static void id3v2_read_ttag(AVFormatContext *s, int taglen, char *dst, int dstlen)

{

    char *q;

    int len;

    if(dstlen > 0)

        dst[0]= 0;

    if(taglen < 1)

        return;

    taglen--; /* account for encoding type byte */

    dstlen--; /* Leave space for zero terminator */

    switch(get_byte(s->pb)) { /* encoding type */

    case 0:  /* ISO-8859-1 (0 - 255 maps directly into unicode) */

        q = dst;

        while(taglen--) {

            uint8_t tmp;

            PUT_UTF8(get_byte(s->pb), tmp, if (q - dst < dstlen - 1) *q++ = tmp;)

        }

        *q = '\0';

        break;

    case 3:  /* UTF-8 */

        len = FFMIN(taglen, dstlen);

        get_buffer(s->pb, dst, len);

        dst[len] = 0;

        break;

    }

}


static void spatial_decompose97i(DWTELEM *buffer, int width, int height, int stride){

    int y;

    DWTELEM *b0= buffer + mirror(-4-1, height-1)*stride;

    DWTELEM *b1= buffer + mirror(-4  , height-1)*stride;

    DWTELEM *b2= buffer + mirror(-4+1, height-1)*stride;

    DWTELEM *b3= buffer + mirror(-4+2, height-1)*stride;

    for(y=-4; y<height; y+=2){

        DWTELEM *b4= buffer + mirror(y+3, height-1)*stride;

        DWTELEM *b5= buffer + mirror(y+4, height-1)*stride;

{START_TIMER

        if(b3 <= b5)     horizontal_decompose97i(b4, width);

        if(y+4 < height) horizontal_decompose97i(b5, width);

if(width>400){

STOP_TIMER("horizontal_decompose97i")

}}

{START_TIMER

        if(b3 <= b5) vertical_decompose97iH0(b3, b4, b5, width);

        if(b2 <= b4) vertical_decompose97iL0(b2, b3, b4, width);

        if(b1 <= b3) vertical_decompose97iH1(b1, b2, b3, width);

        if(b0 <= b2) vertical_decompose97iL1(b0, b1, b2, width);

if(width>400){

STOP_TIMER("vertical_decompose97i")

}}

        b0=b2;

        b1=b3;

        b2=b4;

        b3=b5;

    }

}


static inline void RENAME(yuy2ToY)(uint8_t *dst, const uint8_t *src, int width, uint32_t *unused)

{

#if COMPILE_TEMPLATE_MMX

    __asm__ volatile(

        "movq "MANGLE(bm01010101)", %%mm2           \n\t"

        "mov                    %0, %%"REG_a"       \n\t"

        "1:                                         \n\t"

        "movq    (%1, %%"REG_a",2), %%mm0           \n\t"

        "movq   8(%1, %%"REG_a",2), %%mm1           \n\t"

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

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

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

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

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

        " js                    1b                  \n\t"

        : : "g" ((x86_reg)-width), "r" (src+width*2), "r" (dst+width)

        : "%"REG_a

    );

#else

    int i;

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

        dst[i]= src[2*i];

#endif

}


static ssize_t gem_receive(VLANClientState *nc, const uint8_t *buf, size_t size)

{

    unsigned    desc[2];

    target_phys_addr_t packet_desc_addr, last_desc_addr;

    GemState *s;

    unsigned   rxbufsize, bytes_to_copy;

    unsigned   rxbuf_offset;

    uint8_t    rxbuf[2048];

    uint8_t   *rxbuf_ptr;

    s = DO_UPCAST(NICState, nc, nc)->opaque;

    /* Do nothing if receive is not enabled. */

    if (!(s->regs[GEM_NWCTRL] & GEM_NWCTRL_RXENA)) {

        return -1;

    }

    /* Is this destination MAC address "for us" ? */

    if (gem_mac_address_filter(s, buf) == GEM_RX_REJECT) {

        return -1;

    }

    /* Discard packets with receive length error enabled ? */

    if (s->regs[GEM_NWCFG] & GEM_NWCFG_LERR_DISC) {

        unsigned type_len;

        /* Fish the ethertype / length field out of the RX packet */

        type_len = buf[12] << 8 | buf[13];

        /* It is a length field, not an ethertype */

        if (type_len < 0x600) {

            if (size < type_len) {

                /* discard */

                return -1;

            }

        }

    }

    /*

     * Determine configured receive buffer offset (probably 0)

     */

    rxbuf_offset = (s->regs[GEM_NWCFG] & GEM_NWCFG_BUFF_OFST_M) >>

                   GEM_NWCFG_BUFF_OFST_S;

    /* The configure size of each receive buffer.  Determines how many

     * buffers needed to hold this packet.

     */

    rxbufsize = ((s->regs[GEM_DMACFG] & GEM_DMACFG_RBUFSZ_M) >>

                 GEM_DMACFG_RBUFSZ_S) * GEM_DMACFG_RBUFSZ_MUL;

    bytes_to_copy = size;

    /* Strip of FCS field ? (usually yes) */

    if (s->regs[GEM_NWCFG] & GEM_NWCFG_STRIP_FCS) {

        rxbuf_ptr = (void *)buf;

    } else {

        unsigned crc_val;

        int      crc_offset;

        /* The application wants the FCS field, which QEMU does not provide.

         * We must try and caclculate one.

         */

        memcpy(rxbuf, buf, size);

        memset(rxbuf + size, 0, sizeof(rxbuf - size));

        rxbuf_ptr = rxbuf;

        crc_val = cpu_to_le32(crc32(0, rxbuf, MAX(size, 60)));

        if (size < 60) {

            crc_offset = 60;

        } else {

            crc_offset = size;

        }

        memcpy(rxbuf + crc_offset, &crc_val, sizeof(crc_val));

        bytes_to_copy += 4;

        size += 4;

    }

    /* Pad to minimum length */

    if (size < 64) {

        size = 64;

    }

    DB_PRINT("config bufsize: %d packet size: %ld\n", rxbufsize, size);

    packet_desc_addr = s->rx_desc_addr;

    while (1) {

        DB_PRINT("read descriptor 0x%x\n", packet_desc_addr);

        /* read current descriptor */

        cpu_physical_memory_read(packet_desc_addr,

                                 (uint8_t *)&desc[0], sizeof(desc));

        /* Descriptor owned by software ? */

        if (rx_desc_get_ownership(desc) == 1) {

            DB_PRINT("descriptor 0x%x owned by sw.\n", packet_desc_addr);

            s->regs[GEM_RXSTATUS] |= GEM_RXSTATUS_NOBUF;

            /* Handle interrupt consequences */

            gem_update_int_status(s);

            return -1;

        }

        DB_PRINT("copy %d bytes to 0x%x\n", MIN(bytes_to_copy, rxbufsize),

                rx_desc_get_buffer(desc));

        /*

         * Let's have QEMU lend a helping hand.

         */

        if (rx_desc_get_buffer(desc) == 0) {

            DB_PRINT("Invalid RX buffer (NULL) for descriptor 0x%x\n",

                       packet_desc_addr);

            break;

        }

        /* Copy packet data to emulated DMA buffer */

        cpu_physical_memory_write(rx_desc_get_buffer(desc) + rxbuf_offset,

                                  rxbuf_ptr, MIN(bytes_to_copy, rxbufsize));

        bytes_to_copy -= MIN(bytes_to_copy, rxbufsize);

        rxbuf_ptr += MIN(bytes_to_copy, rxbufsize);

        if (bytes_to_copy == 0) {

            break;

        }

        /* Next descriptor */

        if (rx_desc_get_wrap(desc)) {

            packet_desc_addr = s->regs[GEM_RXQBASE];

        } else {

            packet_desc_addr += 8;

        }

    }

    DB_PRINT("set length: %ld, EOF on descriptor 0x%x\n", size,

            (unsigned)packet_desc_addr);

    /* Update last descriptor with EOF and total length */

    rx_desc_set_eof(desc);

    rx_desc_set_length(desc, size);

    cpu_physical_memory_write(packet_desc_addr,

                              (uint8_t *)&desc[0], sizeof(desc));

    /* Advance RX packet descriptor Q */

    last_desc_addr = packet_desc_addr;

    packet_desc_addr = s->rx_desc_addr;

    s->rx_desc_addr = last_desc_addr;

    if (rx_desc_get_wrap(desc)) {

        s->rx_desc_addr = s->regs[GEM_RXQBASE];

    } else {

        s->rx_desc_addr += 8;

    }

    DB_PRINT("set SOF, OWN on descriptor 0x%08x\n", packet_desc_addr);

    /* Count it */

    gem_receive_updatestats(s, buf, size);

    /* Update first descriptor (which could also be the last) */

    /* read descriptor */

    cpu_physical_memory_read(packet_desc_addr,

                             (uint8_t *)&desc[0], sizeof(desc));

    rx_desc_set_sof(desc);

    rx_desc_set_ownership(desc);

    cpu_physical_memory_write(packet_desc_addr,

                              (uint8_t *)&desc[0], sizeof(desc));

    s->regs[GEM_RXSTATUS] |= GEM_RXSTATUS_FRMRCVD;

    /* Handle interrupt consequences */

    gem_update_int_status(s);

    return size;

}


static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb,

                                AVStream *st, MOVStreamContext *sc,

                                int size)

{

    if (st->codec->codec_tag == MKTAG('t','m','c','d')) {

        st->codec->extradata_size = size;

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

        if (!st->codec->extradata)

            return AVERROR(ENOMEM);

        avio_read(pb, st->codec->extradata, size);

    } else {

        /* other codec type, just skip (rtp, mp4s ...) */

        avio_skip(pb, size);

    }

    return 0;

}


int kvm_irqchip_update_msi_route(KVMState *s, int virq, MSIMessage msg)

{

    struct kvm_irq_routing_entry kroute;

    if (!kvm_irqchip_in_kernel()) {

        return -ENOSYS;

    }

    kroute.gsi = virq;

    kroute.type = KVM_IRQ_ROUTING_MSI;

    kroute.flags = 0;

    kroute.u.msi.address_lo = (uint32_t)msg.address;

    kroute.u.msi.address_hi = msg.address >> 32;

    kroute.u.msi.data = le32_to_cpu(msg.data);

    return kvm_update_routing_entry(s, &kroute);

}


static void rv34_gen_vlc(const uint8_t *bits, int size, VLC *vlc, const uint8_t *insyms,

                         const int num)

{

    int i;

    int counts[17] = {0}, codes[17];

    uint16_t cw[size], syms[size];

    uint8_t bits2[size];

    int maxbits = 0, realsize = 0;

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

        if(bits[i]){

            bits2[realsize] = bits[i];

            syms[realsize] = insyms ? insyms[i] : i;

            realsize++;

            maxbits = FFMAX(maxbits, bits[i]);

            counts[bits[i]]++;

        }

    }

    codes[0] = 0;

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

        codes[i+1] = (codes[i] + counts[i]) << 1;

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

        cw[i] = codes[bits2[i]]++;

    vlc->table = &table_data[table_offs[num]];

    vlc->table_allocated = table_offs[num + 1] - table_offs[num];

    init_vlc_sparse(vlc, FFMIN(maxbits, 9), realsize,

                    bits2, 1, 1,

                    cw,    2, 2,

                    syms,  2, 2, INIT_VLC_USE_NEW_STATIC);

}


static int proxy_lremovexattr(FsContext *ctx, V9fsPath *fs_path,

                              const char *name)

{

    int retval;

    V9fsString xname;

    v9fs_string_init(&xname);

    v9fs_string_sprintf(&xname, "%s", name);

    retval = v9fs_request(ctx->private, T_LREMOVEXATTR, NULL, "ss",

                          fs_path, &xname);

    v9fs_string_free(&xname);

    if (retval < 0) {

        errno = -retval;

    }

    return retval;

}


static int get_blocksize(BlockDriverState *bdrv)

{

    uint8_t cmd[10];

    uint8_t buf[8];

    uint8_t sensebuf[8];

    sg_io_hdr_t io_header;

    int ret;

    memset(cmd, 0, sizeof(cmd));

    memset(buf, 0, sizeof(buf));

    cmd[0] = READ_CAPACITY_10;

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

    io_header.interface_id = 'S';

    io_header.dxfer_direction = SG_DXFER_FROM_DEV;

    io_header.dxfer_len = sizeof(buf);

    io_header.dxferp = buf;

    io_header.cmdp = cmd;

    io_header.cmd_len = sizeof(cmd);

    io_header.mx_sb_len = sizeof(sensebuf);

    io_header.sbp = sensebuf;

    io_header.timeout = 6000; /* XXX */

    ret = bdrv_ioctl(bdrv, SG_IO, &io_header);

    if (ret < 0)

        return -1;

    return (buf[4] << 24) | (buf[5] << 16) | (buf[6] << 8) | buf[7];

}


ssize_t nbd_receive_reply(int csock, struct nbd_reply *reply)

{

    uint8_t buf[NBD_REPLY_SIZE];

    uint32_t magic;

    if (read_sync(csock, buf, sizeof(buf)) != sizeof(buf)) {

        LOG("read failed");

        errno = EINVAL;

        return -1;

    }

    /* Reply

       [ 0 ..  3]    magic   (NBD_REPLY_MAGIC)

       [ 4 ..  7]    error   (0 == no error)

       [ 7 .. 15]    handle

     */

    magic = be32_to_cpup((uint32_t*)buf);

    reply->error  = be32_to_cpup((uint32_t*)(buf + 4));

    reply->handle = be64_to_cpup((uint64_t*)(buf + 8));

    TRACE("Got reply: "

          "{ magic = 0x%x, .error = %d, handle = %" PRIu64" }",

          magic, reply->error, reply->handle);

    if (magic != NBD_REPLY_MAGIC) {

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

        errno = EINVAL;

        return -1;

    }

    return 0;

}


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

{

    USBDeviceClass *uc = USB_DEVICE_CLASS(klass);

    uc->init           = usb_mouse_initfn;

    uc->product_desc   = "QEMU USB Mouse";

    uc->usb_desc       = &desc_mouse;

    uc->handle_packet  = usb_generic_handle_packet;

    uc->handle_reset   = usb_hid_handle_reset;

    uc->handle_control = usb_hid_handle_control;

    uc->handle_data    = usb_hid_handle_data;

    uc->handle_destroy = usb_hid_handle_destroy;

}


static void test_validate_fail_struct_nested(TestInputVisitorData *data,

                                              const void *unused)

{

    UserDefNested *udp = NULL;

    Error *err = NULL;

    Visitor *v;

    v = validate_test_init(data, "{ 'string0': 'string0', 'dict1': { 'string1': 'string1', 'dict2': { 'userdef1': { 'integer': 42, 'string': 'string', 'extra': [42, 23, {'foo':'bar'}] }, 'string2': 'string2'}}}");

    visit_type_UserDefNested(v, &udp, NULL, &err);

    g_assert(err);

    qapi_free_UserDefNested(udp);

}


static int expand_zero_clusters_in_l1(BlockDriverState *bs, uint64_t *l1_table,

                                      int l1_size, int64_t *visited_l1_entries,

                                      int64_t l1_entries,

                                      BlockDriverAmendStatusCB *status_cb)

{

    BDRVQcowState *s = bs->opaque;

    bool is_active_l1 = (l1_table == s->l1_table);

    uint64_t *l2_table = NULL;

    int ret;

    int i, j;

    if (!is_active_l1) {

        /* inactive L2 tables require a buffer to be stored in when loading

         * them from disk */

        l2_table = qemu_try_blockalign(bs->file, s->cluster_size);

        if (l2_table == NULL) {

            return -ENOMEM;

        }

    }

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

        uint64_t l2_offset = l1_table[i] & L1E_OFFSET_MASK;

        bool l2_dirty = false;

        uint64_t l2_refcount;

        if (!l2_offset) {

            /* unallocated */

            (*visited_l1_entries)++;

            if (status_cb) {

                status_cb(bs, *visited_l1_entries, l1_entries);

            }

            continue;

        }

        if (offset_into_cluster(s, l2_offset)) {

            qcow2_signal_corruption(bs, true, -1, -1, "L2 table offset %#"

                                    PRIx64 " unaligned (L1 index: %#x)",

                                    l2_offset, i);

            ret = -EIO;

            goto fail;

        }

        if (is_active_l1) {

            /* get active L2 tables from cache */

            ret = qcow2_cache_get(bs, s->l2_table_cache, l2_offset,

                    (void **)&l2_table);

        } else {

            /* load inactive L2 tables from disk */

            ret = bdrv_read(bs->file, l2_offset / BDRV_SECTOR_SIZE,

                    (void *)l2_table, s->cluster_sectors);

        }

        if (ret < 0) {

            goto fail;

        }

        ret = qcow2_get_refcount(bs, l2_offset >> s->cluster_bits,

                                 &l2_refcount);

        if (ret < 0) {

            goto fail;

        }

        for (j = 0; j < s->l2_size; j++) {

            uint64_t l2_entry = be64_to_cpu(l2_table[j]);

            int64_t offset = l2_entry & L2E_OFFSET_MASK;

            int cluster_type = qcow2_get_cluster_type(l2_entry);

            bool preallocated = offset != 0;

            if (cluster_type != QCOW2_CLUSTER_ZERO) {

                continue;

            }

            if (!preallocated) {

                if (!bs->backing_hd) {

                    /* not backed; therefore we can simply deallocate the

                     * cluster */

                    l2_table[j] = 0;

                    l2_dirty = true;

                    continue;

                }

                offset = qcow2_alloc_clusters(bs, s->cluster_size);

                if (offset < 0) {

                    ret = offset;

                    goto fail;

                }

                if (l2_refcount > 1) {

                    /* For shared L2 tables, set the refcount accordingly (it is

                     * already 1 and needs to be l2_refcount) */

                    ret = qcow2_update_cluster_refcount(bs,

                            offset >> s->cluster_bits,

                            refcount_diff(1, l2_refcount), false,

                            QCOW2_DISCARD_OTHER);

                    if (ret < 0) {

                        qcow2_free_clusters(bs, offset, s->cluster_size,

                                            QCOW2_DISCARD_OTHER);

                        goto fail;

                    }

                }

            }

            if (offset_into_cluster(s, offset)) {

                qcow2_signal_corruption(bs, true, -1, -1, "Data cluster offset "

                                        "%#" PRIx64 " unaligned (L2 offset: %#"

                                        PRIx64 ", L2 index: %#x)", offset,

                                        l2_offset, j);

                if (!preallocated) {

                    qcow2_free_clusters(bs, offset, s->cluster_size,

                                        QCOW2_DISCARD_ALWAYS);

                }

                ret = -EIO;

                goto fail;

            }

            ret = qcow2_pre_write_overlap_check(bs, 0, offset, s->cluster_size);

            if (ret < 0) {

                if (!preallocated) {

                    qcow2_free_clusters(bs, offset, s->cluster_size,

                                        QCOW2_DISCARD_ALWAYS);

                }

                goto fail;

            }

            ret = bdrv_write_zeroes(bs->file, offset / BDRV_SECTOR_SIZE,

                                    s->cluster_sectors, 0);

            if (ret < 0) {

                if (!preallocated) {

                    qcow2_free_clusters(bs, offset, s->cluster_size,

                                        QCOW2_DISCARD_ALWAYS);

                }

                goto fail;

            }

            if (l2_refcount == 1) {

                l2_table[j] = cpu_to_be64(offset | QCOW_OFLAG_COPIED);

            } else {

                l2_table[j] = cpu_to_be64(offset);

            }

            l2_dirty = true;

        }

        if (is_active_l1) {

            if (l2_dirty) {

                qcow2_cache_entry_mark_dirty(bs, s->l2_table_cache, l2_table);

                qcow2_cache_depends_on_flush(s->l2_table_cache);

            }

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

            if (ret < 0) {

                l2_table = NULL;

                goto fail;

            }

        } else {

            if (l2_dirty) {

                ret = qcow2_pre_write_overlap_check(bs,

                        QCOW2_OL_INACTIVE_L2 | QCOW2_OL_ACTIVE_L2, l2_offset,

                        s->cluster_size);

                if (ret < 0) {

                    goto fail;

                }

                ret = bdrv_write(bs->file, l2_offset / BDRV_SECTOR_SIZE,

                        (void *)l2_table, s->cluster_sectors);

                if (ret < 0) {

                    goto fail;

                }

            }

        }

        (*visited_l1_entries)++;

        if (status_cb) {

            status_cb(bs, *visited_l1_entries, l1_entries);

        }

    }

    ret = 0;

fail:

    if (l2_table) {

        if (!is_active_l1) {

            qemu_vfree(l2_table);

        } else {

            if (ret < 0) {

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

            } else {

                ret = qcow2_cache_put(bs, s->l2_table_cache,

                        (void **)&l2_table);

            }

        }

    }

    return ret;

}


static int request_frame(AVFilterLink *outlink)

{

    AVFilterContext *ctx = outlink->src;

    TrimContext       *s = ctx->priv;

    int ret;

    s->got_output = 0;

    while (!s->got_output) {

        if (s->eof)

            return AVERROR_EOF;

        ret = ff_request_frame(ctx->inputs[0]);

        if (ret < 0)

            return ret;

    }

    return 0;

}


int ff_ivi_decode_frame(AVCodecContext *avctx, void *data, int *got_frame,

                        AVPacket *avpkt)

{

    IVI45DecContext *ctx = avctx->priv_data;

    const uint8_t   *buf = avpkt->data;

    AVFrame       *frame = data;

    int             buf_size = avpkt->size;

    int             result, p, b;

    init_get_bits(&ctx->gb, buf, buf_size * 8);

    ctx->frame_data = buf;

    ctx->frame_size = buf_size;

    result = ctx->decode_pic_hdr(ctx, avctx);

    if (result) {

        av_log(avctx, AV_LOG_ERROR,

               "Error while decoding picture header: %d\n", result);

        return result;

    }

    if (ctx->gop_invalid)

        return AVERROR_INVALIDDATA;

    if (avctx->codec_id == AV_CODEC_ID_INDEO4 &&

        ctx->frame_type == IVI4_FRAMETYPE_NULL_LAST) {

        if (ctx->got_p_frame) {

            av_frame_move_ref(data, ctx->p_frame);

            *got_frame = 1;

            ctx->got_p_frame = 0;

        } else {

            *got_frame = 0;

        }

        return buf_size;

    }

    if (ctx->gop_flags & IVI5_IS_PROTECTED) {

        avpriv_report_missing_feature(avctx, "Password-protected clip!\n");

        return AVERROR_PATCHWELCOME;

    }

    if (!ctx->planes[0].bands) {

        av_log(avctx, AV_LOG_ERROR, "Color planes not initialized yet\n");

        return AVERROR_INVALIDDATA;

    }

    ctx->switch_buffers(ctx);

    //{ START_TIMER;

    if (ctx->is_nonnull_frame(ctx)) {

        for (p = 0; p < 3; p++) {

            for (b = 0; b < ctx->planes[p].num_bands; b++) {

                result = decode_band(ctx, &ctx->planes[p].bands[b], avctx);

                if (result < 0) {

                    av_log(avctx, AV_LOG_ERROR,

                           "Error while decoding band: %d, plane: %d\n", b, p);

                    return result;

                }

            }

        }

    } else {

        if (ctx->is_scalable)

            return AVERROR_INVALIDDATA;

        for (p = 0; p < 3; p++) {

            if (!ctx->planes[p].bands[0].buf)

                return AVERROR_INVALIDDATA;

        }

    }

    //STOP_TIMER("decode_planes"); }

    result = ff_set_dimensions(avctx, ctx->planes[0].width, ctx->planes[0].height);

    if (result < 0)

        return result;

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

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

        return result;

    }

    if (ctx->is_scalable) {

        if (avctx->codec_id == AV_CODEC_ID_INDEO4)

            ff_ivi_recompose_haar(&ctx->planes[0], frame->data[0], frame->linesize[0]);

        else

            ff_ivi_recompose53   (&ctx->planes[0], frame->data[0], frame->linesize[0]);

    } else {

        ivi_output_plane(&ctx->planes[0], frame->data[0], frame->linesize[0]);

    }

    ivi_output_plane(&ctx->planes[2], frame->data[1], frame->linesize[1]);

    ivi_output_plane(&ctx->planes[1], frame->data[2], frame->linesize[2]);

    *got_frame = 1;

    /* If the bidirectional mode is enabled, next I and the following P

     * frame will be sent together. Unfortunately the approach below seems

     * to be the only way to handle the B-frames mode.

     * That's exactly the same Intel decoders do.

     */

    if (avctx->codec_id == AV_CODEC_ID_INDEO4 &&

        ctx->frame_type == IVI4_FRAMETYPE_INTRA) {

        int left;

        while (get_bits(&ctx->gb, 8)); // skip version string

        left = get_bits_count(&ctx->gb) & 0x18;

        skip_bits_long(&ctx->gb, 64 - left);

        if (get_bits_left(&ctx->gb) > 18 &&

            show_bits_long(&ctx->gb, 21) == 0xBFFF8) { // syncheader + inter type

            AVPacket pkt;

            pkt.data = avpkt->data + (get_bits_count(&ctx->gb) >> 3);

            pkt.size = get_bits_left(&ctx->gb) >> 3;

            ff_ivi_decode_frame(avctx, ctx->p_frame, &ctx->got_p_frame, &pkt);

        }

    }

    return buf_size;

}


static void tcg_out_brcond32(TCGContext *s, TCGCond cond,

                             TCGArg arg1, TCGArg arg2, int const_arg2,

                             int label_index, int small)

{

    tcg_out_cmp(s, arg1, arg2, const_arg2, 0);

    tcg_out_jxx(s, tcg_cond_to_jcc[cond], label_index, small);

}


void qemu_chr_free(CharDriverState *chr)

{

    if (chr->chr_close) {

        chr->chr_close(chr);

    }

    g_free(chr->filename);

    g_free(chr->label);

    qemu_opts_del(chr->opts);

    g_free(chr);

}


void replay_shutdown_request(void)

{

    if (replay_mode == REPLAY_MODE_RECORD) {

        replay_mutex_lock();

        replay_put_event(EVENT_SHUTDOWN);

        replay_mutex_unlock();

    }

}


target_phys_addr_t memory_region_section_get_iotlb(CPUArchState *env,

                                                   MemoryRegionSection *section,

                                                   target_ulong vaddr,

                                                   target_phys_addr_t paddr,

                                                   int prot,

                                                   target_ulong *address)

{

    target_phys_addr_t iotlb;

    CPUWatchpoint *wp;

    if (memory_region_is_ram(section->mr)) {

        /* Normal RAM.  */

        iotlb = (memory_region_get_ram_addr(section->mr) & TARGET_PAGE_MASK)

            + memory_region_section_addr(section, paddr);

        if (!section->readonly) {

            iotlb |= phys_section_notdirty;

        } else {

            iotlb |= phys_section_rom;

        }

    } else {

        /* IO handlers are currently passed a physical address.

           It would be nice to pass an offset from the base address

           of that region.  This would avoid having to special case RAM,

           and avoid full address decoding in every device.

           We can't use the high bits of pd for this because

           IO_MEM_ROMD uses these as a ram address.  */

        iotlb = section - phys_sections;

        iotlb += memory_region_section_addr(section, paddr);

    }

    /* Make accesses to pages with watchpoints go via the

       watchpoint trap routines.  */

    QTAILQ_FOREACH(wp, &env->watchpoints, entry) {

        if (vaddr == (wp->vaddr & TARGET_PAGE_MASK)) {

            /* Avoid trapping reads of pages with a write breakpoint. */

            if ((prot & PAGE_WRITE) || (wp->flags & BP_MEM_READ)) {

                iotlb = phys_section_watch + paddr;

                *address |= TLB_MMIO;

                break;

            }

        }

    }

    return iotlb;

}


static int vpx_decode(AVCodecContext *avctx,
                      void *data, int *got_frame, AVPacket *avpkt)
{
    VPxContext *ctx = avctx->priv_data;
    AVFrame *picture = data;
    const void *iter = NULL;
    const void *iter_alpha = NULL;
    struct vpx_image *img, *img_alpha;
    int ret;
    uint8_t *side_data = NULL;
    int side_data_size = 0;
    ret = decode_frame(avctx, &ctx->decoder, avpkt->data, avpkt->size);
    if (ret)
        return ret;
    side_data = av_packet_get_side_data(avpkt,
                                        AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL,
                                        &side_data_size);
    if (side_data_size > 1) {
        const uint64_t additional_id = AV_RB64(side_data);
        side_data += 8;
        side_data_size -= 8;
        if (additional_id == 1) {  // 1 stands for alpha channel data.
            if (!ctx->has_alpha_channel) {
                ctx->has_alpha_channel = 1;
                ret = vpx_init(avctx,
#if CONFIG_LIBVPX_VP8_DECODER && CONFIG_LIBVPX_VP9_DECODER
                               (avctx->codec_id == AV_CODEC_ID_VP8) ?
                               &vpx_codec_vp8_dx_algo : &vpx_codec_vp9_dx_algo,
#elif CONFIG_LIBVPX_VP8_DECODER
                               &vpx_codec_vp8_dx_algo,
#else
                               &vpx_codec_vp9_dx_algo,
#endif
                               1);
                if (ret)
                    return ret;
            ret = decode_frame(avctx, &ctx->decoder_alpha, side_data,
                               side_data_size);
            if (ret)
                return ret;
    if ((img = vpx_codec_get_frame(&ctx->decoder, &iter)) &&
        (!ctx->has_alpha_channel ||
         (img_alpha = vpx_codec_get_frame(&ctx->decoder_alpha, &iter_alpha)))) {
        uint8_t *planes[4];
        int linesizes[4];
        if ((ret = set_pix_fmt(avctx, img, ctx->has_alpha_channel)) < 0) {
#ifdef VPX_IMG_FMT_HIGHBITDEPTH
            av_log(avctx, AV_LOG_ERROR, "Unsupported output colorspace (%d) / bit_depth (%d)\n",
                   img->fmt, img->bit_depth);
#else
            av_log(avctx, AV_LOG_ERROR, "Unsupported output colorspace (%d) / bit_depth (%d)\n",
                   img->fmt, 8);
#endif
            return ret;
        if ((int) img->d_w != avctx->width || (int) img->d_h != avctx->height) {
            av_log(avctx, AV_LOG_INFO, "dimension change! %dx%d -> %dx%d\n",
                   avctx->width, avctx->height, img->d_w, img->d_h);
            ret = ff_set_dimensions(avctx, img->d_w, img->d_h);
            if (ret < 0)
                return ret;
        if ((ret = ff_get_buffer(avctx, picture, 0)) < 0)
            return ret;
        planes[0] = img->planes[VPX_PLANE_Y];
        planes[1] = img->planes[VPX_PLANE_U];
        planes[2] = img->planes[VPX_PLANE_V];
        planes[3] =
            ctx->has_alpha_channel ? img_alpha->planes[VPX_PLANE_Y] : NULL;
        linesizes[0] = img->stride[VPX_PLANE_Y];
        linesizes[1] = img->stride[VPX_PLANE_U];
        linesizes[2] = img->stride[VPX_PLANE_V];
        linesizes[3] =
            ctx->has_alpha_channel ? img_alpha->stride[VPX_PLANE_Y] : 0;
        av_image_copy(picture->data, picture->linesize, (const uint8_t**)planes,
                      linesizes, avctx->pix_fmt, img->d_w, img->d_h);
        *got_frame           = 1;
    return avpkt->size;


static void tcg_out_movi_int(TCGContext *s, TCGType type, TCGReg ret,

                             tcg_target_long arg, bool in_prologue)

{

    intptr_t tb_diff;

    tcg_target_long tmp;

    int shift;

    tcg_debug_assert(TCG_TARGET_REG_BITS == 64 || type == TCG_TYPE_I32);

    if (TCG_TARGET_REG_BITS == 64 && type == TCG_TYPE_I32) {

        arg = (int32_t)arg;

    }

    /* Load 16-bit immediates with one insn.  */

    if (tcg_out_movi_one(s, ret, arg)) {

        return;

    }

    /* Load addresses within the TB with one insn.  */

    tb_diff = arg - (intptr_t)s->code_gen_ptr;

    if (!in_prologue && USE_REG_TB && tb_diff == (int16_t)tb_diff) {

        tcg_out32(s, ADDI | TAI(ret, TCG_REG_TB, tb_diff));

        return;

    }

    /* Load 32-bit immediates with two insns.  Note that we've already

       eliminated bare ADDIS, so we know both insns are required.  */

    if (TCG_TARGET_REG_BITS == 32 || arg == (int32_t)arg) {

        tcg_out32(s, ADDIS | TAI(ret, 0, arg >> 16));

        tcg_out32(s, ORI | SAI(ret, ret, arg));

        return;

    }

    if (arg == (uint32_t)arg && !(arg & 0x8000)) {

        tcg_out32(s, ADDI | TAI(ret, 0, arg));

        tcg_out32(s, ORIS | SAI(ret, ret, arg >> 16));

        return;

    }

    /* Load masked 16-bit value.  */

    if (arg > 0 && (arg & 0x8000)) {

        tmp = arg | 0x7fff;

        if ((tmp & (tmp + 1)) == 0) {

            int mb = clz64(tmp + 1) + 1;

            tcg_out32(s, ADDI | TAI(ret, 0, arg));

            tcg_out_rld(s, RLDICL, ret, ret, 0, mb);

            return;

        }

    }

    /* Load common masks with 2 insns.  */

    shift = ctz64(arg);

    tmp = arg >> shift;

    if (tmp == (int16_t)tmp) {

        tcg_out32(s, ADDI | TAI(ret, 0, tmp));

        tcg_out_shli64(s, ret, ret, shift);

        return;

    }

    shift = clz64(arg);

    if (tcg_out_movi_one(s, ret, arg << shift)) {

        tcg_out_shri64(s, ret, ret, shift);

        return;

    }

    /* Load addresses within 2GB of TB with 2 (or rarely 3) insns.  */

    if (!in_prologue && USE_REG_TB && tb_diff == (int32_t)tb_diff) {

        tcg_out_mem_long(s, ADDI, ADD, ret, TCG_REG_TB, tb_diff);

        return;

    }

    /* Use the constant pool, if possible.  */

    if (!in_prologue && USE_REG_TB) {

        new_pool_label(s, arg, R_PPC_ADDR16, s->code_ptr,

                       -(intptr_t)s->code_gen_ptr);

        tcg_out32(s, LD | TAI(ret, TCG_REG_TB, 0));

        return;

    }

    tmp = arg >> 31 >> 1;

    tcg_out_movi(s, TCG_TYPE_I32, ret, tmp);

    if (tmp) {

        tcg_out_shli64(s, ret, ret, 32);

    }

    if (arg & 0xffff0000) {

        tcg_out32(s, ORIS | SAI(ret, ret, arg >> 16));

    }

    if (arg & 0xffff) {

        tcg_out32(s, ORI | SAI(ret, ret, arg));

    }

}


static int mpjpeg_read_probe(AVProbeData *p)

{

    AVIOContext *pb;

    char line[128] = { 0 };

    int ret = 0;

    pb = avio_alloc_context(p->buf, p->buf_size, 0, NULL, NULL, NULL, NULL);

    if (!pb)

        return AVERROR(ENOMEM);

    if (p->buf_size < 2 || p->buf[0] != '-' || p->buf[1] != '-')

        return 0;

    while (!pb->eof_reached) {

        ret = get_line(pb, line, sizeof(line));

        if (ret < 0)

            break;

        ret = check_content_type(line);

        if (!ret) {

            ret = AVPROBE_SCORE_MAX;

            break;

        }

    }

    av_free(pb);

    return ret;

}


static int flic_read_header(AVFormatContext *s)

{

    FlicDemuxContext *flic = s->priv_data;

    AVIOContext *pb = s->pb;

    unsigned char header[FLIC_HEADER_SIZE];

    AVStream *st, *ast;

    int speed;

    int magic_number;

    unsigned char preamble[FLIC_PREAMBLE_SIZE];

    flic->frame_number = 0;

    /* load the whole header and pull out the width and height */

    if (avio_read(pb, header, FLIC_HEADER_SIZE) != FLIC_HEADER_SIZE)

        return AVERROR(EIO);

    magic_number = AV_RL16(&header[4]);

    speed = AV_RL32(&header[0x10]);

    if (speed == 0)

        speed = FLIC_DEFAULT_SPEED;

    /* initialize the decoder streams */

    st = avformat_new_stream(s, NULL);

    if (!st)

        return AVERROR(ENOMEM);

    flic->video_stream_index = st->index;

    st->codec->codec_type = AVMEDIA_TYPE_VIDEO;

    st->codec->codec_id = AV_CODEC_ID_FLIC;

    st->codec->codec_tag = 0;  /* no fourcc */

    st->codec->width = AV_RL16(&header[0x08]);

    st->codec->height = AV_RL16(&header[0x0A]);

    if (!st->codec->width || !st->codec->height) {

        /* Ugly hack needed for the following sample: */

        /* http://samples.mplayerhq.hu/fli-flc/fli-bugs/specular.flc */

        av_log(s, AV_LOG_WARNING,

               "File with no specified width/height. Trying 640x480.\n");

        st->codec->width  = 640;

        st->codec->height = 480;

    }

    /* send over the whole 128-byte FLIC header */

    st->codec->extradata_size = FLIC_HEADER_SIZE;

    st->codec->extradata = av_malloc(FLIC_HEADER_SIZE);

    memcpy(st->codec->extradata, header, FLIC_HEADER_SIZE);

    /* peek at the preamble to detect TFTD videos - they seem to always start with an audio chunk */

    if (avio_read(pb, preamble, FLIC_PREAMBLE_SIZE) != FLIC_PREAMBLE_SIZE) {

        av_log(s, AV_LOG_ERROR, "Failed to peek at preamble\n");

        return AVERROR(EIO);

    }

    avio_seek(pb, -FLIC_PREAMBLE_SIZE, SEEK_CUR);

    /* Time to figure out the framerate:

     * If the first preamble's magic number is 0xAAAA then this file is from

     * X-COM: Terror from the Deep. If on the other hand there is a FLIC chunk

     * magic number at offset 0x10 assume this file is from Magic Carpet instead.

     * If neither of the above is true then this is a normal FLIC file.

     */

    if (AV_RL16(&preamble[4]) == FLIC_TFTD_CHUNK_AUDIO) {

        /* TFTD videos have an extra 22050 Hz 8-bit mono audio stream */

        ast = avformat_new_stream(s, NULL);

        if (!ast)

            return AVERROR(ENOMEM);

        flic->audio_stream_index = ast->index;

        /* all audio frames are the same size, so use the size of the first chunk for block_align */

        ast->codec->block_align = AV_RL32(&preamble[0]);

        ast->codec->codec_type = AVMEDIA_TYPE_AUDIO;

        ast->codec->codec_id = AV_CODEC_ID_PCM_U8;

        ast->codec->codec_tag = 0;

        ast->codec->sample_rate = FLIC_TFTD_SAMPLE_RATE;

        ast->codec->channels = 1;

        ast->codec->bit_rate = st->codec->sample_rate * 8;

        ast->codec->bits_per_coded_sample = 8;

        ast->codec->channel_layout = AV_CH_LAYOUT_MONO;

        ast->codec->extradata_size = 0;

        /* Since the header information is incorrect we have to figure out the

         * framerate using block_align and the fact that the audio is 22050 Hz.

         * We usually have two cases: 2205 -> 10 fps and 1470 -> 15 fps */

        avpriv_set_pts_info(st, 64, ast->codec->block_align, FLIC_TFTD_SAMPLE_RATE);

        avpriv_set_pts_info(ast, 64, 1, FLIC_TFTD_SAMPLE_RATE);

    } else if (AV_RL16(&header[0x10]) == FLIC_CHUNK_MAGIC_1) {

        avpriv_set_pts_info(st, 64, FLIC_MC_SPEED, 70);

        /* rewind the stream since the first chunk is at offset 12 */

        avio_seek(pb, 12, SEEK_SET);

        /* send over abbreviated FLIC header chunk */

        av_free(st->codec->extradata);

        st->codec->extradata_size = 12;

        st->codec->extradata = av_malloc(12);

        memcpy(st->codec->extradata, header, 12);

    } else if (magic_number == FLIC_FILE_MAGIC_1) {

        avpriv_set_pts_info(st, 64, speed, 70);

    } else if ((magic_number == FLIC_FILE_MAGIC_2) ||

               (magic_number == FLIC_FILE_MAGIC_3)) {

        avpriv_set_pts_info(st, 64, speed, 1000);

    } else {

        av_log(s, AV_LOG_ERROR, "Invalid or unsupported magic chunk in file\n");

        return AVERROR_INVALIDDATA;

    }

    return 0;

}


ds1225y_t *ds1225y_init(target_phys_addr_t mem_base, const char *filename)

{

    ds1225y_t *s;

    int mem_index1, mem_index2;

    s = qemu_mallocz(sizeof(ds1225y_t));

    if (!s)

        return NULL;

    s->mem_base = mem_base;

    s->capacity = 0x2000; /* Fixed for ds1225y chip: 8K */

    s->filename = filename;

    /* Read/write memory */

    mem_index1 = cpu_register_io_memory(0, nvram_read, nvram_write, s);

    cpu_register_physical_memory(mem_base, s->capacity, mem_index1);

    /* Read-only memory */

    mem_index2 = cpu_register_io_memory(0, nvram_read, nvram_none, s);

    cpu_register_physical_memory(mem_base + s->capacity, s->capacity, mem_index2);

    return s;

}


static void sdp_parse_line(AVFormatContext *s, SDPParseState *s1,

                           int letter, const char *buf)

{

    RTSPState *rt = s->priv_data;

    char buf1[64], st_type[64];

    const char *p;

    enum AVMediaType codec_type;

    int payload_type;

    AVStream *st;

    RTSPStream *rtsp_st;

    RTSPSource *rtsp_src;

    struct sockaddr_storage sdp_ip;

    int ttl;

    av_dlog(s, "sdp: %c='%s'\n", letter, buf);

    p = buf;

    if (s1->skip_media && letter != 'm')

        return;

    switch (letter) {

    case 'c':

        get_word(buf1, sizeof(buf1), &p);

        if (strcmp(buf1, "IN") != 0)

            return;

        get_word(buf1, sizeof(buf1), &p);

        if (strcmp(buf1, "IP4") && strcmp(buf1, "IP6"))

            return;

        get_word_sep(buf1, sizeof(buf1), "/", &p);

        if (get_sockaddr(buf1, &sdp_ip))

            return;

        ttl = 16;

        if (*p == '/') {

            p++;

            get_word_sep(buf1, sizeof(buf1), "/", &p);

            ttl = atoi(buf1);

        }

        if (s->nb_streams == 0) {

            s1->default_ip = sdp_ip;

            s1->default_ttl = ttl;

        } else {

            rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];

            rtsp_st->sdp_ip = sdp_ip;

            rtsp_st->sdp_ttl = ttl;

        }

        break;

    case 's':

        av_dict_set(&s->metadata, "title", p, 0);

        break;

    case 'i':

        if (s->nb_streams == 0) {

            av_dict_set(&s->metadata, "comment", p, 0);

            break;

        }

        break;

    case 'm':

        /* new stream */

        s1->skip_media  = 0;

        s1->seen_fmtp   = 0;

        s1->seen_rtpmap = 0;

        codec_type = AVMEDIA_TYPE_UNKNOWN;

        get_word(st_type, sizeof(st_type), &p);

        if (!strcmp(st_type, "audio")) {

            codec_type = AVMEDIA_TYPE_AUDIO;

        } else if (!strcmp(st_type, "video")) {

            codec_type = AVMEDIA_TYPE_VIDEO;

        } else if (!strcmp(st_type, "application")) {

            codec_type = AVMEDIA_TYPE_DATA;

        }

        if (codec_type == AVMEDIA_TYPE_UNKNOWN || !(rt->media_type_mask & (1 << codec_type))) {

            s1->skip_media = 1;

            return;

        }

        rtsp_st = av_mallocz(sizeof(RTSPStream));

        if (!rtsp_st)

            return;

        rtsp_st->stream_index = -1;

        dynarray_add(&rt->rtsp_streams, &rt->nb_rtsp_streams, rtsp_st);

        rtsp_st->sdp_ip = s1->default_ip;

        rtsp_st->sdp_ttl = s1->default_ttl;

        copy_default_source_addrs(s1->default_include_source_addrs,

                                  s1->nb_default_include_source_addrs,

                                  &rtsp_st->include_source_addrs,

                                  &rtsp_st->nb_include_source_addrs);

        copy_default_source_addrs(s1->default_exclude_source_addrs,

                                  s1->nb_default_exclude_source_addrs,

                                  &rtsp_st->exclude_source_addrs,

                                  &rtsp_st->nb_exclude_source_addrs);

        get_word(buf1, sizeof(buf1), &p); /* port */

        rtsp_st->sdp_port = atoi(buf1);

        get_word(buf1, sizeof(buf1), &p); /* protocol */

        if (!strcmp(buf1, "udp"))

            rt->transport = RTSP_TRANSPORT_RAW;

        else if (strstr(buf1, "/AVPF") || strstr(buf1, "/SAVPF"))

            rtsp_st->feedback = 1;

        /* XXX: handle list of formats */

        get_word(buf1, sizeof(buf1), &p); /* format list */

        rtsp_st->sdp_payload_type = atoi(buf1);

        if (!strcmp(ff_rtp_enc_name(rtsp_st->sdp_payload_type), "MP2T")) {

            /* no corresponding stream */

            if (rt->transport == RTSP_TRANSPORT_RAW) {

                if (!rt->ts && CONFIG_RTPDEC)

                    rt->ts = ff_mpegts_parse_open(s);

            } else {

                RTPDynamicProtocolHandler *handler;

                handler = ff_rtp_handler_find_by_id(

                              rtsp_st->sdp_payload_type, AVMEDIA_TYPE_DATA);

                init_rtp_handler(handler, rtsp_st, NULL);

                if (handler && handler->init)

                    handler->init(s, -1, rtsp_st->dynamic_protocol_context);

            }

        } else if (rt->server_type == RTSP_SERVER_WMS &&

                   codec_type == AVMEDIA_TYPE_DATA) {

            /* RTX stream, a stream that carries all the other actual

             * audio/video streams. Don't expose this to the callers. */

        } else {

            st = avformat_new_stream(s, NULL);

            if (!st)

                return;

            st->id = rt->nb_rtsp_streams - 1;

            rtsp_st->stream_index = st->index;

            st->codec->codec_type = codec_type;

            if (rtsp_st->sdp_payload_type < RTP_PT_PRIVATE) {

                RTPDynamicProtocolHandler *handler;

                /* if standard payload type, we can find the codec right now */

                ff_rtp_get_codec_info(st->codec, rtsp_st->sdp_payload_type);

                if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&

                    st->codec->sample_rate > 0)

                    avpriv_set_pts_info(st, 32, 1, st->codec->sample_rate);

                /* Even static payload types may need a custom depacketizer */

                handler = ff_rtp_handler_find_by_id(

                              rtsp_st->sdp_payload_type, st->codec->codec_type);

                init_rtp_handler(handler, rtsp_st, st->codec);

                if (handler && handler->init)

                    handler->init(s, st->index,

                                  rtsp_st->dynamic_protocol_context);

            }

        }

        /* put a default control url */

        av_strlcpy(rtsp_st->control_url, rt->control_uri,

                   sizeof(rtsp_st->control_url));

        break;

    case 'a':

        if (av_strstart(p, "control:", &p)) {

            if (s->nb_streams == 0) {

                if (!strncmp(p, "rtsp://", 7))

                    av_strlcpy(rt->control_uri, p,

                               sizeof(rt->control_uri));

            } else {

                char proto[32];

                /* get the control url */

                rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];

                /* XXX: may need to add full url resolution */

                av_url_split(proto, sizeof(proto), NULL, 0, NULL, 0,

                             NULL, NULL, 0, p);

                if (proto[0] == '\0') {

                    /* relative control URL */

                    if (rtsp_st->control_url[strlen(rtsp_st->control_url)-1]!='/')

                    av_strlcat(rtsp_st->control_url, "/",

                               sizeof(rtsp_st->control_url));

                    av_strlcat(rtsp_st->control_url, p,

                               sizeof(rtsp_st->control_url));

                } else

                    av_strlcpy(rtsp_st->control_url, p,

                               sizeof(rtsp_st->control_url));

            }

        } else if (av_strstart(p, "rtpmap:", &p) && s->nb_streams > 0) {

            /* NOTE: rtpmap is only supported AFTER the 'm=' tag */

            get_word(buf1, sizeof(buf1), &p);

            payload_type = atoi(buf1);

            rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];

            if (rtsp_st->stream_index >= 0) {

                st = s->streams[rtsp_st->stream_index];

                sdp_parse_rtpmap(s, st, rtsp_st, payload_type, p);

            }

            s1->seen_rtpmap = 1;

            if (s1->seen_fmtp) {

                parse_fmtp(s, rt, payload_type, s1->delayed_fmtp);

            }

        } else if (av_strstart(p, "fmtp:", &p) ||

                   av_strstart(p, "framesize:", &p)) {

            // let dynamic protocol handlers have a stab at the line.

            get_word(buf1, sizeof(buf1), &p);

            payload_type = atoi(buf1);

            if (s1->seen_rtpmap) {

                parse_fmtp(s, rt, payload_type, buf);

            } else {

                s1->seen_fmtp = 1;

                av_strlcpy(s1->delayed_fmtp, buf, sizeof(s1->delayed_fmtp));

            }

        } else if (av_strstart(p, "range:", &p)) {

            int64_t start, end;

            // this is so that seeking on a streamed file can work.

            rtsp_parse_range_npt(p, &start, &end);

            s->start_time = start;

            /* AV_NOPTS_VALUE means live broadcast (and can't seek) */

            s->duration   = (end == AV_NOPTS_VALUE) ?

                            AV_NOPTS_VALUE : end - start;

        } else if (av_strstart(p, "IsRealDataType:integer;",&p)) {

            if (atoi(p) == 1)

                rt->transport = RTSP_TRANSPORT_RDT;

        } else if (av_strstart(p, "SampleRate:integer;", &p) &&

                   s->nb_streams > 0) {

            st = s->streams[s->nb_streams - 1];

            st->codec->sample_rate = atoi(p);

        } else if (av_strstart(p, "crypto:", &p) && s->nb_streams > 0) {

            // RFC 4568

            rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];

            get_word(buf1, sizeof(buf1), &p); // ignore tag

            get_word(rtsp_st->crypto_suite, sizeof(rtsp_st->crypto_suite), &p);

            p += strspn(p, SPACE_CHARS);

            if (av_strstart(p, "inline:", &p))

                get_word(rtsp_st->crypto_params, sizeof(rtsp_st->crypto_params), &p);

        } else if (av_strstart(p, "source-filter:", &p)) {

            int exclude = 0;

            get_word(buf1, sizeof(buf1), &p);

            if (strcmp(buf1, "incl") && strcmp(buf1, "excl"))

                return;

            exclude = !strcmp(buf1, "excl");

            get_word(buf1, sizeof(buf1), &p);

            if (strcmp(buf1, "IN") != 0)

                return;

            get_word(buf1, sizeof(buf1), &p);

            if (strcmp(buf1, "IP4") && strcmp(buf1, "IP6") && strcmp(buf1, "*"))

                return;

            // not checking that the destination address actually matches or is wildcard

            get_word(buf1, sizeof(buf1), &p);

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

                rtsp_src = av_mallocz(sizeof(*rtsp_src));

                if (!rtsp_src)

                    return;

                get_word(rtsp_src->addr, sizeof(rtsp_src->addr), &p);

                if (exclude) {

                    if (s->nb_streams == 0) {

                        dynarray_add(&s1->default_exclude_source_addrs, &s1->nb_default_exclude_source_addrs, rtsp_src);

                    } else {

                        rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];

                        dynarray_add(&rtsp_st->exclude_source_addrs, &rtsp_st->nb_exclude_source_addrs, rtsp_src);

                    }

                } else {

                    if (s->nb_streams == 0) {

                        dynarray_add(&s1->default_include_source_addrs, &s1->nb_default_include_source_addrs, rtsp_src);

                    } else {

                        rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];

                        dynarray_add(&rtsp_st->include_source_addrs, &rtsp_st->nb_include_source_addrs, rtsp_src);

                    }

                }

            }

        } else {

            if (rt->server_type == RTSP_SERVER_WMS)

                ff_wms_parse_sdp_a_line(s, p);

            if (s->nb_streams > 0) {

                rtsp_st = rt->rtsp_streams[rt->nb_rtsp_streams - 1];

                if (rt->server_type == RTSP_SERVER_REAL)

                    ff_real_parse_sdp_a_line(s, rtsp_st->stream_index, p);

                if (rtsp_st->dynamic_handler &&

                    rtsp_st->dynamic_handler->parse_sdp_a_line)

                    rtsp_st->dynamic_handler->parse_sdp_a_line(s,

                        rtsp_st->stream_index,

                        rtsp_st->dynamic_protocol_context, buf);

            }

        }

        break;

    }

}


av_cold void ff_mlpdsp_init(MLPDSPContext *c)

{

    c->mlp_filter_channel = mlp_filter_channel;

    if (ARCH_X86)

        ff_mlpdsp_init_x86(c);

}


int coroutine_fn qemu_co_sendv(int sockfd, struct iovec *iov,

                               int len, int iov_offset)

{

    int total = 0;

    int ret;

    while (len) {

        ret = qemu_sendv(sockfd, iov, len, iov_offset + total);

        if (ret < 0) {

            if (errno == EAGAIN) {

                qemu_coroutine_yield();

                continue;

            }

            if (total == 0) {

                total = -1;

            }

            break;

        }

        total += ret, len -= ret;

    }

    return total;

}


static PullupField *make_field_queue(PullupContext *s, int len)

{

    PullupField *head, *f;

    f = head = av_mallocz(sizeof(*head));

    if (!f)

        return NULL;

    if (alloc_metrics(s, f) < 0) {

        av_free(f);

        return NULL;

    }

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

        f->next = av_mallocz(sizeof(*f->next));

        if (!f->next) {

            free_field_queue(head, &f);

            return NULL;

        }

        f->next->prev = f;

        f = f->next;

        if (alloc_metrics(s, f) < 0) {

            free_field_queue(head, &f);

            return NULL;

        }

    }

    f->next = head;

    head->prev = f;

    return head;

}


static void lan9118_writel(void *opaque, target_phys_addr_t offset,

                           uint32_t val)

{

    lan9118_state *s = (lan9118_state *)opaque;

    offset &= 0xff;

    //DPRINTF("Write reg 0x%02x = 0x%08x\n", (int)offset, val);

    if (offset >= 0x20 && offset < 0x40) {

        /* TX FIFO */

        tx_fifo_push(s, val);

        return;

    }

    switch (offset) {

    case CSR_IRQ_CFG:

        /* TODO: Implement interrupt deassertion intervals.  */

        s->irq_cfg = (s->irq_cfg & IRQ_INT) | (val & IRQ_EN);

        break;

    case CSR_INT_STS:

        s->int_sts &= ~val;

        break;

    case CSR_INT_EN:

        s->int_en = val & ~RESERVED_INT;

        s->int_sts |= val & SW_INT;

        break;

    case CSR_FIFO_INT:

        DPRINTF("FIFO INT levels %08x\n", val);

        s->fifo_int = val;

        break;

    case CSR_RX_CFG:

        if (val & 0x8000) {

            /* RX_DUMP */

            s->rx_fifo_used = 0;

            s->rx_status_fifo_used = 0;

            s->rx_packet_size_tail = s->rx_packet_size_head;

            s->rx_packet_size[s->rx_packet_size_head] = 0;

        }

        s->rx_cfg = val & 0xcfff1ff0;

        break;

    case CSR_TX_CFG:

        if (val & 0x8000) {

            s->tx_status_fifo_used = 0;

        }

        if (val & 0x4000) {

            s->txp->state = TX_IDLE;

            s->txp->fifo_used = 0;

            s->txp->cmd_a = 0xffffffff;

        }

        s->tx_cfg = val & 6;

        break;

    case CSR_HW_CFG:

        if (val & 1) {

            /* SRST */

            lan9118_reset(&s->busdev.qdev);

        } else {

            s->hw_cfg = val & 0x003f300;

        }

        break;

    case CSR_RX_DP_CTRL:

        if (val & 0x80000000) {

            /* Skip forward to next packet.  */

            s->rxp_pad = 0;

            s->rxp_offset = 0;

            if (s->rxp_size == 0) {

                /* Pop a word to start the next packet.  */

                rx_fifo_pop(s);

                s->rxp_pad = 0;

                s->rxp_offset = 0;

            }

            s->rx_fifo_head += s->rxp_size;

            if (s->rx_fifo_head >= s->rx_fifo_size) {

                s->rx_fifo_head -= s->rx_fifo_size;

            }

        }

        break;

    case CSR_PMT_CTRL:

        if (val & 0x400) {

            phy_reset(s);

        }

        s->pmt_ctrl &= ~0x34e;

        s->pmt_ctrl |= (val & 0x34e);

        break;

    case CSR_GPIO_CFG:

        /* Probably just enabling LEDs.  */

        s->gpio_cfg = val & 0x7777071f;

        break;

    case CSR_GPT_CFG:

        if ((s->gpt_cfg ^ val) & GPT_TIMER_EN) {

            if (val & GPT_TIMER_EN) {

                ptimer_set_count(s->timer, val & 0xffff);

                ptimer_run(s->timer, 0);

            } else {

                ptimer_stop(s->timer);

                ptimer_set_count(s->timer, 0xffff);

            }

        }

        s->gpt_cfg = val & (GPT_TIMER_EN | 0xffff);

        break;

    case CSR_WORD_SWAP:

        /* Ignored because we're in 32-bit mode.  */

        s->word_swap = val;

        break;

    case CSR_MAC_CSR_CMD:

        s->mac_cmd = val & 0x4000000f;

        if (val & 0x80000000) {

            if (val & 0x40000000) {

                s->mac_data = do_mac_read(s, val & 0xf);

                DPRINTF("MAC read %d = 0x%08x\n", val & 0xf, s->mac_data);

            } else {

                DPRINTF("MAC write %d = 0x%08x\n", val & 0xf, s->mac_data);

                do_mac_write(s, val & 0xf, s->mac_data);

            }

        }

        break;

    case CSR_MAC_CSR_DATA:

        s->mac_data = val;

        break;

    case CSR_AFC_CFG:

        s->afc_cfg = val & 0x00ffffff;

        break;

    case CSR_E2P_CMD:

        lan9118_eeprom_cmd(s, (val >> 28) & 7, val & 0xff);

        break;

    case CSR_E2P_DATA:

        s->e2p_data = val & 0xff;

        break;

    default:

        hw_error("lan9118_write: Bad reg 0x%x = %x\n", (int)offset, val);

        break;

    }

    lan9118_update(s);

}


static av_cold int fdk_aac_decode_init(AVCodecContext *avctx)

{

    FDKAACDecContext *s = avctx->priv_data;

    AAC_DECODER_ERROR err;

    int ret;

    s->handle = aacDecoder_Open(avctx->extradata_size ? TT_MP4_RAW : TT_MP4_ADTS, 1);

    if (!s->handle) {

        av_log(avctx, AV_LOG_ERROR, "Error opening decoder\n");

        return AVERROR_UNKNOWN;

    }

    if (avctx->extradata_size) {

        if ((err = aacDecoder_ConfigRaw(s->handle, &avctx->extradata,

                                        &avctx->extradata_size)) != AAC_DEC_OK) {

            av_log(avctx, AV_LOG_ERROR, "Unable to set extradata\n");

            return AVERROR_INVALIDDATA;

        }

    }

    if ((err = aacDecoder_SetParam(s->handle, AAC_CONCEAL_METHOD,

                                   s->conceal_method)) != AAC_DEC_OK) {

        av_log(avctx, AV_LOG_ERROR, "Unable to set error concealment method\n");

        return AVERROR_UNKNOWN;

    }

    if (avctx->request_channel_layout > 0 &&

        avctx->request_channel_layout != AV_CH_LAYOUT_NATIVE) {

        int downmix_channels = -1;

        switch (avctx->request_channel_layout) {

        case AV_CH_LAYOUT_STEREO:

        case AV_CH_LAYOUT_STEREO_DOWNMIX:

            downmix_channels = 2;

            break;

        case AV_CH_LAYOUT_MONO:

            downmix_channels = 1;

            break;

        default:

            av_log(avctx, AV_LOG_WARNING, "Invalid request_channel_layout\n");

            break;

        }

        if (downmix_channels != -1) {

            if (aacDecoder_SetParam(s->handle, AAC_PCM_MAX_OUTPUT_CHANNELS,

                                    downmix_channels) != AAC_DEC_OK) {

               av_log(avctx, AV_LOG_WARNING, "Unable to set output channels in the decoder\n");

            } else {

               s->anc_buffer = av_malloc(DMX_ANC_BUFFSIZE);

               if (!s->anc_buffer) {

                   av_log(avctx, AV_LOG_ERROR, "Unable to allocate ancillary buffer for the decoder\n");

                   ret = AVERROR(ENOMEM);

                   goto fail;

               }

               if (aacDecoder_AncDataInit(s->handle, s->anc_buffer, DMX_ANC_BUFFSIZE)) {

                   av_log(avctx, AV_LOG_ERROR, "Unable to register downmix ancillary buffer in the decoder\n");

                   ret = AVERROR_UNKNOWN;

                   goto fail;

               }

            }

        }

    }

    if (s->drc_boost != -1) {

        if (aacDecoder_SetParam(s->handle, AAC_DRC_BOOST_FACTOR, s->drc_boost) != AAC_DEC_OK) {

            av_log(avctx, AV_LOG_ERROR, "Unable to set DRC boost factor in the decoder\n");

            return AVERROR_UNKNOWN;

        }

    }

    if (s->drc_cut != -1) {

        if (aacDecoder_SetParam(s->handle, AAC_DRC_ATTENUATION_FACTOR, s->drc_cut) != AAC_DEC_OK) {

            av_log(avctx, AV_LOG_ERROR, "Unable to set DRC attenuation factor in the decoder\n");

            return AVERROR_UNKNOWN;

        }

    }

    if (s->drc_level != -1) {

        if (aacDecoder_SetParam(s->handle, AAC_DRC_REFERENCE_LEVEL, s->drc_level) != AAC_DEC_OK) {

            av_log(avctx, AV_LOG_ERROR, "Unable to set DRC reference level in the decoder\n");

            return AVERROR_UNKNOWN;

        }

    }

    if (s->drc_heavy != -1) {

        if (aacDecoder_SetParam(s->handle, AAC_DRC_HEAVY_COMPRESSION, s->drc_heavy) != AAC_DEC_OK) {

            av_log(avctx, AV_LOG_ERROR, "Unable to set DRC heavy compression in the decoder\n");

            return AVERROR_UNKNOWN;

        }

    }

#ifdef AACDECODER_LIB_VL0

    if (aacDecoder_SetParam(s->handle, AAC_PCM_LIMITER_ENABLE, s->level_limit) != AAC_DEC_OK) {

        av_log(avctx, AV_LOG_ERROR, "Unable to set in signal level limiting in the decoder\n");

        return AVERROR_UNKNOWN;

    }

#endif

    avctx->sample_fmt = AV_SAMPLE_FMT_S16;

    s->decoder_buffer_size = DECODER_BUFFSIZE * DECODER_MAX_CHANNELS;

    s->decoder_buffer = av_malloc(s->decoder_buffer_size);

    if (!s->decoder_buffer) {

        ret = AVERROR(ENOMEM);

        goto fail;

    }

    return 0;

fail:

    fdk_aac_decode_close(avctx);

    return ret;

}


int ff_hevc_decode_extradata(const uint8_t *data, int size, HEVCParamSets *ps,

                             int *is_nalff, int *nal_length_size,

                             int err_recognition, void *logctx)

{

    int ret = 0;

    GetByteContext gb;

    bytestream2_init(&gb, data, size);

    if (size > 3 && (data[0] || data[1] || data[2] > 1)) {

        /* It seems the extradata is encoded as hvcC format.

         * Temporarily, we support configurationVersion==0 until 14496-15 3rd

         * is finalized. When finalized, configurationVersion will be 1 and we

         * can recognize hvcC by checking if avctx->extradata[0]==1 or not. */

        int i, j, num_arrays, nal_len_size;

        *is_nalff = 1;

        bytestream2_skip(&gb, 21);

        nal_len_size = (bytestream2_get_byte(&gb) & 3) + 1;

        num_arrays   = bytestream2_get_byte(&gb);

        /* nal units in the hvcC always have length coded with 2 bytes,

         * so put a fake nal_length_size = 2 while parsing them */

        *nal_length_size = 2;

        /* Decode nal units from hvcC. */

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

            int type = bytestream2_get_byte(&gb) & 0x3f;

            int cnt  = bytestream2_get_be16(&gb);

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

                // +2 for the nal size field

                int nalsize = bytestream2_peek_be16(&gb) + 2;

                if (bytestream2_get_bytes_left(&gb) < nalsize) {

                    av_log(logctx, AV_LOG_ERROR,

                           "Invalid NAL unit size in extradata.\n");

                    return AVERROR_INVALIDDATA;

                }

                ret = hevc_decode_nal_units(gb.buffer, nalsize, ps, *is_nalff, *nal_length_size, logctx);

                if (ret < 0) {

                    av_log(logctx, AV_LOG_ERROR,

                           "Decoding nal unit %d %d from hvcC failed\n",

                           type, i);

                    return ret;

                }

                bytestream2_skip(&gb, nalsize);

            }

        }

        /* Now store right nal length size, that will be used to parse

         * all other nals */

        *nal_length_size = nal_len_size;

    } else {

        *is_nalff = 0;

        ret = hevc_decode_nal_units(data, size, ps, *is_nalff, *nal_length_size, logctx);

        if (ret < 0)

            return ret;

    }

    return ret;

}


static void frame_thread_free(AVCodecContext *avctx, int thread_count)

{

    FrameThreadContext *fctx = avctx->thread_opaque;

    AVCodec *codec = avctx->codec;

    int i;

    park_frame_worker_threads(fctx, thread_count);

    if (fctx->prev_thread && fctx->prev_thread != fctx->threads)

        update_context_from_thread(fctx->threads->avctx, fctx->prev_thread->avctx, 0);

    fctx->die = 1;

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

        PerThreadContext *p = &fctx->threads[i];

        pthread_mutex_lock(&p->mutex);

        pthread_cond_signal(&p->input_cond);

        pthread_mutex_unlock(&p->mutex);

        pthread_join(p->thread, NULL);

        if (codec->close)

            codec->close(p->avctx);

        avctx->codec = NULL;

        release_delayed_buffers(p);

    }

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

        PerThreadContext *p = &fctx->threads[i];

        avcodec_default_free_buffers(p->avctx);

        pthread_mutex_destroy(&p->mutex);

        pthread_mutex_destroy(&p->progress_mutex);

        pthread_cond_destroy(&p->input_cond);

        pthread_cond_destroy(&p->progress_cond);

        pthread_cond_destroy(&p->output_cond);

        av_freep(&p->avpkt.data);

        if (i)

            av_freep(&p->avctx->priv_data);

        av_freep(&p->avctx);

    }

    av_freep(&fctx->threads);

    pthread_mutex_destroy(&fctx->buffer_mutex);

    av_freep(&avctx->thread_opaque);

    avctx->has_b_frames -= avctx->thread_count - 1;

}


int qio_dns_resolver_lookup_sync(QIODNSResolver *resolver,

                                 SocketAddress *addr,

                                 size_t *naddrs,

                                 SocketAddress ***addrs,

                                 Error **errp)

{

    switch (addr->type) {

    case SOCKET_ADDRESS_KIND_INET:

        return qio_dns_resolver_lookup_sync_inet(resolver,

                                                 addr,

                                                 naddrs,

                                                 addrs,

                                                 errp);

    case SOCKET_ADDRESS_KIND_UNIX:

    case SOCKET_ADDRESS_KIND_VSOCK:

    case SOCKET_ADDRESS_KIND_FD:

        return qio_dns_resolver_lookup_sync_nop(resolver,

                                                addr,

                                                naddrs,

                                                addrs,

                                                errp);

    default:

        abort();

    }

}


int fw_cfg_add_file(FWCfgState *s,  const char *dir, const char *filename,

                    uint8_t *data, uint32_t len)

{

    const char *basename;

    int index;

    if (!s->files) {

        int dsize = sizeof(uint32_t) + sizeof(FWCfgFile) * FW_CFG_FILE_SLOTS;

        s->files = qemu_mallocz(dsize);

        fw_cfg_add_bytes(s, FW_CFG_FILE_DIR, (uint8_t*)s->files, dsize);

    }

    index = be32_to_cpu(s->files->count);

    if (index == FW_CFG_FILE_SLOTS) {

        fprintf(stderr, "fw_cfg: out of file slots\n");

        return 0;

    }

    fw_cfg_add_bytes(s, FW_CFG_FILE_FIRST + index, data, len);

    basename = strrchr(filename, '/');

    if (basename) {

        basename++;

    } else {

        basename = filename;

    }

    if (dir) {

        snprintf(s->files->f[index].name, sizeof(s->files->f[index].name),

                 "%s/%s", dir, basename);

    } else {

        snprintf(s->files->f[index].name, sizeof(s->files->f[index].name),

                 "%s", basename);

    }

    s->files->f[index].size   = cpu_to_be32(len);

    s->files->f[index].select = cpu_to_be16(FW_CFG_FILE_FIRST + index);

    FW_CFG_DPRINTF("%s: #%d: %s (%d bytes)\n", __FUNCTION__,

                   index, s->files->f[index].name, len);

    s->files->count = cpu_to_be32(index+1);

    return 1;

}


static void mov_text_text_cb(void *priv, const char *text, int len)

{

    MovTextContext *s = priv;

    av_strlcpy(s->ptr, text, FFMIN(s->end - s->ptr, len + 1));

    s->ptr += len;

}


void qmp_balloon(int64_t value, Error **errp)

{

    if (kvm_enabled() && !kvm_has_sync_mmu()) {

        error_set(errp, QERR_KVM_MISSING_CAP, "synchronous MMU", "balloon");

        return;

    }

    if (value <= 0) {

        error_set(errp, QERR_INVALID_PARAMETER_VALUE, "target", "a size");

        return;

    }

    if (qemu_balloon(value) == 0) {

        error_set(errp, QERR_DEVICE_NOT_ACTIVE, "balloon");

    }

}


struct GuestFileSeek *qmp_guest_file_seek(int64_t handle, int64_t offset,

                                          int64_t whence, Error **errp)

{

    GuestFileHandle *gfh = guest_file_handle_find(handle, errp);

    GuestFileSeek *seek_data = NULL;

    FILE *fh;

    int ret;

    if (!gfh) {

        return NULL;

    }

    fh = gfh->fh;

    ret = fseek(fh, offset, whence);

    if (ret == -1) {

        error_setg_errno(errp, errno, "failed to seek file");

        if (errno == ESPIPE) {

            /* file is non-seekable, stdio shouldn't be buffering anyways */

            gfh->state = RW_STATE_NEW;

        }

    } else {

        seek_data = g_new0(GuestFileSeek, 1);

        seek_data->position = ftell(fh);

        seek_data->eof = feof(fh);

        gfh->state = RW_STATE_NEW;

    }

    clearerr(fh);

    return seek_data;

}


static bool virtio_device_endian_needed(void *opaque)

{

    VirtIODevice *vdev = opaque;

    assert(vdev->device_endian != VIRTIO_DEVICE_ENDIAN_UNKNOWN);

    if (!virtio_has_feature(vdev, VIRTIO_F_VERSION_1)) {

        return vdev->device_endian != virtio_default_endian();

    }

    /* Devices conforming to VIRTIO 1.0 or later are always LE. */

    return vdev->device_endian != VIRTIO_DEVICE_ENDIAN_LITTLE;

}


static int uhci_handle_td(UHCIState *s, uint32_t addr, UHCI_TD *td, uint32_t *int_mask)

{

    UHCIAsync *async;

    int len = 0, max_len;

    uint8_t pid;

    /* Is active ? */

    if (!(td->ctrl & TD_CTRL_ACTIVE))

        return 1;

    async = uhci_async_find_td(s, addr, td->token);

    if (async) {

        /* Already submitted */

        async->valid = 32;

        if (!async->done)

            return 1;

        uhci_async_unlink(s, async);

        goto done;

    }

    /* Allocate new packet */

    async = uhci_async_alloc(s);

    if (!async)

        return 1;

    async->valid = 10;

    async->td    = addr;

    async->token = td->token;

    max_len = ((td->token >> 21) + 1) & 0x7ff;

    pid = td->token & 0xff;

    async->packet.pid     = pid;

    async->packet.devaddr = (td->token >> 8) & 0x7f;

    async->packet.devep   = (td->token >> 15) & 0xf;

    async->packet.data    = async->buffer;

    async->packet.len     = max_len;

    async->packet.complete_cb     = uhci_async_complete;

    async->packet.complete_opaque = s;

    switch(pid) {

    case USB_TOKEN_OUT:

    case USB_TOKEN_SETUP:

        cpu_physical_memory_read(td->buffer, async->buffer, max_len);

        len = uhci_broadcast_packet(s, &async->packet);

        if (len >= 0)

            len = max_len;

        break;

    case USB_TOKEN_IN:

        len = uhci_broadcast_packet(s, &async->packet);

        break;

    default:

        /* invalid pid : frame interrupted */

        uhci_async_free(s, async);

        s->status |= UHCI_STS_HCPERR;

        uhci_update_irq(s);

        return -1;

    }

    if (len == USB_RET_ASYNC) {

        uhci_async_link(s, async);

        return 2;

    }

    async->packet.len = len;

done:

    len = uhci_complete_td(s, td, async, int_mask);

    uhci_async_free(s, async);

    return len;

}


static void omap_pwt_write(void *opaque, hwaddr addr,

                           uint64_t value, unsigned size)

{

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

    int offset = addr & OMAP_MPUI_REG_MASK;

    if (size != 1) {

        omap_badwidth_write8(opaque, addr, value);

        return;

    }

    switch (offset) {

    case 0x00:	/* FRC */

        s->frc = value & 0x3f;

        break;

    case 0x04:	/* VRC */

        if ((value ^ s->vrc) & 1) {

            if (value & 1)

                printf("%s: %iHz buzz on\n", __FUNCTION__, (int)

                                /* 1.5 MHz from a 12-MHz or 13-MHz PWT_CLK */

                                ((omap_clk_getrate(s->clk) >> 3) /

                                 /* Pre-multiplexer divider */

                                 ((s->gcr & 2) ? 1 : 154) /

                                 /* Octave multiplexer */

                                 (2 << (value & 3)) *

                                 /* 101/107 divider */

                                 ((value & (1 << 2)) ? 101 : 107) *

                                 /*  49/55 divider */

                                 ((value & (1 << 3)) ?  49 : 55) *

                                 /*  50/63 divider */

                                 ((value & (1 << 4)) ?  50 : 63) *

                                 /*  80/127 divider */

                                 ((value & (1 << 5)) ?  80 : 127) /

                                 (107 * 55 * 63 * 127)));

            else

                printf("%s: silence!\n", __FUNCTION__);

        }

        s->vrc = value & 0x7f;

        break;

    case 0x08:	/* GCR */

        s->gcr = value & 3;

        break;

    default:

        OMAP_BAD_REG(addr);

        return;

    }

}


START_TEST(unterminated_array_comma)

{

    QObject *obj = qobject_from_json("[32,");

    fail_unless(obj == NULL);

}


uint64_t ppc_hash64_start_access(PowerPCCPU *cpu, target_ulong pte_index)

{

    uint64_t token = 0;

    hwaddr pte_offset;

    pte_offset = pte_index * HASH_PTE_SIZE_64;

    if (cpu->env.external_htab == MMU_HASH64_KVM_MANAGED_HPT) {

        /*

         * HTAB is controlled by KVM. Fetch the PTEG into a new buffer.

         */

        token = kvmppc_hash64_read_pteg(cpu, pte_index);

    } else if (cpu->env.external_htab) {

        /*

         * HTAB is controlled by QEMU. Just point to the internally

         * accessible PTEG.

         */

        token = (uint64_t)(uintptr_t) cpu->env.external_htab + pte_offset;

    } else if (cpu->env.htab_base) {

        token = cpu->env.htab_base + pte_offset;

    }

    return token;

}


static inline void gen_neon_negl(TCGv var, int size)

{

    switch (size) {

    case 0: gen_helper_neon_negl_u16(var, var); break;

    case 1: gen_helper_neon_negl_u32(var, var); break;

    case 2: gen_helper_neon_negl_u64(var, var); break;

    default: abort();

    }

}


void curses_display_init(DisplayState *ds, int full_screen)

{

#ifndef _WIN32

    if (!isatty(1)) {

        fprintf(stderr, "We need a terminal output\n");

        exit(1);

    }

#endif

    curses_setup();

    curses_keyboard_setup();

    atexit(curses_atexit);

#ifndef _WIN32

    signal(SIGINT, SIG_DFL);

    signal(SIGQUIT, SIG_DFL);

#if defined(SIGWINCH) && defined(KEY_RESIZE)

    /* some curses implementations provide a handler, but we

     * want to be sure this is handled regardless of the library */

    signal(SIGWINCH, curses_winch_handler);

#endif

#endif

    ds->data = (void *) screen;

    ds->linesize = 0;

    ds->depth = 0;

    ds->width = 640;

    ds->height = 400;

    ds->dpy_update = curses_update;

    ds->dpy_resize = curses_resize;

    ds->dpy_refresh = curses_refresh;

    ds->dpy_text_cursor = curses_cursor_position;

    invalidate = 1;

    /* Standard VGA initial text mode dimensions */

    curses_resize(ds, 80, 25);

}