static void v9fs_create(void *opaque)

{

    int32_t fid;

    int err = 0;

    size_t offset = 7;

    V9fsFidState *fidp;

    V9fsQID qid;

    int32_t perm;

    int8_t mode;

    V9fsPath path;

    struct stat stbuf;

    V9fsString name;

    V9fsString extension;

    int iounit;

    V9fsPDU *pdu = opaque;

    v9fs_path_init(&path);

    pdu_unmarshal(pdu, offset, "dsdbs", &fid, &name,

                  &perm, &mode, &extension);

    trace_v9fs_create(pdu->tag, pdu->id, fid, name.data, perm, mode);

    fidp = get_fid(pdu, fid);

    if (fidp == NULL) {

        err = -EINVAL;

        goto out_nofid;

    }

    if (perm & P9_STAT_MODE_DIR) {

        err = v9fs_co_mkdir(pdu, fidp, &name, perm & 0777,

                            fidp->uid, -1, &stbuf);

        if (err < 0) {

            goto out;

        }

        err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path);

        if (err < 0) {

            goto out;

        }

        v9fs_path_copy(&fidp->path, &path);

        err = v9fs_co_opendir(pdu, fidp);

        if (err < 0) {

            goto out;

        }

        fidp->fid_type = P9_FID_DIR;

    } else if (perm & P9_STAT_MODE_SYMLINK) {

        err = v9fs_co_symlink(pdu, fidp, &name,

                              extension.data, -1 , &stbuf);

        if (err < 0) {

            goto out;

        }

        err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path);

        if (err < 0) {

            goto out;

        }

        v9fs_path_copy(&fidp->path, &path);

    } else if (perm & P9_STAT_MODE_LINK) {

        int32_t ofid = atoi(extension.data);

        V9fsFidState *ofidp = get_fid(pdu, ofid);

        if (ofidp == NULL) {

            err = -EINVAL;

            goto out;

        }

        err = v9fs_co_link(pdu, ofidp, fidp, &name);

        put_fid(pdu, ofidp);

        if (err < 0) {

            goto out;

        }

        err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path);

        if (err < 0) {

            fidp->fid_type = P9_FID_NONE;

            goto out;

        }

        v9fs_path_copy(&fidp->path, &path);

        err = v9fs_co_lstat(pdu, &fidp->path, &stbuf);

        if (err < 0) {

            fidp->fid_type = P9_FID_NONE;

            goto out;

        }

    } else if (perm & P9_STAT_MODE_DEVICE) {

        char ctype;

        uint32_t major, minor;

        mode_t nmode = 0;

        if (sscanf(extension.data, "%c %u %u", &ctype, &major, &minor) != 3) {

            err = -errno;

            goto out;

        }

        switch (ctype) {

        case 'c':

            nmode = S_IFCHR;

            break;

        case 'b':

            nmode = S_IFBLK;

            break;

        default:

            err = -EIO;

            goto out;

        }

        nmode |= perm & 0777;

        err = v9fs_co_mknod(pdu, fidp, &name, fidp->uid, -1,

                            makedev(major, minor), nmode, &stbuf);

        if (err < 0) {

            goto out;

        }

        err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path);

        if (err < 0) {

            goto out;

        }

        v9fs_path_copy(&fidp->path, &path);

    } else if (perm & P9_STAT_MODE_NAMED_PIPE) {

        err = v9fs_co_mknod(pdu, fidp, &name, fidp->uid, -1,

                            0, S_IFIFO | (perm & 0777), &stbuf);

        if (err < 0) {

            goto out;

        }

        err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path);

        if (err < 0) {

            goto out;

        }

        v9fs_path_copy(&fidp->path, &path);

    } else if (perm & P9_STAT_MODE_SOCKET) {

        err = v9fs_co_mknod(pdu, fidp, &name, fidp->uid, -1,

                            0, S_IFSOCK | (perm & 0777), &stbuf);

        if (err < 0) {

            goto out;

        }

        err = v9fs_co_name_to_path(pdu, &fidp->path, name.data, &path);

        if (err < 0) {

            goto out;

        }

        v9fs_path_copy(&fidp->path, &path);

    } else {

        err = v9fs_co_open2(pdu, fidp, &name, -1,

                            omode_to_uflags(mode)|O_CREAT, perm, &stbuf);

        if (err < 0) {

            goto out;

        }

        fidp->fid_type = P9_FID_FILE;

        fidp->open_flags = omode_to_uflags(mode);

        if (fidp->open_flags & O_EXCL) {

            /*

             * We let the host file system do O_EXCL check

             * We should not reclaim such fd

             */

            fidp->flags |= FID_NON_RECLAIMABLE;

        }

    }

    iounit = get_iounit(pdu, &fidp->path);

    stat_to_qid(&stbuf, &qid);

    offset += pdu_marshal(pdu, offset, "Qd", &qid, iounit);

    err = offset;

    trace_v9fs_create_return(pdu->tag, pdu->id,

                             qid.type, qid.version, qid.path, iounit);

out:

    put_fid(pdu, fidp);

out_nofid:

   complete_pdu(pdu->s, pdu, err);

   v9fs_string_free(&name);

   v9fs_string_free(&extension);

   v9fs_path_free(&path);

}


static void dma_bdrv_cb(void *opaque, int ret)

{

    DMAAIOCB *dbs = (DMAAIOCB *)opaque;

    dma_addr_t cur_addr, cur_len;

    void *mem;

    trace_dma_bdrv_cb(dbs, ret);

    dbs->acb = NULL;

    dbs->sector_num += dbs->iov.size / 512;

    if (dbs->sg_cur_index == dbs->sg->nsg || ret < 0) {

        dma_complete(dbs, ret);

        return;

    }

    dma_bdrv_unmap(dbs);

    while (dbs->sg_cur_index < dbs->sg->nsg) {

        cur_addr = dbs->sg->sg[dbs->sg_cur_index].base + dbs->sg_cur_byte;

        cur_len = dbs->sg->sg[dbs->sg_cur_index].len - dbs->sg_cur_byte;

        mem = dma_memory_map(dbs->sg->as, cur_addr, &cur_len, dbs->dir);

        if (!mem)

            break;

        qemu_iovec_add(&dbs->iov, mem, cur_len);

        dbs->sg_cur_byte += cur_len;

        if (dbs->sg_cur_byte == dbs->sg->sg[dbs->sg_cur_index].len) {

            dbs->sg_cur_byte = 0;

            ++dbs->sg_cur_index;

        }

    }

    if (dbs->iov.size == 0) {

        trace_dma_map_wait(dbs);

        cpu_register_map_client(dbs, continue_after_map_failure);

        return;

    }

    if (dbs->iov.size & ~BDRV_SECTOR_MASK) {

        qemu_iovec_discard_back(&dbs->iov, dbs->iov.size & ~BDRV_SECTOR_MASK);

    }

    dbs->acb = dbs->io_func(dbs->bs, dbs->sector_num, &dbs->iov,

                            dbs->iov.size / 512, dma_bdrv_cb, dbs);

    assert(dbs->acb);

}


static void vtd_root_table_setup(IntelIOMMUState *s)

{

    s->root = vtd_get_quad_raw(s, DMAR_RTADDR_REG);

    s->root_extended = s->root & VTD_RTADDR_RTT;

    s->root &= VTD_RTADDR_ADDR_MASK(VTD_HOST_ADDRESS_WIDTH);

    trace_vtd_reg_dmar_root(s->root, s->root_extended);

}


CharDriverState *qemu_chr_new_from_opts(QemuOpts *opts,

                                    void (*init)(struct CharDriverState *s),

                                    Error **errp)

{

    Error *local_err = NULL;

    CharDriver *cd;

    CharDriverState *chr;

    GSList *i;

    ChardevReturn *ret = NULL;

    ChardevBackend *backend;

    const char *id = qemu_opts_id(opts);

    char *bid = NULL;

    if (id == NULL) {

        error_setg(errp, "chardev: no id specified");

        goto err;

    }

    if (qemu_opt_get(opts, "backend") == NULL) {

        error_setg(errp, "chardev: \"%s\" missing backend",

                   qemu_opts_id(opts));

        goto err;

    }

    for (i = backends; i; i = i->next) {

        cd = i->data;

        if (strcmp(cd->name, qemu_opt_get(opts, "backend")) == 0) {

            break;

        }

    }

    if (i == NULL) {

        error_setg(errp, "chardev: backend \"%s\" not found",

                   qemu_opt_get(opts, "backend"));

        goto err;

    }

    backend = g_new0(ChardevBackend, 1);

    if (qemu_opt_get_bool(opts, "mux", 0)) {

        bid = g_strdup_printf("%s-base", id);

    }

    chr = NULL;

    backend->kind = cd->kind;

    if (cd->parse) {

        cd->parse(opts, backend, &local_err);

        if (local_err) {

            error_propagate(errp, local_err);

            goto qapi_out;

        }

    }

    ret = qmp_chardev_add(bid ? bid : id, backend, errp);

    if (!ret) {

        goto qapi_out;

    }

    if (bid) {

        qapi_free_ChardevBackend(backend);

        qapi_free_ChardevReturn(ret);

        backend = g_new0(ChardevBackend, 1);

        backend->mux = g_new0(ChardevMux, 1);

        backend->kind = CHARDEV_BACKEND_KIND_MUX;

        backend->mux->chardev = g_strdup(bid);

        ret = qmp_chardev_add(id, backend, errp);

        if (!ret) {

            chr = qemu_chr_find(bid);

            qemu_chr_delete(chr);

            chr = NULL;

            goto qapi_out;

        }

    }

    chr = qemu_chr_find(id);

    chr->opts = opts;

qapi_out:

    qapi_free_ChardevBackend(backend);

    qapi_free_ChardevReturn(ret);

    g_free(bid);

    return chr;

err:

    qemu_opts_del(opts);

    return NULL;

}


void hmp_cont(Monitor *mon, const QDict *qdict)

{

    Error *errp = NULL;

    qmp_cont(&errp);

    if (error_is_set(&errp)) {

        if (error_is_type(errp, QERR_DEVICE_ENCRYPTED)) {

            const char *device;

            /* The device is encrypted. Ask the user for the password

               and retry */

            device = error_get_field(errp, "device");

            assert(device != NULL);

            monitor_read_block_device_key(mon, device, hmp_cont_cb, mon);

            error_free(errp);

            return;

        }

        hmp_handle_error(mon, &errp);

    }

}


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

                             int *got_frame_ptr, AVPacket *avpkt)

