int av_parser_parse2(AVCodecParserContext *s, AVCodecContext *avctx,
                     uint8_t **poutbuf, int *poutbuf_size,
                     const uint8_t *buf, int buf_size,
                     int64_t pts, int64_t dts, int64_t pos)
{
    int index, i;
    uint8_t dummy_buf[AV_INPUT_BUFFER_PADDING_SIZE];
    if (!(s->flags & PARSER_FLAG_FETCHED_OFFSET)) {
        s->next_frame_offset =
        s->cur_offset        = pos;
        s->flags            |= PARSER_FLAG_FETCHED_OFFSET;
    }
    if (buf_size == 0) {
        /* padding is always necessary even if EOF, so we add it here */
        memset(dummy_buf, 0, sizeof(dummy_buf));
        buf = dummy_buf;
    } else if (s->cur_offset + buf_size != s->cur_frame_end[s->cur_frame_start_index]) { /* skip remainder packets */
        /* add a new packet descriptor */
        i = (s->cur_frame_start_index + 1) & (AV_PARSER_PTS_NB - 1);
        s->cur_frame_start_index = i;
        s->cur_frame_offset[i]   = s->cur_offset;
        s->cur_frame_end[i]      = s->cur_offset + buf_size;
        s->cur_frame_pts[i]      = pts;
        s->cur_frame_dts[i]      = dts;
        s->cur_frame_pos[i]      = pos;
    }
    if (s->fetch_timestamp) {
        s->fetch_timestamp = 0;
        s->last_pts        = s->pts;
        s->last_dts        = s->dts;
        s->last_pos        = s->pos;
        ff_fetch_timestamp(s, 0, 0, 0);
    }
    /* WARNING: the returned index can be negative */
    index = s->parser->parser_parse(s, avctx, (const uint8_t **) poutbuf,
                                    poutbuf_size, buf, buf_size);
    av_assert0(index > -0x20000000); // The API does not allow returning AVERROR codes
    /* update the file pointer */
    if (*poutbuf_size) {
        /* fill the data for the current frame */
        s->frame_offset = s->next_frame_offset;
        /* offset of the next frame */
        s->next_frame_offset = s->cur_offset + index;
        s->fetch_timestamp   = 1;
    }
    if (index < 0)
        index = 0;
    s->cur_offset += index;
    return index;
}


static int nbd_co_readv_1(NbdClientSession *client, int64_t sector_num,

                          int nb_sectors, QEMUIOVector *qiov,

                          int offset)

{

    struct nbd_request request;

    struct nbd_reply reply;

    ssize_t ret;

    request.type = NBD_CMD_READ;

    request.from = sector_num * 512;

    request.len = nb_sectors * 512;

    nbd_coroutine_start(client, &request);

    ret = nbd_co_send_request(client, &request, NULL, 0);

    if (ret < 0) {

        reply.error = -ret;

    } else {

        nbd_co_receive_reply(client, &request, &reply, qiov, offset);

    }

    nbd_coroutine_end(client, &request);

    return -reply.error;

}


static AVIOContext * wtvfile_open2(AVFormatContext *s, const uint8_t *buf, int buf_size, const uint8_t *filename, int filename_size)

{

    const uint8_t *buf_end = buf + buf_size;

    while(buf + 48 <= buf_end) {

        int dir_length, name_size, first_sector, depth;

        uint64_t file_length;

        const uint8_t *name;

        if (ff_guidcmp(buf, dir_entry_guid)) {

            av_log(s, AV_LOG_ERROR, "unknown guid "FF_PRI_GUID", expected dir_entry_guid; "

                   "remaining directory entries ignored\n", FF_ARG_GUID(buf));

            break;

        }

        dir_length  = AV_RL16(buf + 16);

        file_length = AV_RL64(buf + 24);

        name_size   = 2 * AV_RL32(buf + 32);

        if (buf + 48 + name_size > buf_end) {

            av_log(s, AV_LOG_ERROR, "filename exceeds buffer size; remaining directory entries ignored\n");

            break;

        }

        first_sector = AV_RL32(buf + 40 + name_size);

        depth        = AV_RL32(buf + 44 + name_size);

        /* compare file name; test optional null terminator */

        name = buf + 40;

        if (name_size >= filename_size &&

            !memcmp(name, filename, filename_size) &&

            (name_size < filename_size + 2 || !AV_RN16(name + filename_size)))

            return wtvfile_open_sector(first_sector, file_length, depth, s);

        buf += dir_length;

    }

    return 0;

}


static void stereo_processing(PSContext *ps, INTFLOAT (*l)[32][2], INTFLOAT (*r)[32][2], int is34)

{

    int e, b, k;

    INTFLOAT (*H11)[PS_MAX_NUM_ENV+1][PS_MAX_NR_IIDICC] = ps->H11;

    INTFLOAT (*H12)[PS_MAX_NUM_ENV+1][PS_MAX_NR_IIDICC] = ps->H12;

    INTFLOAT (*H21)[PS_MAX_NUM_ENV+1][PS_MAX_NR_IIDICC] = ps->H21;

    INTFLOAT (*H22)[PS_MAX_NUM_ENV+1][PS_MAX_NR_IIDICC] = ps->H22;

    int8_t *opd_hist = ps->opd_hist;

    int8_t *ipd_hist = ps->ipd_hist;

    int8_t iid_mapped_buf[PS_MAX_NUM_ENV][PS_MAX_NR_IIDICC];

    int8_t icc_mapped_buf[PS_MAX_NUM_ENV][PS_MAX_NR_IIDICC];

    int8_t ipd_mapped_buf[PS_MAX_NUM_ENV][PS_MAX_NR_IIDICC];

    int8_t opd_mapped_buf[PS_MAX_NUM_ENV][PS_MAX_NR_IIDICC];

    int8_t (*iid_mapped)[PS_MAX_NR_IIDICC] = iid_mapped_buf;

    int8_t (*icc_mapped)[PS_MAX_NR_IIDICC] = icc_mapped_buf;

    int8_t (*ipd_mapped)[PS_MAX_NR_IIDICC] = ipd_mapped_buf;

    int8_t (*opd_mapped)[PS_MAX_NR_IIDICC] = opd_mapped_buf;

    const int8_t *k_to_i = is34 ? k_to_i_34 : k_to_i_20;

    TABLE_CONST INTFLOAT (*H_LUT)[8][4] = (PS_BASELINE || ps->icc_mode < 3) ? HA : HB;

    //Remapping

    if (ps->num_env_old) {

        memcpy(H11[0][0], H11[0][ps->num_env_old], PS_MAX_NR_IIDICC*sizeof(H11[0][0][0]));

        memcpy(H11[1][0], H11[1][ps->num_env_old], PS_MAX_NR_IIDICC*sizeof(H11[1][0][0]));

        memcpy(H12[0][0], H12[0][ps->num_env_old], PS_MAX_NR_IIDICC*sizeof(H12[0][0][0]));

        memcpy(H12[1][0], H12[1][ps->num_env_old], PS_MAX_NR_IIDICC*sizeof(H12[1][0][0]));

        memcpy(H21[0][0], H21[0][ps->num_env_old], PS_MAX_NR_IIDICC*sizeof(H21[0][0][0]));

        memcpy(H21[1][0], H21[1][ps->num_env_old], PS_MAX_NR_IIDICC*sizeof(H21[1][0][0]));

        memcpy(H22[0][0], H22[0][ps->num_env_old], PS_MAX_NR_IIDICC*sizeof(H22[0][0][0]));

        memcpy(H22[1][0], H22[1][ps->num_env_old], PS_MAX_NR_IIDICC*sizeof(H22[1][0][0]));

    }

    if (is34) {

        remap34(&iid_mapped, ps->iid_par, ps->nr_iid_par, ps->num_env, 1);

        remap34(&icc_mapped, ps->icc_par, ps->nr_icc_par, ps->num_env, 1);

        if (ps->enable_ipdopd) {

            remap34(&ipd_mapped, ps->ipd_par, ps->nr_ipdopd_par, ps->num_env, 0);

            remap34(&opd_mapped, ps->opd_par, ps->nr_ipdopd_par, ps->num_env, 0);

        }

        if (!ps->is34bands_old) {

            map_val_20_to_34(H11[0][0]);

            map_val_20_to_34(H11[1][0]);

            map_val_20_to_34(H12[0][0]);

            map_val_20_to_34(H12[1][0]);

            map_val_20_to_34(H21[0][0]);

            map_val_20_to_34(H21[1][0]);

            map_val_20_to_34(H22[0][0]);

            map_val_20_to_34(H22[1][0]);

            ipdopd_reset(ipd_hist, opd_hist);

        }

    } else {

        remap20(&iid_mapped, ps->iid_par, ps->nr_iid_par, ps->num_env, 1);

        remap20(&icc_mapped, ps->icc_par, ps->nr_icc_par, ps->num_env, 1);

        if (ps->enable_ipdopd) {

            remap20(&ipd_mapped, ps->ipd_par, ps->nr_ipdopd_par, ps->num_env, 0);

            remap20(&opd_mapped, ps->opd_par, ps->nr_ipdopd_par, ps->num_env, 0);

        }

        if (ps->is34bands_old) {

            map_val_34_to_20(H11[0][0]);

            map_val_34_to_20(H11[1][0]);

            map_val_34_to_20(H12[0][0]);

            map_val_34_to_20(H12[1][0]);

            map_val_34_to_20(H21[0][0]);

            map_val_34_to_20(H21[1][0]);

            map_val_34_to_20(H22[0][0]);

            map_val_34_to_20(H22[1][0]);

            ipdopd_reset(ipd_hist, opd_hist);

        }

    }

    //Mixing

    for (e = 0; e < ps->num_env; e++) {

        for (b = 0; b < NR_PAR_BANDS[is34]; b++) {

            INTFLOAT h11, h12, h21, h22;

            h11 = H_LUT[iid_mapped[e][b] + 7 + 23 * ps->iid_quant][icc_mapped[e][b]][0];

            h12 = H_LUT[iid_mapped[e][b] + 7 + 23 * ps->iid_quant][icc_mapped[e][b]][1];

            h21 = H_LUT[iid_mapped[e][b] + 7 + 23 * ps->iid_quant][icc_mapped[e][b]][2];

            h22 = H_LUT[iid_mapped[e][b] + 7 + 23 * ps->iid_quant][icc_mapped[e][b]][3];

            if (!PS_BASELINE && ps->enable_ipdopd && b < NR_IPDOPD_BANDS[is34]) {

                //The spec say says to only run this smoother when enable_ipdopd

                //is set but the reference decoder appears to run it constantly

                INTFLOAT h11i, h12i, h21i, h22i;

                INTFLOAT ipd_adj_re, ipd_adj_im;

                int opd_idx = opd_hist[b] * 8 + opd_mapped[e][b];

                int ipd_idx = ipd_hist[b] * 8 + ipd_mapped[e][b];

                INTFLOAT opd_re = pd_re_smooth[opd_idx];

                INTFLOAT opd_im = pd_im_smooth[opd_idx];

                INTFLOAT ipd_re = pd_re_smooth[ipd_idx];

                INTFLOAT ipd_im = pd_im_smooth[ipd_idx];

                opd_hist[b] = opd_idx & 0x3F;

                ipd_hist[b] = ipd_idx & 0x3F;

                ipd_adj_re = AAC_MADD30(opd_re, ipd_re, opd_im, ipd_im);

                ipd_adj_im = AAC_MSUB30(opd_im, ipd_re, opd_re, ipd_im);

                h11i = AAC_MUL30(h11,  opd_im);

                h11  = AAC_MUL30(h11,  opd_re);

                h12i = AAC_MUL30(h12,  ipd_adj_im);

                h12  = AAC_MUL30(h12,  ipd_adj_re);

                h21i = AAC_MUL30(h21,  opd_im);

                h21  = AAC_MUL30(h21,  opd_re);

                h22i = AAC_MUL30(h22,  ipd_adj_im);

                h22  = AAC_MUL30(h22,  ipd_adj_re);

                H11[1][e+1][b] = h11i;

                H12[1][e+1][b] = h12i;

                H21[1][e+1][b] = h21i;

                H22[1][e+1][b] = h22i;

            }

            H11[0][e+1][b] = h11;

            H12[0][e+1][b] = h12;

            H21[0][e+1][b] = h21;

            H22[0][e+1][b] = h22;

        }

        for (k = 0; k < NR_BANDS[is34]; k++) {

            LOCAL_ALIGNED_16(INTFLOAT, h, [2], [4]);

            LOCAL_ALIGNED_16(INTFLOAT, h_step, [2], [4]);

            int start = ps->border_position[e];

            int stop  = ps->border_position[e+1];

            INTFLOAT width = Q30(1.f) / ((stop - start) ? (stop - start) : 1);

#if USE_FIXED

            width <<= 1;

#endif

            b = k_to_i[k];

            h[0][0] = H11[0][e][b];

            h[0][1] = H12[0][e][b];

            h[0][2] = H21[0][e][b];

            h[0][3] = H22[0][e][b];

            if (!PS_BASELINE && ps->enable_ipdopd) {

            //Is this necessary? ps_04_new seems unchanged

            if ((is34 && k <= 13 && k >= 9) || (!is34 && k <= 1)) {

                h[1][0] = -H11[1][e][b];

                h[1][1] = -H12[1][e][b];

                h[1][2] = -H21[1][e][b];

                h[1][3] = -H22[1][e][b];

            } else {

                h[1][0] = H11[1][e][b];

                h[1][1] = H12[1][e][b];

                h[1][2] = H21[1][e][b];

                h[1][3] = H22[1][e][b];

            }

            }

            //Interpolation

            h_step[0][0] = AAC_MSUB31_V3(H11[0][e+1][b], h[0][0], width);

            h_step[0][1] = AAC_MSUB31_V3(H12[0][e+1][b], h[0][1], width);

            h_step[0][2] = AAC_MSUB31_V3(H21[0][e+1][b], h[0][2], width);

            h_step[0][3] = AAC_MSUB31_V3(H22[0][e+1][b], h[0][3], width);

            if (!PS_BASELINE && ps->enable_ipdopd) {

                h_step[1][0] = AAC_MSUB31_V3(H11[1][e+1][b], h[1][0], width);

                h_step[1][1] = AAC_MSUB31_V3(H12[1][e+1][b], h[1][1], width);

                h_step[1][2] = AAC_MSUB31_V3(H21[1][e+1][b], h[1][2], width);

                h_step[1][3] = AAC_MSUB31_V3(H22[1][e+1][b], h[1][3], width);

            }

            ps->dsp.stereo_interpolate[!PS_BASELINE && ps->enable_ipdopd](

                l[k] + start + 1, r[k] + start + 1,

                h, h_step, stop - start);

        }

    }

}


