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

{

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

                               .type = RDMA_CONTROL_REGISTER_RESULT,

                               .repeat = 0,

                             };

    RDMAControlHeader unreg_resp = { .len = 0,

                               .type = RDMA_CONTROL_UNREGISTER_FINISHED,

                               .repeat = 0,

                             };

    RDMAControlHeader blocks = { .type = RDMA_CONTROL_RAM_BLOCKS_RESULT,

                                 .repeat = 1 };

    QEMUFileRDMA *rfile = opaque;

    RDMAContext *rdma = rfile->rdma;

    RDMALocalBlocks *local = &rdma->local_ram_blocks;

    RDMAControlHeader head;

    RDMARegister *reg, *registers;

    RDMACompress *comp;

    RDMARegisterResult *reg_result;

    static RDMARegisterResult results[RDMA_CONTROL_MAX_COMMANDS_PER_MESSAGE];

    RDMALocalBlock *block;

    void *host_addr;

    int ret = 0;

    int idx = 0;

    int count = 0;

    int i = 0;

    CHECK_ERROR_STATE();

    do {

        trace_qemu_rdma_registration_handle_wait();

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

        if (ret < 0) {

        if (head.repeat > RDMA_CONTROL_MAX_COMMANDS_PER_MESSAGE) {

            error_report("rdma: Too many requests in this message (%d)."

                            "Bailing.", head.repeat);

            ret = -EIO;

        switch (head.type) {

        case RDMA_CONTROL_COMPRESS:

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

            network_to_compress(comp);

            trace_qemu_rdma_registration_handle_compress(comp->length,

                                                         comp->block_idx,

                                                         comp->offset);

            if (comp->block_idx >= rdma->local_ram_blocks.nb_blocks) {

                error_report("rdma: 'compress' bad block index %u (vs %d)",

                             (unsigned int)comp->block_idx,

                             rdma->local_ram_blocks.nb_blocks);

                ret = -EIO;

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

            host_addr = block->local_host_addr +

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

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

        case RDMA_CONTROL_REGISTER_FINISHED:

            trace_qemu_rdma_registration_handle_finished();

            goto out;

        case RDMA_CONTROL_RAM_BLOCKS_REQUEST:

            trace_qemu_rdma_registration_handle_ram_blocks();

            /* Sort our local RAM Block list so it's the same as the source,

             * we can do this since we've filled in a src_index in the list

             * as we received the RAMBlock list earlier.

             */

            qsort(rdma->local_ram_blocks.block,

                  rdma->local_ram_blocks.nb_blocks,

                  sizeof(RDMALocalBlock), dest_ram_sort_func);

            if (rdma->pin_all) {

                ret = qemu_rdma_reg_whole_ram_blocks(rdma);

                if (ret) {

                    error_report("rdma migration: error dest "

                                    "registering ram blocks");

                    goto out;

            /*

             * Dest uses this to prepare to transmit the RAMBlock descriptions

             * to the source VM after connection setup.

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

             * their "local" descriptions with what was sent.

             */

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

                rdma->dest_blocks[i].remote_host_addr =

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

                if (rdma->pin_all) {

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

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

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

                dest_block_to_network(&rdma->dest_blocks[i]);

                trace_qemu_rdma_registration_handle_ram_blocks_loop(

                    local->block[i].block_name,

                    local->block[i].offset,

                    local->block[i].length,

                    local->block[i].local_host_addr,

                    local->block[i].src_index);

            blocks.len = rdma->local_ram_blocks.nb_blocks

                                                * sizeof(RDMADestBlock);

            ret = qemu_rdma_post_send_control(rdma,

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

            if (ret < 0) {

                error_report("rdma migration: error sending remote info");

                goto out;

        case RDMA_CONTROL_REGISTER_REQUEST:

            trace_qemu_rdma_registration_handle_register(head.repeat);

            reg_resp.repeat = head.repeat;

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

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

                uint64_t chunk;

                uint8_t *chunk_start, *chunk_end;

                reg = &registers[count];

                network_to_register(reg);

                reg_result = &results[count];

                trace_qemu_rdma_registration_handle_register_loop(count,

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

                if (reg->current_index >= rdma->local_ram_blocks.nb_blocks) {

                    error_report("rdma: 'register' bad block index %u (vs %d)",

                                 (unsigned int)reg->current_index,

                                 rdma->local_ram_blocks.nb_blocks);

                    ret = -ENOENT;

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

                if (block->is_ram_block) {

                    if (block->offset > reg->key.current_addr) {

                        error_report("rdma: bad register address for block %s"

                            " offset: %" PRIx64 " current_addr: %" PRIx64,

                            block->block_name, block->offset,

                            reg->key.current_addr);

                    host_addr = (block->local_host_addr +

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

                    chunk = ram_chunk_index(block->local_host_addr,

                                            (uint8_t *) host_addr);

                } else {

                    chunk = reg->key.chunk;

                    host_addr = block->local_host_addr +

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

                chunk_start = ram_chunk_start(block, chunk);

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

                if (qemu_rdma_register_and_get_keys(rdma, block,

                            (uintptr_t)host_addr, NULL, &reg_result->rkey,

                            chunk, chunk_start, chunk_end)) {

                    error_report("cannot get rkey");

                    ret = -EINVAL;

                    goto out;

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

                trace_qemu_rdma_registration_handle_register_rkey(

                                                           reg_result->rkey);

                result_to_network(reg_result);

            ret = qemu_rdma_post_send_control(rdma,

                            (uint8_t *) results, &reg_resp);

            if (ret < 0) {

                error_report("Failed to send control buffer");

                goto out;

        case RDMA_CONTROL_UNREGISTER_REQUEST:

            trace_qemu_rdma_registration_handle_unregister(head.repeat);

            unreg_resp.repeat = head.repeat;

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

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

                reg = &registers[count];

                network_to_register(reg);

                trace_qemu_rdma_registration_handle_unregister_loop(count,

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

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

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

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

                if (ret != 0) {

                    perror("rdma unregistration chunk failed");

                    ret = -ret;

                    goto out;

                rdma->total_registrations--;

                trace_qemu_rdma_registration_handle_unregister_success(

                                                       reg->key.chunk);

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

            if (ret < 0) {

                error_report("Failed to send control buffer");

                goto out;

        case RDMA_CONTROL_REGISTER_RESULT:

            error_report("Invalid RESULT message at dest.");

            ret = -EIO;

            goto out;

        default:

            error_report("Unknown control message %s", control_desc[head.type]);

            ret = -EIO;

            goto out;

    } while (1);

out:

    if (ret < 0) {

        rdma->error_state = ret;

    return ret;


static void set_sigmask(const sigset_t *set)

{

    do_sigprocmask(SIG_SETMASK, set, NULL);

}


int qcow2_grow_l1_table(BlockDriverState *bs, uint64_t min_size,
                        bool exact_size)
{
    BDRVQcowState *s = bs->opaque;
    int new_l1_size2, ret, i;
    uint64_t *new_l1_table;
    int64_t old_l1_table_offset, old_l1_size;
    int64_t new_l1_table_offset, new_l1_size;
    uint8_t data[12];
    if (min_size <= s->l1_size)
        return 0;
    if (exact_size) {
        new_l1_size = min_size;
    } else {
        /* Bump size up to reduce the number of times we have to grow */
        new_l1_size = s->l1_size;
        if (new_l1_size == 0) {
            new_l1_size = 1;
        while (min_size > new_l1_size) {
            new_l1_size = (new_l1_size * 3 + 1) / 2;
    if (new_l1_size > INT_MAX / sizeof(uint64_t)) {
#ifdef DEBUG_ALLOC2
    fprintf(stderr, "grow l1_table from %d to %" PRId64 "\n",
            s->l1_size, new_l1_size);
#endif
    new_l1_size2 = sizeof(uint64_t) * new_l1_size;
    new_l1_table = g_malloc0(align_offset(new_l1_size2, 512));
    memcpy(new_l1_table, s->l1_table, s->l1_size * sizeof(uint64_t));
    /* write new table (align to cluster) */
    BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_ALLOC_TABLE);
    new_l1_table_offset = qcow2_alloc_clusters(bs, new_l1_size2);
    if (new_l1_table_offset < 0) {
        g_free(new_l1_table);
        return new_l1_table_offset;
    ret = qcow2_cache_flush(bs, s->refcount_block_cache);
    if (ret < 0) {
        goto fail;
    /* the L1 position has not yet been updated, so these clusters must
     * indeed be completely free */
    ret = qcow2_pre_write_overlap_check(bs, 0, new_l1_table_offset,
                                        new_l1_size2);
    if (ret < 0) {
        goto fail;
    BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_WRITE_TABLE);
    for(i = 0; i < s->l1_size; i++)
        new_l1_table[i] = cpu_to_be64(new_l1_table[i]);
    ret = bdrv_pwrite_sync(bs->file, new_l1_table_offset, new_l1_table, new_l1_size2);
    if (ret < 0)
        goto fail;
    for(i = 0; i < s->l1_size; i++)
        new_l1_table[i] = be64_to_cpu(new_l1_table[i]);
    /* set new table */
    BLKDBG_EVENT(bs->file, BLKDBG_L1_GROW_ACTIVATE_TABLE);
    cpu_to_be32w((uint32_t*)data, new_l1_size);
    stq_be_p(data + 4, new_l1_table_offset);
    ret = bdrv_pwrite_sync(bs->file, offsetof(QCowHeader, l1_size), data,sizeof(data));
    if (ret < 0) {
        goto fail;
    g_free(s->l1_table);
    old_l1_table_offset = s->l1_table_offset;
    s->l1_table_offset = new_l1_table_offset;
    s->l1_table = new_l1_table;
    old_l1_size = s->l1_size;
    s->l1_size = new_l1_size;
    qcow2_free_clusters(bs, old_l1_table_offset, old_l1_size * sizeof(uint64_t),
                        QCOW2_DISCARD_OTHER);
    return 0;
 fail:
    g_free(new_l1_table);
    qcow2_free_clusters(bs, new_l1_table_offset, new_l1_size2,
                        QCOW2_DISCARD_OTHER);
    return ret;


static void test_submit_aio(void)

{

    WorkerTestData data = { .n = 0, .ret = -EINPROGRESS };

    data.aiocb = thread_pool_submit_aio(pool, worker_cb, &data,

                                        done_cb, &data);

    /* The callbacks are not called until after the first wait.  */

    active = 1;

    g_assert_cmpint(data.ret, ==, -EINPROGRESS);

    qemu_aio_wait_all();

    g_assert_cmpint(active, ==, 0);

    g_assert_cmpint(data.n, ==, 1);

    g_assert_cmpint(data.ret, ==, 0);

}


static inline void silk_stabilize_lsf(int16_t nlsf[16], int order, const uint16_t min_delta[17])

{

    int pass, i;

    for (pass = 0; pass < 20; pass++) {

        int k, min_diff = 0;

        for (i = 0; i < order+1; i++) {

            int low  = i != 0     ? nlsf[i-1] : 0;

            int high = i != order ? nlsf[i]   : 32768;

            int diff = (high - low) - (min_delta[i]);

            if (diff < min_diff) {

                min_diff = diff;

                k = i;

                if (pass == 20)

                    break;

            }

        }

        if (min_diff == 0) /* no issues; stabilized */

            return;

        /* wiggle one or two LSFs */

        if (k == 0) {

            /* repel away from lower bound */

            nlsf[0] = min_delta[0];

        } else if (k == order) {

            /* repel away from higher bound */

            nlsf[order-1] = 32768 - min_delta[order];

        } else {

            /* repel away from current position */

            int min_center = 0, max_center = 32768, center_val;

            /* lower extent */

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

                min_center += min_delta[i];

            min_center += min_delta[k] >> 1;

            /* upper extent */

            for (i = order; i > k; i--)

                max_center -= min_delta[i];

            max_center -= min_delta[k] >> 1;

            /* move apart */

            center_val = nlsf[k - 1] + nlsf[k];

            center_val = (center_val >> 1) + (center_val & 1); // rounded divide by 2

            center_val = FFMIN(max_center, FFMAX(min_center, center_val));

            nlsf[k - 1] = center_val - (min_delta[k] >> 1);

            nlsf[k]     = nlsf[k - 1] + min_delta[k];

        }

    }

    /* resort to the fall-back method, the standard method for LSF stabilization */

    /* sort; as the LSFs should be nearly sorted, use insertion sort */

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

        int j, value = nlsf[i];

        for (j = i - 1; j >= 0 && nlsf[j] > value; j--)

            nlsf[j + 1] = nlsf[j];

        nlsf[j + 1] = value;

    }

    /* push forwards to increase distance */

    if (nlsf[0] < min_delta[0])

        nlsf[0] = min_delta[0];

    for (i = 1; i < order; i++)

        if (nlsf[i] < nlsf[i - 1] + min_delta[i])

            nlsf[i] = nlsf[i - 1] + min_delta[i];

    /* push backwards to increase distance */

    if (nlsf[order-1] > 32768 - min_delta[order])

        nlsf[order-1] = 32768 - min_delta[order];

    for (i = order-2; i >= 0; i--)

        if (nlsf[i] > nlsf[i + 1] - min_delta[i+1])

            nlsf[i] = nlsf[i + 1] - min_delta[i+1];

    return;

}


static void virtio_scsi_handle_ctrl(VirtIODevice *vdev, VirtQueue *vq)

{

    VirtIOSCSI *s = (VirtIOSCSI *)vdev;

    VirtIOSCSIReq *req;

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

        virtio_scsi_dataplane_start(s);

        return;

    }

    while ((req = virtio_scsi_pop_req(s, vq))) {

        virtio_scsi_handle_ctrl_req(s, req);

    }

}


static int decode_channel_sound_unit(ATRAC3Context *q, GetBitContext *gb,

                                     ChannelUnit *snd, float *output,

                                     int channel_num, int coding_mode)

{

    int band, ret, num_subbands, last_tonal, num_bands;

    GainBlock *gain1 = &snd->gain_block[    snd->gc_blk_switch];

    GainBlock *gain2 = &snd->gain_block[1 - snd->gc_blk_switch];

    if (coding_mode == JOINT_STEREO && channel_num == 1) {

        if (get_bits(gb, 2) != 3) {

            av_log(NULL,AV_LOG_ERROR,"JS mono Sound Unit id != 3.\n");

            return AVERROR_INVALIDDATA;

        }

    } else {

        if (get_bits(gb, 6) != 0x28) {

            av_log(NULL,AV_LOG_ERROR,"Sound Unit id != 0x28.\n");

            return AVERROR_INVALIDDATA;

        }

    }

    /* number of coded QMF bands */

    snd->bands_coded = get_bits(gb, 2);

    ret = decode_gain_control(gb, gain2, snd->bands_coded);

    if (ret)

        return ret;

    snd->num_components = decode_tonal_components(gb, snd->components,

                                                  snd->bands_coded);

    if (snd->num_components < 0)

        return snd->num_components;

    num_subbands = decode_spectrum(gb, snd->spectrum);

    /* Merge the decoded spectrum and tonal components. */

    last_tonal = add_tonal_components(snd->spectrum, snd->num_components,

                                      snd->components);

    /* calculate number of used MLT/QMF bands according to the amount of coded

       spectral lines */

    num_bands = (subband_tab[num_subbands] - 1) >> 8;

    if (last_tonal >= 0)

        num_bands = FFMAX((last_tonal + 256) >> 8, num_bands);

    /* Reconstruct time domain samples. */

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

        /* Perform the IMDCT step without overlapping. */

        if (band <= num_bands)

            imlt(q, &snd->spectrum[band * 256], snd->imdct_buf, band & 1);

        else

            memset(snd->imdct_buf, 0, 512 * sizeof(*snd->imdct_buf));

        /* gain compensation and overlapping */

        ff_atrac_gain_compensation(&q->gainc_ctx, snd->imdct_buf,

                                   &snd->prev_frame[band * 256],

                                   &gain1->g_block[band], &gain2->g_block[band],

                                   256, &output[band * 256]);

    }

    /* Swap the gain control buffers for the next frame. */

    snd->gc_blk_switch ^= 1;

    return 0;

}


static void RENAME(extract_odd2)(const uint8_t *src, uint8_t *dst0, uint8_t *dst1, x86_reg count)

{

    dst0+=   count;

    dst1+=   count;

    src += 4*count;

    count= - count;

#if COMPILE_TEMPLATE_MMX

    if(count <= -8) {

        count += 7;

        __asm__ volatile(

            "pcmpeqw       %%mm7, %%mm7        \n\t"

            "psrlw            $8, %%mm7        \n\t"

            "1:                                \n\t"

            "movq -28(%1, %0, 4), %%mm0        \n\t"

            "movq -20(%1, %0, 4), %%mm1        \n\t"

            "movq -12(%1, %0, 4), %%mm2        \n\t"

            "movq  -4(%1, %0, 4), %%mm3        \n\t"

            "psrlw            $8, %%mm0        \n\t"

            "psrlw            $8, %%mm1        \n\t"

            "psrlw            $8, %%mm2        \n\t"

            "psrlw            $8, %%mm3        \n\t"

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

            "packuswb      %%mm3, %%mm2        \n\t"

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

            "movq          %%mm2, %%mm3        \n\t"

            "psrlw            $8, %%mm0        \n\t"

            "psrlw            $8, %%mm2        \n\t"

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

            "pand          %%mm7, %%mm3        \n\t"

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

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

            MOVNTQ"        %%mm0,- 7(%3, %0)   \n\t"

            MOVNTQ"        %%mm1,- 7(%2, %0)   \n\t"

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

            " js 1b                            \n\t"

            : "+r"(count)

            : "r"(src), "r"(dst0), "r"(dst1)

        );

        count -= 7;

    }

#endif

    src++;

    while(count<0) {

        dst0[count]= src[4*count+0];

        dst1[count]= src[4*count+2];

        count++;

    }

}


static int decode_frame(AVCodecContext *avctx,

                             void *data, int *data_size,

                             AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    H264Context *h = avctx->priv_data;

    MpegEncContext *s = &h->s;

    AVFrame *pict = data;

    int buf_index;

    s->flags= avctx->flags;

    s->flags2= avctx->flags2;

   /* end of stream, output what is still in the buffers */

    if (buf_size == 0) {

        Picture *out;

        int i, out_idx;

//FIXME factorize this with the output code below

        out = h->delayed_pic[0];

        out_idx = 0;

        for(i=1; h->delayed_pic[i] && (h->delayed_pic[i]->poc && !h->delayed_pic[i]->key_frame); i++)

            if(h->delayed_pic[i]->poc < out->poc){

                out = h->delayed_pic[i];

                out_idx = i;

            }

        for(i=out_idx; h->delayed_pic[i]; i++)

            h->delayed_pic[i] = h->delayed_pic[i+1];

        if(out){

            *data_size = sizeof(AVFrame);

            *pict= *(AVFrame*)out;

        }

        return 0;

    }

    if(h->is_avc && !h->got_avcC) {

        int i, cnt, nalsize;

        unsigned char *p = avctx->extradata;

        if(avctx->extradata_size < 7) {

            av_log(avctx, AV_LOG_ERROR, "avcC too short\n");

            return -1;

        }

        if(*p != 1) {

            av_log(avctx, AV_LOG_ERROR, "Unknown avcC version %d\n", *p);

            return -1;

        }

        /* sps and pps in the avcC always have length coded with 2 bytes,

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

        h->nal_length_size = 2;

        // Decode sps from avcC

        cnt = *(p+5) & 0x1f; // Number of sps

        p += 6;

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

            nalsize = AV_RB16(p) + 2;

            if(decode_nal_units(h, p, nalsize) < 0) {

                av_log(avctx, AV_LOG_ERROR, "Decoding sps %d from avcC failed\n", i);

                return -1;

            }

            p += nalsize;

        }

        // Decode pps from avcC

        cnt = *(p++); // Number of pps

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

            nalsize = AV_RB16(p) + 2;

            if(decode_nal_units(h, p, nalsize)  != nalsize) {

                av_log(avctx, AV_LOG_ERROR, "Decoding pps %d from avcC failed\n", i);

                return -1;

            }

            p += nalsize;

        }

        // Now store right nal length size, that will be use to parse all other nals

        h->nal_length_size = ((*(((char*)(avctx->extradata))+4))&0x03)+1;

        // Do not reparse avcC

        h->got_avcC = 1;

    }

    if(!h->got_avcC && !h->is_avc && s->avctx->extradata_size){

        if(decode_nal_units(h, s->avctx->extradata, s->avctx->extradata_size) < 0)

            return -1;

        h->got_avcC = 1;

    }

    buf_index=decode_nal_units(h, buf, buf_size);

    if(buf_index < 0)

        return -1;

    if(!(s->flags2 & CODEC_FLAG2_CHUNKS) && !s->current_picture_ptr){

        if (avctx->skip_frame >= AVDISCARD_NONREF || s->hurry_up) return 0;

        av_log(avctx, AV_LOG_ERROR, "no frame!\n");

        return -1;

    }

    if(!(s->flags2 & CODEC_FLAG2_CHUNKS) || (s->mb_y >= s->mb_height && s->mb_height)){

        Picture *out = s->current_picture_ptr;

        Picture *cur = s->current_picture_ptr;

        int i, pics, cross_idr, out_of_order, out_idx;

        field_end(h);

        if (cur->field_poc[0]==INT_MAX || cur->field_poc[1]==INT_MAX) {

            /* Wait for second field. */

            *data_size = 0;

        } else {

            cur->repeat_pict = 0;

            /* Signal interlacing information externally. */

            /* Prioritize picture timing SEI information over used decoding process if it exists. */

            if (h->sei_ct_type)

                cur->interlaced_frame = (h->sei_ct_type & (1<<1)) != 0;

            else

                cur->interlaced_frame = FIELD_OR_MBAFF_PICTURE;

            if(h->sps.pic_struct_present_flag){

                switch (h->sei_pic_struct)

                {

                case SEI_PIC_STRUCT_TOP_BOTTOM_TOP:

                case SEI_PIC_STRUCT_BOTTOM_TOP_BOTTOM:

                    // Signal the possibility of telecined film externally (pic_struct 5,6)

                    // From these hints, let the applications decide if they apply deinterlacing.

                    cur->repeat_pict = 1;

                    break;

                case SEI_PIC_STRUCT_FRAME_DOUBLING:

                    // Force progressive here, as doubling interlaced frame is a bad idea.

                    cur->interlaced_frame = 0;

                    cur->repeat_pict = 2;

                    break;

                case SEI_PIC_STRUCT_FRAME_TRIPLING:

                    cur->interlaced_frame = 0;

                    cur->repeat_pict = 4;

                    break;

                }

            }else{

                /* Derive interlacing flag from used decoding process. */

                cur->interlaced_frame = FIELD_OR_MBAFF_PICTURE;

            }

            if (cur->field_poc[0] != cur->field_poc[1]){

                /* Derive top_field_first from field pocs. */

                cur->top_field_first = cur->field_poc[0] < cur->field_poc[1];

            }else{

                if(cur->interlaced_frame || h->sps.pic_struct_present_flag){

                    /* Use picture timing SEI information. Even if it is a information of a past frame, better than nothing. */

                    if(h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM

                      || h->sei_pic_struct == SEI_PIC_STRUCT_TOP_BOTTOM_TOP)

                        cur->top_field_first = 1;

                    else

                        cur->top_field_first = 0;

                }else{

                    /* Most likely progressive */

                    cur->top_field_first = 0;

                }

            }

        //FIXME do something with unavailable reference frames

            /* Sort B-frames into display order */

            if(h->sps.bitstream_restriction_flag

               && s->avctx->has_b_frames < h->sps.num_reorder_frames){

                s->avctx->has_b_frames = h->sps.num_reorder_frames;

                s->low_delay = 0;

            }

            if(   s->avctx->strict_std_compliance >= FF_COMPLIANCE_STRICT

               && !h->sps.bitstream_restriction_flag){

                s->avctx->has_b_frames= MAX_DELAYED_PIC_COUNT;

                s->low_delay= 0;

            }

            pics = 0;

            while(h->delayed_pic[pics]) pics++;

            assert(pics <= MAX_DELAYED_PIC_COUNT);

            h->delayed_pic[pics++] = cur;

            if(cur->reference == 0)

                cur->reference = DELAYED_PIC_REF;

            out = h->delayed_pic[0];

            out_idx = 0;

            for(i=1; h->delayed_pic[i] && (h->delayed_pic[i]->poc && !h->delayed_pic[i]->key_frame); i++)

                if(h->delayed_pic[i]->poc < out->poc){

                    out = h->delayed_pic[i];

                    out_idx = i;

                }

            cross_idr = !h->delayed_pic[0]->poc || !!h->delayed_pic[i] || h->delayed_pic[0]->key_frame;

            out_of_order = !cross_idr && out->poc < h->outputed_poc;

            if(h->sps.bitstream_restriction_flag && s->avctx->has_b_frames >= h->sps.num_reorder_frames)

                { }

            else if((out_of_order && pics-1 == s->avctx->has_b_frames && s->avctx->has_b_frames < MAX_DELAYED_PIC_COUNT)

               || (s->low_delay &&

                ((!cross_idr && out->poc > h->outputed_poc + 2)

                 || cur->pict_type == FF_B_TYPE)))

            {

                s->low_delay = 0;

                s->avctx->has_b_frames++;

            }

            if(out_of_order || pics > s->avctx->has_b_frames){

                out->reference &= ~DELAYED_PIC_REF;

                for(i=out_idx; h->delayed_pic[i]; i++)

                    h->delayed_pic[i] = h->delayed_pic[i+1];

            }

            if(!out_of_order && pics > s->avctx->has_b_frames){

                *data_size = sizeof(AVFrame);

                h->outputed_poc = out->poc;

                *pict= *(AVFrame*)out;

            }else{

                av_log(avctx, AV_LOG_DEBUG, "no picture\n");

            }

        }

    }

    assert(pict->data[0] || !*data_size);

    ff_print_debug_info(s, pict);

//printf("out %d\n", (int)pict->data[0]);

#if 0 //?

    /* Return the Picture timestamp as the frame number */

    /* we subtract 1 because it is added on utils.c     */

    avctx->frame_number = s->picture_number - 1;

#endif

    return get_consumed_bytes(s, buf_index, buf_size);

}


static int tscc2_decode_mb(TSCC2Context *c, int *q, int vlc_set,

                           uint8_t *dst, int stride, int plane)

{

    GetBitContext *gb = &c->gb;

    int prev_dc, dc, nc, ac, bpos, val;

    int i, j, k, l;

    if (get_bits1(gb)) {

        if (get_bits1(gb)) {

            val = get_bits(gb, 8);

            for (i = 0; i < 8; i++, dst += stride)

                memset(dst, val, 16);

        } else {

            if (get_bits_left(gb) < 16 * 8 * 8)

                return AVERROR_INVALIDDATA;

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

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

                    dst[j] = get_bits(gb, 8);

                dst += stride;

            }

        }

        return 0;

    }

    prev_dc = 0;

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

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

            if (!(j | k)) {

                dc = get_bits(gb, 8);

            } else {

                dc = get_vlc2(gb, c->dc_vlc.table, 9, 2);

                if (dc == -1)

                    return AVERROR_INVALIDDATA;

                if (dc == 0x100)

                    dc = get_bits(gb, 8);

            }

            dc          = (dc + prev_dc) & 0xFF;

            prev_dc     = dc;

            c->block[0] = dc;

            nc = get_vlc2(gb, c->nc_vlc[vlc_set].table, 9, 1);

            if (nc == -1)

                return AVERROR_INVALIDDATA;

            bpos = 1;

            memset(c->block + 1, 0, 15 * sizeof(*c->block));

            for (l = 0; l < nc; l++) {

                ac = get_vlc2(gb, c->ac_vlc[vlc_set].table, 9, 2);

                if (ac == -1)

                    return AVERROR_INVALIDDATA;

                if (ac == 0x1000)

                    ac = get_bits(gb, 12);

                bpos += ac & 0xF;

                if (bpos >= 64)

                    return AVERROR_INVALIDDATA;

                val = sign_extend(ac >> 4, 8);

                c->block[tscc2_zigzag[bpos++]] = val;

            }

            tscc2_idct4_put(c->block, q, dst + k * 4, stride);

        }

        dst += 4 * stride;

    }

    return 0;

}


static void subband_transform(DCAEncContext *c, const int32_t *input)

{

    int ch, subs, i, k, j;

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

        /* History is copied because it is also needed for PSY */

        int32_t hist[512];

        int hist_start = 0;

        const int chi = c->channel_order_tab[ch];

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

            hist[i] = c->history[i][ch];

        for (subs = 0; subs < SUBBAND_SAMPLES; subs++) {

            int32_t accum[64];

            int32_t resp;

            int band;

            /* Calculate the convolutions at once */

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

                accum[i] = 0;

            for (k = 0, i = hist_start, j = 0;

                    i < 512; k = (k + 1) & 63, i++, j++)

                accum[k] += mul32(hist[i], c->band_interpolation[j]);

            for (i = 0; i < hist_start; k = (k + 1) & 63, i++, j++)

                accum[k] += mul32(hist[i], c->band_interpolation[j]);

            for (k = 16; k < 32; k++)

                accum[k] = accum[k] - accum[31 - k];

            for (k = 32; k < 48; k++)

                accum[k] = accum[k] + accum[95 - k];

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

                resp = 0;

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

                    int s = (2 * band + 1) * (2 * (i + 16) + 1);

                    resp += mul32(accum[i], cos_t(s << 3)) >> 3;

                }

                c->subband[subs][band][ch] = ((band + 1) & 2) ? -resp : resp;

            }

            /* Copy in 32 new samples from input */

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

                hist[i + hist_start] = input[(subs * 32 + i) * c->channels + chi];

            hist_start = (hist_start + 32) & 511;

        }

    }

}


static void test_in_coroutine(void)

{

    Coroutine *coroutine;

    g_assert(!qemu_in_coroutine());

    coroutine = qemu_coroutine_create(verify_in_coroutine);

    qemu_coroutine_enter(coroutine, NULL);

}


static void pcx_palette(const uint8_t **src, uint32_t *dst, unsigned int pallen) {

    unsigned int i;

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

        *dst++ = 0xFF000000 | bytestream_get_be24(src);

    if (pallen < 256)

        memset(dst, 0, (256 - pallen) * sizeof(*dst));

}


block_crypto_open_opts_init(QCryptoBlockFormat format,

                            QemuOpts *opts,

                            Error **errp)

{

    OptsVisitor *ov;

    QCryptoBlockOpenOptions *ret = NULL;

    Error *local_err = NULL;

    ret = g_new0(QCryptoBlockOpenOptions, 1);

    ret->format = format;

    ov = opts_visitor_new(opts);

    visit_start_struct(opts_get_visitor(ov),

                       NULL, NULL, 0, &local_err);

    if (local_err) {

        goto out;

    }

    switch (format) {

    case Q_CRYPTO_BLOCK_FORMAT_LUKS:

        visit_type_QCryptoBlockOptionsLUKS_members(

            opts_get_visitor(ov), &ret->u.luks, &local_err);

        break;

    default:

        error_setg(&local_err, "Unsupported block format %d", format);

        break;

    }

    error_propagate(errp, local_err);

    local_err = NULL;

    visit_end_struct(opts_get_visitor(ov), &local_err);

 out:

    if (local_err) {

        error_propagate(errp, local_err);

        qapi_free_QCryptoBlockOpenOptions(ret);

        ret = NULL;

    }

    opts_visitor_cleanup(ov);

    return ret;

}


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

{

    PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);

    DeviceClass *dc = DEVICE_CLASS(klass);

    dc->vmsd    = &vmstate_xhci;

    dc->props   = xhci_properties;

    dc->reset   = xhci_reset;

    k->init         = usb_xhci_initfn;

    k->vendor_id    = PCI_VENDOR_ID_NEC;

    k->device_id    = PCI_DEVICE_ID_NEC_UPD720200;

    k->class_id     = PCI_CLASS_SERIAL_USB;

    k->revision     = 0x03;

    k->is_express   = 1;

}


static int mxf_read_sequence(MXFSequence *sequence, ByteIOContext *pb, int tag)

{

    switch(tag) {

    case 0x0202:

        sequence->duration = get_be64(pb);

        break;

    case 0x0201:

        get_buffer(pb, sequence->data_definition_ul, 16);

        break;

    case 0x1001:

        sequence->structural_components_count = get_be32(pb);

        if (sequence->structural_components_count >= UINT_MAX / sizeof(UID))

            return -1;

        sequence->structural_components_refs = av_malloc(sequence->structural_components_count * sizeof(UID));

        if (!sequence->structural_components_refs)

            return -1;

        url_fskip(pb, 4); /* useless size of objects, always 16 according to specs */

        get_buffer(pb, (uint8_t *)sequence->structural_components_refs, sequence->structural_components_count * sizeof(UID));

        break;

    }

    return 0;

}


static int common_init(AVCodecContext *avctx){

    HYuvContext *s = avctx->priv_data;

    int i;

    s->avctx= avctx;

    s->flags= avctx->flags;

    dsputil_init(&s->dsp, avctx);

    s->width= avctx->width;

    s->height= avctx->height;

    assert(s->width>0 && s->height>0);

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

        s->temp[i]= av_malloc(avctx->width + 16);

    }

    return 0;

}


static int pic_arrays_init(HEVCContext *s, const HEVCSPS *sps)

{

    int log2_min_cb_size = sps->log2_min_cb_size;

    int width            = sps->width;

    int height           = sps->height;

    int pic_size_in_ctb  = ((width  >> log2_min_cb_size) + 1) *

                           ((height >> log2_min_cb_size) + 1);

    int ctb_count        = sps->ctb_width * sps->ctb_height;

    int min_pu_size      = sps->min_pu_width * sps->min_pu_height;

    s->bs_width  = (width  >> 2) + 1;

    s->bs_height = (height >> 2) + 1;

    s->sao           = av_mallocz_array(ctb_count, sizeof(*s->sao));

    s->deblock       = av_mallocz_array(ctb_count, sizeof(*s->deblock));

    if (!s->sao || !s->deblock)

        goto fail;

    s->skip_flag    = av_malloc(sps->min_cb_height * sps->min_cb_width);

    s->tab_ct_depth = av_malloc_array(sps->min_cb_height, sps->min_cb_width);

    if (!s->skip_flag || !s->tab_ct_depth)

        goto fail;

    s->cbf_luma = av_malloc_array(sps->min_tb_width, sps->min_tb_height);

    s->tab_ipm  = av_mallocz(min_pu_size);

    s->is_pcm   = av_malloc((sps->min_pu_width + 1) * (sps->min_pu_height + 1));

    if (!s->tab_ipm || !s->cbf_luma || !s->is_pcm)

        goto fail;

    s->filter_slice_edges = av_malloc(ctb_count);

    s->tab_slice_address  = av_malloc_array(pic_size_in_ctb,

                                      sizeof(*s->tab_slice_address));

    s->qp_y_tab           = av_malloc_array(pic_size_in_ctb,

                                      sizeof(*s->qp_y_tab));

    if (!s->qp_y_tab || !s->filter_slice_edges || !s->tab_slice_address)

        goto fail;

    s->horizontal_bs = av_mallocz_array(s->bs_width, s->bs_height);

    s->vertical_bs   = av_mallocz_array(s->bs_width, s->bs_height);

    if (!s->horizontal_bs || !s->vertical_bs)

        goto fail;

    s->tab_mvf_pool = av_buffer_pool_init(min_pu_size * sizeof(MvField),

                                          av_buffer_allocz);

    s->rpl_tab_pool = av_buffer_pool_init(ctb_count * sizeof(RefPicListTab),

                                          av_buffer_allocz);

    if (!s->tab_mvf_pool || !s->rpl_tab_pool)

        goto fail;

    return 0;

fail:

    pic_arrays_free(s);

    return AVERROR(ENOMEM);

}


static int decode_dc_progressive(MJpegDecodeContext *s, int16_t *block,

                                 int component, int dc_index,

                                 int16_t *quant_matrix, int Al)

{

    int val;

    s->bdsp.clear_block(block);

    val = mjpeg_decode_dc(s, dc_index);

    if (val == 0xfffff) {

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

        return AVERROR_INVALIDDATA;

    }

    val = (val * (quant_matrix[0] << Al)) + s->last_dc[component];

    s->last_dc[component] = val;

    block[0] = val;

    return 0;

}


static int config_input(AVFilterLink *inlink)
{
    HQDN3DContext *s = inlink->dst->priv;
    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
    int i;
    s->hsub  = desc->log2_chroma_w;
    s->vsub  = desc->log2_chroma_h;
    s->depth = desc->comp[0].depth_minus1+1;
    s->line = av_malloc(inlink->w * sizeof(*s->line));
    if (!s->line)
        return AVERROR(ENOMEM);
    for (i = 0; i < 4; i++) {
        s->coefs[i] = precalc_coefs(s->strength[i], s->depth);
        if (!s->coefs[i])
            return AVERROR(ENOMEM);
    }
    if (ARCH_X86)
        ff_hqdn3d_init_x86(s);
    return 0;
}


static int64_t mkv_write_cues(AVIOContext *pb, mkv_cues *cues, mkv_track *tracks, int num_tracks)

{

    ebml_master cues_element;

    int64_t currentpos;

    int i, j;

    currentpos = avio_tell(pb);

    cues_element = start_ebml_master(pb, MATROSKA_ID_CUES, 0);

    for (i = 0; i < cues->num_entries; i++) {

        ebml_master cuepoint, track_positions;

        mkv_cuepoint *entry = &cues->entries[i];

        uint64_t pts = entry->pts;

        cuepoint = start_ebml_master(pb, MATROSKA_ID_POINTENTRY, MAX_CUEPOINT_SIZE(num_tracks));

        put_ebml_uint(pb, MATROSKA_ID_CUETIME, pts);

        // put all the entries from different tracks that have the exact same

        // timestamp into the same CuePoint

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

            tracks[j].has_cue = 0;

        for (j = 0; j < cues->num_entries - i && entry[j].pts == pts; j++) {

            if (tracks[entry[j].tracknum].has_cue)

                continue;

            tracks[entry[j].tracknum].has_cue = 1;

            track_positions = start_ebml_master(pb, MATROSKA_ID_CUETRACKPOSITION, MAX_CUETRACKPOS_SIZE);

            put_ebml_uint(pb, MATROSKA_ID_CUETRACK          , entry[j].tracknum   );

            put_ebml_uint(pb, MATROSKA_ID_CUECLUSTERPOSITION, entry[j].cluster_pos);

            end_ebml_master(pb, track_positions);

        }

        i += j - 1;

        end_ebml_master(pb, cuepoint);

    }

    end_ebml_master(pb, cues_element);

    return currentpos;

}


static void decode_plane(FFV1Context *s, uint8_t *src,

                         int w, int h, int stride, int plane_index,

                         int pixel_stride)

{

    int x, y;

    int16_t *sample[2];

    sample[0] = s->sample_buffer + 3;

    sample[1] = s->sample_buffer + w + 6 + 3;

    s->run_index = 0;

    memset(s->sample_buffer, 0, 2 * (w + 6) * sizeof(*s->sample_buffer));

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

        int16_t *temp = sample[0]; // FIXME: try a normal buffer

        sample[0] = sample[1];

        sample[1] = temp;

        sample[1][-1] = sample[0][0];

        sample[0][w]  = sample[0][w - 1];

// { START_TIMER

        if (s->avctx->bits_per_raw_sample <= 8) {

            decode_line(s, w, sample, plane_index, 8);

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

                src[x*pixel_stride + stride * y] = sample[1][x];

        } else {

            decode_line(s, w, sample, plane_index, s->avctx->bits_per_raw_sample);

            if (s->packed_at_lsb) {

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

                    ((uint16_t*)(src + stride*y))[x*pixel_stride] = sample[1][x];

                }

            } else {

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

                    ((uint16_t*)(src + stride*y))[x*pixel_stride] = sample[1][x] << (16 - s->avctx->bits_per_raw_sample) | ((uint16_t **)sample)[1][x] >> (2 * s->avctx->bits_per_raw_sample - 16);

                }

            }

        }

// STOP_TIMER("decode-line") }

    }

}


void curses_display_init(DisplayState *ds, int full_screen)

{

#ifndef _WIN32

    if (!isatty(1)) {

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

        exit(1);

    }

#endif

    curses_setup();

    curses_keyboard_setup();

    atexit(curses_atexit);

    curses_winch_init();

    dcl = (DisplayChangeListener *) g_malloc0(sizeof(DisplayChangeListener));

    dcl->ops = &dcl_ops;

    register_displaychangelistener(dcl);

    invalidate = 1;

}


static int wav_read_header(AVFormatContext *s,

                           AVFormatParameters *ap)

{

    int size;

    unsigned int tag;

    ByteIOContext *pb = s->pb;

    AVStream *st;

    WAVContext *wav = s->priv_data;

    /* check RIFF header */

    tag = get_le32(pb);

    if (tag != MKTAG('R', 'I', 'F', 'F'))

        return -1;

    get_le32(pb); /* file size */

    tag = get_le32(pb);

    if (tag != MKTAG('W', 'A', 'V', 'E'))

        return -1;

    /* parse fmt header */

    size = find_tag(pb, MKTAG('f', 'm', 't', ' '));

    if (size < 0)

        return -1;

    st = av_new_stream(s, 0);

    if (!st)

        return AVERROR(ENOMEM);

    get_wav_header(pb, st->codec, size);

    st->need_parsing = AVSTREAM_PARSE_FULL;

    av_set_pts_info(st, 64, 1, st->codec->sample_rate);

    size = find_tag(pb, MKTAG('d', 'a', 't', 'a'));

    if (size < 0)

        return -1;

    wav->data_end= url_ftell(pb) + size;

    return 0;

}


static void add_to_iovec(QEMUFile *f, const uint8_t *buf, int size)

{

    /* check for adjacent buffer and coalesce them */

    if (f->iovcnt > 0 && buf == f->iov[f->iovcnt - 1].iov_base +

        f->iov[f->iovcnt - 1].iov_len) {

        f->iov[f->iovcnt - 1].iov_len += size;

    } else {

        f->iov[f->iovcnt].iov_base = (uint8_t *)buf;

        f->iov[f->iovcnt++].iov_len = size;

    }

    if (f->iovcnt >= MAX_IOV_SIZE) {

        qemu_fflush(f);

    }

}


int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,

                                              int *got_picture_ptr,

                                              AVPacket *avpkt)

{

    AVCodecInternal *avci = avctx->internal;

    int ret;

    *got_picture_ptr = 0;

    if ((avctx->coded_width || avctx->coded_height) && av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx))

        return -1;

    avctx->internal->pkt = avpkt;

    ret = apply_param_change(avctx, avpkt);

    if (ret < 0) {

        av_log(avctx, AV_LOG_ERROR, "Error applying parameter changes.\n");

        if (avctx->err_recognition & AV_EF_EXPLODE)

            return ret;

    }

    avcodec_get_frame_defaults(picture);

    if (!avctx->refcounted_frames)

        av_frame_unref(&avci->to_free);

    if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type & FF_THREAD_FRAME)) {

        if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)

            ret = ff_thread_decode_frame(avctx, picture, got_picture_ptr,

                                         avpkt);

        else {

            ret = avctx->codec->decode(avctx, picture, got_picture_ptr,

                                       avpkt);

            picture->pkt_dts = avpkt->dts;

            /* get_buffer is supposed to set frame parameters */

            if (!(avctx->codec->capabilities & CODEC_CAP_DR1)) {

                picture->sample_aspect_ratio = avctx->sample_aspect_ratio;

                picture->width               = avctx->width;

                picture->height              = avctx->height;

                picture->format              = avctx->pix_fmt;

            }

        }

        emms_c(); //needed to avoid an emms_c() call before every return;

        if (ret < 0 && picture->buf[0])

            av_frame_unref(picture);

        if (*got_picture_ptr) {

            if (!avctx->refcounted_frames) {

                avci->to_free = *picture;

                avci->to_free.extended_data = avci->to_free.data;

                memset(picture->buf, 0, sizeof(picture->buf));

            }

            avctx->frame_number++;

        }

    } else

        ret = 0;

    return ret;

}


int av_new_packet(AVPacket *pkt, int size)

{

    uint8_t *data;

    if((unsigned)size > (unsigned)size + FF_INPUT_BUFFER_PADDING_SIZE)

        return AVERROR(ENOMEM);

    data = av_malloc(size + FF_INPUT_BUFFER_PADDING_SIZE);

    if (!data)

        return AVERROR(ENOMEM);

    memset(data + size, 0, FF_INPUT_BUFFER_PADDING_SIZE);

    av_init_packet(pkt);

    pkt->data = data;

    pkt->size = size;

    pkt->destruct = av_destruct_packet;

    return 0;

}


static int decode_slice(H264Context *h){

    MpegEncContext * const s = &h->s;

    const int part_mask= s->partitioned_frame ? (AC_END|AC_ERROR) : 0x7F;

    s->mb_skip_run= -1;

    if( h->pps.cabac ) {

        int i;

        /* realign */

        align_get_bits( &s->gb );

        /* init cabac */

        ff_init_cabac_states( &h->cabac, ff_h264_lps_range, ff_h264_mps_state, ff_h264_lps_state, 64 );

        ff_init_cabac_decoder( &h->cabac,

                               s->gb.buffer + get_bits_count(&s->gb)/8,

                               ( s->gb.size_in_bits - get_bits_count(&s->gb) + 7)/8);

        /* calculate pre-state */

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

            int pre;

            if( h->slice_type == I_TYPE )

                pre = clip( ((cabac_context_init_I[i][0] * s->qscale) >>4 ) + cabac_context_init_I[i][1], 1, 126 );

            else

                pre = clip( ((cabac_context_init_PB[h->cabac_init_idc][i][0] * s->qscale) >>4 ) + cabac_context_init_PB[h->cabac_init_idc][i][1], 1, 126 );

            if( pre <= 63 )

                h->cabac_state[i] = 2 * ( 63 - pre ) + 0;

            else

                h->cabac_state[i] = 2 * ( pre - 64 ) + 1;

        }

        for(;;){

            int ret = decode_mb_cabac(h);

            int eos;

            if(ret>=0) hl_decode_mb(h);

            /* XXX: useless as decode_mb_cabac it doesn't support that ... */

            if( ret >= 0 && h->mb_aff_frame ) { //FIXME optimal? or let mb_decode decode 16x32 ?

                s->mb_y++;

                if(ret>=0) ret = decode_mb_cabac(h);

                hl_decode_mb(h);

                s->mb_y--;

            }

            eos = get_cabac_terminate( &h->cabac );

            if( ret < 0 || h->cabac.bytestream > h->cabac.bytestream_end + 1) {

                av_log(h->s.avctx, AV_LOG_ERROR, "error while decoding MB %d %d\n", s->mb_x, s->mb_y);

                ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);

                return -1;

            }

            if( ++s->mb_x >= s->mb_width ) {

                s->mb_x = 0;

                ff_draw_horiz_band(s, 16*s->mb_y, 16);

                ++s->mb_y;

                if(h->mb_aff_frame) {

                    ++s->mb_y;

                }

            }

            if( eos || s->mb_y >= s->mb_height ) {

                tprintf("slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);

                ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);

                return 0;

            }

        }

    } else {

        for(;;){

            int ret = decode_mb_cavlc(h);

            if(ret>=0) hl_decode_mb(h);

            if(ret>=0 && h->mb_aff_frame){ //FIXME optimal? or let mb_decode decode 16x32 ?

                s->mb_y++;

                ret = decode_mb_cavlc(h);

                if(ret>=0) hl_decode_mb(h);

                s->mb_y--;

            }

            if(ret<0){

                av_log(h->s.avctx, AV_LOG_ERROR, "error while decoding MB %d %d\n", s->mb_x, s->mb_y);

                ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);

                return -1;

            }

            if(++s->mb_x >= s->mb_width){

                s->mb_x=0;

                ff_draw_horiz_band(s, 16*s->mb_y, 16);

                ++s->mb_y;

                if(h->mb_aff_frame) {

                    ++s->mb_y;

                }

                if(s->mb_y >= s->mb_height){

                    tprintf("slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);

                    if(get_bits_count(&s->gb) == s->gb.size_in_bits ) {

                        ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);

                        return 0;

                    }else{

                        ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);

                        return -1;

                    }

                }

            }

            if(get_bits_count(&s->gb) >= s->gb.size_in_bits && s->mb_skip_run<=0){

                tprintf("slice end %d %d\n", get_bits_count(&s->gb), s->gb.size_in_bits);

                if(get_bits_count(&s->gb) == s->gb.size_in_bits ){

                    ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);

                    return 0;

                }else{

                    ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);

                    return -1;

                }

            }

        }

    }

#if 0

    for(;s->mb_y < s->mb_height; s->mb_y++){

        for(;s->mb_x < s->mb_width; s->mb_x++){

            int ret= decode_mb(h);

            hl_decode_mb(h);

            if(ret<0){

                fprintf(stderr, "error while decoding MB %d %d\n", s->mb_x, s->mb_y);

                ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);

                return -1;

            }

            if(++s->mb_x >= s->mb_width){

                s->mb_x=0;

                if(++s->mb_y >= s->mb_height){

                    if(get_bits_count(s->gb) == s->gb.size_in_bits){

                        ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);

                        return 0;

                    }else{

                        ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);

                        return -1;

                    }

                }

            }

            if(get_bits_count(s->?gb) >= s->gb?.size_in_bits){

                if(get_bits_count(s->gb) == s->gb.size_in_bits){

                    ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x-1, s->mb_y, (AC_END|DC_END|MV_END)&part_mask);

                    return 0;

                }else{

                    ff_er_add_slice(s, s->resync_mb_x, s->resync_mb_y, s->mb_x, s->mb_y, (AC_ERROR|DC_ERROR|MV_ERROR)&part_mask);

                    return -1;

                }

            }

        }

        s->mb_x=0;

        ff_draw_horiz_band(s, 16*s->mb_y, 16);

    }