{

    SmackerAudioContext *s = avctx->priv_data;

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    GetBitContext gb;

    HuffContext h[4] = { { 0 } };

    VLC vlc[4]       = { { 0 } };

    int16_t *samples;

    uint8_t *samples8;

    int val;

    int i, res, ret;

    int unp_size;

    int bits, stereo;

    int pred[2] = {0, 0};

    if (buf_size <= 4) {

        av_log(avctx, AV_LOG_ERROR, "packet is too small\n");

        return AVERROR(EINVAL);

    }

    unp_size = AV_RL32(buf);

    if (unp_size > (1U<<24)) {

        av_log(avctx, AV_LOG_ERROR, "packet is too big\n");

        return AVERROR_INVALIDDATA;

    }

    init_get_bits(&gb, buf + 4, (buf_size - 4) * 8);

    if(!get_bits1(&gb)){

        av_log(avctx, AV_LOG_INFO, "Sound: no data\n");

        *got_frame_ptr = 0;

        return 1;

    }

    stereo = get_bits1(&gb);

    bits = get_bits1(&gb);

    if (stereo ^ (avctx->channels != 1)) {

        av_log(avctx, AV_LOG_ERROR, "channels mismatch\n");

        return AVERROR(EINVAL);

    }

    if (bits && avctx->sample_fmt == AV_SAMPLE_FMT_U8) {

        av_log(avctx, AV_LOG_ERROR, "sample format mismatch\n");

        return AVERROR(EINVAL);

    }

    /* get output buffer */

    s->frame.nb_samples = unp_size / (avctx->channels * (bits + 1));

    if ((ret = avctx->get_buffer(avctx, &s->frame)) < 0) {

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

        return ret;

    }

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

    samples8 =            s->frame.data[0];

    // Initialize

    for(i = 0; i < (1 << (bits + stereo)); i++) {

        h[i].length = 256;

        h[i].maxlength = 0;

        h[i].current = 0;

        h[i].bits = av_mallocz(256 * 4);

        h[i].lengths = av_mallocz(256 * sizeof(int));

        h[i].values = av_mallocz(256 * sizeof(int));

        skip_bits1(&gb);

        smacker_decode_tree(&gb, &h[i], 0, 0);

        skip_bits1(&gb);

        if(h[i].current > 1) {

            res = init_vlc(&vlc[i], SMKTREE_BITS, h[i].length,

                    h[i].lengths, sizeof(int), sizeof(int),

                    h[i].bits, sizeof(uint32_t), sizeof(uint32_t), INIT_VLC_LE);

            if(res < 0) {

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

                return AVERROR_INVALIDDATA;

            }

        }

    }

    if(bits) { //decode 16-bit data

        for(i = stereo; i >= 0; i--)

            pred[i] = sign_extend(av_bswap16(get_bits(&gb, 16)), 16);

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

            *samples++ = pred[i];

        for(; i < unp_size / 2; i++) {

            if(get_bits_left(&gb)<0)

                return AVERROR_INVALIDDATA;

            if(i & stereo) {

                if(vlc[2].table)

                    res = get_vlc2(&gb, vlc[2].table, SMKTREE_BITS, 3);

                else

                    res = 0;

                if (res < 0) {

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

                    return AVERROR_INVALIDDATA;

                }

                val  = h[2].values[res];

                if(vlc[3].table)

                    res = get_vlc2(&gb, vlc[3].table, SMKTREE_BITS, 3);

                else

                    res = 0;

                if (res < 0) {

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

                    return AVERROR_INVALIDDATA;

                }

                val |= h[3].values[res] << 8;

                pred[1] += sign_extend(val, 16);

                *samples++ = av_clip_int16(pred[1]);

            } else {

                if(vlc[0].table)

                    res = get_vlc2(&gb, vlc[0].table, SMKTREE_BITS, 3);

                else

                    res = 0;

                if (res < 0) {

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

                    return AVERROR_INVALIDDATA;

                }

                val  = h[0].values[res];

                if(vlc[1].table)

                    res = get_vlc2(&gb, vlc[1].table, SMKTREE_BITS, 3);

                else

                    res = 0;

                if (res < 0) {

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

                    return AVERROR_INVALIDDATA;

                }

                val |= h[1].values[res] << 8;

                pred[0] += sign_extend(val, 16);

                *samples++ = av_clip_int16(pred[0]);

            }

        }

    } else { //8-bit data

        for(i = stereo; i >= 0; i--)

            pred[i] = get_bits(&gb, 8);

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

            *samples8++ = pred[i];

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

            if(get_bits_left(&gb)<0)

                return AVERROR_INVALIDDATA;

            if(i & stereo){

                if(vlc[1].table)

                    res = get_vlc2(&gb, vlc[1].table, SMKTREE_BITS, 3);

                else

                    res = 0;

                if (res < 0) {

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

                    return AVERROR_INVALIDDATA;

                }

                pred[1] += sign_extend(h[1].values[res], 8);

                *samples8++ = av_clip_uint8(pred[1]);

            } else {

                if(vlc[0].table)

                    res = get_vlc2(&gb, vlc[0].table, SMKTREE_BITS, 3);

                else

                    res = 0;

                if (res < 0) {

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

                    return AVERROR_INVALIDDATA;

                }

                pred[0] += sign_extend(h[0].values[res], 8);

                *samples8++ = av_clip_uint8(pred[0]);

            }

        }

    }

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

        if(vlc[i].table)

            ff_free_vlc(&vlc[i]);

        av_free(h[i].bits);

        av_free(h[i].lengths);

        av_free(h[i].values);

    }

    *got_frame_ptr   = 1;

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

    return buf_size;

}


CharDriverState *qemu_chr_open(const char *filename)

{

    const char *p;

    if (!strcmp(filename, "vc")) {

        return text_console_init(&display_state);

    } else if (!strcmp(filename, "null")) {

        return qemu_chr_open_null();

    } else

    if (strstart(filename, "tcp:", &p)) {

        return qemu_chr_open_tcp(p, 0, 0);

    } else

    if (strstart(filename, "telnet:", &p)) {

        return qemu_chr_open_tcp(p, 1, 0);

    } else

    if (strstart(filename, "udp:", &p)) {

        return qemu_chr_open_udp(p);

    } else

    if (strstart(filename, "mon:", &p)) {

        CharDriverState *drv = qemu_chr_open(p);

        if (drv) {

            drv = qemu_chr_open_mux(drv);

            monitor_init(drv, !nographic);

            return drv;

        }

        printf("Unable to open driver: %s\n", p);

        return 0;

    } else

#ifndef _WIN32

    if (strstart(filename, "unix:", &p)) {

	return qemu_chr_open_tcp(p, 0, 1);

    } else if (strstart(filename, "file:", &p)) {

        return qemu_chr_open_file_out(p);

    } else if (strstart(filename, "pipe:", &p)) {

        return qemu_chr_open_pipe(p);

    } else if (!strcmp(filename, "pty")) {

        return qemu_chr_open_pty();

    } else if (!strcmp(filename, "stdio")) {

        return qemu_chr_open_stdio();

    } else

#if defined(__linux__)

    if (strstart(filename, "/dev/parport", NULL)) {

        return qemu_chr_open_pp(filename);

    } else

#endif

    if (strstart(filename, "/dev/", NULL)) {

        return qemu_chr_open_tty(filename);

    } else

#else /* !_WIN32 */

    if (strstart(filename, "COM", NULL)) {

        return qemu_chr_open_win(filename);

    } else

    if (strstart(filename, "pipe:", &p)) {

        return qemu_chr_open_win_pipe(p);

    } else

    if (strstart(filename, "con:", NULL)) {

        return qemu_chr_open_win_con(filename);

    } else

    if (strstart(filename, "file:", &p)) {

        return qemu_chr_open_win_file_out(p);

    }

#endif

    {

        return NULL;

    }

}


void spapr_events_init(sPAPREnvironment *spapr)

{

    spapr->epow_irq = xics_alloc(spapr->icp, 0, 0, false);

    spapr->epow_notifier.notify = spapr_powerdown_req;

    qemu_register_powerdown_notifier(&spapr->epow_notifier);

    spapr_rtas_register(RTAS_CHECK_EXCEPTION, "check-exception",

                        check_exception);

}


GuestFileWrite *qmp_guest_file_write(int64_t handle, const char *buf_b64,

                                     bool has_count, int64_t count,

                                     Error **errp)

{

    GuestFileWrite *write_data = NULL;

    guchar *buf;

    gsize buf_len;

    bool is_ok;

    DWORD write_count;

    GuestFileHandle *gfh = guest_file_handle_find(handle, errp);

    HANDLE fh;

    if (!gfh) {

        return NULL;

    }

    fh = gfh->fh;

    buf = g_base64_decode(buf_b64, &buf_len);

    if (!has_count) {

        count = buf_len;

    } else if (count < 0 || count > buf_len) {

        error_setg(errp, "value '%" PRId64

                   "' is invalid for argument count", count);

        goto done;

    }

    is_ok = WriteFile(fh, buf, count, &write_count, NULL);

    if (!is_ok) {

        error_setg_win32(errp, GetLastError(), "failed to write to file");

        slog("guest-file-write-failed, handle: %" PRId64, handle);

    } else {

        write_data = g_new0(GuestFileWrite, 1);

        write_data->count = (size_t) write_count;

    }

done:

    g_free(buf);

    return write_data;

}


static int nbd_config(BDRVNBDState *s, QDict *options, char **export)

{

    Error *local_err = NULL;

    if (qdict_haskey(options, "path") == qdict_haskey(options, "host")) {

        if (qdict_haskey(options, "path")) {

            qerror_report(ERROR_CLASS_GENERIC_ERROR, "path and host may not "

                          "be used at the same time.");

        } else {

            qerror_report(ERROR_CLASS_GENERIC_ERROR, "one of path and host "

                          "must be specified.");

        }

        return -EINVAL;

    }

    s->client.is_unix = qdict_haskey(options, "path");

    s->socket_opts = qemu_opts_create(&socket_optslist, NULL, 0,

                                      &error_abort);

    qemu_opts_absorb_qdict(s->socket_opts, options, &local_err);

    if (local_err) {

        qerror_report_err(local_err);

        error_free(local_err);

        return -EINVAL;

    }

    if (!qemu_opt_get(s->socket_opts, "port")) {

        qemu_opt_set_number(s->socket_opts, "port", NBD_DEFAULT_PORT);

    }

    *export = g_strdup(qdict_get_try_str(options, "export"));

    if (*export) {

        qdict_del(options, "export");

    }

    return 0;

}


int qemu_loadvm_state(QEMUFile *f)

{

    LIST_HEAD(, LoadStateEntry) loadvm_handlers =

        LIST_HEAD_INITIALIZER(loadvm_handlers);

    LoadStateEntry *le, *new_le;

    uint8_t section_type;

    unsigned int v;

    int ret;

    v = qemu_get_be32(f);

    if (v != QEMU_VM_FILE_MAGIC)

        return -EINVAL;

    v = qemu_get_be32(f);

    if (v == QEMU_VM_FILE_VERSION_COMPAT) {

        fprintf(stderr, "SaveVM v2 format is obsolete and don't work anymore\n");

        return -ENOTSUP;

    }

    if (v != QEMU_VM_FILE_VERSION)

        return -ENOTSUP;

    while ((section_type = qemu_get_byte(f)) != QEMU_VM_EOF) {

        uint32_t instance_id, version_id, section_id;

        SaveStateEntry *se;

        char idstr[257];

        int len;

        switch (section_type) {

        case QEMU_VM_SECTION_START:

        case QEMU_VM_SECTION_FULL:

            /* Read section start */

            section_id = qemu_get_be32(f);

            len = qemu_get_byte(f);

            qemu_get_buffer(f, (uint8_t *)idstr, len);

            idstr[len] = 0;

            instance_id = qemu_get_be32(f);

            version_id = qemu_get_be32(f);

            /* Find savevm section */

            se = find_se(idstr, instance_id);

            if (se == NULL) {

                fprintf(stderr, "Unknown savevm section or instance '%s' %d\n", idstr, instance_id);

                ret = -EINVAL;

                goto out;

            }

            /* Validate version */

            if (version_id > se->version_id) {

                fprintf(stderr, "savevm: unsupported version %d for '%s' v%d\n",

                        version_id, idstr, se->version_id);

                ret = -EINVAL;

                goto out;

            }

            /* Add entry */

            le = qemu_mallocz(sizeof(*le));

            le->se = se;

            le->section_id = section_id;

            le->version_id = version_id;

            LIST_INSERT_HEAD(&loadvm_handlers, le, entry);

            ret = vmstate_load(f, le->se, le->version_id);

            if (ret < 0) {

                fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",

                        instance_id, idstr);

                goto out;

            }

            break;

        case QEMU_VM_SECTION_PART:

        case QEMU_VM_SECTION_END:

            section_id = qemu_get_be32(f);

            LIST_FOREACH(le, &loadvm_handlers, entry) {

                if (le->section_id == section_id) {

                    break;

                }

            }

            if (le == NULL) {

                fprintf(stderr, "Unknown savevm section %d\n", section_id);

                ret = -EINVAL;

                goto out;

            }

            ret = vmstate_load(f, le->se, le->version_id);

            if (ret < 0) {

                fprintf(stderr, "qemu: warning: error while loading state section id %d\n",

                        section_id);

                goto out;

            }

            break;

        default:

            fprintf(stderr, "Unknown savevm section type %d\n", section_type);

            ret = -EINVAL;

            goto out;

        }

    }

    ret = 0;

out:

    LIST_FOREACH_SAFE(le, &loadvm_handlers, entry, new_le) {

        LIST_REMOVE(le, entry);

        qemu_free(le);

    }

    if (qemu_file_has_error(f))

        ret = -EIO;

    return ret;

}


int cpu_breakpoint_remove(CPUState *cpu, vaddr pc, int flags)

{

#if defined(TARGET_HAS_ICE)

    CPUBreakpoint *bp;

    QTAILQ_FOREACH(bp, &cpu->breakpoints, entry) {

        if (bp->pc == pc && bp->flags == flags) {

            cpu_breakpoint_remove_by_ref(cpu, bp);

            return 0;

        }

    }

    return -ENOENT;

#else

    return -ENOSYS;

#endif

}


void kvm_s390_interrupt(S390CPU *cpu, int type, uint32_t code)

{

    kvm_s390_interrupt_internal(cpu, type, code, 0, 0);

}