static void handle_qmp_command(JSONMessageParser *parser, QList *tokens)

{

    int err;

    QObject *obj;

    QDict *input, *args;

    const mon_cmd_t *cmd;

    Monitor *mon = cur_mon;

    const char *cmd_name, *info_item;

    args = NULL;

    obj = json_parser_parse(tokens, NULL);

    if (!obj) {

        // FIXME: should be triggered in json_parser_parse()

        qerror_report(QERR_JSON_PARSING);

        goto err_out;

        qerror_report(QERR_QMP_BAD_INPUT_OBJECT, "object");

        qobject_decref(obj);

        goto err_out;

    }

    input = qobject_to_qdict(obj);

    mon->mc->id = qdict_get(input, "id");

    qobject_incref(mon->mc->id);

    obj = qdict_get(input, "execute");

    if (!obj) {

        qerror_report(QERR_QMP_BAD_INPUT_OBJECT, "execute");

    } else if (qobject_type(obj) != QTYPE_QSTRING) {

        qerror_report(QERR_QMP_BAD_INPUT_OBJECT_MEMBER, "execute", "string");

    }

    cmd_name = qstring_get_str(qobject_to_qstring(obj));

    if (invalid_qmp_mode(mon, cmd_name)) {

        qerror_report(QERR_COMMAND_NOT_FOUND, cmd_name);

    }

    /*

     * XXX: We need this special case until we get info handlers

     * converted into 'query-' commands

     */

    if (compare_cmd(cmd_name, "info")) {

        qerror_report(QERR_COMMAND_NOT_FOUND, cmd_name);

    } else if (strstart(cmd_name, "query-", &info_item)) {

        cmd = monitor_find_command("info");

        qdict_put_obj(input, "arguments",

                      qobject_from_jsonf("{ 'item': %s }", info_item));

    } else {

        cmd = monitor_find_command(cmd_name);

        if (!cmd || !monitor_handler_ported(cmd)) {

            qerror_report(QERR_COMMAND_NOT_FOUND, cmd_name);

        }

    }

    obj = qdict_get(input, "arguments");

    if (!obj) {

        args = qdict_new();

    } else {

        args = qobject_to_qdict(obj);

        QINCREF(args);

    }

    QDECREF(input);

    err = monitor_check_qmp_args(cmd, args);

    if (err < 0) {

        goto err_out;

    }

    if (monitor_handler_is_async(cmd)) {

        qmp_async_cmd_handler(mon, cmd, args);

    } else {

        monitor_call_handler(mon, cmd, args);

    }

    goto out;

err_input:

    QDECREF(input);

err_out:

    monitor_protocol_emitter(mon, NULL);

out:

    QDECREF(args);

}


static int idcin_decode_init(AVCodecContext *avctx)

{

    IdcinContext *s = avctx->priv_data;

    int i, j, histogram_index = 0;

    unsigned char *histograms;

    s->avctx = avctx;

    avctx->pix_fmt = PIX_FMT_PAL8;

    dsputil_init(&s->dsp, avctx);

    /* make sure the Huffman tables make it */

    if (s->avctx->extradata_size != HUFFMAN_TABLE_SIZE) {

        av_log(s->avctx, AV_LOG_ERROR, "  Id CIN video: expected extradata size of %d\n", HUFFMAN_TABLE_SIZE);

        return -1;

    }

    /* build the 256 Huffman decode trees */

    histograms = (unsigned char *)s->avctx->extradata;

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

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

            s->huff_nodes[i][j].count = histograms[histogram_index++];

        huff_build_tree(s, i);

    }

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

    return 0;

}


static void find_best_solid_area(VncState *vs, int x, int y, int w, int h,

                                 uint32_t color, int *w_ptr, int *h_ptr)

{

    int dx, dy, dw, dh;

    int w_prev;

    int w_best = 0, h_best = 0;

    w_prev = w;

    for (dy = y; dy < y + h; dy += VNC_TIGHT_MAX_SPLIT_TILE_SIZE) {

        dh = MIN(VNC_TIGHT_MAX_SPLIT_TILE_SIZE, y + h - dy);

        dw = MIN(VNC_TIGHT_MAX_SPLIT_TILE_SIZE, w_prev);

        if (!check_solid_tile(vs, x, dy, dw, dh, &color, true)) {

            break;

        }

        for (dx = x + dw; dx < x + w_prev;) {

            dw = MIN(VNC_TIGHT_MAX_SPLIT_TILE_SIZE, x + w_prev - dx);

            if (!check_solid_tile(vs, dx, dy, dw, dh, &color, true)) {

                break;

            }

            dx += dw;

        }

        w_prev = dx - x;

        if (w_prev * (dy + dh - y) > w_best * h_best) {

            w_best = w_prev;

            h_best = dy + dh - y;

        }

    }

    *w_ptr = w_best;

    *h_ptr = h_best;

}


static RAMBlock *qemu_get_ram_block(ram_addr_t addr)

{

    RAMBlock *block;

    /* The list is protected by the iothread lock here.  */

    block = ram_list.mru_block;

    if (block && addr - block->offset < block->max_length) {

        goto found;

    }

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

        if (addr - block->offset < block->max_length) {

            goto found;

        }

    }

    fprintf(stderr, "Bad ram offset %" PRIx64 "\n", (uint64_t)addr);

    abort();

found:

    ram_list.mru_block = block;

    return block;

}


static int usbnet_can_receive(VLANClientState *nc)

{

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

    if (s->rndis && !s->rndis_state == RNDIS_DATA_INITIALIZED)

        return 1;

    return !s->in_len;

}


static int scsi_disk_emulate_mode_sense(SCSIRequest *req, uint8_t *outbuf)

{

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

    uint64_t nb_sectors;

    int page, dbd, buflen, page_control;

    uint8_t *p;

    uint8_t dev_specific_param;

    dbd = req->cmd.buf[1]  & 0x8;

    page = req->cmd.buf[2] & 0x3f;

    page_control = (req->cmd.buf[2] & 0xc0) >> 6;

    DPRINTF("Mode Sense(%d) (page %d, len %d, page_control %d)\n",

        (req->cmd.buf[0] == MODE_SENSE) ? 6 : 10, page, len, page_control);

    memset(outbuf, 0, req->cmd.xfer);

    p = outbuf;

    if (bdrv_is_read_only(s->bs)) {

        dev_specific_param = 0x80; /* Readonly.  */

    } else {

        dev_specific_param = 0x00;

    }

    if (req->cmd.buf[0] == MODE_SENSE) {

        p[1] = 0; /* Default media type.  */

        p[2] = dev_specific_param;

        p[3] = 0; /* Block descriptor length.  */

        p += 4;

    } else { /* MODE_SENSE_10 */

        p[2] = 0; /* Default media type.  */

        p[3] = dev_specific_param;

        p[6] = p[7] = 0; /* Block descriptor length.  */

        p += 8;

    }

    bdrv_get_geometry(s->bs, &nb_sectors);

    if ((~dbd) & nb_sectors) {

        if (req->cmd.buf[0] == MODE_SENSE) {

            outbuf[3] = 8; /* Block descriptor length  */

        } else { /* MODE_SENSE_10 */

            outbuf[7] = 8; /* Block descriptor length  */

        }

        nb_sectors /= s->cluster_size;

        if (nb_sectors > 0xffffff)

            nb_sectors = 0;

        p[0] = 0; /* media density code */

        p[1] = (nb_sectors >> 16) & 0xff;

        p[2] = (nb_sectors >> 8) & 0xff;

        p[3] = nb_sectors & 0xff;

        p[4] = 0; /* reserved */

        p[5] = 0; /* bytes 5-7 are the sector size in bytes */

        p[6] = s->cluster_size * 2;

        p[7] = 0;

        p += 8;

    }

    if (page_control == 3) { /* Saved Values */

        return -1; /* ILLEGAL_REQUEST */

    }

    switch (page) {

    case 0x04:

    case 0x05:

    case 0x08:

    case 0x2a:

        p += mode_sense_page(req, page, p, page_control);

        break;

    case 0x3f:

        p += mode_sense_page(req, 0x08, p, page_control);

        p += mode_sense_page(req, 0x2a, p, page_control);

        break;

    default:

        return -1; /* ILLEGAL_REQUEST */

    }

    buflen = p - outbuf;

    /*

     * The mode data length field specifies the length in bytes of the

     * following data that is available to be transferred. The mode data

     * length does not include itself.

     */

    if (req->cmd.buf[0] == MODE_SENSE) {

        outbuf[0] = buflen - 1;

    } else { /* MODE_SENSE_10 */

        outbuf[0] = ((buflen - 2) >> 8) & 0xff;

        outbuf[1] = (buflen - 2) & 0xff;

    }

    if (buflen > req->cmd.xfer)

        buflen = req->cmd.xfer;

    return buflen;

}


void tcg_add_target_add_op_defs(const TCGTargetOpDef *tdefs)

{

    TCGOpcode op;

    TCGOpDef *def;

    const char *ct_str;

    int i, nb_args;

    for(;;) {

        if (tdefs->op == (TCGOpcode)-1)

            break;

        op = tdefs->op;

        assert((unsigned)op < NB_OPS);

        def = &tcg_op_defs[op];

#if defined(CONFIG_DEBUG_TCG)

        /* Duplicate entry in op definitions? */

        assert(!def->used);

        def->used = 1;

#endif

        nb_args = def->nb_iargs + def->nb_oargs;

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

            ct_str = tdefs->args_ct_str[i];

            /* Incomplete TCGTargetOpDef entry? */

            assert(ct_str != NULL);

            tcg_regset_clear(def->args_ct[i].u.regs);

            def->args_ct[i].ct = 0;

            if (ct_str[0] >= '0' && ct_str[0] <= '9') {

                int oarg;

                oarg = ct_str[0] - '0';

                assert(oarg < def->nb_oargs);

                assert(def->args_ct[oarg].ct & TCG_CT_REG);

                /* TCG_CT_ALIAS is for the output arguments. The input

                   argument is tagged with TCG_CT_IALIAS. */

                def->args_ct[i] = def->args_ct[oarg];

                def->args_ct[oarg].ct = TCG_CT_ALIAS;

                def->args_ct[oarg].alias_index = i;

                def->args_ct[i].ct |= TCG_CT_IALIAS;

                def->args_ct[i].alias_index = oarg;

            } else {

                for(;;) {

                    if (*ct_str == '\0')

                        break;

                    switch(*ct_str) {

                    case 'i':

                        def->args_ct[i].ct |= TCG_CT_CONST;

                        ct_str++;

                        break;

                    default:

                        if (target_parse_constraint(&def->args_ct[i], &ct_str) < 0) {

                            fprintf(stderr, "Invalid constraint '%s' for arg %d of operation '%s'\n",

                                    ct_str, i, def->name);

                            exit(1);

                        }

                    }

                }

            }

        }

        /* TCGTargetOpDef entry with too much information? */

        assert(i == TCG_MAX_OP_ARGS || tdefs->args_ct_str[i] == NULL);

        /* sort the constraints (XXX: this is just an heuristic) */

        sort_constraints(def, 0, def->nb_oargs);

        sort_constraints(def, def->nb_oargs, def->nb_iargs);

#if 0

        {

            int i;

            printf("%s: sorted=", def->name);

            for(i = 0; i < def->nb_oargs + def->nb_iargs; i++)

                printf(" %d", def->sorted_args[i]);

            printf("\n");

        }

#endif

        tdefs++;

    }

#if defined(CONFIG_DEBUG_TCG)

    i = 0;

    for (op = 0; op < tcg_op_defs_max; op++) {

        const TCGOpDef *def = &tcg_op_defs[op];

        if (def->flags & TCG_OPF_NOT_PRESENT) {

            /* Wrong entry in op definitions? */

            if (def->used) {

                fprintf(stderr, "Invalid op definition for %s\n", def->name);

                i = 1;

            }

        } else {

            /* Missing entry in op definitions? */

            if (!def->used) {

                fprintf(stderr, "Missing op definition for %s\n", def->name);

                i = 1;

            }

        }

    }

    if (i == 1) {

        tcg_abort();

    }