#endif

    return -1; //not reached

}


static av_cold int dirac_decode_init(AVCodecContext *avctx)

{

    DiracContext *s = avctx->priv_data;

    int i;

    s->avctx = avctx;

    s->frame_number = -1;

    if (avctx->flags&CODEC_FLAG_EMU_EDGE) {

        av_log(avctx, AV_LOG_ERROR, "Edge emulation not supported!\n");

        return AVERROR_PATCHWELCOME;

    }

    ff_dsputil_init(&s->dsp, avctx);

    ff_diracdsp_init(&s->diracdsp);

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

        s->all_frames[i].avframe = av_frame_alloc();

    return 0;

}


static int qemu_chr_open_win_file(HANDLE fd_out, CharDriverState **pchr)

{

    CharDriverState *chr;

    WinCharState *s;

    chr = g_malloc0(sizeof(CharDriverState));

    s = g_malloc0(sizeof(WinCharState));

    s->hcom = fd_out;

    chr->opaque = s;

    chr->chr_write = win_chr_write;

    qemu_chr_generic_open(chr);

    *pchr = chr;

    return 0;

}


int qcrypto_cipher_encrypt(QCryptoCipher *cipher,

                           const void *in,

                           void *out,

                           size_t len,

                           Error **errp)

{

    QCryptoCipherNettle *ctx = cipher->opaque;

    switch (cipher->mode) {

    case QCRYPTO_CIPHER_MODE_ECB:

        ctx->alg_encrypt(ctx->ctx_encrypt, len, out, in);

        break;

    case QCRYPTO_CIPHER_MODE_CBC:

        cbc_encrypt(ctx->ctx_encrypt, ctx->alg_encrypt,

                    ctx->niv, ctx->iv,

                    len, out, in);

        break;

    default:

        error_setg(errp, "Unsupported cipher algorithm %d",

                   cipher->alg);

        return -1;

    }

    return 0;

}