static int device_init(AVFormatContext *ctx, int *width, int *height,

                       uint32_t pix_fmt)

{

    struct video_data *s = ctx->priv_data;

    int fd = s->fd;

    struct v4l2_format fmt;

    struct v4l2_pix_format *pix = &fmt.fmt.pix;

    int res;

    memset(&fmt, 0, sizeof(struct v4l2_format));

    fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;

    pix->width = *width;

    pix->height = *height;

    pix->pixelformat = pix_fmt;

    pix->field = V4L2_FIELD_ANY;

    res = ioctl(fd, VIDIOC_S_FMT, &fmt);

    if ((*width != fmt.fmt.pix.width) || (*height != fmt.fmt.pix.height)) {

        av_log(ctx, AV_LOG_INFO,

               "The V4L2 driver changed the video from %dx%d to %dx%d\n",

               *width, *height, fmt.fmt.pix.width, fmt.fmt.pix.height);

        *width = fmt.fmt.pix.width;

        *height = fmt.fmt.pix.height;

    }

    if (pix_fmt != fmt.fmt.pix.pixelformat) {

        av_log(ctx, AV_LOG_DEBUG,

               "The V4L2 driver changed the pixel format "

               "from 0x%08X to 0x%08X\n",

               pix_fmt, fmt.fmt.pix.pixelformat);

        res = -1;

    }

    if (fmt.fmt.pix.field == V4L2_FIELD_INTERLACED) {

        av_log(ctx, AV_LOG_DEBUG, "The V4L2 driver using the interlaced mode");

        s->interlaced = 1;

    }

    return res;

}


static void arm1026_initfn(Object *obj)

{

    ARMCPU *cpu = ARM_CPU(obj);

    cpu->dtb_compatible = "arm,arm1026";

    set_feature(&cpu->env, ARM_FEATURE_V5);

    set_feature(&cpu->env, ARM_FEATURE_VFP);

    set_feature(&cpu->env, ARM_FEATURE_AUXCR);

    set_feature(&cpu->env, ARM_FEATURE_DUMMY_C15_REGS);

    set_feature(&cpu->env, ARM_FEATURE_CACHE_TEST_CLEAN);

    cpu->midr = 0x4106a262;

    cpu->reset_fpsid = 0x410110a0;

    cpu->ctr = 0x1dd20d2;

    cpu->reset_sctlr = 0x00090078;

    cpu->reset_auxcr = 1;

    {

        /* The 1026 had an IFAR at c6,c0,0,1 rather than the ARMv6 c6,c0,0,2 */

        ARMCPRegInfo ifar = {

            .name = "IFAR", .cp = 15, .crn = 6, .crm = 0, .opc1 = 0, .opc2 = 1,

            .access = PL1_RW,

            .fieldoffset = offsetofhigh32(CPUARMState, cp15.far_el[1]),

            .resetvalue = 0

        };

        define_one_arm_cp_reg(cpu, &ifar);

    }

}


void msi_uninit(struct PCIDevice *dev)

{

    uint16_t flags;

    uint8_t cap_size;

    if (!(dev->cap_present & QEMU_PCI_CAP_MSI)) {

        return;

    }

    flags = pci_get_word(dev->config + msi_flags_off(dev));

    cap_size = msi_cap_sizeof(flags);

    pci_del_capability(dev, PCI_CAP_ID_MSI, cap_size);

    dev->cap_present &= ~QEMU_PCI_CAP_MSI;

    MSI_DEV_PRINTF(dev, "uninit\n");

}


static uint64_t mv88w8618_pic_read(void *opaque, target_phys_addr_t offset,

                                   unsigned size)

{

    mv88w8618_pic_state *s = opaque;

    switch (offset) {

    case MP_PIC_STATUS:

        return s->level & s->enabled;

    default:

        return 0;

    }

}


static int nic_can_receive(void *opaque)

{

    dp8393xState *s = opaque;

    if (!(s->regs[SONIC_CR] & SONIC_CR_RXEN))

        return 0;

    if (s->regs[SONIC_ISR] & SONIC_ISR_RBE)

        return 0;

    return 1;

}


void sm501_init(MemoryRegion *address_space_mem, uint32_t base,

                uint32_t local_mem_bytes, qemu_irq irq, CharDriverState *chr)

{

    SM501State * s;

    DeviceState *dev;

    MemoryRegion *sm501_system_config = g_new(MemoryRegion, 1);

    MemoryRegion *sm501_disp_ctrl = g_new(MemoryRegion, 1);

    MemoryRegion *sm501_2d_engine = g_new(MemoryRegion, 1);

    /* allocate management data region */

    s = (SM501State *)g_malloc0(sizeof(SM501State));

    s->base = base;

    s->local_mem_size_index

	= get_local_mem_size_index(local_mem_bytes);

    SM501_DPRINTF("local mem size=%x. index=%d\n", get_local_mem_size(s),

		  s->local_mem_size_index);

    s->system_control = 0x00100000;

    s->misc_control = 0x00001000; /* assumes SH, active=low */

    s->dc_panel_control = 0x00010000;

    s->dc_crt_control = 0x00010000;

    /* allocate local memory */

    memory_region_init_ram(&s->local_mem_region, "sm501.local",

                           local_mem_bytes);

    vmstate_register_ram_global(&s->local_mem_region);

    s->local_mem = memory_region_get_ram_ptr(&s->local_mem_region);

    memory_region_add_subregion(address_space_mem, base, &s->local_mem_region);

    /* map mmio */

    memory_region_init_io(sm501_system_config, &sm501_system_config_ops, s,

                          "sm501-system-config", 0x6c);

    memory_region_add_subregion(address_space_mem, base + MMIO_BASE_OFFSET,

                                sm501_system_config);

    memory_region_init_io(sm501_disp_ctrl, &sm501_disp_ctrl_ops, s,

                          "sm501-disp-ctrl", 0x1000);

    memory_region_add_subregion(address_space_mem,

                                base + MMIO_BASE_OFFSET + SM501_DC,

                                sm501_disp_ctrl);

    memory_region_init_io(sm501_2d_engine, &sm501_2d_engine_ops, s,

                          "sm501-2d-engine", 0x54);

    memory_region_add_subregion(address_space_mem,

                                base + MMIO_BASE_OFFSET + SM501_2D_ENGINE,

                                sm501_2d_engine);

    /* bridge to usb host emulation module */

    dev = qdev_create(NULL, "sysbus-ohci");

    qdev_prop_set_uint32(dev, "num-ports", 2);

    qdev_prop_set_taddr(dev, "dma-offset", base);

    qdev_init_nofail(dev);

    sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0,

                    base + MMIO_BASE_OFFSET + SM501_USB_HOST);

    sysbus_connect_irq(SYS_BUS_DEVICE(dev), 0, irq);

    /* bridge to serial emulation module */

    if (chr) {

        serial_mm_init(address_space_mem,

                       base + MMIO_BASE_OFFSET + SM501_UART0, 2,

                       NULL, /* TODO : chain irq to IRL */

                       115200, chr, DEVICE_NATIVE_ENDIAN);

    }

    /* create qemu graphic console */

    s->con = graphic_console_init(sm501_update_display, NULL,

                                  NULL, NULL, s);

}


static void pc_cpu_unplug_request_cb(HotplugHandler *hotplug_dev,

                                     DeviceState *dev, Error **errp)

{

    int idx = -1;

    HotplugHandlerClass *hhc;

    Error *local_err = NULL;

    PCMachineState *pcms = PC_MACHINE(hotplug_dev);

    pc_find_cpu_slot(pcms, CPU(dev), &idx);

    assert(idx != -1);

    if (idx == 0) {

        error_setg(&local_err, "Boot CPU is unpluggable");

        goto out;

    }

    if (idx < pcms->possible_cpus->len - 1 &&

        pcms->possible_cpus->cpus[idx + 1].cpu != NULL) {

        X86CPU *cpu;

        for (idx = pcms->possible_cpus->len - 1;

             pcms->possible_cpus->cpus[idx].cpu == NULL; idx--) {

            ;;

        }

        cpu = X86_CPU(pcms->possible_cpus->cpus[idx].cpu);

        error_setg(&local_err, "CPU [socket-id: %u, core-id: %u,"

                   " thread-id: %u] should be removed first",

                   cpu->socket_id, cpu->core_id, cpu->thread_id);

        goto out;

    }

    hhc = HOTPLUG_HANDLER_GET_CLASS(pcms->acpi_dev);

    hhc->unplug_request(HOTPLUG_HANDLER(pcms->acpi_dev), dev, &local_err);

    if (local_err) {

        goto out;

    }

 out:

    error_propagate(errp, local_err);

}


static int smc91c111_can_receive(void *opaque)

{

    smc91c111_state *s = (smc91c111_state *)opaque;

    if ((s->rcr & RCR_RXEN) == 0 || (s->rcr & RCR_SOFT_RST))

        return 1;

    if (s->allocated == (1 << NUM_PACKETS) - 1)

        return 0;

    return 1;

}


static void sigchld_bh_handler(void *opaque)

{

    ChildProcessRecord *rec, *next;

    QLIST_FOREACH_SAFE(rec, &child_watches, next, next) {

        if (waitpid(rec->pid, NULL, WNOHANG) == rec->pid) {

            QLIST_REMOVE(rec, next);

            g_free(rec);

        }

    }

}


static PCIIDEState *pci_from_bm(BMDMAState *bm)

{

    return bm->pci_dev;

}


static int local_set_mapped_file_attrat(int dirfd, const char *name,

                                        FsCred *credp)

{

    FILE *fp;

    int ret;

    char buf[ATTR_MAX];

    int uid = -1, gid = -1, mode = -1, rdev = -1;

    int map_dirfd;

    ret = mkdirat(dirfd, VIRTFS_META_DIR, 0700);

    if (ret < 0 && errno != EEXIST) {

        return -1;

    }

    map_dirfd = openat_dir(dirfd, VIRTFS_META_DIR);

    if (map_dirfd == -1) {

        return -1;

    }

    fp = local_fopenat(map_dirfd, name, "r");

    if (!fp) {

        if (errno == ENOENT) {

            goto update_map_file;

        } else {

            close_preserve_errno(map_dirfd);

            return -1;

        }

    }

    memset(buf, 0, ATTR_MAX);

    while (fgets(buf, ATTR_MAX, fp)) {

        if (!strncmp(buf, "virtfs.uid", 10)) {

            uid = atoi(buf + 11);

        } else if (!strncmp(buf, "virtfs.gid", 10)) {

            gid = atoi(buf + 11);

        } else if (!strncmp(buf, "virtfs.mode", 11)) {

            mode = atoi(buf + 12);

        } else if (!strncmp(buf, "virtfs.rdev", 11)) {

            rdev = atoi(buf + 12);

        }

        memset(buf, 0, ATTR_MAX);

    }

    fclose(fp);

update_map_file:

    fp = local_fopenat(map_dirfd, name, "w");

    close_preserve_errno(map_dirfd);

    if (!fp) {

        return -1;

    }

    if (credp->fc_uid != -1) {

        uid = credp->fc_uid;

    }

    if (credp->fc_gid != -1) {

        gid = credp->fc_gid;

    }

    if (credp->fc_mode != -1) {

        mode = credp->fc_mode;

    }

    if (credp->fc_rdev != -1) {

        rdev = credp->fc_rdev;

    }

    if (uid != -1) {

        fprintf(fp, "virtfs.uid=%d\n", uid);

    }

    if (gid != -1) {

        fprintf(fp, "virtfs.gid=%d\n", gid);

    }

    if (mode != -1) {

        fprintf(fp, "virtfs.mode=%d\n", mode);

    }

    if (rdev != -1) {

        fprintf(fp, "virtfs.rdev=%d\n", rdev);

    }

    fclose(fp);

    return 0;

}


static void check_ieee_exceptions(CPUSPARCState *env)

{

    target_ulong status;

    status = get_float_exception_flags(&env->fp_status);

    if (status) {

        /* Copy IEEE 754 flags into FSR */

        if (status & float_flag_invalid) {

            env->fsr |= FSR_NVC;

        }

        if (status & float_flag_overflow) {

            env->fsr |= FSR_OFC;

        }

        if (status & float_flag_underflow) {

            env->fsr |= FSR_UFC;

        }

        if (status & float_flag_divbyzero) {

            env->fsr |= FSR_DZC;

        }

        if (status & float_flag_inexact) {

            env->fsr |= FSR_NXC;

        }

        if ((env->fsr & FSR_CEXC_MASK) & ((env->fsr & FSR_TEM_MASK) >> 23)) {

            /* Unmasked exception, generate a trap */

            env->fsr |= FSR_FTT_IEEE_EXCP;

            helper_raise_exception(env, TT_FP_EXCP);

        } else {

            /* Accumulate exceptions */

            env->fsr |= (env->fsr & FSR_CEXC_MASK) << 5;

        }

    }

}