#endif

}


void AUD_vlog (const char *cap, const char *fmt, va_list ap)

{

    if (conf.log_to_monitor) {

        if (cap) {

            monitor_printf(default_mon, "%s: ", cap);

        }

        monitor_vprintf(default_mon, fmt, ap);

    }

    else {

        if (cap) {

            fprintf (stderr, "%s: ", cap);

        }

        vfprintf (stderr, fmt, ap);

    }

}


static int ogg_build_flac_headers(const uint8_t *extradata, int extradata_size,

                                  OGGStreamContext *oggstream, int bitexact)

{

    const char *vendor = bitexact ? "ffmpeg" : LIBAVFORMAT_IDENT;

    uint8_t *p;

    if (extradata_size != 34)

        return -1;

    oggstream->header_len[0] = 51;

    oggstream->header[0] = av_mallocz(51); // per ogg flac specs

    p = oggstream->header[0];

    bytestream_put_byte(&p, 0x7F);

    bytestream_put_buffer(&p, "FLAC", 4);

    bytestream_put_byte(&p, 1); // major version

    bytestream_put_byte(&p, 0); // minor version

    bytestream_put_be16(&p, 1); // headers packets without this one

    bytestream_put_buffer(&p, "fLaC", 4);

    bytestream_put_byte(&p, 0x00); // streaminfo

    bytestream_put_be24(&p, 34);

    bytestream_put_buffer(&p, extradata, 34);

    oggstream->header_len[1] = 1+3+4+strlen(vendor)+4;

    oggstream->header[1] = av_mallocz(oggstream->header_len[1]);

    p = oggstream->header[1];

    bytestream_put_byte(&p, 0x84); // last metadata block and vorbis comment

    bytestream_put_be24(&p, oggstream->header_len[1] - 4);

    bytestream_put_le32(&p, strlen(vendor));

    bytestream_put_buffer(&p, vendor, strlen(vendor));

    bytestream_put_le32(&p, 0); // user comment list length

    return 0;

}


static void put_subframe(DCAEncContext *c, int subframe)

{

    int i, band, ss, ch;

    /* Subsubframes count */

    put_bits(&c->pb, 2, SUBSUBFRAMES -1);

    /* Partial subsubframe sample count: dummy */

    put_bits(&c->pb, 3, 0);

    /* Prediction mode: no ADPCM, in each channel and subband */

    for (ch = 0; ch < c->fullband_channels; ch++)

        for (band = 0; band < DCAENC_SUBBANDS; band++)

            put_bits(&c->pb, 1, 0);

    /* Prediction VQ address: not transmitted */

    /* Bit allocation index */

    for (ch = 0; ch < c->fullband_channels; ch++)

        for (band = 0; band < DCAENC_SUBBANDS; band++)

            put_bits(&c->pb, 5, c->abits[band][ch]);

    if (SUBSUBFRAMES > 1) {

        /* Transition mode: none for each channel and subband */

        for (ch = 0; ch < c->fullband_channels; ch++)

            for (band = 0; band < DCAENC_SUBBANDS; band++)

                put_bits(&c->pb, 1, 0); /* codebook A4 */

    }

    /* Scale factors */

    for (ch = 0; ch < c->fullband_channels; ch++)

        for (band = 0; band < DCAENC_SUBBANDS; band++)

            put_bits(&c->pb, 7, c->scale_factor[band][ch]);

    /* Joint subband scale factor codebook select: not transmitted */

    /* Scale factors for joint subband coding: not transmitted */

    /* Stereo down-mix coefficients: not transmitted */

    /* Dynamic range coefficient: not transmitted */

    /* Stde information CRC check word: not transmitted */

    /* VQ encoded high frequency subbands: not transmitted */

    /* LFE data: 8 samples and scalefactor */

    if (c->lfe_channel) {

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

            put_bits(&c->pb, 8, quantize_value(c->downsampled_lfe[i], c->lfe_quant) & 0xff);

        put_bits(&c->pb, 8, c->lfe_scale_factor);

    }

    /* Audio data (subsubframes) */

    for (ss = 0; ss < SUBSUBFRAMES ; ss++)

        for (ch = 0; ch < c->fullband_channels; ch++)

            for (band = 0; band < DCAENC_SUBBANDS; band++)

                    put_subframe_samples(c, ss, band, ch);

    /* DSYNC */

    put_bits(&c->pb, 16, 0xffff);

}


static void decode_gray_bitstream(HYuvContext *s, int count)

{

    int i;

    count/=2;

    if (count >= (get_bits_left(&s->gb)) / (31 * 2)) {

        for (i = 0; i < count && get_bits_left(&s->gb) > 0; i++) {

            READ_2PIX(s->temp[0][2 * i], s->temp[0][2 * i + 1], 0);

        }

    } else {

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

            READ_2PIX(s->temp[0][2 * i], s->temp[0][2 * i + 1], 0);

        }

    }

}


static int start_auth_vencrypt_subauth(VncState *vs)

{

    switch (vs->vd->subauth) {

    case VNC_AUTH_VENCRYPT_TLSNONE:

    case VNC_AUTH_VENCRYPT_X509NONE:

       VNC_DEBUG("Accept TLS auth none\n");

       vnc_write_u32(vs, 0); /* Accept auth completion */

       vnc_read_when(vs, protocol_client_init, 1);

       break;

    case VNC_AUTH_VENCRYPT_TLSVNC:

    case VNC_AUTH_VENCRYPT_X509VNC:

       VNC_DEBUG("Start TLS auth VNC\n");

       return start_auth_vnc(vs);

    default: /* Should not be possible, but just in case */

       VNC_DEBUG("Reject auth %d\n", vs->vd->auth);

       vnc_write_u8(vs, 1);

       if (vs->minor >= 8) {

           static const char err[] = "Unsupported authentication type";

           vnc_write_u32(vs, sizeof(err));

           vnc_write(vs, err, sizeof(err));

       }

       vnc_client_error(vs);

    }

    return 0;

}


iscsi_unmap_cb(struct iscsi_context *iscsi, int status,

                     void *command_data, void *opaque)

{

    IscsiAIOCB *acb = opaque;

    if (acb->canceled != 0) {

        return;

    }

    acb->status = 0;

    if (status < 0) {

        error_report("Failed to unmap data on iSCSI lun. %s",

                     iscsi_get_error(iscsi));

        acb->status = -EIO;

    }

    iscsi_schedule_bh(acb);

}


static void virtio_notify(struct subchannel_id schid)

{

    kvm_hypercall(KVM_S390_VIRTIO_CCW_NOTIFY, *(u32*)&schid, 0);

}


static void kvm_mce_inj_srao_memscrub2(CPUState *env, target_phys_addr_t paddr)

{

    struct kvm_x86_mce mce = {

        .bank = 9,

        .status = MCI_STATUS_VAL | MCI_STATUS_UC | MCI_STATUS_EN

                  | MCI_STATUS_MISCV | MCI_STATUS_ADDRV | MCI_STATUS_S

                  | 0xc0,

        .mcg_status = MCG_STATUS_MCIP | MCG_STATUS_RIPV,

        .addr = paddr,

        .misc = (MCM_ADDR_PHYS << 6) | 0xc,

    };

    kvm_inject_x86_mce_on(env, &mce, ABORT_ON_ERROR);

    kvm_mce_broadcast_rest(env);

}


static void lm32_evr_init(QEMUMachineInitArgs *args)

{

    const char *cpu_model = args->cpu_model;

    const char *kernel_filename = args->kernel_filename;

    LM32CPU *cpu;

    CPULM32State *env;

    DriveInfo *dinfo;

    MemoryRegion *address_space_mem =  get_system_memory();

    MemoryRegion *phys_ram = g_new(MemoryRegion, 1);

    qemu_irq *cpu_irq, irq[32];

    ResetInfo *reset_info;

    int i;

    /* memory map */

    target_phys_addr_t flash_base  = 0x04000000;

    size_t flash_sector_size       = 256 * 1024;

    size_t flash_size              = 32 * 1024 * 1024;

    target_phys_addr_t ram_base    = 0x08000000;

    size_t ram_size                = 64 * 1024 * 1024;

    target_phys_addr_t timer0_base = 0x80002000;

    target_phys_addr_t uart0_base  = 0x80006000;

    target_phys_addr_t timer1_base = 0x8000a000;

    int uart0_irq                  = 0;

    int timer0_irq                 = 1;

    int timer1_irq                 = 3;

    reset_info = g_malloc0(sizeof(ResetInfo));

    if (cpu_model == NULL) {

        cpu_model = "lm32-full";

    }

    cpu = cpu_lm32_init(cpu_model);

    env = &cpu->env;

    reset_info->cpu = cpu;

    reset_info->flash_base = flash_base;

    memory_region_init_ram(phys_ram, "lm32_evr.sdram", ram_size);

    vmstate_register_ram_global(phys_ram);

    memory_region_add_subregion(address_space_mem, ram_base, phys_ram);

    dinfo = drive_get(IF_PFLASH, 0, 0);

    /* Spansion S29NS128P */

    pflash_cfi02_register(flash_base, NULL, "lm32_evr.flash", flash_size,

                          dinfo ? dinfo->bdrv : NULL, flash_sector_size,

                          flash_size / flash_sector_size, 1, 2,

                          0x01, 0x7e, 0x43, 0x00, 0x555, 0x2aa, 1);

    /* create irq lines */

    cpu_irq = qemu_allocate_irqs(cpu_irq_handler, env, 1);

    env->pic_state = lm32_pic_init(*cpu_irq);

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

        irq[i] = qdev_get_gpio_in(env->pic_state, i);

    }

    sysbus_create_simple("lm32-uart", uart0_base, irq[uart0_irq]);

    sysbus_create_simple("lm32-timer", timer0_base, irq[timer0_irq]);

    sysbus_create_simple("lm32-timer", timer1_base, irq[timer1_irq]);

    /* make sure juart isn't the first chardev */

    env->juart_state = lm32_juart_init();

    reset_info->bootstrap_pc = flash_base;

    if (kernel_filename) {

        uint64_t entry;

        int kernel_size;

        kernel_size = load_elf(kernel_filename, NULL, NULL, &entry, NULL, NULL,

                               1, ELF_MACHINE, 0);

        reset_info->bootstrap_pc = entry;

        if (kernel_size < 0) {

            kernel_size = load_image_targphys(kernel_filename, ram_base,

                                              ram_size);

            reset_info->bootstrap_pc = ram_base;

        }

        if (kernel_size < 0) {

            fprintf(stderr, "qemu: could not load kernel '%s'\n",

                    kernel_filename);

            exit(1);

        }

    }

    qemu_register_reset(main_cpu_reset, reset_info);

}


static void gen_msa_branch(CPUMIPSState *env, DisasContext *ctx, uint32_t op1)

{

    uint8_t df = (ctx->opcode >> 21) & 0x3;

    uint8_t wt = (ctx->opcode >> 16) & 0x1f;

    int64_t s16 = (int16_t)ctx->opcode;

    check_msa_access(ctx);

    if (ctx->insn_flags & ISA_MIPS32R6 && ctx->hflags & MIPS_HFLAG_BMASK) {

        generate_exception_end(ctx, EXCP_RI);

        return;

    }

    switch (op1) {

    case OPC_BZ_V:

    case OPC_BNZ_V:

        {

            TCGv_i64 t0 = tcg_temp_new_i64();

            tcg_gen_or_i64(t0, msa_wr_d[wt<<1], msa_wr_d[(wt<<1)+1]);

            tcg_gen_setcondi_i64((op1 == OPC_BZ_V) ?

                    TCG_COND_EQ : TCG_COND_NE, t0, t0, 0);

            tcg_gen_trunc_i64_tl(bcond, t0);

            tcg_temp_free_i64(t0);

        }

        break;

    case OPC_BZ_B:

    case OPC_BZ_H:

    case OPC_BZ_W:

    case OPC_BZ_D:

        gen_check_zero_element(bcond, df, wt);

        break;

    case OPC_BNZ_B:

    case OPC_BNZ_H:

    case OPC_BNZ_W:

    case OPC_BNZ_D:

        gen_check_zero_element(bcond, df, wt);

        tcg_gen_setcondi_tl(TCG_COND_EQ, bcond, bcond, 0);

        break;

    }

    ctx->btarget = ctx->pc + (s16 << 2) + 4;

    ctx->hflags |= MIPS_HFLAG_BC;

    ctx->hflags |= MIPS_HFLAG_BDS32;

}


static QObject *parse_keyword(JSONParserContext *ctxt, QList **tokens)

{

    QObject *token, *ret;

    QList *working = qlist_copy(*tokens);

    token = qlist_pop(working);

    if (token == NULL) {

        goto out;

    }

    if (token_get_type(token) != JSON_KEYWORD) {

        goto out;

    }

    if (token_is_keyword(token, "true")) {

        ret = QOBJECT(qbool_from_int(true));

    } else if (token_is_keyword(token, "false")) {

        ret = QOBJECT(qbool_from_int(false));

    } else {

        parse_error(ctxt, token, "invalid keyword `%s'", token_get_value(token));

        goto out;

    }

    qobject_decref(token);

    QDECREF(*tokens);

    *tokens = working;

    return ret;

out:

    qobject_decref(token);

    QDECREF(working);

    return NULL;

}