static int color_distance(uint32_t a, uint32_t b)

{

    int r = 0, d, i;

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

        d = ((a >> i) & 0xFF) - ((b >> i) & 0xFF);

        r += d * d;

    }

    return r;

}


static int32_t scsi_send_command(SCSIDevice *d, uint32_t tag,

                                 uint8_t *cmd, int lun)

{

    SCSIGenericState *s = DO_UPCAST(SCSIGenericState, qdev, d);

    SCSIGenericReq *r;

    SCSIBus *bus;

    int ret;

    if (cmd[0] != REQUEST_SENSE &&

        (lun != s->lun || (cmd[1] >> 5) != s->lun)) {

        DPRINTF("Unimplemented LUN %d\n", lun ? lun : cmd[1] >> 5);

        s->sensebuf[0] = 0x70;

        s->sensebuf[1] = 0x00;

        s->sensebuf[2] = ILLEGAL_REQUEST;

        s->sensebuf[3] = 0x00;

        s->sensebuf[4] = 0x00;

        s->sensebuf[5] = 0x00;

        s->sensebuf[6] = 0x00;

        s->senselen = 7;

        s->driver_status = SG_ERR_DRIVER_SENSE;

        bus = scsi_bus_from_device(d);

        bus->ops->complete(bus, SCSI_REASON_DONE, tag, CHECK_CONDITION);

        return 0;

    }

    r = scsi_find_request(s, tag);

    if (r) {

        BADF("Tag 0x%x already in use %p\n", tag, r);

        scsi_cancel_io(d, tag);

    }

    r = scsi_new_request(d, tag, lun);

    if (-1 == scsi_req_parse(&r->req, cmd)) {

        BADF("Unsupported command length, command %x\n", cmd[0]);

        scsi_remove_request(r);

        return 0;

    }

    scsi_req_fixup(&r->req);

    DPRINTF("Command: lun=%d tag=0x%x len %zd data=0x%02x", lun, tag,

            r->req.cmd.xfer, cmd[0]);

#ifdef DEBUG_SCSI

    {

        int i;

        for (i = 1; i < r->req.cmd.len; i++) {

            printf(" 0x%02x", cmd[i]);

        }

        printf("\n");

    }

#endif

    if (r->req.cmd.xfer == 0) {

        if (r->buf != NULL)

            qemu_free(r->buf);

        r->buflen = 0;

        r->buf = NULL;

        ret = execute_command(s->bs, r, SG_DXFER_NONE, scsi_command_complete);

        if (ret == -1) {

            scsi_command_complete(r, -EINVAL);

            return 0;

        }

        return 0;

    }

    if (r->buflen != r->req.cmd.xfer) {

        if (r->buf != NULL)

            qemu_free(r->buf);

        r->buf = qemu_malloc(r->req.cmd.xfer);

        r->buflen = r->req.cmd.xfer;

    }

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

    r->len = r->req.cmd.xfer;

    if (r->req.cmd.mode == SCSI_XFER_TO_DEV) {

        r->len = 0;

        return -r->req.cmd.xfer;

    }

    return r->req.cmd.xfer;

}