static hwaddr ppc_hash64_htab_lookup(PowerPCCPU *cpu,

                                     ppc_slb_t *slb, target_ulong eaddr,

                                     ppc_hash_pte64_t *pte, unsigned *pshift)

{

    CPUPPCState *env = &cpu->env;

    hwaddr hash, ptex;

    uint64_t vsid, epnmask, epn, ptem;

    const struct ppc_one_seg_page_size *sps = slb->sps;

    /* The SLB store path should prevent any bad page size encodings

     * getting in there, so: */

    assert(sps);

    /* If ISL is set in LPCR we need to clamp the page size to 4K */

    if (env->spr[SPR_LPCR] & LPCR_ISL) {

        /* We assume that when using TCG, 4k is first entry of SPS */

        sps = &env->sps.sps[0];

        assert(sps->page_shift == 12);

    }

    epnmask = ~((1ULL << sps->page_shift) - 1);

    if (slb->vsid & SLB_VSID_B) {

        /* 1TB segment */

        vsid = (slb->vsid & SLB_VSID_VSID) >> SLB_VSID_SHIFT_1T;

        epn = (eaddr & ~SEGMENT_MASK_1T) & epnmask;

        hash = vsid ^ (vsid << 25) ^ (epn >> sps->page_shift);

    } else {

        /* 256M segment */

        vsid = (slb->vsid & SLB_VSID_VSID) >> SLB_VSID_SHIFT;

        epn = (eaddr & ~SEGMENT_MASK_256M) & epnmask;

        hash = vsid ^ (epn >> sps->page_shift);

    }

    ptem = (slb->vsid & SLB_VSID_PTEM) | ((epn >> 16) & HPTE64_V_AVPN);

    ptem |= HPTE64_V_VALID;

    /* Page address translation */

    qemu_log_mask(CPU_LOG_MMU,

            "htab_base " TARGET_FMT_plx " htab_mask " TARGET_FMT_plx

            " hash " TARGET_FMT_plx "\n",

            env->htab_base, env->htab_mask, hash);

    /* Primary PTEG lookup */

    qemu_log_mask(CPU_LOG_MMU,

            "0 htab=" TARGET_FMT_plx "/" TARGET_FMT_plx

            " vsid=" TARGET_FMT_lx " ptem=" TARGET_FMT_lx

            " hash=" TARGET_FMT_plx "\n",

            env->htab_base, env->htab_mask, vsid, ptem,  hash);

    ptex = ppc_hash64_pteg_search(cpu, hash, sps, ptem, pte, pshift);

    if (ptex == -1) {

        /* Secondary PTEG lookup */

        ptem |= HPTE64_V_SECONDARY;

        qemu_log_mask(CPU_LOG_MMU,

                "1 htab=" TARGET_FMT_plx "/" TARGET_FMT_plx

                " vsid=" TARGET_FMT_lx " api=" TARGET_FMT_lx

                " hash=" TARGET_FMT_plx "\n", env->htab_base,

                env->htab_mask, vsid, ptem, ~hash);

        ptex = ppc_hash64_pteg_search(cpu, ~hash, sps, ptem, pte, pshift);

    }

    return ptex;

}


QemuOpts *qemu_opts_create(QemuOptsList *list, const char *id,

                           int fail_if_exists, Error **errp)

{

    QemuOpts *opts = NULL;

    if (id) {

        if (!id_wellformed(id)) {

            error_set(errp,QERR_INVALID_PARAMETER_VALUE, "id", "an identifier");

#if 0 /* conversion from qerror_report() to error_set() broke this: */

            error_printf_unless_qmp("Identifiers consist of letters, digits, '-', '.', '_', starting with a letter.\n");

#endif

            return NULL;

        }

        opts = qemu_opts_find(list, id);

        if (opts != NULL) {

            if (fail_if_exists && !list->merge_lists) {

                error_setg(errp, "Duplicate ID '%s' for %s", id, list->name);

                return NULL;

            } else {

                return opts;

            }

        }

    } else if (list->merge_lists) {

        opts = qemu_opts_find(list, NULL);

        if (opts) {

            return opts;

        }

    }

    opts = g_malloc0(sizeof(*opts));

    opts->id = g_strdup(id);

    opts->list = list;

    loc_save(&opts->loc);

    QTAILQ_INIT(&opts->head);

    QTAILQ_INSERT_TAIL(&list->head, opts, next);

    return opts;

}


static int coroutine_fn backup_run_incremental(BackupBlockJob *job)

{

    bool error_is_read;

    int ret = 0;

    int clusters_per_iter;

    uint32_t granularity;

    int64_t sector;

    int64_t cluster;

    int64_t end;

    int64_t last_cluster = -1;

    int64_t sectors_per_cluster = cluster_size_sectors(job);

    BdrvDirtyBitmapIter *dbi;

    granularity = bdrv_dirty_bitmap_granularity(job->sync_bitmap);

    clusters_per_iter = MAX((granularity / job->cluster_size), 1);

    dbi = bdrv_dirty_iter_new(job->sync_bitmap, 0);

    /* Find the next dirty sector(s) */

    while ((sector = bdrv_dirty_iter_next(dbi)) != -1) {

        cluster = sector / sectors_per_cluster;

        /* Fake progress updates for any clusters we skipped */

        if (cluster != last_cluster + 1) {

            job->common.offset += ((cluster - last_cluster - 1) *

                                   job->cluster_size);

        }

        for (end = cluster + clusters_per_iter; cluster < end; cluster++) {

            do {

                if (yield_and_check(job)) {

                    goto out;

                }

                ret = backup_do_cow(job, cluster * job->cluster_size,

                                    job->cluster_size, &error_is_read,

                                    false);

                if ((ret < 0) &&

                    backup_error_action(job, error_is_read, -ret) ==

                    BLOCK_ERROR_ACTION_REPORT) {

                    goto out;

                }

            } while (ret < 0);

        }

        /* If the bitmap granularity is smaller than the backup granularity,

         * we need to advance the iterator pointer to the next cluster. */

        if (granularity < job->cluster_size) {

            bdrv_set_dirty_iter(dbi, cluster * sectors_per_cluster);

        }

        last_cluster = cluster - 1;

    }

    /* Play some final catchup with the progress meter */

    end = DIV_ROUND_UP(job->common.len, job->cluster_size);

    if (last_cluster + 1 < end) {

        job->common.offset += ((end - last_cluster - 1) * job->cluster_size);

    }

out:

    bdrv_dirty_iter_free(dbi);

    return ret;

}


static uint64_t omap_eac_read(void *opaque, target_phys_addr_t addr,

                              unsigned size)

{

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

    uint32_t ret;

    if (size != 2) {

        return omap_badwidth_read16(opaque, addr);

    }

    switch (addr) {

    case 0x000:	/* CPCFR1 */

        return s->config[0];

    case 0x004:	/* CPCFR2 */

        return s->config[1];

    case 0x008:	/* CPCFR3 */

        return s->config[2];

    case 0x00c:	/* CPCFR4 */

        return s->config[3];

    case 0x010:	/* CPTCTL */

        return s->control | ((s->codec.rxavail + s->codec.rxlen > 0) << 7) |

                ((s->codec.txlen < s->codec.txavail) << 5);

    case 0x014:	/* CPTTADR */

        return s->address;

    case 0x018:	/* CPTDATL */

        return s->data & 0xff;

    case 0x01c:	/* CPTDATH */

        return s->data >> 8;

    case 0x020:	/* CPTVSLL */

        return s->vtol;

    case 0x024:	/* CPTVSLH */

        return s->vtsl | (3 << 5);	/* CRDY1 | CRDY2 */

    case 0x040:	/* MPCTR */

        return s->modem.control;

    case 0x044:	/* MPMCCFR */

        return s->modem.config;

    case 0x060:	/* BPCTR */

        return s->bt.control;

    case 0x064:	/* BPMCCFR */

        return s->bt.config;

    case 0x080:	/* AMSCFR */

        return s->mixer;

    case 0x084:	/* AMVCTR */

        return s->gain[0];

    case 0x088:	/* AM1VCTR */

        return s->gain[1];

    case 0x08c:	/* AM2VCTR */

        return s->gain[2];

    case 0x090:	/* AM3VCTR */

        return s->gain[3];

    case 0x094:	/* ASTCTR */

        return s->att;

    case 0x098:	/* APD1LCR */

        return s->max[0];

    case 0x09c:	/* APD1RCR */

        return s->max[1];

    case 0x0a0:	/* APD2LCR */

        return s->max[2];

    case 0x0a4:	/* APD2RCR */

        return s->max[3];

    case 0x0a8:	/* APD3LCR */

        return s->max[4];

    case 0x0ac:	/* APD3RCR */

        return s->max[5];

    case 0x0b0:	/* APD4R */

        return s->max[6];

    case 0x0b4:	/* ADWR */

        /* This should be write-only?  Docs list it as read-only.  */

        return 0x0000;

    case 0x0b8:	/* ADRDR */

        if (likely(s->codec.rxlen > 1)) {

            ret = s->codec.rxbuf[s->codec.rxoff ++];

            s->codec.rxlen --;

            s->codec.rxoff &= EAC_BUF_LEN - 1;

            return ret;

        } else if (s->codec.rxlen) {

            ret = s->codec.rxbuf[s->codec.rxoff ++];

            s->codec.rxlen --;

            s->codec.rxoff &= EAC_BUF_LEN - 1;

            if (s->codec.rxavail)

                omap_eac_in_refill(s);

            omap_eac_in_dmarequest_update(s);

            return ret;

        }

        return 0x0000;

    case 0x0bc:	/* AGCFR */

        return s->codec.config[0];

    case 0x0c0:	/* AGCTR */

        return s->codec.config[1] | ((s->codec.config[1] & 2) << 14);

    case 0x0c4:	/* AGCFR2 */

        return s->codec.config[2];

    case 0x0c8:	/* AGCFR3 */

        return s->codec.config[3];

    case 0x0cc:	/* MBPDMACTR */

    case 0x0d0:	/* MPDDMARR */

    case 0x0d8:	/* MPUDMARR */

    case 0x0e4:	/* BPDDMARR */

    case 0x0ec:	/* BPUDMARR */

        return 0x0000;

    case 0x100:	/* VERSION_NUMBER */

        return 0x0010;

    case 0x104:	/* SYSCONFIG */

        return s->sysconfig;

    case 0x108:	/* SYSSTATUS */

        return 1 | 0xe;					/* RESETDONE | stuff */

    }

    OMAP_BAD_REG(addr);

    return 0;

}


static int encode_packets(Jpeg2000EncoderContext *s, Jpeg2000Tile *tile, int tileno)

{

    int compno, reslevelno, ret;

    Jpeg2000CodingStyle *codsty = &s->codsty;

    Jpeg2000QuantStyle  *qntsty = &s->qntsty;

    av_log(s->avctx, AV_LOG_DEBUG, "tier2\n");

    // lay-rlevel-comp-pos progression

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

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

            int precno;

            Jpeg2000ResLevel *reslevel = s->tile[tileno].comp[compno].reslevel + reslevelno;

            for (precno = 0; precno < reslevel->num_precincts_x * reslevel->num_precincts_y; precno++){

                if (ret = encode_packet(s, reslevel, precno, qntsty->expn + (reslevelno ? 3*reslevelno-2 : 0),

                              qntsty->nguardbits))

                    return ret;

            }

        }

    }

    av_log(s->avctx, AV_LOG_DEBUG, "after tier2\n");

    return 0;

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    dc->vmsd = &vmstate_allwinner_ahci;

}


static QemuOpts *opts_parse(QemuOptsList *list, const char *params,

                            int permit_abbrev, bool defaults)