static av_cold int vaapi_encode_config_attributes(AVCodecContext *avctx)

{

    VAAPIEncodeContext *ctx = avctx->priv_data;

    VAStatus vas;

    int i, n, err;

    VAProfile    *profiles    = NULL;

    VAEntrypoint *entrypoints = NULL;

    VAConfigAttrib attr[] = {

        { VAConfigAttribRTFormat        },

        { VAConfigAttribRateControl     },

        { VAConfigAttribEncMaxRefFrames },

    };

    n = vaMaxNumProfiles(ctx->hwctx->display);

    profiles = av_malloc_array(n, sizeof(VAProfile));

    if (!profiles) {

        err = AVERROR(ENOMEM);

        goto fail;

    }

    vas = vaQueryConfigProfiles(ctx->hwctx->display, profiles, &n);

    if (vas != VA_STATUS_SUCCESS) {

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

               vas, vaErrorStr(vas));

        err = AVERROR(ENOSYS);

        goto fail;

    }

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

        if (profiles[i] == ctx->va_profile)

            break;

    }

    if (i >= n) {

        av_log(ctx, AV_LOG_ERROR, "Encoding profile not found (%d).\n",

               ctx->va_profile);

        err = AVERROR(ENOSYS);

        goto fail;

    }

    n = vaMaxNumEntrypoints(ctx->hwctx->display);

    entrypoints = av_malloc_array(n, sizeof(VAEntrypoint));

    if (!entrypoints) {

        err = AVERROR(ENOMEM);

        goto fail;

    }

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

                                   entrypoints, &n);

    if (vas != VA_STATUS_SUCCESS) {

        av_log(ctx, AV_LOG_ERROR, "Failed to query entrypoints for "

               "profile %u: %d (%s).\n", ctx->va_profile,

               vas, vaErrorStr(vas));

        err = AVERROR(ENOSYS);

        goto fail;

    }

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

        if (entrypoints[i] == ctx->va_entrypoint)

            break;

    }

    if (i >= n) {

        av_log(ctx, AV_LOG_ERROR, "Encoding entrypoint not found "

               "(%d / %d).\n", ctx->va_profile, ctx->va_entrypoint);

        err = AVERROR(ENOSYS);

        goto fail;

    }

    vas = vaGetConfigAttributes(ctx->hwctx->display,

                                ctx->va_profile, ctx->va_entrypoint,

                                attr, FF_ARRAY_ELEMS(attr));

    if (vas != VA_STATUS_SUCCESS) {

        av_log(avctx, AV_LOG_ERROR, "Failed to fetch config "

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

        return AVERROR(EINVAL);

    }

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

        if (attr[i].value == VA_ATTRIB_NOT_SUPPORTED) {

            // Unfortunately we have to treat this as "don't know" and hope

            // for the best, because the Intel MJPEG encoder returns this

            // for all the interesting attributes.

            continue;

        }

        switch (attr[i].type) {

        case VAConfigAttribRTFormat:

            if (!(ctx->va_rt_format & attr[i].value)) {

                av_log(avctx, AV_LOG_ERROR, "Surface RT format %#x "

                       "is not supported (mask %#x).\n",

                       ctx->va_rt_format, attr[i].value);

                err = AVERROR(EINVAL);

                goto fail;

            }

            ctx->config_attributes[ctx->nb_config_attributes++] =

                (VAConfigAttrib) {

                .type  = VAConfigAttribRTFormat,

                .value = ctx->va_rt_format,

            };

            break;

        case VAConfigAttribRateControl:

            if (!(ctx->va_rc_mode & attr[i].value)) {

                av_log(avctx, AV_LOG_ERROR, "Rate control mode %#x "

                       "is not supported (mask: %#x).\n",

                       ctx->va_rc_mode, attr[i].value);

                err = AVERROR(EINVAL);

                goto fail;

            }

            ctx->config_attributes[ctx->nb_config_attributes++] =

                (VAConfigAttrib) {

                .type  = VAConfigAttribRateControl,

                .value = ctx->va_rc_mode,

            };

            break;

        case VAConfigAttribEncMaxRefFrames:

        {

            unsigned int ref_l0 = attr[i].value & 0xffff;

            unsigned int ref_l1 = (attr[i].value >> 16) & 0xffff;

            if (avctx->gop_size > 1 && ref_l0 < 1) {

                av_log(avctx, AV_LOG_ERROR, "P frames are not "

                       "supported (%#x).\n", attr[i].value);

                err = AVERROR(EINVAL);

                goto fail;

            }

            if (avctx->max_b_frames > 0 && ref_l1 < 1) {

                av_log(avctx, AV_LOG_ERROR, "B frames are not "

                       "supported (%#x).\n", attr[i].value);

                err = AVERROR(EINVAL);

                goto fail;

            }

        }

        break;

        default:

            av_assert0(0 && "Unexpected config attribute.");

        }

    }

    err = 0;

fail:

    av_freep(&profiles);

    av_freep(&entrypoints);

    return err;

}


static int targa_encode_frame(AVCodecContext *avctx, AVPacket *pkt,

                              const AVFrame *p, int *got_packet)

{

    int bpp, picsize, datasize = -1, ret;

    uint8_t *out;

    if(avctx->width > 0xffff || avctx->height > 0xffff) {

        av_log(avctx, AV_LOG_ERROR, "image dimensions too large\n");

        return AVERROR(EINVAL);

    }

    picsize = av_image_get_buffer_size(avctx->pix_fmt,

                                       avctx->width, avctx->height, 1);

    if ((ret = ff_alloc_packet(pkt, picsize + 45)) < 0) {

        av_log(avctx, AV_LOG_ERROR, "encoded frame too large\n");

        return ret;

    }

    /* zero out the header and only set applicable fields */

    memset(pkt->data, 0, 12);

    AV_WL16(pkt->data+12, avctx->width);

    AV_WL16(pkt->data+14, avctx->height);

    /* image descriptor byte: origin is always top-left, bits 0-3 specify alpha */

    pkt->data[17] = 0x20 | (avctx->pix_fmt == AV_PIX_FMT_BGRA ? 8 : 0);

    switch(avctx->pix_fmt) {

    case AV_PIX_FMT_GRAY8:

        pkt->data[2]  = TGA_BW;     /* uncompressed grayscale image */

        pkt->data[16] = 8;          /* bpp */

        break;

    case AV_PIX_FMT_RGB555LE:

        pkt->data[2]  = TGA_RGB;    /* uncompresses true-color image */

        pkt->data[16] = 16;         /* bpp */

        break;

    case AV_PIX_FMT_BGR24:

        pkt->data[2]  = TGA_RGB;    /* uncompressed true-color image */

        pkt->data[16] = 24;         /* bpp */

        break;

    case AV_PIX_FMT_BGRA:

        pkt->data[2]  = TGA_RGB;    /* uncompressed true-color image */

        pkt->data[16] = 32;         /* bpp */

        break;

    default:

        av_log(avctx, AV_LOG_ERROR, "Pixel format '%s' not supported.\n",

               av_get_pix_fmt_name(avctx->pix_fmt));

        return AVERROR(EINVAL);

    }

    bpp = pkt->data[16] >> 3;

    out = pkt->data + 18;  /* skip past the header we just output */

    /* try RLE compression */

    if (avctx->coder_type != FF_CODER_TYPE_RAW)

        datasize = targa_encode_rle(out, picsize, p, bpp, avctx->width, avctx->height);

    /* if that worked well, mark the picture as RLE compressed */

    if(datasize >= 0)

        pkt->data[2] |= 8;

    /* if RLE didn't make it smaller, go back to no compression */

    else datasize = targa_encode_normal(out, p, bpp, avctx->width, avctx->height);

    out += datasize;

    /* The standard recommends including this section, even if we don't use

     * any of the features it affords. TODO: take advantage of the pixel

     * aspect ratio and encoder ID fields available? */

    memcpy(out, "\0\0\0\0\0\0\0\0TRUEVISION-XFILE.", 26);

    pkt->size   = out + 26 - pkt->data;

    pkt->flags |= AV_PKT_FLAG_KEY;

    *got_packet = 1;

    return 0;

}


static int scsi_req_length(SCSICommand *cmd, SCSIDevice *dev, uint8_t *buf)

{

    cmd->xfer = scsi_cdb_length(buf);

    switch (buf[0]) {

    case TEST_UNIT_READY:

    case REWIND:

    case START_STOP:

    case SET_CAPACITY:

    case WRITE_FILEMARKS:

    case WRITE_FILEMARKS_16:

    case SPACE:

    case RESERVE:

    case RELEASE:

    case ERASE:

    case ALLOW_MEDIUM_REMOVAL:

    case SEEK_10:

    case SYNCHRONIZE_CACHE:

    case SYNCHRONIZE_CACHE_16:

    case LOCATE_16:

    case LOCK_UNLOCK_CACHE:

    case SET_CD_SPEED:

    case SET_LIMITS:

    case WRITE_LONG_10:

    case UPDATE_BLOCK:

    case RESERVE_TRACK:

    case SET_READ_AHEAD:

    case PRE_FETCH:

    case PRE_FETCH_16:

    case ALLOW_OVERWRITE:

        cmd->xfer = 0;

        break;

    case VERIFY_10:

    case VERIFY_12:

    case VERIFY_16:

        if ((buf[1] & 2) == 0) {

            cmd->xfer = 0;

        } else if ((buf[1] & 4) == 1) {

            cmd->xfer = 1;

        }

        cmd->xfer *= dev->blocksize;

        break;

    case MODE_SENSE:

        break;

    case WRITE_SAME_10:

    case WRITE_SAME_16:

        cmd->xfer = dev->blocksize;

        break;

    case READ_CAPACITY_10:

        cmd->xfer = 8;

        break;

    case READ_BLOCK_LIMITS:

        cmd->xfer = 6;

        break;

    case SEND_VOLUME_TAG:

        /* GPCMD_SET_STREAMING from multimedia commands.  */

        if (dev->type == TYPE_ROM) {

            cmd->xfer = buf[10] | (buf[9] << 8);

        } else {

            cmd->xfer = buf[9] | (buf[8] << 8);

        }

        break;

    case WRITE_6:

        /* length 0 means 256 blocks */

        if (cmd->xfer == 0) {

            cmd->xfer = 256;

        }

    case WRITE_10:

    case WRITE_VERIFY_10:

    case WRITE_12:

    case WRITE_VERIFY_12:

    case WRITE_16:

    case WRITE_VERIFY_16:

        cmd->xfer *= dev->blocksize;

        break;

    case READ_6:

    case READ_REVERSE:

        /* length 0 means 256 blocks */

        if (cmd->xfer == 0) {

            cmd->xfer = 256;

        }

    case READ_10:

    case RECOVER_BUFFERED_DATA:

    case READ_12:

    case READ_16:

        cmd->xfer *= dev->blocksize;

        break;

    case FORMAT_UNIT:

        /* MMC mandates the parameter list to be 12-bytes long.  Parameters

         * for block devices are restricted to the header right now.  */

        if (dev->type == TYPE_ROM && (buf[1] & 16)) {

            cmd->xfer = 12;

        } else {

            cmd->xfer = (buf[1] & 16) == 0 ? 0 : (buf[1] & 32 ? 8 : 4);

        }

        break;

    case INQUIRY:

    case RECEIVE_DIAGNOSTIC:

    case SEND_DIAGNOSTIC:

        cmd->xfer = buf[4] | (buf[3] << 8);

        break;

    case READ_CD:

    case READ_BUFFER:

    case WRITE_BUFFER:

    case SEND_CUE_SHEET:

        cmd->xfer = buf[8] | (buf[7] << 8) | (buf[6] << 16);

        break;

    case PERSISTENT_RESERVE_OUT:

        cmd->xfer = ldl_be_p(&buf[5]) & 0xffffffffULL;

        break;

    case ERASE_12:

        if (dev->type == TYPE_ROM) {

            /* MMC command GET PERFORMANCE.  */

            cmd->xfer = scsi_get_performance_length(buf[9] | (buf[8] << 8),

                                                    buf[10], buf[1] & 0x1f);

        }

        break;

    case MECHANISM_STATUS:

    case READ_DVD_STRUCTURE:

    case SEND_DVD_STRUCTURE:

    case MAINTENANCE_OUT:

    case MAINTENANCE_IN:

        if (dev->type == TYPE_ROM) {

            /* GPCMD_REPORT_KEY and GPCMD_SEND_KEY from multi media commands */

            cmd->xfer = buf[9] | (buf[8] << 8);

        }

        break;

    case ATA_PASSTHROUGH_12:

        if (dev->type == TYPE_ROM) {

            /* BLANK command of MMC */

            cmd->xfer = 0;

        } else {

            cmd->xfer = ata_passthrough_12_xfer_size(dev, buf);

        }

        break;

    case ATA_PASSTHROUGH_16:

        cmd->xfer = ata_passthrough_16_xfer_size(dev, buf);

        break;

    }

    return 0;

}