static void gen_mfsr_64b(DisasContext *ctx)

{

#if defined(CONFIG_USER_ONLY)

    gen_inval_exception(ctx, POWERPC_EXCP_PRIV_REG);

#else

    TCGv t0;

    if (unlikely(ctx->pr)) {

        gen_inval_exception(ctx, POWERPC_EXCP_PRIV_REG);

        return;

    }

    t0 = tcg_const_tl(SR(ctx->opcode));

    gen_helper_load_sr(cpu_gpr[rD(ctx->opcode)], cpu_env, t0);

    tcg_temp_free(t0);

#endif

}


struct omap_gpmc_s *omap_gpmc_init(target_phys_addr_t base, qemu_irq irq)

{

    struct omap_gpmc_s *s = (struct omap_gpmc_s *)

            g_malloc0(sizeof(struct omap_gpmc_s));

    memory_region_init_io(&s->iomem, &omap_gpmc_ops, s, "omap-gpmc", 0x1000);

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

    omap_gpmc_reset(s);

    return s;

}


static void sbr_qmf_deint_bfly_c(INTFLOAT *v, const INTFLOAT *src0, const INTFLOAT *src1)

{

    int i;

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

        v[      i] = AAC_SRA_R((src0[i] - src1[63 - i]), 5);

        v[127 - i] = AAC_SRA_R((src0[i] + src1[63 - i]), 5);

    }

}