{

    const char *firstname;

    char value[1024], *id = NULL;

    const char *p;

    QemuOpts *opts;

    assert(!permit_abbrev || list->implied_opt_name);

    firstname = permit_abbrev ? list->implied_opt_name : NULL;

    if (strncmp(params, "id=", 3) == 0) {

        get_opt_value(value, sizeof(value), params+3);

        id = value;

    } else if ((p = strstr(params, ",id=")) != NULL) {

        get_opt_value(value, sizeof(value), p+4);

        id = value;

    }

    if (defaults) {

        if (!id && !QTAILQ_EMPTY(&list->head)) {

            opts = qemu_opts_find(list, NULL);

        } else {

            opts = qemu_opts_create(list, id, 0);

        }

    } else {

        opts = qemu_opts_create(list, id, 1);

    }

    if (opts == NULL)

        return NULL;

    if (opts_do_parse(opts, params, firstname, defaults) != 0) {

        qemu_opts_del(opts);

        return NULL;

    }

    return opts;

}


static void chomp3(ChannelData *ctx, int16_t *output, uint8_t val,

                   const uint16_t tab1[],

                   const int16_t *tab2, int tab2_stride,

                   uint32_t numChannels)

{

    int16_t current;

    current = tab2[((ctx->index & 0x7f0) >> 4)*tab2_stride + val];

    current = mace_broken_clip_int16(current + ctx->lev);

    ctx->lev = current - (current >> 3);

    *output = QT_8S_2_16S(current);

    if (( ctx->index += tab1[val]-(ctx->index >> 5) ) < 0)

        ctx->index = 0;

}


static void srt_to_ass(AVCodecContext *avctx, AVBPrint *dst,

                       const char *in, int x1, int y1, int x2, int y2)

{

    if (x1 >= 0 && y1 >= 0) {

        /* XXX: here we rescale coordinate assuming they are in DVD resolution

         * (720x480) since we don't have anything better */

        if (x2 >= 0 && y2 >= 0 && (x2 != x1 || y2 != y1) && x2 >= x1 && y2 >= y1) {

            /* text rectangle defined, write the text at the center of the rectangle */

            const int cx = x1 + (x2 - x1)/2;

            const int cy = y1 + (y2 - y1)/2;

            const int scaled_x = cx * ASS_DEFAULT_PLAYRESX / 720;

            const int scaled_y = cy * ASS_DEFAULT_PLAYRESY / 480;

            av_bprintf(dst, "{\\an5}{\\pos(%d,%d)}", scaled_x, scaled_y);

        } else {

            /* only the top left corner, assume the text starts in that corner */

            const int scaled_x = x1 * ASS_DEFAULT_PLAYRESX / 720;

            const int scaled_y = y1 * ASS_DEFAULT_PLAYRESY / 480;

            av_bprintf(dst, "{\\an1}{\\pos(%d,%d)}", scaled_x, scaled_y);

        }

    }

    ff_htmlmarkup_to_ass(avctx, dst, in);

}


static void mmio_basic(void)

{

    QVirtioMMIODevice *dev;

    QVirtQueue *vq;

    QGuestAllocator *alloc;

    int n_size = TEST_IMAGE_SIZE / 2;

    uint64_t capacity;

    arm_test_start();

    dev = qvirtio_mmio_init_device(MMIO_DEV_BASE_ADDR, MMIO_PAGE_SIZE);

    g_assert(dev != NULL);

    g_assert_cmphex(dev->vdev.device_type, ==, VIRTIO_ID_BLOCK);

    qvirtio_reset(&qvirtio_mmio, &dev->vdev);

    qvirtio_set_acknowledge(&qvirtio_mmio, &dev->vdev);

    qvirtio_set_driver(&qvirtio_mmio, &dev->vdev);

    alloc = generic_alloc_init(MMIO_RAM_ADDR, MMIO_RAM_SIZE, MMIO_PAGE_SIZE);

    vq = qvirtqueue_setup(&qvirtio_mmio, &dev->vdev, alloc, 0);

    test_basic(&qvirtio_mmio, &dev->vdev, alloc, vq,

                            QVIRTIO_MMIO_DEVICE_SPECIFIC);

    qmp("{ 'execute': 'block_resize', 'arguments': { 'device': 'drive0', "

                                                    " 'size': %d } }", n_size);

    qvirtio_wait_queue_isr(&qvirtio_mmio, &dev->vdev, vq,

                           QVIRTIO_BLK_TIMEOUT_US);

    capacity = qvirtio_config_readq(&qvirtio_mmio, &dev->vdev,

                                                QVIRTIO_MMIO_DEVICE_SPECIFIC);

    g_assert_cmpint(capacity, ==, n_size / 512);

    /* End test */

    guest_free(alloc, vq->desc);

    generic_alloc_uninit(alloc);

    g_free(dev);

    test_end();

}


int ff_twinvq_decode_frame(AVCodecContext *avctx, void *data,

                           int *got_frame_ptr, AVPacket *avpkt)

{

    AVFrame *frame     = data;

    const uint8_t *buf = avpkt->data;

    int buf_size       = avpkt->size;

    TwinVQContext *tctx = avctx->priv_data;

    const TwinVQModeTab *mtab = tctx->mtab;

    float **out = NULL;

    int ret;

    /* get output buffer */

    if (tctx->discarded_packets >= 2) {

        frame->nb_samples = mtab->size;

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

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

            return ret;

        }

        out = (float **)frame->extended_data;

    }

    if ((ret = tctx->read_bitstream(avctx, tctx, buf, buf_size)) < 0)

        return ret;

    read_and_decode_spectrum(tctx, tctx->spectrum, tctx->bits.ftype);

    imdct_output(tctx, tctx->bits.ftype, tctx->bits.window_type, out);

    FFSWAP(float *, tctx->curr_frame, tctx->prev_frame);

    if (tctx->discarded_packets < 2) {

        tctx->discarded_packets++;

        *got_frame_ptr = 0;

        return buf_size;

    }

    *got_frame_ptr = 1;

    return buf_size;

}


static int split_field_ref_list(Picture *dest, int dest_len,

                                Picture *src,  int src_len,

                                int parity,    int long_i){

    int i = split_field_half_ref_list(dest, dest_len, src, long_i, parity);

    dest += i;

    dest_len -= i;

    i += split_field_half_ref_list(dest, dest_len, src + long_i,

                                   src_len - long_i, parity);

    return i;

}


static int fourxm_read_packet(AVFormatContext *s,

                              AVPacket *pkt)

{

    FourxmDemuxContext *fourxm = s->priv_data;

    ByteIOContext *pb = s->pb;

    unsigned int fourcc_tag;

    unsigned int size, out_size;

    int ret = 0;

    unsigned int track_number;

    int packet_read = 0;

    unsigned char header[8];

    int audio_frame_count;

    while (!packet_read) {

        if ((ret = get_buffer(s->pb, header, 8)) < 0)

            return ret;

        fourcc_tag = AV_RL32(&header[0]);

        size = AV_RL32(&header[4]);

        if (url_feof(pb))

            return AVERROR(EIO);

        switch (fourcc_tag) {

        case LIST_TAG:

            /* this is a good time to bump the video pts */

            fourxm->video_pts ++;

            /* skip the LIST-* tag and move on to the next fourcc */

            get_le32(pb);

            break;

        case ifrm_TAG:

        case pfrm_TAG:

        case cfrm_TAG:

        case ifr2_TAG:

        case pfr2_TAG:

        case cfr2_TAG:

            /* allocate 8 more bytes than 'size' to account for fourcc

             * and size */

            if (size + 8 < size || av_new_packet(pkt, size + 8))

                return AVERROR(EIO);

            pkt->stream_index = fourxm->video_stream_index;

            pkt->pts = fourxm->video_pts;

            pkt->pos = url_ftell(s->pb);

            memcpy(pkt->data, header, 8);

            ret = get_buffer(s->pb, &pkt->data[8], size);

            if (ret < 0){

                av_free_packet(pkt);

            }else

                packet_read = 1;

            break;

        case snd__TAG:

            track_number = get_le32(pb);

            out_size= get_le32(pb);

            size-=8;

            if (track_number < fourxm->track_count) {

                ret= av_get_packet(s->pb, pkt, size);

                if(ret<0)

                    return AVERROR(EIO);

                pkt->stream_index =

                    fourxm->tracks[track_number].stream_index;

                pkt->pts = fourxm->tracks[track_number].audio_pts;

                packet_read = 1;

                /* pts accounting */

                audio_frame_count = size;

                if (fourxm->tracks[track_number].adpcm)

                    audio_frame_count -=

                        2 * (fourxm->tracks[track_number].channels);

                audio_frame_count /=

                      fourxm->tracks[track_number].channels;

                if (fourxm->tracks[track_number].adpcm){

                    audio_frame_count *= 2;

                }else

                    audio_frame_count /=

                    (fourxm->tracks[track_number].bits / 8);

                fourxm->tracks[track_number].audio_pts += audio_frame_count;

            } else {

                url_fseek(pb, size, SEEK_CUR);

            }

            break;

        default:

            url_fseek(pb, size, SEEK_CUR);

            break;

        }

    }

    return ret;

}


SwsFunc ff_yuv2rgb_init_mmx(SwsContext *c)

{

    int cpu_flags = av_get_cpu_flags();

    if (c->srcFormat != PIX_FMT_YUV420P &&

        c->srcFormat != PIX_FMT_YUVA420P)

        return NULL;

#if HAVE_MMX2

    if (cpu_flags & AV_CPU_FLAG_MMX2) {

        switch (c->dstFormat) {

        case PIX_FMT_RGB24:  return yuv420_rgb24_MMX2;

        case PIX_FMT_BGR24:  return yuv420_bgr24_MMX2;

        }

    }

#endif

    if (cpu_flags & AV_CPU_FLAG_MMX) {

        switch (c->dstFormat) {

            case PIX_FMT_RGB32:

                if (c->srcFormat == PIX_FMT_YUVA420P) {

#if HAVE_7REGS && CONFIG_SWSCALE_ALPHA

                    return yuva420_rgb32_MMX;

#endif

                    break;

                } else return yuv420_rgb32_MMX;

            case PIX_FMT_BGR32:

                if (c->srcFormat == PIX_FMT_YUVA420P) {

#if HAVE_7REGS && CONFIG_SWSCALE_ALPHA

                    return yuva420_bgr32_MMX;

#endif

                    break;

                } else return yuv420_bgr32_MMX;

            case PIX_FMT_RGB24:  return yuv420_rgb24_MMX;

            case PIX_FMT_BGR24:  return yuv420_bgr24_MMX;

            case PIX_FMT_RGB565: return yuv420_rgb16_MMX;

            case PIX_FMT_RGB555: return yuv420_rgb15_MMX;

        }

    }

    return NULL;

}


void cpsr_write(CPUARMState *env, uint32_t val, uint32_t mask)

{

    if (mask & CPSR_NZCV) {

        env->ZF = (~val) & CPSR_Z;

        env->NF = val;

        env->CF = (val >> 29) & 1;

        env->VF = (val << 3) & 0x80000000;

    }

    if (mask & CPSR_Q)

        env->QF = ((val & CPSR_Q) != 0);

    if (mask & CPSR_T)

        env->thumb = ((val & CPSR_T) != 0);

    if (mask & CPSR_IT_0_1) {

        env->condexec_bits &= ~3;

        env->condexec_bits |= (val >> 25) & 3;

    }

    if (mask & CPSR_IT_2_7) {

        env->condexec_bits &= 3;

        env->condexec_bits |= (val >> 8) & 0xfc;

    }

    if (mask & CPSR_GE) {

        env->GE = (val >> 16) & 0xf;

    }

    if ((env->uncached_cpsr ^ val) & mask & CPSR_M) {

        switch_mode(env, val & CPSR_M);

    }

    mask &= ~CACHED_CPSR_BITS;

    env->uncached_cpsr = (env->uncached_cpsr & ~mask) | (val & mask);

}


static av_always_inline av_flatten void FUNCC(h264_loop_filter_luma)(uint8_t *p_pix, int xstride, int ystride, int inner_iters, int alpha, int beta, int8_t *tc0)