static void qdm2_init(QDM2Context *q) {

    static int inited = 0;

    if (inited != 0)

        return;

    inited = 1;

    qdm2_init_vlc();

    ff_mpa_synth_init(mpa_window);

    softclip_table_init();

    rnd_table_init();

    init_noise_samples();

    av_log(NULL, AV_LOG_DEBUG, "init done\n");

}


static int encode_frame(FlacEncodeContext *s)

{

    int ch, count;

    count = count_frame_header(s);

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

        count += encode_residual_ch(s, ch);

    count += (8 - (count & 7)) & 7; // byte alignment

    count += 16;                    // CRC-16

    return count >> 3;

}


static int vfio_add_std_cap(VFIOPCIDevice *vdev, uint8_t pos)

{

    PCIDevice *pdev = &vdev->pdev;

    uint8_t cap_id, next, size;

    int ret;

    cap_id = pdev->config[pos];

    next = pdev->config[pos + PCI_CAP_LIST_NEXT];

    /*

     * If it becomes important to configure capabilities to their actual

     * size, use this as the default when it's something we don't recognize.

     * Since QEMU doesn't actually handle many of the config accesses,

     * exact size doesn't seem worthwhile.

     */

    size = vfio_std_cap_max_size(pdev, pos);

    /*

     * pci_add_capability always inserts the new capability at the head

     * of the chain.  Therefore to end up with a chain that matches the

     * physical device, we insert from the end by making this recursive.

     * This is also why we pre-calculate size above as cached config space

     * will be changed as we unwind the stack.

     */

    if (next) {

        ret = vfio_add_std_cap(vdev, next);

        if (ret) {

            return ret;

        }

    } else {

        /* Begin the rebuild, use QEMU emulated list bits */

        pdev->config[PCI_CAPABILITY_LIST] = 0;

        vdev->emulated_config_bits[PCI_CAPABILITY_LIST] = 0xff;

        vdev->emulated_config_bits[PCI_STATUS] |= PCI_STATUS_CAP_LIST;

    }

    /* Use emulated next pointer to allow dropping caps */

    pci_set_byte(vdev->emulated_config_bits + pos + PCI_CAP_LIST_NEXT, 0xff);

    switch (cap_id) {

    case PCI_CAP_ID_MSI:

        ret = vfio_msi_setup(vdev, pos);

        break;

    case PCI_CAP_ID_EXP:

        vfio_check_pcie_flr(vdev, pos);

        ret = vfio_setup_pcie_cap(vdev, pos, size);

        break;

    case PCI_CAP_ID_MSIX:

        ret = vfio_msix_setup(vdev, pos);

        break;

    case PCI_CAP_ID_PM:

        vfio_check_pm_reset(vdev, pos);

        vdev->pm_cap = pos;

        ret = pci_add_capability(pdev, cap_id, pos, size);

        break;

    case PCI_CAP_ID_AF:

        vfio_check_af_flr(vdev, pos);

        ret = pci_add_capability(pdev, cap_id, pos, size);

        break;

    default:

        ret = pci_add_capability(pdev, cap_id, pos, size);

        break;

    }

    if (ret < 0) {

        error_report("vfio: %04x:%02x:%02x.%x Error adding PCI capability "

                     "0x%x[0x%x]@0x%x: %d", vdev->host.domain,

                     vdev->host.bus, vdev->host.slot, vdev->host.function,

                     cap_id, size, pos, ret);

        return ret;

    }

    return 0;

}


int cpu_exec(CPUState *env1)

{

#define DECLARE_HOST_REGS 1

#include "hostregs_helper.h"

    int ret, interrupt_request;

    TranslationBlock *tb;

    uint8_t *tc_ptr;

    unsigned long next_tb;

    if (cpu_halted(env1) == EXCP_HALTED)

        return EXCP_HALTED;

    cpu_single_env = env1;

    /* first we save global registers */

#define SAVE_HOST_REGS 1

#include "hostregs_helper.h"

    env = env1;

#if defined(TARGET_I386)

    /* put eflags in CPU temporary format */

    CC_SRC = env->eflags & (CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C);

    DF = 1 - (2 * ((env->eflags >> 10) & 1));

    CC_OP = CC_OP_EFLAGS;

    env->eflags &= ~(DF_MASK | CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C);

#elif defined(TARGET_SPARC)

#elif defined(TARGET_M68K)

    env->cc_op = CC_OP_FLAGS;

    env->cc_dest = env->sr & 0xf;

    env->cc_x = (env->sr >> 4) & 1;

#elif defined(TARGET_ALPHA)

#elif defined(TARGET_ARM)

#elif defined(TARGET_PPC)

#elif defined(TARGET_MICROBLAZE)

#elif defined(TARGET_MIPS)

#elif defined(TARGET_SH4)

#elif defined(TARGET_CRIS)

#elif defined(TARGET_S390X)

    /* XXXXX */

#else

#error unsupported target CPU

#endif

    env->exception_index = -1;

    /* prepare setjmp context for exception handling */

    for(;;) {

        if (setjmp(env->jmp_env) == 0) {

#if defined(__sparc__) && !defined(CONFIG_SOLARIS)

#undef env

                    env = cpu_single_env;

#define env cpu_single_env

#endif

            /* if an exception is pending, we execute it here */

            if (env->exception_index >= 0) {

                if (env->exception_index >= EXCP_INTERRUPT) {

                    /* exit request from the cpu execution loop */

                    ret = env->exception_index;

                    if (ret == EXCP_DEBUG)

                        cpu_handle_debug_exception(env);

                    break;

                } else {

#if defined(CONFIG_USER_ONLY)

                    /* if user mode only, we simulate a fake exception

                       which will be handled outside the cpu execution

                       loop */

#if defined(TARGET_I386)

                    do_interrupt_user(env->exception_index,

                                      env->exception_is_int,

                                      env->error_code,

                                      env->exception_next_eip);

                    /* successfully delivered */

                    env->old_exception = -1;

#endif

                    ret = env->exception_index;

                    break;

#else

#if defined(TARGET_I386)

                    /* simulate a real cpu exception. On i386, it can

                       trigger new exceptions, but we do not handle

                       double or triple faults yet. */

                    do_interrupt(env->exception_index,

                                 env->exception_is_int,

                                 env->error_code,

                                 env->exception_next_eip, 0);

                    /* successfully delivered */

                    env->old_exception = -1;

#elif defined(TARGET_PPC)

                    do_interrupt(env);

#elif defined(TARGET_MICROBLAZE)

                    do_interrupt(env);

#elif defined(TARGET_MIPS)

                    do_interrupt(env);

#elif defined(TARGET_SPARC)

                    do_interrupt(env);

#elif defined(TARGET_ARM)

                    do_interrupt(env);

#elif defined(TARGET_SH4)

		    do_interrupt(env);

#elif defined(TARGET_ALPHA)

                    do_interrupt(env);

#elif defined(TARGET_CRIS)

                    do_interrupt(env);

#elif defined(TARGET_M68K)

                    do_interrupt(0);

#endif

                    env->exception_index = -1;

#endif

                }

            }

            if (kvm_enabled()) {

                kvm_cpu_exec(env);

                longjmp(env->jmp_env, 1);

            }

            next_tb = 0; /* force lookup of first TB */

            for(;;) {

                interrupt_request = env->interrupt_request;

                if (unlikely(interrupt_request)) {

                    if (unlikely(env->singlestep_enabled & SSTEP_NOIRQ)) {

                        /* Mask out external interrupts for this step. */

                        interrupt_request &= ~(CPU_INTERRUPT_HARD |

                                               CPU_INTERRUPT_FIQ |

                                               CPU_INTERRUPT_SMI |

                                               CPU_INTERRUPT_NMI);

                    }

                    if (interrupt_request & CPU_INTERRUPT_DEBUG) {

                        env->interrupt_request &= ~CPU_INTERRUPT_DEBUG;

                        env->exception_index = EXCP_DEBUG;

                        cpu_loop_exit();

                    }

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

    defined(TARGET_PPC) || defined(TARGET_ALPHA) || defined(TARGET_CRIS) || \

    defined(TARGET_MICROBLAZE)

                    if (interrupt_request & CPU_INTERRUPT_HALT) {

                        env->interrupt_request &= ~CPU_INTERRUPT_HALT;

                        env->halted = 1;

                        env->exception_index = EXCP_HLT;

                        cpu_loop_exit();

                    }

#endif

#if defined(TARGET_I386)

                    if (interrupt_request & CPU_INTERRUPT_INIT) {

                            svm_check_intercept(SVM_EXIT_INIT);

                            do_cpu_init(env);

                            env->exception_index = EXCP_HALTED;

                            cpu_loop_exit();

                    } else if (interrupt_request & CPU_INTERRUPT_SIPI) {

                            do_cpu_sipi(env);

                    } else if (env->hflags2 & HF2_GIF_MASK) {

                        if ((interrupt_request & CPU_INTERRUPT_SMI) &&

                            !(env->hflags & HF_SMM_MASK)) {

                            svm_check_intercept(SVM_EXIT_SMI);

                            env->interrupt_request &= ~CPU_INTERRUPT_SMI;

                            do_smm_enter();

                            next_tb = 0;

                        } else if ((interrupt_request & CPU_INTERRUPT_NMI) &&

                                   !(env->hflags2 & HF2_NMI_MASK)) {

                            env->interrupt_request &= ~CPU_INTERRUPT_NMI;

                            env->hflags2 |= HF2_NMI_MASK;

                            do_interrupt(EXCP02_NMI, 0, 0, 0, 1);

                            next_tb = 0;

			} else if (interrupt_request & CPU_INTERRUPT_MCE) {

                            env->interrupt_request &= ~CPU_INTERRUPT_MCE;

                            do_interrupt(EXCP12_MCHK, 0, 0, 0, 0);

                            next_tb = 0;

                        } else if ((interrupt_request & CPU_INTERRUPT_HARD) &&

                                   (((env->hflags2 & HF2_VINTR_MASK) &&

                                     (env->hflags2 & HF2_HIF_MASK)) ||

                                    (!(env->hflags2 & HF2_VINTR_MASK) &&

                                     (env->eflags & IF_MASK &&

                                      !(env->hflags & HF_INHIBIT_IRQ_MASK))))) {

                            int intno;

                            svm_check_intercept(SVM_EXIT_INTR);

                            env->interrupt_request &= ~(CPU_INTERRUPT_HARD | CPU_INTERRUPT_VIRQ);

                            intno = cpu_get_pic_interrupt(env);

                            qemu_log_mask(CPU_LOG_TB_IN_ASM, "Servicing hardware INT=0x%02x\n", intno);

#if defined(__sparc__) && !defined(CONFIG_SOLARIS)

#undef env

                    env = cpu_single_env;

#define env cpu_single_env

#endif

                            do_interrupt(intno, 0, 0, 0, 1);

                            /* ensure that no TB jump will be modified as

                               the program flow was changed */

                            next_tb = 0;

#if !defined(CONFIG_USER_ONLY)

                        } else if ((interrupt_request & CPU_INTERRUPT_VIRQ) &&

                                   (env->eflags & IF_MASK) &&

                                   !(env->hflags & HF_INHIBIT_IRQ_MASK)) {

                            int intno;

                            /* FIXME: this should respect TPR */

                            svm_check_intercept(SVM_EXIT_VINTR);

                            intno = ldl_phys(env->vm_vmcb + offsetof(struct vmcb, control.int_vector));

                            qemu_log_mask(CPU_LOG_TB_IN_ASM, "Servicing virtual hardware INT=0x%02x\n", intno);

                            do_interrupt(intno, 0, 0, 0, 1);

                            env->interrupt_request &= ~CPU_INTERRUPT_VIRQ;

                            next_tb = 0;

#endif

                        }

                    }

#elif defined(TARGET_PPC)

#if 0

                    if ((interrupt_request & CPU_INTERRUPT_RESET)) {

                        cpu_reset(env);

                    }

#endif

                    if (interrupt_request & CPU_INTERRUPT_HARD) {

                        ppc_hw_interrupt(env);

                        if (env->pending_interrupts == 0)

                            env->interrupt_request &= ~CPU_INTERRUPT_HARD;

                        next_tb = 0;

                    }

#elif defined(TARGET_MICROBLAZE)

                    if ((interrupt_request & CPU_INTERRUPT_HARD)

                        && (env->sregs[SR_MSR] & MSR_IE)

                        && !(env->sregs[SR_MSR] & (MSR_EIP | MSR_BIP))

                        && !(env->iflags & (D_FLAG | IMM_FLAG))) {

                        env->exception_index = EXCP_IRQ;

                        do_interrupt(env);

                        next_tb = 0;

                    }

#elif defined(TARGET_MIPS)

                    if ((interrupt_request & CPU_INTERRUPT_HARD) &&

                        (env->CP0_Status & env->CP0_Cause & CP0Ca_IP_mask) &&

                        (env->CP0_Status & (1 << CP0St_IE)) &&

                        !(env->CP0_Status & (1 << CP0St_EXL)) &&

                        !(env->CP0_Status & (1 << CP0St_ERL)) &&

                        !(env->hflags & MIPS_HFLAG_DM)) {

                        /* Raise it */

                        env->exception_index = EXCP_EXT_INTERRUPT;

                        env->error_code = 0;

                        do_interrupt(env);

                        next_tb = 0;

                    }

#elif defined(TARGET_SPARC)

                    if (interrupt_request & CPU_INTERRUPT_HARD) {

                        if (cpu_interrupts_enabled(env) &&

                            env->interrupt_index > 0) {

                            int pil = env->interrupt_index & 0xf;

                            int type = env->interrupt_index & 0xf0;

                            if (((type == TT_EXTINT) &&

                                  cpu_pil_allowed(env, pil)) ||

                                  type != TT_EXTINT) {

                                env->exception_index = env->interrupt_index;

                                do_interrupt(env);

                                next_tb = 0;

                            }

                        }

		    } else if (interrupt_request & CPU_INTERRUPT_TIMER) {

			//do_interrupt(0, 0, 0, 0, 0);

			env->interrupt_request &= ~CPU_INTERRUPT_TIMER;

		    }

#elif defined(TARGET_ARM)

                    if (interrupt_request & CPU_INTERRUPT_FIQ

                        && !(env->uncached_cpsr & CPSR_F)) {

                        env->exception_index = EXCP_FIQ;

                        do_interrupt(env);

                        next_tb = 0;

                    }

                    /* ARMv7-M interrupt return works by loading a magic value

                       into the PC.  On real hardware the load causes the

                       return to occur.  The qemu implementation performs the

                       jump normally, then does the exception return when the

                       CPU tries to execute code at the magic address.

                       This will cause the magic PC value to be pushed to

                       the stack if an interrupt occured at the wrong time.

                       We avoid this by disabling interrupts when

                       pc contains a magic address.  */

                    if (interrupt_request & CPU_INTERRUPT_HARD

                        && ((IS_M(env) && env->regs[15] < 0xfffffff0)

                            || !(env->uncached_cpsr & CPSR_I))) {

                        env->exception_index = EXCP_IRQ;

                        do_interrupt(env);

                        next_tb = 0;

                    }

#elif defined(TARGET_SH4)

                    if (interrupt_request & CPU_INTERRUPT_HARD) {

                        do_interrupt(env);

                        next_tb = 0;

                    }

#elif defined(TARGET_ALPHA)

                    if (interrupt_request & CPU_INTERRUPT_HARD) {

                        do_interrupt(env);

                        next_tb = 0;

                    }

#elif defined(TARGET_CRIS)

                    if (interrupt_request & CPU_INTERRUPT_HARD

                        && (env->pregs[PR_CCS] & I_FLAG)) {

                        env->exception_index = EXCP_IRQ;

                        do_interrupt(env);

                        next_tb = 0;

                    }

                    if (interrupt_request & CPU_INTERRUPT_NMI

                        && (env->pregs[PR_CCS] & M_FLAG)) {

                        env->exception_index = EXCP_NMI;

                        do_interrupt(env);

                        next_tb = 0;

                    }

#elif defined(TARGET_M68K)

                    if (interrupt_request & CPU_INTERRUPT_HARD

                        && ((env->sr & SR_I) >> SR_I_SHIFT)

                            < env->pending_level) {

                        /* Real hardware gets the interrupt vector via an

                           IACK cycle at this point.  Current emulated

                           hardware doesn't rely on this, so we

                           provide/save the vector when the interrupt is

                           first signalled.  */

                        env->exception_index = env->pending_vector;

                        do_interrupt(1);

                        next_tb = 0;

                    }

#endif

                   /* Don't use the cached interupt_request value,

                      do_interrupt may have updated the EXITTB flag. */

                    if (env->interrupt_request & CPU_INTERRUPT_EXITTB) {

                        env->interrupt_request &= ~CPU_INTERRUPT_EXITTB;

                        /* ensure that no TB jump will be modified as

                           the program flow was changed */

                        next_tb = 0;

                    }

                }

                if (unlikely(env->exit_request)) {

                    env->exit_request = 0;

                    env->exception_index = EXCP_INTERRUPT;

                    cpu_loop_exit();

                }

#ifdef CONFIG_DEBUG_EXEC

                if (qemu_loglevel_mask(CPU_LOG_TB_CPU)) {

                    /* restore flags in standard format */

#if defined(TARGET_I386)

                    env->eflags = env->eflags | helper_cc_compute_all(CC_OP) | (DF & DF_MASK);

                    log_cpu_state(env, X86_DUMP_CCOP);

                    env->eflags &= ~(DF_MASK | CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C);

#elif defined(TARGET_ARM)

                    log_cpu_state(env, 0);

#elif defined(TARGET_SPARC)

                    log_cpu_state(env, 0);

#elif defined(TARGET_PPC)

                    log_cpu_state(env, 0);

#elif defined(TARGET_M68K)

                    cpu_m68k_flush_flags(env, env->cc_op);

                    env->cc_op = CC_OP_FLAGS;

                    env->sr = (env->sr & 0xffe0)

                              | env->cc_dest | (env->cc_x << 4);

                    log_cpu_state(env, 0);

#elif defined(TARGET_MICROBLAZE)

                    log_cpu_state(env, 0);

#elif defined(TARGET_MIPS)

                    log_cpu_state(env, 0);

#elif defined(TARGET_SH4)

		    log_cpu_state(env, 0);

#elif defined(TARGET_ALPHA)

                    log_cpu_state(env, 0);

#elif defined(TARGET_CRIS)

                    log_cpu_state(env, 0);

#else

#error unsupported target CPU

#endif

                }

#endif

                spin_lock(&tb_lock);

                tb = tb_find_fast();

                /* Note: we do it here to avoid a gcc bug on Mac OS X when

                   doing it in tb_find_slow */

                if (tb_invalidated_flag) {

                    /* as some TB could have been invalidated because

                       of memory exceptions while generating the code, we

                       must recompute the hash index here */

                    next_tb = 0;

                    tb_invalidated_flag = 0;

                }

#ifdef CONFIG_DEBUG_EXEC

                qemu_log_mask(CPU_LOG_EXEC, "Trace 0x%08lx [" TARGET_FMT_lx "] %s\n",

                             (long)tb->tc_ptr, tb->pc,

                             lookup_symbol(tb->pc));

#endif

                /* see if we can patch the calling TB. When the TB

                   spans two pages, we cannot safely do a direct

                   jump. */

                if (next_tb != 0 && tb->page_addr[1] == -1) {

                    tb_add_jump((TranslationBlock *)(next_tb & ~3), next_tb & 3, tb);

                }

                spin_unlock(&tb_lock);

                /* cpu_interrupt might be called while translating the

                   TB, but before it is linked into a potentially

                   infinite loop and becomes env->current_tb. Avoid

                   starting execution if there is a pending interrupt. */

                if (!unlikely (env->exit_request)) {

                    env->current_tb = tb;

                    tc_ptr = tb->tc_ptr;

                /* execute the generated code */

#if defined(__sparc__) && !defined(CONFIG_SOLARIS)

#undef env

                    env = cpu_single_env;

#define env cpu_single_env

#endif

                    next_tb = tcg_qemu_tb_exec(tc_ptr);

                    env->current_tb = NULL;

                    if ((next_tb & 3) == 2) {

                        /* Instruction counter expired.  */

                        int insns_left;

                        tb = (TranslationBlock *)(long)(next_tb & ~3);

                        /* Restore PC.  */

                        cpu_pc_from_tb(env, tb);

                        insns_left = env->icount_decr.u32;

                        if (env->icount_extra && insns_left >= 0) {

                            /* Refill decrementer and continue execution.  */

                            env->icount_extra += insns_left;

                            if (env->icount_extra > 0xffff) {

                                insns_left = 0xffff;

                            } else {

                                insns_left = env->icount_extra;

                            }

                            env->icount_extra -= insns_left;

                            env->icount_decr.u16.low = insns_left;

                        } else {

                            if (insns_left > 0) {

                                /* Execute remaining instructions.  */

                                cpu_exec_nocache(insns_left, tb);

                            }

                            env->exception_index = EXCP_INTERRUPT;

                            next_tb = 0;

                            cpu_loop_exit();

                        }

                    }

                }

                /* reset soft MMU for next block (it can currently

                   only be set by a memory fault) */

            } /* for(;;) */

        }

    } /* for(;;) */

#if defined(TARGET_I386)

    /* restore flags in standard format */

    env->eflags = env->eflags | helper_cc_compute_all(CC_OP) | (DF & DF_MASK);

#elif defined(TARGET_ARM)

    /* XXX: Save/restore host fpu exception state?.  */

#elif defined(TARGET_SPARC)

#elif defined(TARGET_PPC)

#elif defined(TARGET_M68K)

    cpu_m68k_flush_flags(env, env->cc_op);

    env->cc_op = CC_OP_FLAGS;

    env->sr = (env->sr & 0xffe0)

              | env->cc_dest | (env->cc_x << 4);

#elif defined(TARGET_MICROBLAZE)

#elif defined(TARGET_MIPS)

#elif defined(TARGET_SH4)

#elif defined(TARGET_ALPHA)

#elif defined(TARGET_CRIS)

#elif defined(TARGET_S390X)

    /* XXXXX */

#else

#error unsupported target CPU

#endif

    /* restore global registers */

#include "hostregs_helper.h"

    /* fail safe : never use cpu_single_env outside cpu_exec() */

    cpu_single_env = NULL;

    return ret;

}