static void gif_copy_img_rect(const uint32_t *src, uint32_t *dst,

                              int linesize, int l, int t, int w, int h)

{

    const int y_start = t * linesize;

    const uint32_t *src_px, *src_pr,

                   *src_py = src + y_start,

                   *dst_py = dst + y_start;

    const uint32_t *src_pb = src_py + (t + h) * linesize;

    uint32_t *dst_px;

    for (; src_py < src_pb; src_py += linesize, dst_py += linesize) {

        src_px = src_py + l;

        dst_px = (uint32_t *)dst_py + l;

        src_pr = src_px + w;

        for (; src_px < src_pr; src_px++, dst_px++)

            *dst_px = *src_px;

    }

}


static uint64_t cg3_reg_read(void *opaque, hwaddr addr, unsigned size)

{

    CG3State *s = opaque;

    int val;

    switch (addr) {

    case CG3_REG_BT458_ADDR:

    case CG3_REG_BT458_COLMAP:

        val = 0;

        break;

    case CG3_REG_FBC_CTRL:

        val = s->regs[0];

        break;

    case CG3_REG_FBC_STATUS:

        /* monitor ID 6, board type = 1 (color) */

        val = s->regs[1] | CG3_SR_1152_900_76_B | CG3_SR_ID_COLOR;

        break;

    case CG3_REG_FBC_CURSTART ... CG3_REG_SIZE:

        val = s->regs[addr - 0x10];

        break;

    default:

        qemu_log_mask(LOG_UNIMP,

                  "cg3: Unimplemented register read "

                  "reg 0x%" HWADDR_PRIx " size 0x%x\n",

                  addr, size);

        val = 0;

        break;

    }

    DPRINTF("read %02x from reg %" HWADDR_PRIx "\n", val, addr);

    return val;

}


static int expand_rle_row(SgiState *s, uint8_t *out_buf,

                          uint8_t *out_end, int pixelstride)

{

    unsigned char pixel, count;

    unsigned char *orig = out_buf;

    while (1) {

        if (bytestream2_get_bytes_left(&s->g) < 1)

            return AVERROR_INVALIDDATA;

        pixel = bytestream2_get_byteu(&s->g);

        if (!(count = (pixel & 0x7f))) {

            return (out_buf - orig) / pixelstride;

        }

        /* Check for buffer overflow. */

        if(out_buf + pixelstride * count >= out_end) return -1;

        if (pixel & 0x80) {

            while (count--) {

                *out_buf = bytestream2_get_byte(&s->g);

                out_buf += pixelstride;

            }

        } else {

            pixel = bytestream2_get_byte(&s->g);

            while (count--) {

                *out_buf = pixel;

                out_buf += pixelstride;

            }

        }

    }

}


static void new_connection(int server_fd, int is_rtsp)

{

    struct sockaddr_in from_addr;

    int fd, len;

    HTTPContext *c = NULL;

    len = sizeof(from_addr);

    fd = accept(server_fd, (struct sockaddr *)&from_addr,

                &len);

    if (fd < 0)

        return;

    fcntl(fd, F_SETFL, O_NONBLOCK);

    /* XXX: should output a warning page when coming

       close to the connection limit */

    if (nb_connections >= nb_max_connections)

        goto fail;

    /* add a new connection */

    c = av_mallocz(sizeof(HTTPContext));

    if (!c)

        goto fail;

    c->next = first_http_ctx;

    first_http_ctx = c;

    c->fd = fd;

    c->poll_entry = NULL;

    c->from_addr = from_addr;

    c->buffer_size = IOBUFFER_INIT_SIZE;

    c->buffer = av_malloc(c->buffer_size);

    if (!c->buffer)

        goto fail;

    nb_connections++;

    start_wait_request(c, is_rtsp);

    return;

 fail:

    if (c) {

        av_free(c->buffer);

        av_free(c);

    }

    close(fd);

}