{

    pixel *pix = (pixel*)p_pix;

    int i, d;

    xstride >>= sizeof(pixel)-1;

    ystride >>= sizeof(pixel)-1;

    alpha <<= BIT_DEPTH - 8;

    beta  <<= BIT_DEPTH - 8;

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

        const int tc_orig = tc0[i] << (BIT_DEPTH - 8);

        if( tc_orig < 0 ) {

            pix += inner_iters*ystride;

            continue;

        }

        for( d = 0; d < inner_iters; d++ ) {

            const int p0 = pix[-1*xstride];

            const int p1 = pix[-2*xstride];

            const int p2 = pix[-3*xstride];

            const int q0 = pix[0];

            const int q1 = pix[1*xstride];

            const int q2 = pix[2*xstride];

            if( FFABS( p0 - q0 ) < alpha &&

                FFABS( p1 - p0 ) < beta &&

                FFABS( q1 - q0 ) < beta ) {

                int tc = tc_orig;

                int i_delta;

                if( FFABS( p2 - p0 ) < beta ) {

                    if(tc_orig)

                    pix[-2*xstride] = p1 + av_clip( (( p2 + ( ( p0 + q0 + 1 ) >> 1 ) ) >> 1) - p1, -tc_orig, tc_orig );

                    tc++;

                }

                if( FFABS( q2 - q0 ) < beta ) {

                    if(tc_orig)

                    pix[   xstride] = q1 + av_clip( (( q2 + ( ( p0 + q0 + 1 ) >> 1 ) ) >> 1) - q1, -tc_orig, tc_orig );

                    tc++;

                }

                i_delta = av_clip( (((q0 - p0 ) << 2) + (p1 - q1) + 4) >> 3, -tc, tc );

                pix[-xstride] = av_clip_pixel( p0 + i_delta );    /* p0' */

                pix[0]        = av_clip_pixel( q0 - i_delta );    /* q0' */

            }

            pix += ystride;

        }

    }

}


static int nbd_errno_to_system_errno(int err)

{

    switch (err) {

    case NBD_SUCCESS:

        return 0;

    case NBD_EPERM:

        return EPERM;

    case NBD_EIO:

        return EIO;

    case NBD_ENOMEM:

        return ENOMEM;

    case NBD_ENOSPC:

        return ENOSPC;

    case NBD_EINVAL:

    default:

        return EINVAL;

    }

}


pcie_cap_v1_fill(uint8_t *exp_cap, uint8_t port, uint8_t type, uint8_t version)

{

    /* capability register

    interrupt message number defaults to 0 */

    pci_set_word(exp_cap + PCI_EXP_FLAGS,

                 ((type << PCI_EXP_FLAGS_TYPE_SHIFT) & PCI_EXP_FLAGS_TYPE) |

                 version);

    /* device capability register

     * table 7-12:

     * roll based error reporting bit must be set by all

     * Functions conforming to the ECN, PCI Express Base

     * Specification, Revision 1.1., or subsequent PCI Express Base

     * Specification revisions.

     */

    pci_set_long(exp_cap + PCI_EXP_DEVCAP, PCI_EXP_DEVCAP_RBER);

    pci_set_long(exp_cap + PCI_EXP_LNKCAP,

                 (port << PCI_EXP_LNKCAP_PN_SHIFT) |

                 PCI_EXP_LNKCAP_ASPMS_0S |

                 PCI_EXP_LNK_MLW_1 |

                 PCI_EXP_LNK_LS_25);

    pci_set_word(exp_cap + PCI_EXP_LNKSTA,

                 PCI_EXP_LNK_MLW_1 | PCI_EXP_LNK_LS_25 |PCI_EXP_LNKSTA_DLLLA);

}


static int start_frame(AVFilterLink *inlink, AVFilterBufferRef *picref)

{

    AVFilterContext *ctx = inlink->dst;

    TInterlaceContext *tinterlace = ctx->priv;

    avfilter_unref_buffer(tinterlace->cur);

    tinterlace->cur  = tinterlace->next;

    tinterlace->next = picref;

    return 0;

}


static void write_odml_master(AVFormatContext *s, int stream_index)

{

    AVIOContext *pb = s->pb;

    AVStream *st = s->streams[stream_index];

    AVCodecContext *enc = st->codec;

    AVIStream *avist = st->priv_data;

    unsigned char tag[5];

    int j;

    /* Starting to lay out AVI OpenDML master index.

        * We want to make it JUNK entry for now, since we'd

        * like to get away without making AVI an OpenDML one

        * for compatibility reasons. */

    avist->indexes.entry      = avist->indexes.ents_allocated = 0;

    avist->indexes.indx_start = ff_start_tag(pb, "JUNK");

    avio_wl16(pb, 4);   /* wLongsPerEntry */

    avio_w8(pb, 0);     /* bIndexSubType (0 == frame index) */

    avio_w8(pb, 0);     /* bIndexType (0 == AVI_INDEX_OF_INDEXES) */

    avio_wl32(pb, 0);   /* nEntriesInUse (will fill out later on) */

    ffio_wfourcc(pb, avi_stream2fourcc(tag, stream_index, enc->codec_type));

                        /* dwChunkId */

    avio_wl64(pb, 0);   /* dwReserved[3] */

    avio_wl32(pb, 0);   /* Must be 0.    */

    for (j = 0; j < AVI_MASTER_INDEX_SIZE * 2; j++)

        avio_wl64(pb, 0);

    ff_end_tag(pb, avist->indexes.indx_start);

}


static void cook_imlt(COOKContext *q, float* inbuffer, float* outbuffer)

{

    int i;

    q->mdct_ctx.fft.imdct_calc(&q->mdct_ctx, outbuffer, inbuffer, q->mdct_tmp);

    for(i = 0; i < q->samples_per_channel; i++){

        float tmp = outbuffer[i];

        outbuffer[i] = q->mlt_window[i] * outbuffer[q->samples_per_channel + i];

        outbuffer[q->samples_per_channel + i] = q->mlt_window[q->samples_per_channel - 1 - i] * -tmp;

    }

}


static int mp3_write_trailer(struct AVFormatContext *s)

{

    uint8_t buf[ID3v1_TAG_SIZE];

    MP3Context *mp3 = s->priv_data;

    /* write the id3v1 tag */

    if (id3v1_create_tag(s, buf) > 0) {

        avio_write(s->pb, buf, ID3v1_TAG_SIZE);

    }

    /* write number of frames */

    if (mp3 && mp3->nb_frames_offset) {

        avio_seek(s->pb, mp3->nb_frames_offset, SEEK_SET);

        avio_wb32(s->pb, s->streams[0]->nb_frames);

        avio_seek(s->pb, 0, SEEK_END);

    }

    avio_flush(s->pb);

    return 0;

}


int64_t qemu_get_clock(QEMUClock *clock)

{

    switch(clock->type) {

    case QEMU_TIMER_REALTIME:

        return get_clock() / 1000000;

    default:

    case QEMU_TIMER_VIRTUAL:

        if (use_icount) {

            return cpu_get_icount();

        } else {

            return cpu_get_clock();

        }

    }

}


static int usb_qdev_exit(DeviceState *qdev)

{

    USBDevice *dev = USB_DEVICE(qdev);

    if (dev->attached) {

        usb_device_detach(dev);

    }

    usb_device_handle_destroy(dev);

    if (dev->port) {

        usb_release_port(dev);

    }

    return 0;

}


void scsi_req_build_sense(SCSIRequest *req, SCSISense sense)

{

    trace_scsi_req_build_sense(req->dev->id, req->lun, req->tag,

                               sense.key, sense.asc, sense.ascq);

    memset(req->sense, 0, 18);

    req->sense[0] = 0xf0;

    req->sense[2] = sense.key;

    req->sense[7] = 10;

    req->sense[12] = sense.asc;

    req->sense[13] = sense.ascq;

    req->sense_len = 18;

}


static int vp3_decode_frame(AVCodecContext *avctx,

                            void *data, int *got_frame,

                            AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    Vp3DecodeContext *s = avctx->priv_data;

    GetBitContext gb;

    int i;

    int ret;

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

#if CONFIG_THEORA_DECODER

    if (s->theora && get_bits1(&gb))

    {

        int type = get_bits(&gb, 7);

        skip_bits_long(&gb, 6*8); /* "theora" */

        if (type == 0) {

            if (s->avctx->active_thread_type&FF_THREAD_FRAME) {

                av_log(avctx, AV_LOG_ERROR, "midstream reconfiguration with multithreading is unsupported, try -threads 1\n");

                return AVERROR_PATCHWELCOME;

            }

            vp3_decode_end(avctx);

            ret = theora_decode_header(avctx, &gb);

            if (ret < 0) {

                vp3_decode_end(avctx);

            } else

                ret = vp3_decode_init(avctx);

            return ret;

        } else if (type == 2) {

            ret = theora_decode_tables(avctx, &gb);

            if (ret < 0) {

                vp3_decode_end(avctx);

            } else

                ret = vp3_decode_init(avctx);

            return ret;

        }

        av_log(avctx, AV_LOG_ERROR, "Header packet passed to frame decoder, skipping\n");

        return -1;

    }

#endif

    s->keyframe = !get_bits1(&gb);

    if (!s->all_fragments) {

        av_log(avctx, AV_LOG_ERROR, "Data packet without prior valid headers\n");

        return -1;

    }

    if (!s->theora)

        skip_bits(&gb, 1);

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

        s->last_qps[i] = s->qps[i];

    s->nqps=0;

    do{

        s->qps[s->nqps++]= get_bits(&gb, 6);

    } while(s->theora >= 0x030200 && s->nqps<3 && get_bits1(&gb));

    for (i = s->nqps; i < 3; i++)

        s->qps[i] = -1;

    if (s->avctx->debug & FF_DEBUG_PICT_INFO)

        av_log(s->avctx, AV_LOG_INFO, " VP3 %sframe #%d: Q index = %d\n",

            s->keyframe?"key":"", avctx->frame_number+1, s->qps[0]);

    s->skip_loop_filter = !s->filter_limit_values[s->qps[0]] ||

        avctx->skip_loop_filter >= (s->keyframe ? AVDISCARD_ALL : AVDISCARD_NONKEY);

    if (s->qps[0] != s->last_qps[0])

        init_loop_filter(s);

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

        // reinit all dequantizers if the first one changed, because

        // the DC of the first quantizer must be used for all matrices

        if (s->qps[i] != s->last_qps[i] || s->qps[0] != s->last_qps[0])

            init_dequantizer(s, i);

    if (avctx->skip_frame >= AVDISCARD_NONKEY && !s->keyframe)

        return buf_size;

    s->current_frame.reference = 3;

    s->current_frame.pict_type = s->keyframe ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_P;

    s->current_frame.key_frame = s->keyframe;

    if (ff_thread_get_buffer(avctx, &s->current_frame) < 0) {

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

        goto error;

    }

    if (!s->edge_emu_buffer)

        s->edge_emu_buffer = av_malloc(9*FFABS(s->current_frame.linesize[0]));

    if (s->keyframe) {

        if (!s->theora)

        {

            skip_bits(&gb, 4); /* width code */

            skip_bits(&gb, 4); /* height code */

            if (s->version)

            {

                s->version = get_bits(&gb, 5);

                if (avctx->frame_number == 0)

                    av_log(s->avctx, AV_LOG_DEBUG, "VP version: %d\n", s->version);

            }

        }

        if (s->version || s->theora)

        {

                if (get_bits1(&gb))

                    av_log(s->avctx, AV_LOG_ERROR, "Warning, unsupported keyframe coding type?!\n");

            skip_bits(&gb, 2); /* reserved? */

        }

    } else {

        if (!s->golden_frame.data[0]) {

            av_log(s->avctx, AV_LOG_WARNING, "vp3: first frame not a keyframe\n");

            s->golden_frame.reference = 3;

            s->golden_frame.pict_type = AV_PICTURE_TYPE_I;

            if (ff_thread_get_buffer(avctx, &s->golden_frame) < 0) {

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

                goto error;

            }

            s->last_frame = s->golden_frame;

            s->last_frame.type = FF_BUFFER_TYPE_COPY;

            ff_thread_report_progress(&s->last_frame, INT_MAX, 0);

        }

    }

    memset(s->all_fragments, 0, s->fragment_count * sizeof(Vp3Fragment));

    ff_thread_finish_setup(avctx);

    if (unpack_superblocks(s, &gb)){

        av_log(s->avctx, AV_LOG_ERROR, "error in unpack_superblocks\n");

        goto error;

    }

    if (unpack_modes(s, &gb)){

        av_log(s->avctx, AV_LOG_ERROR, "error in unpack_modes\n");

        goto error;

    }

    if (unpack_vectors(s, &gb)){

        av_log(s->avctx, AV_LOG_ERROR, "error in unpack_vectors\n");

        goto error;

    }

    if (unpack_block_qpis(s, &gb)){

        av_log(s->avctx, AV_LOG_ERROR, "error in unpack_block_qpis\n");

        goto error;

    }

    if (unpack_dct_coeffs(s, &gb)){

        av_log(s->avctx, AV_LOG_ERROR, "error in unpack_dct_coeffs\n");

        goto error;

    }

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

        int height = s->height >> (i && s->chroma_y_shift);

        if (s->flipped_image)

            s->data_offset[i] = 0;

        else

            s->data_offset[i] = (height-1) * s->current_frame.linesize[i];

    }

    s->last_slice_end = 0;

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

        render_slice(s, i);

    // filter the last row

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

        int row = (s->height >> (3+(i && s->chroma_y_shift))) - 1;

        apply_loop_filter(s, i, row, row+1);

    }

    vp3_draw_horiz_band(s, s->avctx->height);

    *got_frame = 1;

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

    if (!HAVE_THREADS || !(s->avctx->active_thread_type&FF_THREAD_FRAME))

        update_frames(avctx);

    return buf_size;