void HELPER(v7m_msr)(CPUARMState *env, uint32_t maskreg, uint32_t val)

{

    /* We're passed bits [11..0] of the instruction; extract

     * SYSm and the mask bits.

     * Invalid combinations of SYSm and mask are UNPREDICTABLE;

     * we choose to treat them as if the mask bits were valid.

     * NB that the pseudocode 'mask' variable is bits [11..10],

     * whereas ours is [11..8].

     */

    uint32_t mask = extract32(maskreg, 8, 4);

    uint32_t reg = extract32(maskreg, 0, 8);

    if (arm_current_el(env) == 0 && reg > 7) {

        /* only xPSR sub-fields may be written by unprivileged */

        return;

    }

    switch (reg) {

    case 0 ... 7: /* xPSR sub-fields */

        /* only APSR is actually writable */

        if (!(reg & 4)) {

            uint32_t apsrmask = 0;

            if (mask & 8) {

                apsrmask |= XPSR_NZCV | XPSR_Q;

            }

            if ((mask & 4) && arm_feature(env, ARM_FEATURE_THUMB_DSP)) {

                apsrmask |= XPSR_GE;

            }

            xpsr_write(env, val, apsrmask);

        }

        break;

    case 8: /* MSP */

        if (env->v7m.control & R_V7M_CONTROL_SPSEL_MASK) {

            env->v7m.other_sp = val;

        } else {

            env->regs[13] = val;

        }

        break;

    case 9: /* PSP */

        if (env->v7m.control & R_V7M_CONTROL_SPSEL_MASK) {

            env->regs[13] = val;

        } else {

            env->v7m.other_sp = val;

        }

        break;

    case 16: /* PRIMASK */

        env->v7m.primask[env->v7m.secure] = val & 1;

        break;

    case 17: /* BASEPRI */

        env->v7m.basepri[env->v7m.secure] = val & 0xff;

        break;

    case 18: /* BASEPRI_MAX */

        val &= 0xff;

        if (val != 0 && (val < env->v7m.basepri[env->v7m.secure]

                         || env->v7m.basepri[env->v7m.secure] == 0)) {

            env->v7m.basepri[env->v7m.secure] = val;

        }

        break;

    case 19: /* FAULTMASK */

        env->v7m.faultmask = val & 1;

        break;

    case 20: /* CONTROL */

        /* Writing to the SPSEL bit only has an effect if we are in

         * thread mode; other bits can be updated by any privileged code.

         * switch_v7m_sp() deals with updating the SPSEL bit in

         * env->v7m.control, so we only need update the others.

         */

        if (!arm_v7m_is_handler_mode(env)) {

            switch_v7m_sp(env, (val & R_V7M_CONTROL_SPSEL_MASK) != 0);

        }

        env->v7m.control &= ~R_V7M_CONTROL_NPRIV_MASK;

        env->v7m.control |= val & R_V7M_CONTROL_NPRIV_MASK;

        break;

    default:

        qemu_log_mask(LOG_GUEST_ERROR, "Attempt to write unknown special"

                                       " register %d\n", reg);

        return;

    }

}


static bool migrate_caps_check(bool *cap_list,

                               MigrationCapabilityStatusList *params,

                               Error **errp)

{

    MigrationCapabilityStatusList *cap;

    bool old_postcopy_cap;

    old_postcopy_cap = cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM];

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

        cap_list[cap->value->capability] = cap->value->state;

    }

#ifndef CONFIG_LIVE_BLOCK_MIGRATION

    if (cap_list[MIGRATION_CAPABILITY_BLOCK]) {

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

                   "block migration");

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

        return false;

    }

#endif

    if (cap_list[MIGRATION_CAPABILITY_POSTCOPY_RAM]) {

        if (cap_list[MIGRATION_CAPABILITY_COMPRESS]) {

            /* The decompression threads asynchronously write into RAM

             * rather than use the atomic copies needed to avoid

             * userfaulting.  It should be possible to fix the decompression

             * threads for compatibility in future.

             */

            error_setg(errp, "Postcopy is not currently compatible "

                       "with compression");

            return false;

        }

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

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

         * special support.

         */

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

            !postcopy_ram_supported_by_host()) {

            /* postcopy_ram_supported_by_host will have emitted a more

             * detailed message

             */

            error_setg(errp, "Postcopy is not supported");

            return false;

        }

    }

    return true;

}