static void apply_independent_coupling_fixed(AACContext *ac,

                                       SingleChannelElement *target,

                                       ChannelElement *cce, int index)

{

    int i, c, shift, round, tmp;

    const int gain = cce->coup.gain[index][0];

    const int *src = cce->ch[0].ret;

    int *dest = target->ret;

    const int len = 1024 << (ac->oc[1].m4ac.sbr == 1);

    c = cce_scale_fixed[gain & 7];

    shift = (gain-1024) >> 3;

    if (shift < 0) {

        shift = -shift;

        round = 1 << (shift - 1);

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

            tmp = (int)(((int64_t)src[i] * c + (int64_t)0x1000000000) >> 37);

            dest[i] += (tmp + round) >> shift;

        }

    }

    else {

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

          tmp = (int)(((int64_t)src[i] * c + (int64_t)0x1000000000) >> 37);

          dest[i] += tmp << shift;

      }

    }

}


int kvm_arch_get_registers(CPUState *cs)

{

    PowerPCCPU *cpu = POWERPC_CPU(cs);

    CPUPPCState *env = &cpu->env;

    struct kvm_regs regs;

    struct kvm_sregs sregs;

    uint32_t cr;

    int i, ret;

    ret = kvm_vcpu_ioctl(cs, KVM_GET_REGS, &regs);

    if (ret < 0)

        return ret;

    cr = regs.cr;

    for (i = 7; i >= 0; i--) {

        env->crf[i] = cr & 15;

        cr >>= 4;

    }

    env->ctr = regs.ctr;

    env->lr = regs.lr;

    cpu_write_xer(env, regs.xer);

    env->msr = regs.msr;

    env->nip = regs.pc;

    env->spr[SPR_SRR0] = regs.srr0;

    env->spr[SPR_SRR1] = regs.srr1;

    env->spr[SPR_SPRG0] = regs.sprg0;

    env->spr[SPR_SPRG1] = regs.sprg1;

    env->spr[SPR_SPRG2] = regs.sprg2;

    env->spr[SPR_SPRG3] = regs.sprg3;

    env->spr[SPR_SPRG4] = regs.sprg4;

    env->spr[SPR_SPRG5] = regs.sprg5;

    env->spr[SPR_SPRG6] = regs.sprg6;

    env->spr[SPR_SPRG7] = regs.sprg7;

    env->spr[SPR_BOOKE_PID] = regs.pid;

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

        env->gpr[i] = regs.gpr[i];

    kvm_get_fp(cs);

    if (cap_booke_sregs) {

        ret = kvm_vcpu_ioctl(cs, KVM_GET_SREGS, &sregs);

        if (ret < 0) {

            return ret;

        }

        if (sregs.u.e.features & KVM_SREGS_E_BASE) {

            env->spr[SPR_BOOKE_CSRR0] = sregs.u.e.csrr0;

            env->spr[SPR_BOOKE_CSRR1] = sregs.u.e.csrr1;

            env->spr[SPR_BOOKE_ESR] = sregs.u.e.esr;

            env->spr[SPR_BOOKE_DEAR] = sregs.u.e.dear;

            env->spr[SPR_BOOKE_MCSR] = sregs.u.e.mcsr;

            env->spr[SPR_BOOKE_TSR] = sregs.u.e.tsr;

            env->spr[SPR_BOOKE_TCR] = sregs.u.e.tcr;

            env->spr[SPR_DECR] = sregs.u.e.dec;

            env->spr[SPR_TBL] = sregs.u.e.tb & 0xffffffff;

            env->spr[SPR_TBU] = sregs.u.e.tb >> 32;

            env->spr[SPR_VRSAVE] = sregs.u.e.vrsave;

        }

        if (sregs.u.e.features & KVM_SREGS_E_ARCH206) {

            env->spr[SPR_BOOKE_PIR] = sregs.u.e.pir;

            env->spr[SPR_BOOKE_MCSRR0] = sregs.u.e.mcsrr0;

            env->spr[SPR_BOOKE_MCSRR1] = sregs.u.e.mcsrr1;

            env->spr[SPR_BOOKE_DECAR] = sregs.u.e.decar;

            env->spr[SPR_BOOKE_IVPR] = sregs.u.e.ivpr;

        }

        if (sregs.u.e.features & KVM_SREGS_E_64) {

            env->spr[SPR_BOOKE_EPCR] = sregs.u.e.epcr;

        }

        if (sregs.u.e.features & KVM_SREGS_E_SPRG8) {

            env->spr[SPR_BOOKE_SPRG8] = sregs.u.e.sprg8;

        }

        if (sregs.u.e.features & KVM_SREGS_E_IVOR) {

            env->spr[SPR_BOOKE_IVOR0] = sregs.u.e.ivor_low[0];

            env->spr[SPR_BOOKE_IVOR1] = sregs.u.e.ivor_low[1];

            env->spr[SPR_BOOKE_IVOR2] = sregs.u.e.ivor_low[2];

            env->spr[SPR_BOOKE_IVOR3] = sregs.u.e.ivor_low[3];

            env->spr[SPR_BOOKE_IVOR4] = sregs.u.e.ivor_low[4];

            env->spr[SPR_BOOKE_IVOR5] = sregs.u.e.ivor_low[5];

            env->spr[SPR_BOOKE_IVOR6] = sregs.u.e.ivor_low[6];

            env->spr[SPR_BOOKE_IVOR7] = sregs.u.e.ivor_low[7];

            env->spr[SPR_BOOKE_IVOR8] = sregs.u.e.ivor_low[8];

            env->spr[SPR_BOOKE_IVOR9] = sregs.u.e.ivor_low[9];

            env->spr[SPR_BOOKE_IVOR10] = sregs.u.e.ivor_low[10];

            env->spr[SPR_BOOKE_IVOR11] = sregs.u.e.ivor_low[11];

            env->spr[SPR_BOOKE_IVOR12] = sregs.u.e.ivor_low[12];

            env->spr[SPR_BOOKE_IVOR13] = sregs.u.e.ivor_low[13];

            env->spr[SPR_BOOKE_IVOR14] = sregs.u.e.ivor_low[14];

            env->spr[SPR_BOOKE_IVOR15] = sregs.u.e.ivor_low[15];

            if (sregs.u.e.features & KVM_SREGS_E_SPE) {

                env->spr[SPR_BOOKE_IVOR32] = sregs.u.e.ivor_high[0];

                env->spr[SPR_BOOKE_IVOR33] = sregs.u.e.ivor_high[1];

                env->spr[SPR_BOOKE_IVOR34] = sregs.u.e.ivor_high[2];

            }

            if (sregs.u.e.features & KVM_SREGS_E_PM) {

                env->spr[SPR_BOOKE_IVOR35] = sregs.u.e.ivor_high[3];

            }

            if (sregs.u.e.features & KVM_SREGS_E_PC) {

                env->spr[SPR_BOOKE_IVOR36] = sregs.u.e.ivor_high[4];

                env->spr[SPR_BOOKE_IVOR37] = sregs.u.e.ivor_high[5];

            }

        }

        if (sregs.u.e.features & KVM_SREGS_E_ARCH206_MMU) {

            env->spr[SPR_BOOKE_MAS0] = sregs.u.e.mas0;

            env->spr[SPR_BOOKE_MAS1] = sregs.u.e.mas1;

            env->spr[SPR_BOOKE_MAS2] = sregs.u.e.mas2;

            env->spr[SPR_BOOKE_MAS3] = sregs.u.e.mas7_3 & 0xffffffff;

            env->spr[SPR_BOOKE_MAS4] = sregs.u.e.mas4;

            env->spr[SPR_BOOKE_MAS6] = sregs.u.e.mas6;

            env->spr[SPR_BOOKE_MAS7] = sregs.u.e.mas7_3 >> 32;

            env->spr[SPR_MMUCFG] = sregs.u.e.mmucfg;

            env->spr[SPR_BOOKE_TLB0CFG] = sregs.u.e.tlbcfg[0];

            env->spr[SPR_BOOKE_TLB1CFG] = sregs.u.e.tlbcfg[1];

        }

        if (sregs.u.e.features & KVM_SREGS_EXP) {

            env->spr[SPR_BOOKE_EPR] = sregs.u.e.epr;

        }

        if (sregs.u.e.features & KVM_SREGS_E_PD) {

            env->spr[SPR_BOOKE_EPLC] = sregs.u.e.eplc;

            env->spr[SPR_BOOKE_EPSC] = sregs.u.e.epsc;

        }

        if (sregs.u.e.impl_id == KVM_SREGS_E_IMPL_FSL) {

            env->spr[SPR_E500_SVR] = sregs.u.e.impl.fsl.svr;

            env->spr[SPR_Exxx_MCAR] = sregs.u.e.impl.fsl.mcar;

            env->spr[SPR_HID0] = sregs.u.e.impl.fsl.hid0;

            if (sregs.u.e.impl.fsl.features & KVM_SREGS_E_FSL_PIDn) {

                env->spr[SPR_BOOKE_PID1] = sregs.u.e.impl.fsl.pid1;

                env->spr[SPR_BOOKE_PID2] = sregs.u.e.impl.fsl.pid2;

            }

        }

    }

    if (cap_segstate) {

        ret = kvm_vcpu_ioctl(cs, KVM_GET_SREGS, &sregs);

        if (ret < 0) {

            return ret;

        }

        ppc_store_sdr1(env, sregs.u.s.sdr1);

        /* Sync SLB */

#ifdef TARGET_PPC64

        /*

         * The packed SLB array we get from KVM_GET_SREGS only contains

         * information about valid entries. So we flush our internal

         * copy to get rid of stale ones, then put all valid SLB entries

         * back in.

         */

        memset(env->slb, 0, sizeof(env->slb));

        for (i = 0; i < ARRAY_SIZE(env->slb); i++) {

            target_ulong rb = sregs.u.s.ppc64.slb[i].slbe;

            target_ulong rs = sregs.u.s.ppc64.slb[i].slbv;

            /*

             * Only restore valid entries

             */

            if (rb & SLB_ESID_V) {

                ppc_store_slb(env, rb, rs);

            }

        }

#endif

        /* Sync SRs */

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

            env->sr[i] = sregs.u.s.ppc32.sr[i];

        }

        /* Sync BATs */

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

            env->DBAT[0][i] = sregs.u.s.ppc32.dbat[i] & 0xffffffff;

            env->DBAT[1][i] = sregs.u.s.ppc32.dbat[i] >> 32;

            env->IBAT[0][i] = sregs.u.s.ppc32.ibat[i] & 0xffffffff;

            env->IBAT[1][i] = sregs.u.s.ppc32.ibat[i] >> 32;

        }

    }

    if (cap_hior) {

        kvm_get_one_spr(cs, KVM_REG_PPC_HIOR, SPR_HIOR);

    }

    if (cap_one_reg) {

        int i;

        /* We deliberately ignore errors here, for kernels which have

         * the ONE_REG calls, but don't support the specific

         * registers, there's a reasonable chance things will still

         * work, at least until we try to migrate. */

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

            uint64_t id = env->spr_cb[i].one_reg_id;

            if (id != 0) {

                kvm_get_one_spr(cs, id, i);

            }

        }

#ifdef TARGET_PPC64

        if (cap_papr) {

            if (kvm_get_vpa(cs) < 0) {

                DPRINTF("Warning: Unable to get VPA information from KVM\n");

            }

        }

#endif

    }

    return 0;

}


static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom)