error:

    ff_thread_report_progress(&s->current_frame, INT_MAX, 0);

    if (!HAVE_THREADS || !(s->avctx->active_thread_type&FF_THREAD_FRAME))

        avctx->release_buffer(avctx, &s->current_frame);

    return -1;

}


void memory_region_reset_dirty(MemoryRegion *mr, hwaddr addr,

                               hwaddr size, unsigned client)

{

    assert(mr->terminates);

    cpu_physical_memory_test_and_clear_dirty(mr->ram_addr + addr, size,

                                             client);

}


void qemu_ram_free_from_ptr(ram_addr_t addr)

{

    RAMBlock *block;

    /* This assumes the iothread lock is taken here too.  */

    qemu_mutex_lock_ramlist();

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

        if (addr == block->offset) {

            QTAILQ_REMOVE(&ram_list.blocks, block, next);

            ram_list.mru_block = NULL;

            ram_list.version++;

            g_free(block);

            break;

        }

    }

    qemu_mutex_unlock_ramlist();

}


void bdrv_io_limits_enable(BlockDriverState *bs)

{

    qemu_co_queue_init(&bs->throttled_reqs);

    bs->block_timer = qemu_new_timer_ns(vm_clock, bdrv_block_timer, bs);

    bs->io_limits_enabled = true;

}


static void cadence_ttc_write(void *opaque, target_phys_addr_t offset,

        uint64_t value, unsigned size)

{

    CadenceTimerState *s = cadence_timer_from_addr(opaque, offset);

    DB_PRINT("addr: %08x data %08x\n", offset, (unsigned)value);

    cadence_timer_sync(s);

    switch (offset) {

    case 0x00: /* clock control */

    case 0x04:

    case 0x08:

        s->reg_clock = value & 0x3F;

        break;

    case 0x0c: /* counter control */

    case 0x10:

    case 0x14:

        if (value & COUNTER_CTRL_RST) {

            s->reg_value = 0;

        }

        s->reg_count = value & 0x3f & ~COUNTER_CTRL_RST;

        break;

    case 0x24: /* interval register */

    case 0x28:

    case 0x2c:

        s->reg_interval = value & 0xffff;

        break;

    case 0x30: /* match register */

    case 0x34:

    case 0x38:

        s->reg_match[0] = value & 0xffff;

    case 0x3c: /* match register */

    case 0x40:

    case 0x44:

        s->reg_match[1] = value & 0xffff;

    case 0x48: /* match register */

    case 0x4c:

    case 0x50:

        s->reg_match[2] = value & 0xffff;

        break;

    case 0x54: /* interrupt register */

    case 0x58:

    case 0x5c:

        break;

    case 0x60: /* interrupt enable */

    case 0x64:

    case 0x68:

        s->reg_intr_en = value & 0x3f;

        break;

    case 0x6c: /* event control */

    case 0x70:

    case 0x74:

        s->reg_event_ctrl = value & 0x07;

        break;

    default:

        return;

    }

    cadence_timer_run(s);

    cadence_timer_update(s);

}


static void virtio_scsi_hotplug(HotplugHandler *hotplug_dev, DeviceState *dev,

                                Error **errp)

{

    VirtIODevice *vdev = VIRTIO_DEVICE(hotplug_dev);

    VirtIOSCSI *s = VIRTIO_SCSI(vdev);

    SCSIDevice *sd = SCSI_DEVICE(dev);

    if (s->ctx && !s->dataplane_disabled) {

        if (blk_op_is_blocked(sd->conf.blk, BLOCK_OP_TYPE_DATAPLANE, errp)) {

            return;

        }

        blk_op_block_all(sd->conf.blk, s->blocker);

    }

    if ((vdev->guest_features >> VIRTIO_SCSI_F_HOTPLUG) & 1) {

        virtio_scsi_push_event(s, sd,

                               VIRTIO_SCSI_T_TRANSPORT_RESET,

                               VIRTIO_SCSI_EVT_RESET_RESCAN);

    }

}


static int write_elf64_load(DumpState *s, MemoryMapping *memory_mapping,

                            int phdr_index, target_phys_addr_t offset)

{

    Elf64_Phdr phdr;

    int ret;

    int endian = s->dump_info.d_endian;

    memset(&phdr, 0, sizeof(Elf64_Phdr));

    phdr.p_type = cpu_convert_to_target32(PT_LOAD, endian);

    phdr.p_offset = cpu_convert_to_target64(offset, endian);

    phdr.p_paddr = cpu_convert_to_target64(memory_mapping->phys_addr, endian);

    if (offset == -1) {

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

        phdr.p_filesz = 0;

    } else {

        phdr.p_filesz = cpu_convert_to_target64(memory_mapping->length, endian);

    }

    phdr.p_memsz = cpu_convert_to_target64(memory_mapping->length, endian);

    phdr.p_vaddr = cpu_convert_to_target64(memory_mapping->virt_addr, endian);

    ret = fd_write_vmcore(&phdr, sizeof(Elf64_Phdr), s);

    if (ret < 0) {

        dump_error(s, "dump: failed to write program header table.\n");

        return -1;

    }

    return 0;

}


static void SET_TYPE(resample_one)(ResampleContext *c,

                                   void *dst0, int dst_index, const void *src0,

                                   int src_size, int index, int frac)

{

    FELEM *dst = dst0;

    const FELEM *src = src0;

    int i;

    int sample_index = index >> c->phase_shift;

    FELEM2 val = 0;

    FELEM *filter = ((FELEM *)c->filter_bank) +

                    c->filter_length * (index & c->phase_mask);

    if (sample_index < 0) {

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

            val += src[FFABS(sample_index + i) % src_size] *

                   (FELEM2)filter[i];

    } else if (c->linear) {

        FELEM2 v2 = 0;

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

            val += src[abs(sample_index + i)] * (FELEM2)filter[i];

            v2  += src[abs(sample_index + i)] * (FELEM2)filter[i + c->filter_length];

        }

        val += (v2 - val) * (FELEML)frac / c->src_incr;

    } else {

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

            val += src[sample_index + i] * (FELEM2)filter[i];

    }

    OUT(dst[dst_index], val);

}


static void v9fs_xattrcreate(void *opaque)

{

    int flags;

    int32_t fid;

    int64_t size;

    ssize_t err = 0;

    V9fsString name;

    size_t offset = 7;

    V9fsFidState *file_fidp;

    V9fsFidState *xattr_fidp;

    V9fsPDU *pdu = opaque;

    V9fsState *s = pdu->s;

    pdu_unmarshal(pdu, offset, "dsqd",

                  &fid, &name, &size, &flags);

    trace_v9fs_xattrcreate(pdu->tag, pdu->id, fid, name.data, size, flags);

    file_fidp = get_fid(pdu, fid);

    if (file_fidp == NULL) {

        err = -EINVAL;

        goto out_nofid;

    }

    /* Make the file fid point to xattr */

    xattr_fidp = file_fidp;

    xattr_fidp->fid_type = P9_FID_XATTR;

    xattr_fidp->fs.xattr.copied_len = 0;

    xattr_fidp->fs.xattr.len = size;

    xattr_fidp->fs.xattr.flags = flags;

    v9fs_string_init(&xattr_fidp->fs.xattr.name);

    v9fs_string_copy(&xattr_fidp->fs.xattr.name, &name);

    if (size) {

        xattr_fidp->fs.xattr.value = g_malloc(size);

    } else {

        xattr_fidp->fs.xattr.value = NULL;

    }

    err = offset;

    put_fid(pdu, file_fidp);

out_nofid:

    complete_pdu(s, pdu, err);

    v9fs_string_free(&name);

}


uint64_t bdrv_dirty_bitmap_serialization_size(const BdrvDirtyBitmap *bitmap,

                                              uint64_t start, uint64_t count)

{

    return hbitmap_serialization_size(bitmap->bitmap, start, count);

}


static coroutine_fn int sd_co_discard(BlockDriverState *bs, int64_t sector_num,

                                      int nb_sectors)

{

    SheepdogAIOCB *acb;

    QEMUIOVector dummy;

    BDRVSheepdogState *s = bs->opaque;

    int ret;

    if (!s->discard_supported) {

            return 0;

    }

    acb = sd_aio_setup(bs, &dummy, sector_num, nb_sectors);

    acb->aiocb_type = AIOCB_DISCARD_OBJ;

    acb->aio_done_func = sd_finish_aiocb;

retry:

    if (check_overwrapping_aiocb(s, acb)) {

        qemu_co_queue_wait(&s->overwrapping_queue);

        goto retry;

    }

    ret = sd_co_rw_vector(acb);

    if (ret <= 0) {

        QLIST_REMOVE(acb, aiocb_siblings);

        qemu_co_queue_restart_all(&s->overwrapping_queue);

        qemu_aio_unref(acb);

        return ret;

    }

    qemu_coroutine_yield();

    QLIST_REMOVE(acb, aiocb_siblings);

    qemu_co_queue_restart_all(&s->overwrapping_queue);

    return acb->ret;

}


static void coroutine_fn qed_need_check_timer_entry(void *opaque)

{

    BDRVQEDState *s = opaque;

    int ret;

    /* The timer should only fire when allocating writes have drained */

    assert(!s->allocating_acb);

    trace_qed_need_check_timer_cb(s);

    qed_acquire(s);

    qed_plug_allocating_write_reqs(s);

    /* Ensure writes are on disk before clearing flag */

    ret = bdrv_co_flush(s->bs->file->bs);

    qed_release(s);

    if (ret < 0) {

        qed_unplug_allocating_write_reqs(s);

        return;

    }

    s->header.features &= ~QED_F_NEED_CHECK;

    ret = qed_write_header(s);

    (void) ret;

    qed_unplug_allocating_write_reqs(s);

    ret = bdrv_co_flush(s->bs);

    (void) ret;

}


static void gen_op_update_neg_cc(void)

{

    tcg_gen_neg_tl(cpu_cc_src, cpu_T[0]);

    tcg_gen_mov_tl(cpu_cc_dst, cpu_T[0]);

}


static int thp_probe(AVProbeData *p)

{

    /* check file header */

    if (p->buf_size < 4)

        return 0;

    if (AV_RL32(p->buf) == MKTAG('T', 'H', 'P', '\0'))

        return AVPROBE_SCORE_MAX;

    else

        return 0;

}


static int coroutine_fn bdrv_aligned_preadv(BlockDriverState *bs,

    BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,

    int64_t align, QEMUIOVector *qiov, int flags)