static int virtio_blk_handle_rw_error(VirtIOBlockReq *req, int error,

    bool is_read)

{

    BlockErrorAction action = bdrv_get_error_action(req->dev->bs, is_read, error);

    VirtIOBlock *s = req->dev;

    if (action == BLOCK_ERROR_ACTION_STOP) {

        req->next = s->rq;

        s->rq = req;

    } else if (action == BLOCK_ERROR_ACTION_REPORT) {

        virtio_blk_req_complete(req, VIRTIO_BLK_S_IOERR);

        block_acct_done(bdrv_get_stats(s->bs), &req->acct);

        virtio_blk_free_request(req);

    }

    bdrv_error_action(s->bs, action, is_read, error);

    return action != BLOCK_ERROR_ACTION_IGNORE;

}


static inline void FUNC(idctRowCondDC_extrashift)(int16_t *row, int extra_shift)

#else

static inline void FUNC(idctRowCondDC)(int16_t *row, int extra_shift)

#endif

{

    int a0, a1, a2, a3, b0, b1, b2, b3;

#if HAVE_FAST_64BIT

#define ROW0_MASK (0xffffLL << 48 * HAVE_BIGENDIAN)

    if (((AV_RN64A(row) & ~ROW0_MASK) | AV_RN64A(row+4)) == 0) {

        uint64_t temp;

        if (DC_SHIFT - extra_shift >= 0) {

            temp = (row[0] * (1 << (DC_SHIFT - extra_shift))) & 0xffff;

        } else {

            temp = ((row[0] + (1<<(extra_shift - DC_SHIFT-1))) >> (extra_shift - DC_SHIFT)) & 0xffff;

        }

        temp += temp * (1 << 16);

        temp += temp * ((uint64_t) 1 << 32);

        AV_WN64A(row, temp);

        AV_WN64A(row + 4, temp);

        return;

    }

#else

    if (!(AV_RN32A(row+2) |

          AV_RN32A(row+4) |

          AV_RN32A(row+6) |

          row[1])) {

        uint32_t temp;

        if (DC_SHIFT - extra_shift >= 0) {

            temp = (row[0] * (1 << (DC_SHIFT - extra_shift))) & 0xffff;

        } else {

            temp = ((row[0] + (1<<(extra_shift - DC_SHIFT-1))) >> (extra_shift - DC_SHIFT)) & 0xffff;

        }

        temp += temp * (1 << 16);

        AV_WN32A(row, temp);

        AV_WN32A(row+2, temp);

        AV_WN32A(row+4, temp);

        AV_WN32A(row+6, temp);

        return;

    }

#endif

    a0 = (W4 * row[0]) + (1 << (ROW_SHIFT + extra_shift - 1));

    a1 = a0;

    a2 = a0;

    a3 = a0;

    a0 += W2 * row[2];

    a1 += W6 * row[2];

    a2 -= W6 * row[2];

    a3 -= W2 * row[2];

    b0 = MUL(W1, row[1]);

    MAC(b0, W3, row[3]);

    b1 = MUL(W3, row[1]);

    MAC(b1, -W7, row[3]);

    b2 = MUL(W5, row[1]);

    MAC(b2, -W1, row[3]);

    b3 = MUL(W7, row[1]);

    MAC(b3, -W5, row[3]);

    if (AV_RN64A(row + 4)) {

        a0 +=   W4*row[4] + W6*row[6];

        a1 += - W4*row[4] - W2*row[6];

        a2 += - W4*row[4] + W2*row[6];

        a3 +=   W4*row[4] - W6*row[6];

        MAC(b0,  W5, row[5]);

        MAC(b0,  W7, row[7]);

        MAC(b1, -W1, row[5]);

        MAC(b1, -W5, row[7]);

        MAC(b2,  W7, row[5]);

        MAC(b2,  W3, row[7]);

        MAC(b3,  W3, row[5]);

        MAC(b3, -W1, row[7]);

    }

    row[0] = (a0 + b0) >> (ROW_SHIFT + extra_shift);

    row[7] = (a0 - b0) >> (ROW_SHIFT + extra_shift);

    row[1] = (a1 + b1) >> (ROW_SHIFT + extra_shift);

    row[6] = (a1 - b1) >> (ROW_SHIFT + extra_shift);

    row[2] = (a2 + b2) >> (ROW_SHIFT + extra_shift);

    row[5] = (a2 - b2) >> (ROW_SHIFT + extra_shift);

    row[3] = (a3 + b3) >> (ROW_SHIFT + extra_shift);

    row[4] = (a3 - b3) >> (ROW_SHIFT + extra_shift);

}


struct omap_mmc_s *omap2_mmc_init(struct omap_target_agent_s *ta,

                BlockDriverState *bd, qemu_irq irq, qemu_irq dma[],

                omap_clk fclk, omap_clk iclk)

{

    struct omap_mmc_s *s = (struct omap_mmc_s *)

            g_malloc0(sizeof(struct omap_mmc_s));

    s->irq = irq;

    s->dma = dma;

    s->clk = fclk;

    s->lines = 4;

    s->rev = 2;

    omap_mmc_reset(s);

    memory_region_init_io(&s->iomem, NULL, &omap_mmc_ops, s, "omap.mmc",

                          omap_l4_region_size(ta, 0));

    omap_l4_attach(ta, 0, &s->iomem);

    /* Instantiate the storage */

    s->card = sd_init(bd, false);

    if (s->card == NULL) {

        exit(1);

    }

    s->cdet = qemu_allocate_irqs(omap_mmc_cover_cb, s, 1)[0];

    sd_set_cb(s->card, NULL, s->cdet);

    return s;

}


static void calxeda_init(MachineState *machine, enum cxmachines machine_id)

{

    ram_addr_t ram_size = machine->ram_size;

    const char *cpu_model = machine->cpu_model;

    const char *kernel_filename = machine->kernel_filename;

    const char *kernel_cmdline = machine->kernel_cmdline;

    const char *initrd_filename = machine->initrd_filename;

    DeviceState *dev = NULL;

    SysBusDevice *busdev;

    qemu_irq pic[128];

    int n;

    qemu_irq cpu_irq[4];

    qemu_irq cpu_fiq[4];

    MemoryRegion *sysram;

    MemoryRegion *dram;

    MemoryRegion *sysmem;

    char *sysboot_filename;

    if (!cpu_model) {

        switch (machine_id) {

        case CALXEDA_HIGHBANK:

            cpu_model = "cortex-a9";

            break;

        case CALXEDA_MIDWAY:

            cpu_model = "cortex-a15";

            break;

        }

    }

    for (n = 0; n < smp_cpus; n++) {

        ObjectClass *oc = cpu_class_by_name(TYPE_ARM_CPU, cpu_model);

        Object *cpuobj;

        ARMCPU *cpu;

        Error *err = NULL;

        if (!oc) {

            error_report("Unable to find CPU definition");

            exit(1);

        }

        cpuobj = object_new(object_class_get_name(oc));

        cpu = ARM_CPU(cpuobj);

        /* By default A9 and A15 CPUs have EL3 enabled.  This board does not

         * currently support EL3 so the CPU EL3 property is disabled before

         * realization.

         */

        if (object_property_find(cpuobj, "has_el3", NULL)) {

            object_property_set_bool(cpuobj, false, "has_el3", &err);

            if (err) {

                error_report_err(err);

                exit(1);

            }

        }

        if (object_property_find(cpuobj, "reset-cbar", NULL)) {

            object_property_set_int(cpuobj, MPCORE_PERIPHBASE,

                                    "reset-cbar", &error_abort);

        }

        object_property_set_bool(cpuobj, true, "realized", &err);

        if (err) {

            error_report_err(err);

            exit(1);

        }

        cpu_irq[n] = qdev_get_gpio_in(DEVICE(cpu), ARM_CPU_IRQ);

        cpu_fiq[n] = qdev_get_gpio_in(DEVICE(cpu), ARM_CPU_FIQ);

    }

    sysmem = get_system_memory();

    dram = g_new(MemoryRegion, 1);

    memory_region_allocate_system_memory(dram, NULL, "highbank.dram", ram_size);

    /* SDRAM at address zero.  */

    memory_region_add_subregion(sysmem, 0, dram);

    sysram = g_new(MemoryRegion, 1);

    memory_region_init_ram(sysram, NULL, "highbank.sysram", 0x8000,

                           &error_fatal);

    memory_region_add_subregion(sysmem, 0xfff88000, sysram);

    if (bios_name != NULL) {

        sysboot_filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);

        if (sysboot_filename != NULL) {

            if (load_image_targphys(sysboot_filename, 0xfff88000, 0x8000) < 0) {

                hw_error("Unable to load %s\n", bios_name);

            }

            g_free(sysboot_filename);

        } else {

           hw_error("Unable to find %s\n", bios_name);

        }

    }

    switch (machine_id) {

    case CALXEDA_HIGHBANK:

        dev = qdev_create(NULL, "l2x0");

        qdev_init_nofail(dev);

        busdev = SYS_BUS_DEVICE(dev);

        sysbus_mmio_map(busdev, 0, 0xfff12000);

        dev = qdev_create(NULL, "a9mpcore_priv");

        break;

    case CALXEDA_MIDWAY:

        dev = qdev_create(NULL, "a15mpcore_priv");

        break;

    }

    qdev_prop_set_uint32(dev, "num-cpu", smp_cpus);

    qdev_prop_set_uint32(dev, "num-irq", NIRQ_GIC);

    qdev_init_nofail(dev);

    busdev = SYS_BUS_DEVICE(dev);

    sysbus_mmio_map(busdev, 0, MPCORE_PERIPHBASE);

    for (n = 0; n < smp_cpus; n++) {

        sysbus_connect_irq(busdev, n, cpu_irq[n]);

        sysbus_connect_irq(busdev, n + smp_cpus, cpu_fiq[n]);

    }

    for (n = 0; n < 128; n++) {

        pic[n] = qdev_get_gpio_in(dev, n);

    }

    dev = qdev_create(NULL, "sp804");

    qdev_prop_set_uint32(dev, "freq0", 150000000);

    qdev_prop_set_uint32(dev, "freq1", 150000000);

    qdev_init_nofail(dev);

    busdev = SYS_BUS_DEVICE(dev);

    sysbus_mmio_map(busdev, 0, 0xfff34000);

    sysbus_connect_irq(busdev, 0, pic[18]);

    sysbus_create_simple("pl011", 0xfff36000, pic[20]);

    dev = qdev_create(NULL, "highbank-regs");

    qdev_init_nofail(dev);

    busdev = SYS_BUS_DEVICE(dev);

    sysbus_mmio_map(busdev, 0, 0xfff3c000);

    sysbus_create_simple("pl061", 0xfff30000, pic[14]);

    sysbus_create_simple("pl061", 0xfff31000, pic[15]);

    sysbus_create_simple("pl061", 0xfff32000, pic[16]);

    sysbus_create_simple("pl061", 0xfff33000, pic[17]);

    sysbus_create_simple("pl031", 0xfff35000, pic[19]);

    sysbus_create_simple("pl022", 0xfff39000, pic[23]);

    sysbus_create_simple("sysbus-ahci", 0xffe08000, pic[83]);

    if (nd_table[0].used) {

        qemu_check_nic_model(&nd_table[0], "xgmac");

        dev = qdev_create(NULL, "xgmac");

        qdev_set_nic_properties(dev, &nd_table[0]);

        qdev_init_nofail(dev);

        sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, 0xfff50000);

        sysbus_connect_irq(SYS_BUS_DEVICE(dev), 0, pic[77]);

        sysbus_connect_irq(SYS_BUS_DEVICE(dev), 1, pic[78]);

        sysbus_connect_irq(SYS_BUS_DEVICE(dev), 2, pic[79]);

        qemu_check_nic_model(&nd_table[1], "xgmac");

        dev = qdev_create(NULL, "xgmac");

        qdev_set_nic_properties(dev, &nd_table[1]);

        qdev_init_nofail(dev);

        sysbus_mmio_map(SYS_BUS_DEVICE(dev), 0, 0xfff51000);

        sysbus_connect_irq(SYS_BUS_DEVICE(dev), 0, pic[80]);

        sysbus_connect_irq(SYS_BUS_DEVICE(dev), 1, pic[81]);

        sysbus_connect_irq(SYS_BUS_DEVICE(dev), 2, pic[82]);

    }

    highbank_binfo.ram_size = ram_size;

    highbank_binfo.kernel_filename = kernel_filename;

    highbank_binfo.kernel_cmdline = kernel_cmdline;

    highbank_binfo.initrd_filename = initrd_filename;

    /* highbank requires a dtb in order to boot, and the dtb will override

     * the board ID. The following value is ignored, so set it to -1 to be

     * clear that the value is meaningless.

     */

    highbank_binfo.board_id = -1;

    highbank_binfo.nb_cpus = smp_cpus;

    highbank_binfo.loader_start = 0;

    highbank_binfo.write_secondary_boot = hb_write_secondary;

    highbank_binfo.secondary_cpu_reset_hook = hb_reset_secondary;

    arm_load_kernel(ARM_CPU(first_cpu), &highbank_binfo);

}