{

    int i;

    int width;

    int height;

    int display_matrix[3][3];

    AVStream *st;

    MOVStreamContext *sc;

    int version;

    int flags;

    if (c->fc->nb_streams < 1)

        return 0;

    st = c->fc->streams[c->fc->nb_streams-1];

    sc = st->priv_data;

    version = avio_r8(pb);

    flags = avio_rb24(pb);

    st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0;

    if (version == 1) {

        avio_rb64(pb);

        avio_rb64(pb);

    } else {

        avio_rb32(pb); /* creation time */

        avio_rb32(pb); /* modification time */

    }

    st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/

    avio_rb32(pb); /* reserved */

    /* highlevel (considering edits) duration in movie timebase */

    (version == 1) ? avio_rb64(pb) : avio_rb32(pb);

    avio_rb32(pb); /* reserved */

    avio_rb32(pb); /* reserved */

    avio_rb16(pb); /* layer */

    avio_rb16(pb); /* alternate group */

    avio_rb16(pb); /* volume */

    avio_rb16(pb); /* reserved */

    //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2)

    // they're kept in fixed point format through all calculations

    // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX

    // side data, but the scale factor is not needed to calculate aspect ratio

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

        display_matrix[i][0] = avio_rb32(pb);   // 16.16 fixed point

        display_matrix[i][1] = avio_rb32(pb);   // 16.16 fixed point

        display_matrix[i][2] = avio_rb32(pb);   //  2.30 fixed point

    }

    width = avio_rb32(pb);       // 16.16 fixed point track width

    height = avio_rb32(pb);      // 16.16 fixed point track height

    sc->width = width >> 16;

    sc->height = height >> 16;

    // save the matrix and add rotate metadata when it is not the default

    // identity

    if (display_matrix[0][0] != (1 << 16) ||

        display_matrix[1][1] != (1 << 16) ||

        display_matrix[2][2] != (1 << 30) ||

        display_matrix[0][1] || display_matrix[0][2] ||

        display_matrix[1][0] || display_matrix[1][2] ||

        display_matrix[2][0] || display_matrix[2][1]) {

        int i, j;

        double rotate;

        av_freep(&sc->display_matrix);

        sc->display_matrix = av_malloc(sizeof(int32_t) * 9);

        if (!sc->display_matrix)

            return AVERROR(ENOMEM);

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

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

                sc->display_matrix[i * 3 + j] = display_matrix[j][i];

        rotate = av_display_rotation_get(sc->display_matrix);

        if (!isnan(rotate)) {

            char rotate_buf[64];

            rotate = -rotate;

            if (rotate < 0) // for backward compatibility

                rotate += 360;

            snprintf(rotate_buf, sizeof(rotate_buf), "%g", rotate);

            av_dict_set(&st->metadata, "rotate", rotate_buf, 0);

        }

    }

    // transform the display width/height according to the matrix

    // to keep the same scale, use [width height 1<<16]

    if (width && height && sc->display_matrix) {

        double disp_transform[2];

#define SQR(a) ((a)*(double)(a))

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

            disp_transform[i] = sqrt(SQR(display_matrix[i][0]) + SQR(display_matrix[i][1]));

        if (disp_transform[0] > 0 && disp_transform[1] > 0 &&

            fabs((disp_transform[0] / disp_transform[1]) - 1.0) > 0.01)

            st->sample_aspect_ratio = av_d2q(

                disp_transform[0] / disp_transform[1],

                INT_MAX);

    }

    return 0;

}


int ff_mjpeg_find_marker(MJpegDecodeContext *s,

                         const uint8_t **buf_ptr, const uint8_t *buf_end,

                         const uint8_t **unescaped_buf_ptr,

                         int *unescaped_buf_size)

{

    int start_code;

    start_code = find_marker(buf_ptr, buf_end);

    av_fast_padded_malloc(&s->buffer, &s->buffer_size, buf_end - *buf_ptr);

    if (!s->buffer)

        return AVERROR(ENOMEM);

    /* unescape buffer of SOS, use special treatment for JPEG-LS */

    if (start_code == SOS && !s->ls) {

        const uint8_t *src = *buf_ptr;

        uint8_t *dst = s->buffer;

        while (src < buf_end) {

            uint8_t x = *(src++);

            *(dst++) = x;

            if (s->avctx->codec_id != AV_CODEC_ID_THP) {

                if (x == 0xff) {

                    while (src < buf_end && x == 0xff)

                        x = *(src++);

                    if (x >= 0xd0 && x <= 0xd7)

                        *(dst++) = x;

                    else if (x)

                        break;

                }

            }

        }

        *unescaped_buf_ptr  = s->buffer;

        *unescaped_buf_size = dst - s->buffer;

        memset(s->buffer + *unescaped_buf_size, 0,

               AV_INPUT_BUFFER_PADDING_SIZE);

        av_log(s->avctx, AV_LOG_DEBUG, "escaping removed %"PTRDIFF_SPECIFIER" bytes\n",

               (buf_end - *buf_ptr) - (dst - s->buffer));

    } else if (start_code == SOS && s->ls) {

        const uint8_t *src = *buf_ptr;

        uint8_t *dst  = s->buffer;

        int bit_count = 0;

        int t = 0, b = 0;

        PutBitContext pb;

        /* find marker */

        while (src + t < buf_end) {

            uint8_t x = src[t++];

            if (x == 0xff) {

                while ((src + t < buf_end) && x == 0xff)

                    x = src[t++];

                if (x & 0x80) {

                    t -= FFMIN(2, t);

                    break;

                }

            }

        }

        bit_count = t * 8;

        init_put_bits(&pb, dst, t);

        /* unescape bitstream */

        while (b < t) {

            uint8_t x = src[b++];

            put_bits(&pb, 8, x);

            if (x == 0xFF) {

                x = src[b++];

                if (x & 0x80) {

                    av_log(s->avctx, AV_LOG_WARNING, "Invalid escape sequence\n");

                    x &= 0x7f;

                }

                put_bits(&pb, 7, x);

                bit_count--;

            }

        }

        flush_put_bits(&pb);

        *unescaped_buf_ptr  = dst;

        *unescaped_buf_size = (bit_count + 7) >> 3;

        memset(s->buffer + *unescaped_buf_size, 0,

               AV_INPUT_BUFFER_PADDING_SIZE);

    } else {

        *unescaped_buf_ptr  = *buf_ptr;

        *unescaped_buf_size = buf_end - *buf_ptr;

    }

    return start_code;

}


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

                                unsigned int size)

{

    rc4030State *s = opaque;

    /* write memory */

    memcpy(memory_region_get_ram_ptr(&s->dma_tt) + addr, &data, size);

    /* update dma address space (only if frame field has been written) */

    if (addr % sizeof(dma_pagetable_entry) == 0) {

        int index = addr / sizeof(dma_pagetable_entry);

        memory_region_transaction_begin();

        rc4030_dma_as_update_one(s, index, (uint32_t)data);

        memory_region_transaction_commit();

    }

}


static int parse_picture_segment(AVCodecContext *avctx,

                                  const uint8_t *buf, int buf_size)

{

    PGSSubContext *ctx = avctx->priv_data;

    uint8_t sequence_desc;

    unsigned int rle_bitmap_len, width, height;

    uint16_t picture_id;

    if (buf_size <= 4)

        return -1;

    buf_size -= 4;

    picture_id = bytestream_get_be16(&buf);

    /* skip 1 unknown byte: Version Number */

    buf++;

    /* Read the Sequence Description to determine if start of RLE data or appended to previous RLE */

    sequence_desc = bytestream_get_byte(&buf);

    if (!(sequence_desc & 0x80)) {

        /* Additional RLE data */

        if (buf_size > ctx->pictures[picture_id].rle_remaining_len)

            return -1;

        memcpy(ctx->pictures[picture_id].rle + ctx->pictures[picture_id].rle_data_len, buf, buf_size);

        ctx->pictures[picture_id].rle_data_len += buf_size;

        ctx->pictures[picture_id].rle_remaining_len -= buf_size;

        return 0;

    }

    if (buf_size <= 7)

        return -1;

    buf_size -= 7;

    /* Decode rle bitmap length, stored size includes width/height data */

    rle_bitmap_len = bytestream_get_be24(&buf) - 2*2;

    /* Get bitmap dimensions from data */

    width  = bytestream_get_be16(&buf);

    height = bytestream_get_be16(&buf);

    /* Make sure the bitmap is not too large */

    if (avctx->width < width || avctx->height < height) {

        av_log(avctx, AV_LOG_ERROR, "Bitmap dimensions larger than video.\n");

        return -1;

    }

    if (buf_size > rle_bitmap_len) {

        av_log(avctx, AV_LOG_ERROR, "too much RLE data\n");

        return AVERROR_INVALIDDATA;

    }

    ctx->pictures[picture_id].w = width;

    ctx->pictures[picture_id].h = height;

    av_fast_malloc(&ctx->pictures[picture_id].rle, &ctx->pictures[picture_id].rle_buffer_size, rle_bitmap_len);

    if (!ctx->pictures[picture_id].rle)

        return -1;

    memcpy(ctx->pictures[picture_id].rle, buf, buf_size);

    ctx->pictures[picture_id].rle_data_len      = buf_size;

    ctx->pictures[picture_id].rle_remaining_len = rle_bitmap_len - buf_size;

    return 0;

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    dc->props = sun4m_fdc_properties;

    set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);

}


static int64_t get_pts(const char *buf, int *duration)

{

    int i, hour, min, sec, hsec;

    int he, me, se, mse;

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

        int64_t start, end;

        if (sscanf(buf, "%d:%2d:%2d%*1[,.]%3d --> %d:%2d:%2d%*1[,.]%3d",

                   &hour, &min, &sec, &hsec, &he, &me, &se, &mse) == 8) {

            min += 60*hour;

            sec += 60*min;

            start = sec*1000+hsec;

            me += 60*he;

            se += 60*me;

            end = se*1000+mse;

            *duration = end - start;

            return start;

        }

        buf += strcspn(buf, "\n") + 1;

    }

    return AV_NOPTS_VALUE;

}


void qemu_savevm_state_begin(QEMUFile *f,

                             const MigrationParams *params)

{

    SaveStateEntry *se;

    int ret;

    trace_savevm_state_begin();

    QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {

        if (!se->ops || !se->ops->set_params) {

            continue;

        }

        se->ops->set_params(params, se->opaque);

    }

    QTAILQ_FOREACH(se, &savevm_state.handlers, entry) {

        if (!se->ops || !se->ops->save_live_setup) {

            continue;

        }

        if (se->ops && se->ops->is_active) {

            if (!se->ops->is_active(se->opaque)) {

                continue;

            }

        }

        save_section_header(f, se, QEMU_VM_SECTION_START);

        ret = se->ops->save_live_setup(f, se->opaque);

        if (ret < 0) {

            qemu_file_set_error(f, ret);

            break;

        }

    }

}


static int gd_vc_chr_write(CharDriverState *chr, const uint8_t *buf, int len)

{

    VirtualConsole *vc = chr->opaque;

    return vc ? write(vc->fd, buf, len) : len;

}


int av_parse_color(uint8_t *rgba_color, const char *color_string, void *log_ctx)

{

    if (!strcasecmp(color_string, "random") || !strcasecmp(color_string, "bikeshed")) {

        int rgba = av_get_random_seed();

        rgba_color[0] = rgba >> 24;

        rgba_color[1] = rgba >> 16;

        rgba_color[2] = rgba >> 8;

        rgba_color[3] = rgba;

    } else

    if (!strncmp(color_string, "0x", 2)) {

        char *tail;

        int len = strlen(color_string);

        unsigned int rgba = strtoul(color_string, &tail, 16);

        if (*tail || (len != 8 && len != 10)) {

            av_log(log_ctx, AV_LOG_ERROR, "Invalid 0xRRGGBB[AA] color string: '%s'\n", color_string);

            return AVERROR(EINVAL);

        }

        if (len == 10) {

            rgba_color[3] = rgba;

            rgba >>= 8;

        }

        rgba_color[0] = rgba >> 16;

        rgba_color[1] = rgba >> 8;

        rgba_color[2] = rgba;

    } else {

        const ColorEntry *entry = bsearch(color_string,

                                          color_table,

                                          FF_ARRAY_ELEMS(color_table),

                                          sizeof(ColorEntry),

                                          color_table_compare);

        if (!entry) {

            av_log(log_ctx, AV_LOG_ERROR, "Cannot find color '%s'\n", color_string);

            return AVERROR(EINVAL);

        }

        memcpy(rgba_color, entry->rgba_color, 4);

    }

    return 0;

}


av_cold int ff_mjpeg_encode_init(MpegEncContext *s)