{

    int64_t total_bytes, max_bytes;

    int ret = 0;

    uint64_t bytes_remaining = bytes;

    int max_transfer;

    assert(is_power_of_2(align));

    assert((offset & (align - 1)) == 0);

    assert((bytes & (align - 1)) == 0);

    assert(!qiov || bytes == qiov->size);

    assert((bs->open_flags & BDRV_O_NO_IO) == 0);

    max_transfer = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_transfer, INT_MAX),

                                   align);

    /* TODO: We would need a per-BDS .supported_read_flags and

     * potential fallback support, if we ever implement any read flags

     * to pass through to drivers.  For now, there aren't any

     * passthrough flags.  */

    assert(!(flags & ~(BDRV_REQ_NO_SERIALISING | BDRV_REQ_COPY_ON_READ)));

    /* Handle Copy on Read and associated serialisation */

    if (flags & BDRV_REQ_COPY_ON_READ) {

        /* If we touch the same cluster it counts as an overlap.  This

         * guarantees that allocating writes will be serialized and not race

         * with each other for the same cluster.  For example, in copy-on-read

         * it ensures that the CoR read and write operations are atomic and

         * guest writes cannot interleave between them. */

        mark_request_serialising(req, bdrv_get_cluster_size(bs));

    }

    if (!(flags & BDRV_REQ_NO_SERIALISING)) {

        wait_serialising_requests(req);

    }

    if (flags & BDRV_REQ_COPY_ON_READ) {

        int64_t start_sector = offset >> BDRV_SECTOR_BITS;

        int64_t end_sector = DIV_ROUND_UP(offset + bytes, BDRV_SECTOR_SIZE);

        unsigned int nb_sectors = end_sector - start_sector;

        int pnum;

        ret = bdrv_is_allocated(bs, start_sector, nb_sectors, &pnum);

        if (ret < 0) {

            goto out;

        }

        if (!ret || pnum != nb_sectors) {

            ret = bdrv_co_do_copy_on_readv(bs, offset, bytes, qiov);

            goto out;

        }

    }

    /* Forward the request to the BlockDriver, possibly fragmenting it */

    total_bytes = bdrv_getlength(bs);

    if (total_bytes < 0) {

        ret = total_bytes;

        goto out;

    }

    max_bytes = ROUND_UP(MAX(0, total_bytes - offset), align);

    if (bytes <= max_bytes && bytes <= max_transfer) {

        ret = bdrv_driver_preadv(bs, offset, bytes, qiov, 0);

        goto out;

    }

    while (bytes_remaining) {

        int num;

        if (max_bytes) {

            QEMUIOVector local_qiov;

            num = MIN(bytes_remaining, MIN(max_bytes, max_transfer));

            assert(num);

            qemu_iovec_init(&local_qiov, qiov->niov);

            qemu_iovec_concat(&local_qiov, qiov, bytes - bytes_remaining, num);

            ret = bdrv_driver_preadv(bs, offset + bytes - bytes_remaining,

                                     num, &local_qiov, 0);

            max_bytes -= num;

            qemu_iovec_destroy(&local_qiov);

        } else {

            num = bytes_remaining;

            ret = qemu_iovec_memset(qiov, bytes - bytes_remaining, 0,

                                    bytes_remaining);

        }

        if (ret < 0) {

            goto out;

        }

        bytes_remaining -= num;

    }

out:

    return ret < 0 ? ret : 0;

}


Visitor *qmp_output_get_visitor(QmpOutputVisitor *v)

{

    return &v->visitor;

}


bool aio_dispatch(AioContext *ctx, bool dispatch_fds)

{

    bool progress;

    progress = aio_bh_poll(ctx);

    if (dispatch_fds) {

        progress |= aio_dispatch_handlers(ctx, INVALID_HANDLE_VALUE);

    }

    progress |= timerlistgroup_run_timers(&ctx->tlg);

    return progress;

}


void helper_check_iob(CPUX86State *env, uint32_t t0)

{

    check_io(env, t0, 1);

}


static void slirp_state_save(QEMUFile *f, void *opaque)

{

    Slirp *slirp = opaque;

    struct ex_list *ex_ptr;

    for (ex_ptr = slirp->exec_list; ex_ptr; ex_ptr = ex_ptr->ex_next)

        if (ex_ptr->ex_pty == 3) {

            struct socket *so;

            so = slirp_find_ctl_socket(slirp, ex_ptr->ex_addr,

                                       ntohs(ex_ptr->ex_fport));

            if (!so)

                continue;

            qemu_put_byte(f, 42);

            vmstate_save_state(f, &vmstate_slirp_socket, so, NULL);

        }

    qemu_put_byte(f, 0);

    qemu_put_be16(f, slirp->ip_id);

    slirp_bootp_save(f, slirp);

}


static inline void tlb_update_dirty(CPUTLBEntry *tlb_entry)

{

    ram_addr_t ram_addr;

    void *p;

    if ((tlb_entry->addr_write & ~TARGET_PAGE_MASK) == io_mem_ram.ram_addr) {

        p = (void *)(unsigned long)((tlb_entry->addr_write & TARGET_PAGE_MASK)

            + tlb_entry->addend);

        ram_addr = qemu_ram_addr_from_host_nofail(p);

        if (!cpu_physical_memory_is_dirty(ram_addr)) {

            tlb_entry->addr_write |= TLB_NOTDIRTY;

        }

    }

}


static IOMMUTLBEntry spapr_tce_translate_iommu(MemoryRegion *iommu, hwaddr addr,

                                               bool is_write)

{

    sPAPRTCETable *tcet = container_of(iommu, sPAPRTCETable, iommu);

    uint64_t tce;

    IOMMUTLBEntry ret = {

        .target_as = &address_space_memory,

        .iova = 0,

        .translated_addr = 0,

        .addr_mask = ~(hwaddr)0,

        .perm = IOMMU_NONE,

    };

    if ((addr >> tcet->page_shift) < tcet->nb_table) {

        /* Check if we are in bound */

        hwaddr page_mask = IOMMU_PAGE_MASK(tcet->page_shift);

        tce = tcet->table[addr >> tcet->page_shift];

        ret.iova = addr & page_mask;

        ret.translated_addr = tce & page_mask;

        ret.addr_mask = ~page_mask;

        ret.perm = spapr_tce_iommu_access_flags(tce);

    }

    trace_spapr_iommu_xlate(tcet->liobn, addr, ret.iova, ret.perm,

                            ret.addr_mask);

    return ret;

}


int rpcit_service_call(S390CPU *cpu, uint8_t r1, uint8_t r2)

{

    CPUS390XState *env = &cpu->env;

    uint32_t fh;

    S390PCIBusDevice *pbdev;

    S390PCIIOMMU *iommu;

    hwaddr start, end;

    IOMMUTLBEntry entry;

    MemoryRegion *mr;

    cpu_synchronize_state(CPU(cpu));

    if (env->psw.mask & PSW_MASK_PSTATE) {

        program_interrupt(env, PGM_PRIVILEGED, 4);

        goto out;

    }

    if (r2 & 0x1) {

        program_interrupt(env, PGM_SPECIFICATION, 4);

        goto out;

    }

    fh = env->regs[r1] >> 32;

    start = env->regs[r2];

    end = start + env->regs[r2 + 1];

    pbdev = s390_pci_find_dev_by_fh(s390_get_phb(), fh);

    if (!pbdev) {

        DPRINTF("rpcit no pci dev\n");

        setcc(cpu, ZPCI_PCI_LS_INVAL_HANDLE);

        goto out;

    }

    switch (pbdev->state) {

    case ZPCI_FS_RESERVED:

    case ZPCI_FS_STANDBY:

    case ZPCI_FS_DISABLED:

    case ZPCI_FS_PERMANENT_ERROR:

        setcc(cpu, ZPCI_PCI_LS_INVAL_HANDLE);

        return 0;

    case ZPCI_FS_ERROR:

        setcc(cpu, ZPCI_PCI_LS_ERR);

        s390_set_status_code(env, r1, ZPCI_MOD_ST_ERROR_RECOVER);

        return 0;

    default:

        break;

    }

    iommu = pbdev->iommu;

    if (!iommu->g_iota) {

        pbdev->state = ZPCI_FS_ERROR;

        setcc(cpu, ZPCI_PCI_LS_ERR);

        s390_set_status_code(env, r1, ZPCI_PCI_ST_INSUF_RES);

        s390_pci_generate_error_event(ERR_EVENT_INVALAS, pbdev->fh, pbdev->fid,

                                      start, 0);

        goto out;

    }

    if (end < iommu->pba || start > iommu->pal) {

        pbdev->state = ZPCI_FS_ERROR;

        setcc(cpu, ZPCI_PCI_LS_ERR);

        s390_set_status_code(env, r1, ZPCI_PCI_ST_INSUF_RES);

        s390_pci_generate_error_event(ERR_EVENT_OORANGE, pbdev->fh, pbdev->fid,

                                      start, 0);

        goto out;

    }

    mr = &iommu->iommu_mr;

    while (start < end) {

        entry = mr->iommu_ops->translate(mr, start, 0);

        if (!entry.translated_addr) {

            pbdev->state = ZPCI_FS_ERROR;

            setcc(cpu, ZPCI_PCI_LS_ERR);

            s390_set_status_code(env, r1, ZPCI_PCI_ST_INSUF_RES);

            s390_pci_generate_error_event(ERR_EVENT_SERR, pbdev->fh, pbdev->fid,

                                          start, ERR_EVENT_Q_BIT);

            goto out;

        }

        memory_region_notify_iommu(mr, entry);

        start += entry.addr_mask + 1;

    }

    setcc(cpu, ZPCI_PCI_LS_OK);

out:

    return 0;

}


static int coroutine_fn qcow2_co_is_allocated(BlockDriverState *bs,

        int64_t sector_num, int nb_sectors, int *pnum)

{

    BDRVQcowState *s = bs->opaque;

    uint64_t cluster_offset;

    int ret;

    *pnum = nb_sectors;

    /* FIXME We can get errors here, but the bdrv_co_is_allocated interface

     * can't pass them on today */

    qemu_co_mutex_lock(&s->lock);

    ret = qcow2_get_cluster_offset(bs, sector_num << 9, pnum, &cluster_offset);

    qemu_co_mutex_unlock(&s->lock);

    if (ret < 0) {

        *pnum = 0;

    }

    return (cluster_offset != 0);

}


static int vmdk_write(BlockDriverState *bs, int64_t sector_num,

                     const uint8_t *buf, int nb_sectors)

{

    BDRVVmdkState *s = bs->opaque;

    int index_in_cluster, n;

    uint64_t cluster_offset;

    static int cid_update = 0;

    while (nb_sectors > 0) {

        index_in_cluster = sector_num & (s->cluster_sectors - 1);

        n = s->cluster_sectors - index_in_cluster;

        if (n > nb_sectors)

            n = nb_sectors;

        cluster_offset = get_cluster_offset(bs, sector_num << 9, 1);

        if (!cluster_offset)

            return -1;

        if (bdrv_pwrite(s->hd, cluster_offset + index_in_cluster * 512, buf, n * 512) != n * 512)

            return -1;

        nb_sectors -= n;

        sector_num += n;

        buf += n * 512;

        // update CID on the first write every time the virtual disk is opened

        if (!cid_update) {

            vmdk_write_cid(bs, time(NULL));

            cid_update++;

        }

    }

    return 0;

}


static int update_thread_context(AVCodecContext *dst, const AVCodecContext *src)

{

    PNGDecContext *psrc = src->priv_data;

    PNGDecContext *pdst = dst->priv_data;

    int ret;

    if (dst == src)

        return 0;

    ff_thread_release_buffer(dst, &pdst->picture);

    if (psrc->picture.f->data[0] &&

        (ret = ff_thread_ref_frame(&pdst->picture, &psrc->picture)) < 0)

        return ret;

    if (CONFIG_APNG_DECODER && dst->codec_id == AV_CODEC_ID_APNG) {

        pdst->width             = psrc->width;

        pdst->height            = psrc->height;

        pdst->bit_depth         = psrc->bit_depth;

        pdst->color_type        = psrc->color_type;

        pdst->compression_type  = psrc->compression_type;

        pdst->interlace_type    = psrc->interlace_type;

        pdst->filter_type       = psrc->filter_type;

        pdst->cur_w = psrc->cur_w;

        pdst->cur_h = psrc->cur_h;

        pdst->x_offset = psrc->x_offset;

        pdst->y_offset = psrc->y_offset;

        pdst->has_trns = psrc->has_trns;

        memcpy(pdst->transparent_color_be, psrc->transparent_color_be, sizeof(pdst->transparent_color_be));

        pdst->dispose_op = psrc->dispose_op;

        memcpy(pdst->palette, psrc->palette, sizeof(pdst->palette));

        pdst->state |= psrc->state & (PNG_IHDR | PNG_PLTE);

        ff_thread_release_buffer(dst, &pdst->last_picture);

        if (psrc->last_picture.f->data[0] &&

            (ret = ff_thread_ref_frame(&pdst->last_picture, &psrc->last_picture)) < 0)

            return ret;

        ff_thread_release_buffer(dst, &pdst->previous_picture);

        if (psrc->previous_picture.f->data[0] &&

            (ret = ff_thread_ref_frame(&pdst->previous_picture, &psrc->previous_picture)) < 0)

            return ret;

    }

    return 0;

}


static int read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)

{

    AVStream *st = s->streams[stream_index];

    avio_seek(s->pb, FFMAX(timestamp, 0) * st->codec->width * st->codec->height * 4, SEEK_SET);

    return 0;

}