static int get_phys_addr_v5(CPUState *env, uint32_t address, int access_type,

			    int is_user, uint32_t *phys_ptr, int *prot)

{

    int code;

    uint32_t table;

    uint32_t desc;

    int type;

    int ap;

    int domain;

    uint32_t phys_addr;

    /* Pagetable walk.  */

    /* Lookup l1 descriptor.  */

    table = get_level1_table_address(env, address);

    desc = ldl_phys(table);

    type = (desc & 3);

    domain = (env->cp15.c3 >> ((desc >> 4) & 0x1e)) & 3;

    if (type == 0) {

        /* Section translation fault.  */

        code = 5;

        goto do_fault;

    }

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

        if (type == 2)

            code = 9; /* Section domain fault.  */

        else

            code = 11; /* Page domain fault.  */

        goto do_fault;

    }

    if (type == 2) {

        /* 1Mb section.  */

        phys_addr = (desc & 0xfff00000) | (address & 0x000fffff);

        ap = (desc >> 10) & 3;

        code = 13;

    } else {

        /* Lookup l2 entry.  */

	if (type == 1) {

	    /* Coarse pagetable.  */

	    table = (desc & 0xfffffc00) | ((address >> 10) & 0x3fc);

	} else {

	    /* Fine pagetable.  */

	    table = (desc & 0xfffff000) | ((address >> 8) & 0xffc);

	}

        desc = ldl_phys(table);

        switch (desc & 3) {

        case 0: /* Page translation fault.  */

            code = 7;

            goto do_fault;

        case 1: /* 64k page.  */

            phys_addr = (desc & 0xffff0000) | (address & 0xffff);

            ap = (desc >> (4 + ((address >> 13) & 6))) & 3;

            break;

        case 2: /* 4k page.  */

            phys_addr = (desc & 0xfffff000) | (address & 0xfff);

            ap = (desc >> (4 + ((address >> 13) & 6))) & 3;

            break;

        case 3: /* 1k page.  */

	    if (type == 1) {

		if (arm_feature(env, ARM_FEATURE_XSCALE)) {

		    phys_addr = (desc & 0xfffff000) | (address & 0xfff);

		} else {

		    /* Page translation fault.  */

		    code = 7;

		    goto do_fault;

		}

	    } else {

		phys_addr = (desc & 0xfffffc00) | (address & 0x3ff);

	    }

            ap = (desc >> 4) & 3;

            break;

        default:

            /* Never happens, but compiler isn't smart enough to tell.  */

            abort();

        }

        code = 15;

    }

    *prot = check_ap(env, ap, domain, access_type, is_user);

    if (!*prot) {

        /* Access permission fault.  */

        goto do_fault;

    }

    *phys_ptr = phys_addr;

    return 0;

do_fault:

    return code | (domain << 4);

}


static void vmxnet3_update_mcast_filters(VMXNET3State *s)

{

    uint16_t list_bytes =

        VMXNET3_READ_DRV_SHARED16(s->drv_shmem,

                                  devRead.rxFilterConf.mfTableLen);

    s->mcast_list_len = list_bytes / sizeof(s->mcast_list[0]);

    s->mcast_list = g_realloc(s->mcast_list, list_bytes);

    if (!s->mcast_list) {

        if (s->mcast_list_len == 0) {

            VMW_CFPRN("Current multicast list is empty");

        } else {

            VMW_ERPRN("Failed to allocate multicast list of %d elements",

                      s->mcast_list_len);

        }

        s->mcast_list_len = 0;

    } else {

        int i;

        hwaddr mcast_list_pa =

            VMXNET3_READ_DRV_SHARED64(s->drv_shmem,

                                      devRead.rxFilterConf.mfTablePA);

        pci_dma_read(PCI_DEVICE(s), mcast_list_pa, s->mcast_list, list_bytes);

        VMW_CFPRN("Current multicast list len is %d:", s->mcast_list_len);

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

            VMW_CFPRN("\t" MAC_FMT, MAC_ARG(s->mcast_list[i].a));

        }

    }

}


int ff_nvdec_decode_init(AVCodecContext *avctx, unsigned int dpb_size)

{

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

    NVDECFramePool      *pool;

    AVHWFramesContext   *frames_ctx;

    const AVPixFmtDescriptor *sw_desc;

    CUVIDDECODECREATEINFO params = { 0 };

    int cuvid_codec_type, cuvid_chroma_format;

    int ret = 0;

    sw_desc = av_pix_fmt_desc_get(avctx->sw_pix_fmt);

    if (!sw_desc)

        return AVERROR_BUG;

    cuvid_codec_type = map_avcodec_id(avctx->codec_id);

    if (cuvid_codec_type < 0) {

        av_log(avctx, AV_LOG_ERROR, "Unsupported codec ID\n");

        return AVERROR_BUG;

    }

    cuvid_chroma_format = map_chroma_format(avctx->sw_pix_fmt);

    if (cuvid_chroma_format < 0) {

        av_log(avctx, AV_LOG_ERROR, "Unsupported chroma format\n");

        return AVERROR(ENOSYS);

    }

    if (avctx->thread_type & FF_THREAD_FRAME)

        dpb_size += avctx->thread_count;

    if (!avctx->hw_frames_ctx) {

        AVHWFramesContext *frames_ctx;

        if (!avctx->hw_device_ctx) {

            av_log(avctx, AV_LOG_ERROR, "A hardware device or frames context "

                   "is required for CUVID decoding.\n");

            return AVERROR(EINVAL);

        }

        avctx->hw_frames_ctx = av_hwframe_ctx_alloc(avctx->hw_device_ctx);

        if (!avctx->hw_frames_ctx)

            return AVERROR(ENOMEM);

        frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;

        frames_ctx->format            = AV_PIX_FMT_CUDA;

        frames_ctx->width             = avctx->coded_width;

        frames_ctx->height            = avctx->coded_height;

        frames_ctx->sw_format         = AV_PIX_FMT_NV12;

        frames_ctx->sw_format         = sw_desc->comp[0].depth > 8 ?

                                        AV_PIX_FMT_P010 : AV_PIX_FMT_NV12;

        frames_ctx->initial_pool_size = dpb_size;

        ret = av_hwframe_ctx_init(avctx->hw_frames_ctx);

        if (ret < 0) {

            av_log(avctx, AV_LOG_ERROR, "Error initializing internal frames context\n");

            return ret;

        }

    }

    frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;

    params.ulWidth             = avctx->coded_width;

    params.ulHeight            = avctx->coded_height;

    params.ulTargetWidth       = avctx->coded_width;

    params.ulTargetHeight      = avctx->coded_height;

    params.bitDepthMinus8      = sw_desc->comp[0].depth - 8;

    params.OutputFormat        = params.bitDepthMinus8 ?

                                 cudaVideoSurfaceFormat_P016 : cudaVideoSurfaceFormat_NV12;

    params.CodecType           = cuvid_codec_type;

    params.ChromaFormat        = cuvid_chroma_format;

    params.ulNumDecodeSurfaces = dpb_size;

    params.ulNumOutputSurfaces = 1;

    ret = nvdec_decoder_create(&ctx->decoder_ref, frames_ctx->device_ref, &params, avctx);

    if (ret < 0)

        return ret;

    pool = av_mallocz(sizeof(*pool));

    if (!pool) {

        ret = AVERROR(ENOMEM);

        goto fail;

    }

    pool->dpb_size = dpb_size;

    ctx->decoder_pool = av_buffer_pool_init2(sizeof(int), pool,

                                             nvdec_decoder_frame_alloc, av_free);

    if (!ctx->decoder_pool) {

        ret = AVERROR(ENOMEM);

        goto fail;

    }

    return 0;

fail:

    ff_nvdec_decode_uninit(avctx);

    return ret;

}


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

{

    BlockDriverState *bs, *bs1;

    QEMUSnapshotInfo *sn_tab, *sn, s, *sn_info = &s;

    int nb_sns, i, ret, available;

    int total;

    int *available_snapshots;

    bs = find_vmstate_bs();

    if (!bs) {

        monitor_printf(mon, "No available block device supports snapshots\n");

        return;

    }

    nb_sns = bdrv_snapshot_list(bs, &sn_tab);

    if (nb_sns < 0) {

        monitor_printf(mon, "bdrv_snapshot_list: error %d\n", nb_sns);

        return;

    }

    if (nb_sns == 0) {

        monitor_printf(mon, "There is no snapshot available.\n");

        return;

    }

    available_snapshots = g_malloc0(sizeof(int) * nb_sns);

    total = 0;

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

        sn = &sn_tab[i];

        available = 1;

        bs1 = NULL;

        while ((bs1 = bdrv_next(bs1))) {

            if (bdrv_can_snapshot(bs1) && bs1 != bs) {

                ret = bdrv_snapshot_find(bs1, sn_info, sn->id_str);

                if (ret < 0) {

                    available = 0;

                    break;

                }

            }

        }

        if (available) {

            available_snapshots[total] = i;

            total++;

        }

    }

    if (total > 0) {

        bdrv_snapshot_dump((fprintf_function)monitor_printf, mon, NULL);

        monitor_printf(mon, "\n");

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

            sn = &sn_tab[available_snapshots[i]];

            bdrv_snapshot_dump((fprintf_function)monitor_printf, mon, sn);

            monitor_printf(mon, "\n");

        }

    } else {

        monitor_printf(mon, "There is no suitable snapshot available\n");

    }

    g_free(sn_tab);

    g_free(available_snapshots);

}


int decode_block_coeffs(VP56RangeCoder *c, int16_t block[16],

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

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

{

    uint8_t *token_prob = probs[i][zero_nhood];

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

        return 0;

    return decode_block_coeffs_internal(c, block, probs, i, token_prob, qmul);

}


static int cirrus_bitblt_solidfill(CirrusVGAState *s, int blt_rop)

{

    cirrus_fill_t rop_func;

    if (blit_is_unsafe(s)) {

        return 0;

    }

    rop_func = cirrus_fill[rop_to_index[blt_rop]][s->cirrus_blt_pixelwidth - 1];

    rop_func(s, s->vga.vram_ptr + (s->cirrus_blt_dstaddr & s->cirrus_addr_mask),

             s->cirrus_blt_dstpitch,

             s->cirrus_blt_width, s->cirrus_blt_height);

    cirrus_invalidate_region(s, s->cirrus_blt_dstaddr,

			     s->cirrus_blt_dstpitch, s->cirrus_blt_width,

			     s->cirrus_blt_height);

    cirrus_bitblt_reset(s);

    return 1;

}


static int load_ipmovie_packet(IPMVEContext *s, AVIOContext *pb,

    AVPacket *pkt) {

    int chunk_type;

    if (s->audio_chunk_offset) {

        /* adjust for PCM audio by skipping chunk header */

        if (s->audio_type != CODEC_ID_INTERPLAY_DPCM) {

            s->audio_chunk_offset += 6;

            s->audio_chunk_size -= 6;

        avio_seek(pb, s->audio_chunk_offset, SEEK_SET);

        s->audio_chunk_offset = 0;

        if (s->audio_chunk_size != av_get_packet(pb, pkt, s->audio_chunk_size))

            return CHUNK_EOF;

        pkt->stream_index = s->audio_stream_index;

        pkt->pts = s->audio_frame_count;

        /* audio frame maintenance */

        if (s->audio_type != CODEC_ID_INTERPLAY_DPCM)

            s->audio_frame_count +=

            (s->audio_chunk_size / s->audio_channels / (s->audio_bits / 8));

        else

            s->audio_frame_count +=

                (s->audio_chunk_size - 6) / s->audio_channels;

        av_dlog(NULL, "sending audio frame with pts %"PRId64" (%d audio frames)\n",

                pkt->pts, s->audio_frame_count);

        chunk_type = CHUNK_VIDEO;

    } else if (s->decode_map_chunk_offset) {

        /* send both the decode map and the video data together */

        if (av_new_packet(pkt, s->decode_map_chunk_size + s->video_chunk_size))

            return CHUNK_NOMEM;

        if (s->has_palette) {

            uint8_t *pal;

            pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE,

                                          AVPALETTE_SIZE);

            if (pal) {

                memcpy(pal, s->palette, AVPALETTE_SIZE);

                s->has_palette = 0;

        pkt->pos= s->decode_map_chunk_offset;

        avio_seek(pb, s->decode_map_chunk_offset, SEEK_SET);

        s->decode_map_chunk_offset = 0;

        if (avio_read(pb, pkt->data, s->decode_map_chunk_size) !=

            s->decode_map_chunk_size) {

            av_free_packet(pkt);

            return CHUNK_EOF;

        avio_seek(pb, s->video_chunk_offset, SEEK_SET);

        s->video_chunk_offset = 0;

        if (avio_read(pb, pkt->data + s->decode_map_chunk_size,

            s->video_chunk_size) != s->video_chunk_size) {

            av_free_packet(pkt);

            return CHUNK_EOF;

        pkt->stream_index = s->video_stream_index;

        pkt->pts = s->video_pts;

        av_dlog(NULL, "sending video frame with pts %"PRId64"\n", pkt->pts);

        s->video_pts += s->frame_pts_inc;

        chunk_type = CHUNK_VIDEO;

    } else {

        avio_seek(pb, s->next_chunk_offset, SEEK_SET);

        chunk_type = CHUNK_DONE;

    return chunk_type;