{

    MJpegContext *m;

    av_assert0(s->slice_context_count == 1);

    if (s->width > 65500 || s->height > 65500) {

        av_log(s, AV_LOG_ERROR, "JPEG does not support resolutions above 65500x65500\n");

        return AVERROR(EINVAL);

    }

    m = av_malloc(sizeof(MJpegContext));

    if (!m)

        return AVERROR(ENOMEM);

    s->min_qcoeff=-1023;

    s->max_qcoeff= 1023;

    // Build default Huffman tables.

    // These may be overwritten later with more optimal Huffman tables, but

    // they are needed at least right now for some processes like trellis.

    ff_mjpeg_build_huffman_codes(m->huff_size_dc_luminance,

                                 m->huff_code_dc_luminance,

                                 avpriv_mjpeg_bits_dc_luminance,

                                 avpriv_mjpeg_val_dc);

    ff_mjpeg_build_huffman_codes(m->huff_size_dc_chrominance,

                                 m->huff_code_dc_chrominance,

                                 avpriv_mjpeg_bits_dc_chrominance,

                                 avpriv_mjpeg_val_dc);

    ff_mjpeg_build_huffman_codes(m->huff_size_ac_luminance,

                                 m->huff_code_ac_luminance,

                                 avpriv_mjpeg_bits_ac_luminance,

                                 avpriv_mjpeg_val_ac_luminance);

    ff_mjpeg_build_huffman_codes(m->huff_size_ac_chrominance,

                                 m->huff_code_ac_chrominance,

                                 avpriv_mjpeg_bits_ac_chrominance,

                                 avpriv_mjpeg_val_ac_chrominance);

    ff_init_uni_ac_vlc(m->huff_size_ac_luminance,   m->uni_ac_vlc_len);

    ff_init_uni_ac_vlc(m->huff_size_ac_chrominance, m->uni_chroma_ac_vlc_len);

    s->intra_ac_vlc_length      =

    s->intra_ac_vlc_last_length = m->uni_ac_vlc_len;

    s->intra_chroma_ac_vlc_length      =

    s->intra_chroma_ac_vlc_last_length = m->uni_chroma_ac_vlc_len;

    // Buffers start out empty.

    m->huff_ncode = 0;

    s->mjpeg_ctx = m;

    return alloc_huffman(s);

}


void fft_calc_altivec(FFTContext *s, FFTComplex *z)

{

POWERPC_TBL_DECLARE(altivec_fft_num, s->nbits >= 6);

#ifdef ALTIVEC_USE_REFERENCE_C_CODE

    int ln = s->nbits;

    int	j, np, np2;

    int	nblocks, nloops;

    register FFTComplex *p, *q;

    FFTComplex *exptab = s->exptab;

    int l;

    FFTSample tmp_re, tmp_im;

POWERPC_TBL_START_COUNT(altivec_fft_num, s->nbits >= 6);

    np = 1 << ln;

    /* pass 0 */

    p=&z[0];

    j=(np >> 1);

    do {

        BF(p[0].re, p[0].im, p[1].re, p[1].im,

           p[0].re, p[0].im, p[1].re, p[1].im);

        p+=2;

    } while (--j != 0);

    /* pass 1 */

    p=&z[0];

    j=np >> 2;

    if (s->inverse) {

        do {

            BF(p[0].re, p[0].im, p[2].re, p[2].im,

               p[0].re, p[0].im, p[2].re, p[2].im);

            BF(p[1].re, p[1].im, p[3].re, p[3].im,

               p[1].re, p[1].im, -p[3].im, p[3].re);

            p+=4;

        } while (--j != 0);

    } else {

        do {

            BF(p[0].re, p[0].im, p[2].re, p[2].im,

               p[0].re, p[0].im, p[2].re, p[2].im);

            BF(p[1].re, p[1].im, p[3].re, p[3].im,

               p[1].re, p[1].im, p[3].im, -p[3].re);

            p+=4;

        } while (--j != 0);

    }

    /* pass 2 .. ln-1 */

    nblocks = np >> 3;

    nloops = 1 << 2;

    np2 = np >> 1;

    do {

        p = z;

        q = z + nloops;

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

            BF(p->re, p->im, q->re, q->im,

               p->re, p->im, q->re, q->im);

            p++;

            q++;

            for(l = nblocks; l < np2; l += nblocks) {

                CMUL(tmp_re, tmp_im, exptab[l].re, exptab[l].im, q->re, q->im);

                BF(p->re, p->im, q->re, q->im,

                   p->re, p->im, tmp_re, tmp_im);

                p++;

                q++;

            }

            p += nloops;

            q += nloops;

        }

        nblocks = nblocks >> 1;

        nloops = nloops << 1;

    } while (nblocks != 0);

POWERPC_TBL_STOP_COUNT(altivec_fft_num, s->nbits >= 6);

#else /* ALTIVEC_USE_REFERENCE_C_CODE */

#ifdef CONFIG_DARWIN

    register const vector float vczero = (const vector float)(0.);

#else

    register const vector float vczero = (const vector float){0.,0.,0.,0.};

#endif

    int ln = s->nbits;

    int	j, np, np2;

    int	nblocks, nloops;

    register FFTComplex *p, *q;

    FFTComplex *cptr, *cptr1;

    int k;

POWERPC_TBL_START_COUNT(altivec_fft_num, s->nbits >= 6);

    np = 1 << ln;

    {

        vector float *r, a, b, a1, c1, c2;

        r = (vector float *)&z[0];

        c1 = vcii(p,p,n,n);

        if (s->inverse)

            {

                c2 = vcii(p,p,n,p);

            }

        else

            {

                c2 = vcii(p,p,p,n);

            }

        j = (np >> 2);

        do {

            a = vec_ld(0, r);

            a1 = vec_ld(sizeof(vector float), r);

            b = vec_perm(a,a,vcprmle(1,0,3,2));

            a = vec_madd(a,c1,b);

            /* do the pass 0 butterfly */

            b = vec_perm(a1,a1,vcprmle(1,0,3,2));

            b = vec_madd(a1,c1,b);

            /* do the pass 0 butterfly */

            /* multiply third by -i */

            b = vec_perm(b,b,vcprmle(2,3,1,0));

            /* do the pass 1 butterfly */

            vec_st(vec_madd(b,c2,a), 0, r);

            vec_st(vec_nmsub(b,c2,a), sizeof(vector float), r);

            r += 2;

        } while (--j != 0);

    }

    /* pass 2 .. ln-1 */

    nblocks = np >> 3;

    nloops = 1 << 2;

    np2 = np >> 1;

    cptr1 = s->exptab1;

    do {

        p = z;

        q = z + nloops;

        j = nblocks;

        do {

            cptr = cptr1;

            k = nloops >> 1;

            do {

                vector float a,b,c,t1;

                a = vec_ld(0, (float*)p);

                b = vec_ld(0, (float*)q);

                /* complex mul */

                c = vec_ld(0, (float*)cptr);

                /*  cre*re cim*re */

                t1 = vec_madd(c, vec_perm(b,b,vcprmle(2,2,0,0)),vczero);

                c = vec_ld(sizeof(vector float), (float*)cptr);

                /*  -cim*im cre*im */

                b = vec_madd(c, vec_perm(b,b,vcprmle(3,3,1,1)),t1);

                /* butterfly */

                vec_st(vec_add(a,b), 0, (float*)p);

                vec_st(vec_sub(a,b), 0, (float*)q);

                p += 2;

                q += 2;

                cptr += 4;

            } while (--k);

            p += nloops;

            q += nloops;

        } while (--j);

        cptr1 += nloops * 2;

        nblocks = nblocks >> 1;

        nloops = nloops << 1;

    } while (nblocks != 0);

POWERPC_TBL_STOP_COUNT(altivec_fft_num, s->nbits >= 6);

#endif /* ALTIVEC_USE_REFERENCE_C_CODE */

}


Aml *aml_and(Aml *arg1, Aml *arg2)

{

    Aml *var = aml_opcode(0x7B /* AndOp */);

    aml_append(var, arg1);

    aml_append(var, arg2);

    build_append_byte(var->buf, 0x00 /* NullNameOp */);

    return var;

}


static QObject *parser_context_peek_token(JSONParserContext *ctxt)

{

    assert(!g_queue_is_empty(ctxt->buf));

    return g_queue_peek_head(ctxt->buf);

}


static int nbd_handle_reply_err(QIOChannel *ioc, nbd_opt_reply *reply,

                                Error **errp)

{

    char *msg = NULL;

    int result = -1;

    if (!(reply->type & (1 << 31))) {

        return 1;

    }

    if (reply->length) {

        if (reply->length > NBD_MAX_BUFFER_SIZE) {

            error_setg(errp, "server's error message is too long");

            goto cleanup;

        }

        msg = g_malloc(reply->length + 1);

        if (read_sync(ioc, msg, reply->length, errp) < 0) {

            error_prepend(errp, "failed to read option error message");

            goto cleanup;

        }

        msg[reply->length] = '\0';

    }

    switch (reply->type) {

    case NBD_REP_ERR_UNSUP:

        TRACE("server doesn't understand request %" PRIx32

              ", attempting fallback", reply->option);

        result = 0;

        goto cleanup;

    case NBD_REP_ERR_POLICY:

        error_setg(errp, "Denied by server for option %" PRIx32,

                   reply->option);

        break;

    case NBD_REP_ERR_INVALID:

        error_setg(errp, "Invalid data length for option %" PRIx32,

                   reply->option);

        break;

    case NBD_REP_ERR_PLATFORM:

        error_setg(errp, "Server lacks support for option %" PRIx32,

                   reply->option);

        break;

    case NBD_REP_ERR_TLS_REQD:

        error_setg(errp, "TLS negotiation required before option %" PRIx32,

                   reply->option);

        break;

    case NBD_REP_ERR_SHUTDOWN:

        error_setg(errp, "Server shutting down before option %" PRIx32,

                   reply->option);

        break;

    default:

        error_setg(errp, "Unknown error code when asking for option %" PRIx32,

                   reply->option);

        break;

    }

    if (msg) {

        error_append_hint(errp, "%s\n", msg);

    }

 cleanup:

    g_free(msg);

    if (result < 0) {

        nbd_send_opt_abort(ioc);

    }

    return result;

}


static void gen_jmp_tb(DisasContext *s, target_ulong eip, int tb_num)

{

    gen_update_cc_op(s);

    set_cc_op(s, CC_OP_DYNAMIC);

    if (s->jmp_opt) {

        gen_goto_tb(s, tb_num, eip);

        s->is_jmp = DISAS_TB_JUMP;

    } else {

        gen_jmp_im(eip);

        gen_eob(s);

    }

}


void helper_movl_sreg_reg (uint32_t sreg, uint32_t reg)

{

	uint32_t srs;

	srs = env->pregs[PR_SRS];

	srs &= 3;

	env->sregs[srs][sreg] = env->regs[reg];

#if !defined(CONFIG_USER_ONLY)

	if (srs == 1 || srs == 2) {

		if (sreg == 6) {

			/* Writes to tlb-hi write to mm_cause as a side

			   effect.  */

			env->sregs[SFR_RW_MM_TLB_HI] = env->regs[reg];

			env->sregs[SFR_R_MM_CAUSE] = env->regs[reg];

		}

		else if (sreg == 5) {

			uint32_t set;

			uint32_t idx;

			uint32_t lo, hi;

			uint32_t vaddr;

			int tlb_v;

			idx = set = env->sregs[SFR_RW_MM_TLB_SEL];

			set >>= 4;

			set &= 3;

			idx &= 15;

			/* We've just made a write to tlb_lo.  */

			lo = env->sregs[SFR_RW_MM_TLB_LO];

			/* Writes are done via r_mm_cause.  */

			hi = env->sregs[SFR_R_MM_CAUSE];

			vaddr = EXTRACT_FIELD(env->tlbsets[srs-1][set][idx].hi,

					      13, 31);

			vaddr <<= TARGET_PAGE_BITS;

			tlb_v = EXTRACT_FIELD(env->tlbsets[srs-1][set][idx].lo,

					    3, 3);

			env->tlbsets[srs - 1][set][idx].lo = lo;

			env->tlbsets[srs - 1][set][idx].hi = hi;

			D_LOG("tlb flush vaddr=%x v=%d pc=%x\n",

				  vaddr, tlb_v, env->pc);

			tlb_flush_page(env, vaddr);

		}

	}

#endif

}