static int decode_gop_header(IVI5DecContext *ctx, AVCodecContext *avctx)

{

    int             result, i, p, tile_size, pic_size_indx, mb_size, blk_size;

    int             quant_mat, blk_size_changed = 0;

    IVIBandDesc     *band, *band1, *band2;

    IVIPicConfig    pic_conf;

    ctx->gop_flags = get_bits(&ctx->gb, 8);

    ctx->gop_hdr_size = (ctx->gop_flags & 1) ? get_bits(&ctx->gb, 16) : 0;

    if (ctx->gop_flags & IVI5_IS_PROTECTED)

        ctx->lock_word = get_bits_long(&ctx->gb, 32);

    tile_size = (ctx->gop_flags & 0x40) ? 64 << get_bits(&ctx->gb, 2) : 0;

    if (tile_size > 256) {

        av_log(avctx, AV_LOG_ERROR, "Invalid tile size: %d\n", tile_size);

        return -1;

    }

    /* decode number of wavelet bands */

    /* num_levels * 3 + 1 */

    pic_conf.luma_bands   = get_bits(&ctx->gb, 2) * 3 + 1;

    pic_conf.chroma_bands = get_bits1(&ctx->gb)   * 3 + 1;

    ctx->is_scalable = pic_conf.luma_bands != 1 || pic_conf.chroma_bands != 1;

    if (ctx->is_scalable && (pic_conf.luma_bands != 4 || pic_conf.chroma_bands != 1)) {

        av_log(avctx, AV_LOG_ERROR, "Scalability: unsupported subdivision! Luma bands: %d, chroma bands: %d\n",

               pic_conf.luma_bands, pic_conf.chroma_bands);

        return -1;

    }

    pic_size_indx = get_bits(&ctx->gb, 4);

    if (pic_size_indx == IVI5_PIC_SIZE_ESC) {

        pic_conf.pic_height = get_bits(&ctx->gb, 13);

        pic_conf.pic_width  = get_bits(&ctx->gb, 13);

    } else {

        pic_conf.pic_height = ivi5_common_pic_sizes[pic_size_indx * 2 + 1] << 2;

        pic_conf.pic_width  = ivi5_common_pic_sizes[pic_size_indx * 2    ] << 2;

    }

    if (ctx->gop_flags & 2) {

        av_log(avctx, AV_LOG_ERROR, "YV12 picture format not supported!\n");

        return -1;

    }

    pic_conf.chroma_height = (pic_conf.pic_height + 3) >> 2;

    pic_conf.chroma_width  = (pic_conf.pic_width  + 3) >> 2;

    if (!tile_size) {

        pic_conf.tile_height = pic_conf.pic_height;

        pic_conf.tile_width  = pic_conf.pic_width;

    } else {

        pic_conf.tile_height = pic_conf.tile_width = tile_size;

    }

    /* check if picture layout was changed and reallocate buffers */

    if (ivi_pic_config_cmp(&pic_conf, &ctx->pic_conf)) {

        result = ff_ivi_init_planes(ctx->planes, &pic_conf);

        if (result) {

            av_log(avctx, AV_LOG_ERROR, "Couldn't reallocate color planes!\n");

            return -1;

        }

        ctx->pic_conf = pic_conf;

        blk_size_changed = 1; /* force reallocation of the internal structures */

    }

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

        for (i = 0; i < (!p ? pic_conf.luma_bands : pic_conf.chroma_bands); i++) {

            band = &ctx->planes[p].bands[i];

            band->is_halfpel = get_bits1(&ctx->gb);

            mb_size  = get_bits1(&ctx->gb);

            blk_size = 8 >> get_bits1(&ctx->gb);

            mb_size  = blk_size << !mb_size;

            blk_size_changed = mb_size != band->mb_size || blk_size != band->blk_size;

            if (blk_size_changed) {

                band->mb_size  = mb_size;

                band->blk_size = blk_size;

            }

            if (get_bits1(&ctx->gb)) {

                av_log(avctx, AV_LOG_ERROR, "Extended transform info encountered!\n");

                return -1;

            }

            /* select transform function and scan pattern according to plane and band number */

            switch ((p << 2) + i) {

            case 0:

                band->inv_transform = ff_ivi_inverse_slant_8x8;

                band->dc_transform  = ff_ivi_dc_slant_2d;

                band->scan          = ff_zigzag_direct;

                break;

            case 1:

                band->inv_transform = ff_ivi_row_slant8;

                band->dc_transform  = ff_ivi_dc_row_slant;

                band->scan          = ff_ivi_vertical_scan_8x8;

                break;

            case 2:

                band->inv_transform = ff_ivi_col_slant8;

                band->dc_transform  = ff_ivi_dc_col_slant;

                band->scan          = ff_ivi_horizontal_scan_8x8;

                break;

            case 3:

                band->inv_transform = ff_ivi_put_pixels_8x8;

                band->dc_transform  = ff_ivi_put_dc_pixel_8x8;

                band->scan          = ff_ivi_horizontal_scan_8x8;

                break;

            case 4:

                band->inv_transform = ff_ivi_inverse_slant_4x4;

                band->dc_transform  = ff_ivi_dc_slant_2d;

                band->scan          = ff_ivi_direct_scan_4x4;

                break;

            }

            band->is_2d_trans = band->inv_transform == ff_ivi_inverse_slant_8x8 ||

                                band->inv_transform == ff_ivi_inverse_slant_4x4;

            /* select dequant matrix according to plane and band number */

            if (!p) {

                quant_mat = (pic_conf.luma_bands > 1) ? i+1 : 0;

            } else {

                quant_mat = 5;

            }

            if (band->blk_size == 8) {

                band->intra_base  = &ivi5_base_quant_8x8_intra[quant_mat][0];

                band->inter_base  = &ivi5_base_quant_8x8_inter[quant_mat][0];

                band->intra_scale = &ivi5_scale_quant_8x8_intra[quant_mat][0];

                band->inter_scale = &ivi5_scale_quant_8x8_inter[quant_mat][0];

            } else {

                band->intra_base  = ivi5_base_quant_4x4_intra;

                band->inter_base  = ivi5_base_quant_4x4_inter;

                band->intra_scale = ivi5_scale_quant_4x4_intra;

                band->inter_scale = ivi5_scale_quant_4x4_inter;

            }

            if (get_bits(&ctx->gb, 2)) {

                av_log(avctx, AV_LOG_ERROR, "End marker missing!\n");

                return -1;

            }

        }

    }

    /* copy chroma parameters into the 2nd chroma plane */

    for (i = 0; i < pic_conf.chroma_bands; i++) {

        band1 = &ctx->planes[1].bands[i];

        band2 = &ctx->planes[2].bands[i];

        band2->width         = band1->width;

        band2->height        = band1->height;

        band2->mb_size       = band1->mb_size;

        band2->blk_size      = band1->blk_size;

        band2->is_halfpel    = band1->is_halfpel;

        band2->intra_base    = band1->intra_base;

        band2->inter_base    = band1->inter_base;

        band2->intra_scale   = band1->intra_scale;

        band2->inter_scale   = band1->inter_scale;

        band2->scan          = band1->scan;

        band2->inv_transform = band1->inv_transform;

        band2->dc_transform  = band1->dc_transform;

        band2->is_2d_trans   = band1->is_2d_trans;

    }

    /* reallocate internal structures if needed */

    if (blk_size_changed) {

        result = ff_ivi_init_tiles(ctx->planes, pic_conf.tile_width,

                                   pic_conf.tile_height);

        if (result) {

            av_log(avctx, AV_LOG_ERROR,

                   "Couldn't reallocate internal structures!\n");

            return -1;

        }

    }

    if (ctx->gop_flags & 8) {

        if (get_bits(&ctx->gb, 3)) {

            av_log(avctx, AV_LOG_ERROR, "Alignment bits are not zero!\n");

            return -1;

        }

        if (get_bits1(&ctx->gb))

            skip_bits_long(&ctx->gb, 24); /* skip transparency fill color */

    }

    align_get_bits(&ctx->gb);

    skip_bits(&ctx->gb, 23); /* FIXME: unknown meaning */

    /* skip GOP extension if any */

    if (get_bits1(&ctx->gb)) {

        do {

            i = get_bits(&ctx->gb, 16);

        } while (i & 0x8000);

    }

    align_get_bits(&ctx->gb);

    return 0;

}


static int build_huff(const uint8_t *src, VLC *vlc, int *fsym)

{

    int i;

    HuffEntry he[256];

    int last;

    uint32_t codes[256];

    uint8_t bits[256];

    uint8_t syms[256];

    uint32_t code;

    *fsym = -1;

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

        he[i].sym = i;

        he[i].len = *src++;

    }

    qsort(he, 256, sizeof(*he), ff_ut_huff_cmp_len);

    if (!he[0].len) {

        *fsym = he[0].sym;

        return 0;

    }

    if (he[0].len > 32)

        return -1;

    last = 255;

    while (he[last].len == 255 && last)

        last--;

    code = 1;

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

        codes[i] = code >> (32 - he[i].len);

        bits[i]  = he[i].len;

        syms[i]  = he[i].sym;

        code += 0x80000000u >> (he[i].len - 1);

    }

    return ff_init_vlc_sparse(vlc, FFMIN(he[last].len, 11), last + 1,

                              bits,  sizeof(*bits),  sizeof(*bits),

                              codes, sizeof(*codes), sizeof(*codes),

                              syms,  sizeof(*syms),  sizeof(*syms), 0);

}


static int nist_read_header(AVFormatContext *s)

{

    char buffer[32], coding[32] = "pcm", format[32] = "01";

    int bps = 0, be = 0;

    int32_t header_size;

    AVStream *st;

    st = avformat_new_stream(s, NULL);

    if (!st)

        return AVERROR(ENOMEM);

    st->codec->codec_type = AVMEDIA_TYPE_AUDIO;

    ff_get_line(s->pb, buffer, sizeof(buffer));

    ff_get_line(s->pb, buffer, sizeof(buffer));

    sscanf(buffer, "%"SCNd32, &header_size);

    if (header_size <= 0)

        return AVERROR_INVALIDDATA;

    while (!url_feof(s->pb)) {

        ff_get_line(s->pb, buffer, sizeof(buffer));

        if (avio_tell(s->pb) >= header_size)

            return AVERROR_INVALIDDATA;

        if (!memcmp(buffer, "end_head", 8)) {

            if (!st->codec->bits_per_coded_sample)

                st->codec->bits_per_coded_sample = bps << 3;

            if (!av_strcasecmp(coding, "pcm")) {

                st->codec->codec_id = ff_get_pcm_codec_id(st->codec->bits_per_coded_sample,

                                                          0, be, 0xFFFF);

            } else if (!av_strcasecmp(coding, "alaw")) {

                st->codec->codec_id = AV_CODEC_ID_PCM_ALAW;

            } else if (!av_strcasecmp(coding, "ulaw") ||

                       !av_strcasecmp(coding, "mu-law")) {

                st->codec->codec_id = AV_CODEC_ID_PCM_MULAW;

            } else {

                avpriv_request_sample(s, "coding %s", coding);

            }

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

            st->codec->block_align = st->codec->bits_per_coded_sample * st->codec->channels / 8;

            if (avio_tell(s->pb) > header_size)

                return AVERROR_INVALIDDATA;

            avio_skip(s->pb, header_size - avio_tell(s->pb));

            return 0;

        } else if (!memcmp(buffer, "channel_count", 13)) {

            sscanf(buffer, "%*s %*s %"SCNd32, &st->codec->channels);

        } else if (!memcmp(buffer, "sample_byte_format", 18)) {

            sscanf(buffer, "%*s %*s %31s", format);

            if (!av_strcasecmp(format, "01")) {

                be = 0;

            } else if (!av_strcasecmp(format, "10")) {

                be = 1;

            } else if (av_strcasecmp(format, "1")) {

                avpriv_request_sample(s, "sample byte format %s", format);

                return AVERROR_PATCHWELCOME;

            }

        } else if (!memcmp(buffer, "sample_coding", 13)) {

            sscanf(buffer, "%*s %*s %31s", coding);

        } else if (!memcmp(buffer, "sample_count", 12)) {

            sscanf(buffer, "%*s %*s %"SCNd64, &st->duration);

        } else if (!memcmp(buffer, "sample_n_bytes", 14)) {

            sscanf(buffer, "%*s %*s %"SCNd32, &bps);

        } else if (!memcmp(buffer, "sample_rate", 11)) {

            sscanf(buffer, "%*s %*s %"SCNd32, &st->codec->sample_rate);

        } else if (!memcmp(buffer, "sample_sig_bits", 15)) {

            sscanf(buffer, "%*s %*s %"SCNd32, &st->codec->bits_per_coded_sample);

        } else {

            char key[32], value[32];

            if (sscanf(buffer, "%31s %*s %31s", key, value) == 3) {

                av_dict_set(&s->metadata, key, value, AV_DICT_APPEND);

            } else {

                av_log(s, AV_LOG_ERROR, "Failed to parse '%s' as metadata\n", buffer);

            }

        }

    }

    return AVERROR_EOF;

}


static int pcm_read_header(AVFormatContext *s)

{

    PCMAudioDemuxerContext *s1 = s->priv_data;

    AVStream *st;

    uint8_t *mime_type = NULL;

    st = avformat_new_stream(s, NULL);

    if (!st)

        return AVERROR(ENOMEM);

    st->codecpar->codec_type  = AVMEDIA_TYPE_AUDIO;

    st->codecpar->codec_id    = s->iformat->raw_codec_id;

    st->codecpar->sample_rate = s1->sample_rate;

    st->codecpar->channels    = s1->channels;

    av_opt_get(s->pb, "mime_type", AV_OPT_SEARCH_CHILDREN, &mime_type);

    if (mime_type && s->iformat->mime_type) {

        int rate = 0, channels = 0;

        size_t len = strlen(s->iformat->mime_type);

        if (!strncmp(s->iformat->mime_type, mime_type, len)) {

            uint8_t *options = mime_type + len;

            len = strlen(mime_type);

            while (options < mime_type + len) {

                options = strstr(options, ";");

                if (!options++)

                    break;

                if (!rate)

                    sscanf(options, " rate=%d",     &rate);

                if (!channels)

                    sscanf(options, " channels=%d", &channels);

            }

            if (rate <= 0) {

                av_log(s, AV_LOG_ERROR,

                       "Invalid sample_rate found in mime_type \"%s\"\n",

                       mime_type);

                return AVERROR_INVALIDDATA;

            }

            st->codecpar->sample_rate = rate;

            if (channels > 0)

                st->codecpar->channels = channels;

        }

    }

    st->codecpar->bits_per_coded_sample =

        av_get_bits_per_sample(st->codecpar->codec_id);

    av_assert0(st->codecpar->bits_per_coded_sample > 0);

    st->codecpar->block_align =

        st->codecpar->bits_per_coded_sample * st->codecpar->channels / 8;

    avpriv_set_pts_info(st, 64, 1, st->codecpar->sample_rate);

    return 0;

}


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

                              int *got_frame_ptr, AVPacket *avpkt)

{

    AMRContext *p = avctx->priv_data;        // pointer to private data

    const uint8_t *buf = avpkt->data;

    int buf_size       = avpkt->size;

    float *buf_out;                          // pointer to the output data buffer

    int i, subframe, ret;

    float fixed_gain_factor;

    AMRFixed fixed_sparse = {0};             // fixed vector up to anti-sparseness processing

    float spare_vector[AMR_SUBFRAME_SIZE];   // extra stack space to hold result from anti-sparseness processing

    float synth_fixed_gain;                  // the fixed gain that synthesis should use

    const float *synth_fixed_vector;         // pointer to the fixed vector that synthesis should use

    /* get output buffer */

    p->avframe.nb_samples = AMR_BLOCK_SIZE;

    if ((ret = avctx->get_buffer(avctx, &p->avframe)) < 0) {

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

        return ret;

    buf_out = (float *)p->avframe.data[0];

    p->cur_frame_mode = unpack_bitstream(p, buf, buf_size);

    if (p->cur_frame_mode == MODE_DTX) {

        av_log_missing_feature(avctx, "dtx mode", 1);

        return -1;

    if (p->cur_frame_mode == MODE_12k2) {

        lsf2lsp_5(p);

    } else

        lsf2lsp_3(p);

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

        ff_acelp_lspd2lpc(p->lsp[i], p->lpc[i], 5);

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

        const AMRNBSubframe *amr_subframe = &p->frame.subframe[subframe];

        decode_pitch_vector(p, amr_subframe, subframe);

        decode_fixed_sparse(&fixed_sparse, amr_subframe->pulses,

                            p->cur_frame_mode, subframe);

        // The fixed gain (section 6.1.3) depends on the fixed vector

        // (section 6.1.2), but the fixed vector calculation uses

        // pitch sharpening based on the on the pitch gain (section 6.1.3).

        // So the correct order is: pitch gain, pitch sharpening, fixed gain.

        decode_gains(p, amr_subframe, p->cur_frame_mode, subframe,

                     &fixed_gain_factor);

        pitch_sharpening(p, subframe, p->cur_frame_mode, &fixed_sparse);

        ff_set_fixed_vector(p->fixed_vector, &fixed_sparse, 1.0,

                            AMR_SUBFRAME_SIZE);

        p->fixed_gain[4] =

            ff_amr_set_fixed_gain(fixed_gain_factor,

                       ff_dot_productf(p->fixed_vector, p->fixed_vector,

                                       AMR_SUBFRAME_SIZE)/AMR_SUBFRAME_SIZE,

                       p->prediction_error,

                       energy_mean[p->cur_frame_mode], energy_pred_fac);

        // The excitation feedback is calculated without any processing such

        // as fixed gain smoothing. This isn't mentioned in the specification.

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

            p->excitation[i] *= p->pitch_gain[4];

        ff_set_fixed_vector(p->excitation, &fixed_sparse, p->fixed_gain[4],

                            AMR_SUBFRAME_SIZE);

        // In the ref decoder, excitation is stored with no fractional bits.

        // This step prevents buzz in silent periods. The ref encoder can

        // emit long sequences with pitch factor greater than one. This

        // creates unwanted feedback if the excitation vector is nonzero.

        // (e.g. test sequence T19_795.COD in 3GPP TS 26.074)

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

            p->excitation[i] = truncf(p->excitation[i]);

        // Smooth fixed gain.

        // The specification is ambiguous, but in the reference source, the

        // smoothed value is NOT fed back into later fixed gain smoothing.

        synth_fixed_gain = fixed_gain_smooth(p, p->lsf_q[subframe],

                                             p->lsf_avg, p->cur_frame_mode);

        synth_fixed_vector = anti_sparseness(p, &fixed_sparse, p->fixed_vector,

                                             synth_fixed_gain, spare_vector);

        if (synthesis(p, p->lpc[subframe], synth_fixed_gain,

                      synth_fixed_vector, &p->samples_in[LP_FILTER_ORDER], 0))

            // overflow detected -> rerun synthesis scaling pitch vector down

            // by a factor of 4, skipping pitch vector contribution emphasis

            // and adaptive gain control

            synthesis(p, p->lpc[subframe], synth_fixed_gain,

                      synth_fixed_vector, &p->samples_in[LP_FILTER_ORDER], 1);

        postfilter(p, p->lpc[subframe], buf_out + subframe * AMR_SUBFRAME_SIZE);

        // update buffers and history

        ff_clear_fixed_vector(p->fixed_vector, &fixed_sparse, AMR_SUBFRAME_SIZE);

        update_state(p);

    ff_acelp_apply_order_2_transfer_function(buf_out, buf_out, highpass_zeros,

                                             highpass_poles,

                                             highpass_gain * AMR_SAMPLE_SCALE,

                                             p->high_pass_mem, AMR_BLOCK_SIZE);

    /* Update averaged lsf vector (used for fixed gain smoothing).

     *

     * Note that lsf_avg should not incorporate the current frame's LSFs

     * for fixed_gain_smooth.

     * The specification has an incorrect formula: the reference decoder uses

     * qbar(n-1) rather than qbar(n) in section 6.1(4) equation 71. */

    ff_weighted_vector_sumf(p->lsf_avg, p->lsf_avg, p->lsf_q[3],

                            0.84, 0.16, LP_FILTER_ORDER);

    *got_frame_ptr   = 1;

    *(AVFrame *)data = p->avframe;

    /* return the amount of bytes consumed if everything was OK */

    return frame_sizes_nb[p->cur_frame_mode] + 1; // +7 for rounding and +8 for TOC


void bdrv_set_aio_context(BlockDriverState *bs, AioContext *new_context)
{
    bdrv_drain(bs); /* ensure there are no in-flight requests */
    bdrv_detach_aio_context(bs);
    /* This function executes in the old AioContext so acquire the new one in
     * case it runs in a different thread.
     */
    aio_context_acquire(new_context);
    bdrv_attach_aio_context(bs, new_context);
    aio_context_release(new_context);


static uint32_t fdctrl_read_data(FDCtrl *fdctrl)

{

    FDrive *cur_drv;

    uint32_t retval = 0;

    int pos;

    cur_drv = get_cur_drv(fdctrl);

    fdctrl->dsr &= ~FD_DSR_PWRDOWN;

    if (!(fdctrl->msr & FD_MSR_RQM) || !(fdctrl->msr & FD_MSR_DIO)) {

        FLOPPY_DPRINTF("error: controller not ready for reading\n");

        return 0;

    }

    pos = fdctrl->data_pos;

    if (fdctrl->msr & FD_MSR_NONDMA) {

        pos %= FD_SECTOR_LEN;

        if (pos == 0) {

            if (fdctrl->data_pos != 0)

                if (!fdctrl_seek_to_next_sect(fdctrl, cur_drv)) {

                    FLOPPY_DPRINTF("error seeking to next sector %d\n",

                                   fd_sector(cur_drv));

                    return 0;

                }

            if (blk_read(cur_drv->blk, fd_sector(cur_drv), fdctrl->fifo, 1)

                < 0) {

                FLOPPY_DPRINTF("error getting sector %d\n",

                               fd_sector(cur_drv));

                /* Sure, image size is too small... */

                memset(fdctrl->fifo, 0, FD_SECTOR_LEN);

            }

        }

    }

    retval = fdctrl->fifo[pos];

    if (++fdctrl->data_pos == fdctrl->data_len) {

        fdctrl->data_pos = 0;

        /* Switch from transfer mode to status mode

         * then from status mode to command mode

         */

        if (fdctrl->msr & FD_MSR_NONDMA) {

            fdctrl_stop_transfer(fdctrl, 0x00, 0x00, 0x00);

        } else {

            fdctrl_reset_fifo(fdctrl);

            fdctrl_reset_irq(fdctrl);

        }

    }

    FLOPPY_DPRINTF("data register: 0x%02x\n", retval);

    return retval;

}


static int decode_residuals(FLACContext *s, int channel, int pred_order)

{

    int i, tmp, partition, method_type, rice_order;

    int sample = 0, samples;

    method_type = get_bits(&s->gb, 2);

    if (method_type != 0){

        av_log(s->avctx, AV_LOG_DEBUG, "illegal residual coding method %d\n", method_type);

    rice_order = get_bits(&s->gb, 4);

    samples= s->blocksize >> rice_order;

    sample=

    i= pred_order;

    for (partition = 0; partition < (1 << rice_order); partition++)

    {

        tmp = get_bits(&s->gb, 4);

        if (tmp == 15)

        {

            av_log(s->avctx, AV_LOG_DEBUG, "fixed len partition\n");

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

            for (; i < samples; i++, sample++)

                s->decoded[channel][sample] = get_sbits(&s->gb, tmp);

        else

        {

//            av_log(s->avctx, AV_LOG_DEBUG, "rice coded partition k=%d\n", tmp);

            for (; i < samples; i++, sample++){

                s->decoded[channel][sample] = get_sr_golomb_flac(&s->gb, tmp, INT_MAX, 0);

        i= 0;

//    av_log(s->avctx, AV_LOG_DEBUG, "partitions: %d, samples: %d\n", 1 << rice_order, sample);

    return 0;


static void qemu_tcg_init_cpu_signals(void)

{

#ifdef CONFIG_IOTHREAD

    sigset_t set;

    struct sigaction sigact;

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

    sigact.sa_handler = cpu_signal;

    sigaction(SIG_IPI, &sigact, NULL);

    sigemptyset(&set);

    sigaddset(&set, SIG_IPI);

    pthread_sigmask(SIG_UNBLOCK, &set, NULL);

#endif

}


static void test_aio_external_client(void)

{

    int i, j;

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

        EventNotifierTestData data = { .n = 0, .active = 10, .auto_set = true };

        event_notifier_init(&data.e, false);

        aio_set_event_notifier(ctx, &data.e, true, event_ready_cb);

        event_notifier_set(&data.e);

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

            aio_disable_external(ctx);

        }

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

            assert(!aio_poll(ctx, false));

            assert(event_notifier_test_and_clear(&data.e));

            event_notifier_set(&data.e);

            aio_enable_external(ctx);

        }

        assert(aio_poll(ctx, false));

        event_notifier_cleanup(&data.e);

    }

}


static QemuConsole *new_console(DisplayState *ds, console_type_t console_type)

{

    Error *local_err = NULL;

    Object *obj;

    QemuConsole *s;

    int i;

    if (nb_consoles >= MAX_CONSOLES)

        return NULL;

    obj = object_new(TYPE_QEMU_CONSOLE);

    s = QEMU_CONSOLE(obj);

    object_property_add_link(obj, "device", TYPE_DEVICE,

                             (Object **)&s->device,

                             object_property_allow_set_link,

                             OBJ_PROP_LINK_UNREF_ON_RELEASE,

                             &local_err);

    object_property_add_uint32_ptr(obj, "head",

                                   &s->head, &local_err);

    if (!active_console || ((active_console->console_type != GRAPHIC_CONSOLE) &&

        (console_type == GRAPHIC_CONSOLE))) {

        active_console = s;

    }

    s->ds = ds;

    s->console_type = console_type;

    if (console_type != GRAPHIC_CONSOLE) {

        s->index = nb_consoles;

        consoles[nb_consoles++] = s;

    } else {

        /* HACK: Put graphical consoles before text consoles.  */

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

            if (consoles[i - 1]->console_type == GRAPHIC_CONSOLE)

                break;

            consoles[i] = consoles[i - 1];

            consoles[i]->index = i;

        }

        s->index = i;

        consoles[i] = s;

        nb_consoles++;

    }

    return s;

}


static void result_to_network(RDMARegisterResult *result)

{

    result->rkey = htonl(result->rkey);

    result->host_addr = htonll(result->host_addr);

};


static int nprobe(AVFormatContext *s, uint8_t *enc_header, int size,

                  const uint8_t *n_val)

{

    OMAContext *oc = s->priv_data;

    uint32_t pos, taglen, datalen;

    struct AVDES av_des;

    if (!enc_header || !n_val)

        return -1;

    pos = OMA_ENC_HEADER_SIZE + oc->k_size;

    if (!memcmp(&enc_header[pos], "EKB ", 4))

        pos += 32;

    if (AV_RB32(&enc_header[pos]) != oc->rid)

        av_log(s, AV_LOG_DEBUG, "Mismatching RID\n");

    taglen  = AV_RB32(&enc_header[pos + 32]);

    datalen = AV_RB32(&enc_header[pos + 36]) >> 4;

    if (taglen + (((uint64_t)datalen) << 4) + 44 > size)

        return -1;

    pos += 44 + taglen;

    av_des_init(&av_des, n_val, 192, 1);

    while (datalen-- > 0) {

        av_des_crypt(&av_des, oc->r_val, &enc_header[pos], 2, NULL, 1);

        kset(s, oc->r_val, NULL, 16);

        if (!rprobe(s, enc_header, oc->r_val))

            return 0;

        pos += 16;

    }

    return -1;

}


static AVFrame *do_vmaf(AVFilterContext *ctx, AVFrame *main, const AVFrame *ref)

{

    LIBVMAFContext *s = ctx->priv;

    pthread_mutex_lock(&s->lock);

    while (s->frame_set != 0) {

        pthread_cond_wait(&s->cond, &s->lock);

    }

    av_frame_ref(s->gref, ref);

    av_frame_ref(s->gmain, main);

    s->frame_set = 1;

    pthread_cond_signal(&s->cond);

    pthread_mutex_unlock(&s->lock);

    return main;

}


int ff_audio_interleave_init(AVFormatContext *s,

                             const int *samples_per_frame,

                             AVRational time_base)

{

    int i;

    if (!samples_per_frame)

        return -1;

    if (!time_base.num) {

        av_log(s, AV_LOG_ERROR, "timebase not set for audio interleave\n");

        return -1;

    }

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

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

        AudioInterleaveContext *aic = st->priv_data;

        if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {

            aic->sample_size = (st->codec->channels *

                                av_get_bits_per_sample(st->codec->codec_id)) / 8;

            if (!aic->sample_size) {

                av_log(s, AV_LOG_ERROR, "could not compute sample size\n");

                return -1;

            }

            aic->samples_per_frame = samples_per_frame;

            aic->samples = aic->samples_per_frame;

            aic->time_base = time_base;

            aic->fifo_size = 100* *aic->samples;

            aic->fifo= av_fifo_alloc_array(100, *aic->samples);

        }

    }

    return 0;

}


static int local_mkdir(FsContext *fs_ctx, V9fsPath *dir_path,

                       const char *name, FsCred *credp)

{

    char *path;

    int err = -1;

    int serrno = 0;

    V9fsString fullname;

    char *buffer = NULL;

    v9fs_string_init(&fullname);

    v9fs_string_sprintf(&fullname, "%s/%s", dir_path->data, name);

    path = fullname.data;

    /* Determine the security model */

    if (fs_ctx->export_flags & V9FS_SM_MAPPED) {

        buffer = rpath(fs_ctx, path);

        err = mkdir(buffer, SM_LOCAL_DIR_MODE_BITS);

        if (err == -1) {

            goto out;

        }

        credp->fc_mode = credp->fc_mode|S_IFDIR;

        err = local_set_xattr(buffer, credp);

        if (err == -1) {

            serrno = errno;

            goto err_end;

        }

    } else if (fs_ctx->export_flags & V9FS_SM_MAPPED_FILE) {

        buffer = rpath(fs_ctx, path);

        err = mkdir(buffer, SM_LOCAL_DIR_MODE_BITS);

        if (err == -1) {

            goto out;

        }

        credp->fc_mode = credp->fc_mode|S_IFDIR;

        err = local_set_mapped_file_attr(fs_ctx, path, credp);

        if (err == -1) {

            serrno = errno;

            goto err_end;

        }

    } else if ((fs_ctx->export_flags & V9FS_SM_PASSTHROUGH) ||

               (fs_ctx->export_flags & V9FS_SM_NONE)) {

        buffer = rpath(fs_ctx, path);

        err = mkdir(buffer, credp->fc_mode);

        if (err == -1) {

            goto out;

        }

        err = local_post_create_passthrough(fs_ctx, path, credp);

        if (err == -1) {

            serrno = errno;

            goto err_end;

        }

    }

    goto out;

err_end:

    remove(buffer);

    errno = serrno;

out:

    g_free(buffer);

    v9fs_string_free(&fullname);

    return err;

}


static void fd_revalidate(FDrive *drv)

{

    int rc;

    FLOPPY_DPRINTF("revalidate\n");

    if (drv->blk != NULL) {

        drv->ro = blk_is_read_only(drv->blk);

        if (!blk_is_inserted(drv->blk)) {

            FLOPPY_DPRINTF("No disk in drive\n");

            drv->disk = FLOPPY_DRIVE_TYPE_NONE;

        } else if (!drv->media_validated) {

            rc = pick_geometry(drv);

            if (rc) {

                FLOPPY_DPRINTF("Could not validate floppy drive media");

            } else {

                drv->media_validated = true;

                FLOPPY_DPRINTF("Floppy disk (%d h %d t %d s) %s\n",

                               (drv->flags & FDISK_DBL_SIDES) ? 2 : 1,

                               drv->max_track, drv->last_sect,

                               drv->ro ? "ro" : "rw");

            }

        }

    } else {

        FLOPPY_DPRINTF("No drive connected\n");

        drv->last_sect = 0;

        drv->max_track = 0;

        drv->flags &= ~FDISK_DBL_SIDES;

        drv->drive = FLOPPY_DRIVE_TYPE_NONE;

        drv->disk = FLOPPY_DRIVE_TYPE_NONE;

    }

}


static coroutine_fn void reconnect_to_sdog(void *opaque)

{

    Error *local_err = NULL;

    BDRVSheepdogState *s = opaque;

    AIOReq *aio_req, *next;

    aio_set_fd_handler(s->aio_context, s->fd, NULL, NULL, NULL);

    close(s->fd);

    s->fd = -1;

    /* Wait for outstanding write requests to be completed. */

    while (s->co_send != NULL) {

        co_write_request(opaque);

    }

    /* Try to reconnect the sheepdog server every one second. */

    while (s->fd < 0) {

        s->fd = get_sheep_fd(s, &local_err);

        if (s->fd < 0) {

            DPRINTF("Wait for connection to be established\n");

            error_report("%s", error_get_pretty(local_err));

            error_free(local_err);

            co_aio_sleep_ns(bdrv_get_aio_context(s->bs), QEMU_CLOCK_REALTIME,

                            1000000000ULL);

        }

    };

    /*

     * Now we have to resend all the request in the inflight queue.  However,

     * resend_aioreq() can yield and newly created requests can be added to the

     * inflight queue before the coroutine is resumed.  To avoid mixing them, we

     * have to move all the inflight requests to the failed queue before

     * resend_aioreq() is called.

     */

    QLIST_FOREACH_SAFE(aio_req, &s->inflight_aio_head, aio_siblings, next) {

        QLIST_REMOVE(aio_req, aio_siblings);

        QLIST_INSERT_HEAD(&s->failed_aio_head, aio_req, aio_siblings);

    }

    /* Resend all the failed aio requests. */

    while (!QLIST_EMPTY(&s->failed_aio_head)) {

        aio_req = QLIST_FIRST(&s->failed_aio_head);

        QLIST_REMOVE(aio_req, aio_siblings);

        QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);

        resend_aioreq(s, aio_req);

    }

}


static void set_frame_distances(MpegEncContext * s){

    assert(s->current_picture_ptr->f.pts != AV_NOPTS_VALUE);

    s->time = s->current_picture_ptr->f.pts * s->avctx->time_base.num;

    if(s->pict_type==AV_PICTURE_TYPE_B){

        s->pb_time= s->pp_time - (s->last_non_b_time - s->time);

        assert(s->pb_time > 0 && s->pb_time < s->pp_time);

    }else{

        s->pp_time= s->time - s->last_non_b_time;

        s->last_non_b_time= s->time;

        assert(s->picture_number==0 || s->pp_time > 0);

    }

}


static void load_tc(QEMUFile *f, TCState *tc)

{

    int i;

    /* Save active TC */

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

        qemu_get_betls(f, &tc->gpr[i]);

    qemu_get_betls(f, &tc->PC);

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

        qemu_get_betls(f, &tc->HI[i]);

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

        qemu_get_betls(f, &tc->LO[i]);

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

        qemu_get_betls(f, &tc->ACX[i]);

    qemu_get_betls(f, &tc->DSPControl);

    qemu_get_sbe32s(f, &tc->CP0_TCStatus);

    qemu_get_sbe32s(f, &tc->CP0_TCBind);

    qemu_get_betls(f, &tc->CP0_TCHalt);

    qemu_get_betls(f, &tc->CP0_TCContext);

    qemu_get_betls(f, &tc->CP0_TCSchedule);

    qemu_get_betls(f, &tc->CP0_TCScheFBack);

    qemu_get_sbe32s(f, &tc->CP0_Debug_tcstatus);

}


static inline void RENAME(rgb16to24)(const uint8_t *src, uint8_t *dst, long src_size)

{

	const uint16_t *end;

#ifdef HAVE_MMX

	const uint16_t *mm_end;

#endif

	uint8_t *d = (uint8_t *)dst;

	const uint16_t *s = (const uint16_t *)src;

	end = s + src_size/2;

#ifdef HAVE_MMX

	__asm __volatile(PREFETCH"	%0"::"m"(*s):"memory");

	mm_end = end - 7;

	while(s < mm_end)

	{

	    __asm __volatile(

		PREFETCH" 32%1\n\t"

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

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

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

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

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

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

		"psllq	$3, %%mm0\n\t"

		"psrlq	$3, %%mm1\n\t"

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

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

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

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

		"punpcklwd %5, %%mm0\n\t"

		"punpcklwd %5, %%mm1\n\t"

		"punpcklwd %5, %%mm2\n\t"

		"punpckhwd %5, %%mm3\n\t"

		"punpckhwd %5, %%mm4\n\t"

		"punpckhwd %5, %%mm5\n\t"

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

		"psllq	$16, %%mm2\n\t"

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

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

		"psllq	$8, %%mm4\n\t"

		"psllq	$16, %%mm5\n\t"

		"por	%%mm4, %%mm3\n\t"

		"por	%%mm5, %%mm3\n\t"

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

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

		"movq	8%1, %%mm0\n\t"

		"movq	8%1, %%mm1\n\t"

		"movq	8%1, %%mm2\n\t"

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

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

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

		"psllq	$3, %%mm0\n\t"

		"psrlq	$3, %%mm1\n\t"

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

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

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

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

		"punpcklwd %5, %%mm0\n\t"

		"punpcklwd %5, %%mm1\n\t"

		"punpcklwd %5, %%mm2\n\t"

		"punpckhwd %5, %%mm3\n\t"

		"punpckhwd %5, %%mm4\n\t"

		"punpckhwd %5, %%mm5\n\t"

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

		"psllq	$16, %%mm2\n\t"

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

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

		"psllq	$8, %%mm4\n\t"

		"psllq	$16, %%mm5\n\t"

		"por	%%mm4, %%mm3\n\t"

		"por	%%mm5, %%mm3\n\t"

		:"=m"(*d)

		:"m"(*s),"m"(mask16b),"m"(mask16g),"m"(mask16r),"m"(mmx_null)

		:"memory");

	    /* Borrowed 32 to 24 */

	    __asm __volatile(

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

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

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

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

		"movq	%%mm4, %%mm6\n\t"

		"movq	%%mm5, %%mm7\n\t"

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

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

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

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

		"psrlq	$8, %%mm6\n\t"

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

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

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

		"pand	%2, %%mm4\n\t"

		"pand	%2, %%mm5\n\t"

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

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

		"pand	%3, %%mm6\n\t"

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

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

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

		"por	%%mm6, %%mm4\n\t"

		"por	%%mm7, %%mm5\n\t"

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

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

		"psllq	$48, %%mm2\n\t"

		"psllq	$32, %%mm3\n\t"

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

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

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

		"psrlq	$16, %%mm1\n\t"

		"psrlq	$32, %%mm4\n\t"

		"psllq	$16, %%mm5\n\t"

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

		"pand	%6, %%mm5\n\t"

		"por	%%mm5, %%mm4\n\t"

		MOVNTQ"	%%mm0, %0\n\t"

		MOVNTQ"	%%mm1, 8%0\n\t"

		MOVNTQ"	%%mm4, 16%0"

		:"=m"(*d)

		:"m"(*s),"m"(mask24l),"m"(mask24h),"m"(mask24hh),"m"(mask24hhh),"m"(mask24hhhh)

		:"memory");

		d += 24;

		s += 8;

	}

	__asm __volatile(SFENCE:::"memory");

	__asm __volatile(EMMS:::"memory");

#endif

	while(s < end)

	{

		register uint16_t bgr;

		bgr = *s++;

		*d++ = (bgr&0x1F)<<3;

		*d++ = (bgr&0x7E0)>>3;

		*d++ = (bgr&0xF800)>>8;

	}

}


int ff_hevc_decode_nal_pps(GetBitContext *gb, AVCodecContext *avctx,

                           HEVCParamSets *ps)

{

    HEVCSPS      *sps = NULL;

    int i, ret = 0;

    unsigned int pps_id = 0;

    ptrdiff_t nal_size;

    AVBufferRef *pps_buf;

    HEVCPPS *pps = av_mallocz(sizeof(*pps));

    if (!pps)

        return AVERROR(ENOMEM);

    pps_buf = av_buffer_create((uint8_t *)pps, sizeof(*pps),

                               hevc_pps_free, NULL, 0);

    if (!pps_buf) {

        av_freep(&pps);

        return AVERROR(ENOMEM);

    }

    av_log(avctx, AV_LOG_DEBUG, "Decoding PPS\n");

    nal_size = gb->buffer_end - gb->buffer;

    if (nal_size > sizeof(pps->data)) {

        av_log(avctx, AV_LOG_WARNING, "Truncating likely oversized PPS "

               "(%"PTRDIFF_SPECIFIER" > %"SIZE_SPECIFIER")\n",

               nal_size, sizeof(pps->data));

        pps->data_size = sizeof(pps->data);

    } else {

        pps->data_size = nal_size;

    }

    memcpy(pps->data, gb->buffer, pps->data_size);

    // Default values

    pps->loop_filter_across_tiles_enabled_flag = 1;

    pps->num_tile_columns                      = 1;

    pps->num_tile_rows                         = 1;

    pps->uniform_spacing_flag                  = 1;

    pps->disable_dbf                           = 0;

    pps->beta_offset                           = 0;

    pps->tc_offset                             = 0;

    pps->log2_max_transform_skip_block_size    = 2;

    // Coded parameters

    pps_id = get_ue_golomb_long(gb);

    if (pps_id >= HEVC_MAX_PPS_COUNT) {

        av_log(avctx, AV_LOG_ERROR, "PPS id out of range: %d\n", pps_id);

        ret = AVERROR_INVALIDDATA;

        goto err;

    }

    pps->sps_id = get_ue_golomb_long(gb);

    if (pps->sps_id >= HEVC_MAX_SPS_COUNT) {

        av_log(avctx, AV_LOG_ERROR, "SPS id out of range: %d\n", pps->sps_id);

        ret = AVERROR_INVALIDDATA;

        goto err;

    }

    if (!ps->sps_list[pps->sps_id]) {

        av_log(avctx, AV_LOG_ERROR, "SPS %u does not exist.\n", pps->sps_id);

        ret = AVERROR_INVALIDDATA;

        goto err;

    }

    sps = (HEVCSPS *)ps->sps_list[pps->sps_id]->data;

    pps->dependent_slice_segments_enabled_flag = get_bits1(gb);

    pps->output_flag_present_flag              = get_bits1(gb);

    pps->num_extra_slice_header_bits           = get_bits(gb, 3);

    pps->sign_data_hiding_flag = get_bits1(gb);

    pps->cabac_init_present_flag = get_bits1(gb);

    pps->num_ref_idx_l0_default_active = get_ue_golomb_long(gb) + 1;

    pps->num_ref_idx_l1_default_active = get_ue_golomb_long(gb) + 1;

    pps->pic_init_qp_minus26 = get_se_golomb(gb);

    pps->constrained_intra_pred_flag = get_bits1(gb);

    pps->transform_skip_enabled_flag = get_bits1(gb);

    pps->cu_qp_delta_enabled_flag = get_bits1(gb);

    pps->diff_cu_qp_delta_depth   = 0;

    if (pps->cu_qp_delta_enabled_flag)

        pps->diff_cu_qp_delta_depth = get_ue_golomb_long(gb);

    if (pps->diff_cu_qp_delta_depth < 0 ||

        pps->diff_cu_qp_delta_depth > sps->log2_diff_max_min_coding_block_size) {

        av_log(avctx, AV_LOG_ERROR, "diff_cu_qp_delta_depth %d is invalid\n",

               pps->diff_cu_qp_delta_depth);

        ret = AVERROR_INVALIDDATA;

        goto err;

    }

    pps->cb_qp_offset = get_se_golomb(gb);

    if (pps->cb_qp_offset < -12 || pps->cb_qp_offset > 12) {

        av_log(avctx, AV_LOG_ERROR, "pps_cb_qp_offset out of range: %d\n",

               pps->cb_qp_offset);

        ret = AVERROR_INVALIDDATA;

        goto err;

    }

    pps->cr_qp_offset = get_se_golomb(gb);

    if (pps->cr_qp_offset < -12 || pps->cr_qp_offset > 12) {

        av_log(avctx, AV_LOG_ERROR, "pps_cr_qp_offset out of range: %d\n",

               pps->cr_qp_offset);

        ret = AVERROR_INVALIDDATA;

        goto err;

    }

    pps->pic_slice_level_chroma_qp_offsets_present_flag = get_bits1(gb);

    pps->weighted_pred_flag   = get_bits1(gb);

    pps->weighted_bipred_flag = get_bits1(gb);

    pps->transquant_bypass_enable_flag    = get_bits1(gb);

    pps->tiles_enabled_flag               = get_bits1(gb);

    pps->entropy_coding_sync_enabled_flag = get_bits1(gb);

    if (pps->tiles_enabled_flag) {

        pps->num_tile_columns = get_ue_golomb_long(gb) + 1;

        pps->num_tile_rows    = get_ue_golomb_long(gb) + 1;

        if (pps->num_tile_columns <= 0 ||

            pps->num_tile_columns >= sps->width) {

            av_log(avctx, AV_LOG_ERROR, "num_tile_columns_minus1 out of range: %d\n",

                   pps->num_tile_columns - 1);

            ret = AVERROR_INVALIDDATA;

            goto err;

        }

        if (pps->num_tile_rows <= 0 ||

            pps->num_tile_rows >= sps->height) {

            av_log(avctx, AV_LOG_ERROR, "num_tile_rows_minus1 out of range: %d\n",

                   pps->num_tile_rows - 1);

            ret = AVERROR_INVALIDDATA;

            goto err;

        }

        pps->column_width = av_malloc_array(pps->num_tile_columns, sizeof(*pps->column_width));

        pps->row_height   = av_malloc_array(pps->num_tile_rows,    sizeof(*pps->row_height));

        if (!pps->column_width || !pps->row_height) {

            ret = AVERROR(ENOMEM);

            goto err;

        }

        pps->uniform_spacing_flag = get_bits1(gb);

        if (!pps->uniform_spacing_flag) {

            uint64_t sum = 0;

            for (i = 0; i < pps->num_tile_columns - 1; i++) {

                pps->column_width[i] = get_ue_golomb_long(gb) + 1;

                sum                 += pps->column_width[i];

            }

            if (sum >= sps->ctb_width) {

                av_log(avctx, AV_LOG_ERROR, "Invalid tile widths.\n");

                ret = AVERROR_INVALIDDATA;

                goto err;

            }

            pps->column_width[pps->num_tile_columns - 1] = sps->ctb_width - sum;

            sum = 0;

            for (i = 0; i < pps->num_tile_rows - 1; i++) {

                pps->row_height[i] = get_ue_golomb_long(gb) + 1;

                sum               += pps->row_height[i];

            }

            if (sum >= sps->ctb_height) {

                av_log(avctx, AV_LOG_ERROR, "Invalid tile heights.\n");

                ret = AVERROR_INVALIDDATA;

                goto err;

            }

            pps->row_height[pps->num_tile_rows - 1] = sps->ctb_height - sum;

        }

        pps->loop_filter_across_tiles_enabled_flag = get_bits1(gb);

    }

    pps->seq_loop_filter_across_slices_enabled_flag = get_bits1(gb);

    pps->deblocking_filter_control_present_flag = get_bits1(gb);

    if (pps->deblocking_filter_control_present_flag) {

        pps->deblocking_filter_override_enabled_flag = get_bits1(gb);

        pps->disable_dbf                             = get_bits1(gb);

        if (!pps->disable_dbf) {

            int beta_offset_div2 = get_se_golomb(gb);

            int tc_offset_div2   = get_se_golomb(gb) ;

            if (beta_offset_div2 < -6 || beta_offset_div2 > 6) {

                av_log(avctx, AV_LOG_ERROR, "pps_beta_offset_div2 out of range: %d\n",

                       beta_offset_div2);

                ret = AVERROR_INVALIDDATA;

                goto err;

            }

            if (tc_offset_div2 < -6 || tc_offset_div2 > 6) {

                av_log(avctx, AV_LOG_ERROR, "pps_tc_offset_div2 out of range: %d\n",

                       tc_offset_div2);

                ret = AVERROR_INVALIDDATA;

                goto err;

            }

            pps->beta_offset = 2 * beta_offset_div2;

            pps->tc_offset   = 2 *   tc_offset_div2;

        }

    }

    pps->scaling_list_data_present_flag = get_bits1(gb);

    if (pps->scaling_list_data_present_flag) {

        set_default_scaling_list_data(&pps->scaling_list);

        ret = scaling_list_data(gb, avctx, &pps->scaling_list, sps);

        if (ret < 0)

            goto err;

    }

    pps->lists_modification_present_flag = get_bits1(gb);

    pps->log2_parallel_merge_level       = get_ue_golomb_long(gb) + 2;

    if (pps->log2_parallel_merge_level > sps->log2_ctb_size) {

        av_log(avctx, AV_LOG_ERROR, "log2_parallel_merge_level_minus2 out of range: %d\n",

               pps->log2_parallel_merge_level - 2);

        ret = AVERROR_INVALIDDATA;

        goto err;

    }

    pps->slice_header_extension_present_flag = get_bits1(gb);

    if (get_bits1(gb)) { // pps_extension_present_flag

        int pps_range_extensions_flag = get_bits1(gb);

        /* int pps_extension_7bits = */ get_bits(gb, 7);

        if (sps->ptl.general_ptl.profile_idc == FF_PROFILE_HEVC_REXT && pps_range_extensions_flag) {

            if ((ret = pps_range_extensions(gb, avctx, pps, sps)) < 0)

                goto err;

        }

    }

    ret = setup_pps(avctx, gb, pps, sps);

    if (ret < 0)

        goto err;

    if (get_bits_left(gb) < 0) {

        av_log(avctx, AV_LOG_ERROR,

               "Overread PPS by %d bits\n", -get_bits_left(gb));

        goto err;

    }

    remove_pps(ps, pps_id);

    ps->pps_list[pps_id] = pps_buf;

    return 0;

err:

    av_buffer_unref(&pps_buf);

    return ret;

}


static inline int onenand_erase(OneNANDState *s, int sec, int num)

{

    uint8_t *blankbuf, *tmpbuf;

    blankbuf = g_malloc(512);

    tmpbuf = g_malloc(512);

    memset(blankbuf, 0xff, 512);

    for (; num > 0; num--, sec++) {

        if (s->blk_cur) {

            int erasesec = s->secs_cur + (sec >> 5);

            if (blk_write(s->blk_cur, sec, blankbuf, 1) < 0) {

                goto fail;

            }

            if (blk_read(s->blk_cur, erasesec, tmpbuf, 1) < 0) {

                goto fail;

            }

            memcpy(tmpbuf + ((sec & 31) << 4), blankbuf, 1 << 4);

            if (blk_write(s->blk_cur, erasesec, tmpbuf, 1) < 0) {

                goto fail;

            }

        } else {

            if (sec + 1 > s->secs_cur) {

                goto fail;

            }

            memcpy(s->current + (sec << 9), blankbuf, 512);

            memcpy(s->current + (s->secs_cur << 9) + (sec << 4),

                   blankbuf, 1 << 4);

        }

    }

    g_free(tmpbuf);

    g_free(blankbuf);

    return 0;

fail:

    g_free(tmpbuf);

    g_free(blankbuf);

    return 1;

}


static av_cold int cinepak_encode_init(AVCodecContext *avctx)

{

    CinepakEncContext *s = avctx->priv_data;

    int x, mb_count, strip_buf_size, frame_buf_size;

    if (avctx->width & 3 || avctx->height & 3) {

        av_log(avctx, AV_LOG_ERROR, "width and height must be multiples of four (got %ix%i)\n",

                avctx->width, avctx->height);

        return AVERROR(EINVAL);

    }

    if (!(s->codebook_input = av_malloc(sizeof(int) * (avctx->pix_fmt == AV_PIX_FMT_YUV420P ? 6 : 4) * (avctx->width * avctx->height) >> 2)))

        return AVERROR(ENOMEM);

    if (!(s->codebook_closest = av_malloc(sizeof(int) * (avctx->width * avctx->height) >> 2)))

        goto enomem;

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

        if(!(s->pict_bufs[x] = av_malloc((avctx->pix_fmt == AV_PIX_FMT_YUV420P ? 6 : 4) * (avctx->width * avctx->height) >> 2)))

            goto enomem;

    mb_count = avctx->width * avctx->height / MB_AREA;

    //the largest possible chunk is 0x31 with all MBs encoded in V4 mode, which is 34 bits per MB

    strip_buf_size = STRIP_HEADER_SIZE + 3 * CHUNK_HEADER_SIZE + 2 * VECTOR_MAX * CODEBOOK_MAX + 4 * (mb_count + (mb_count + 15) / 16);

    frame_buf_size = CVID_HEADER_SIZE + MAX_STRIPS * strip_buf_size;

    if (!(s->strip_buf = av_malloc(strip_buf_size)))

        goto enomem;

    if (!(s->frame_buf = av_malloc(frame_buf_size)))

        goto enomem;

    if (!(s->mb = av_malloc(mb_count*sizeof(mb_info))))

        goto enomem;

#ifdef CINEPAKENC_DEBUG

    if (!(s->best_mb = av_malloc(mb_count*sizeof(mb_info))))

        goto enomem;

#endif

    av_lfg_init(&s->randctx, 1);

    s->avctx = avctx;

    s->w = avctx->width;

    s->h = avctx->height;

    s->curframe = 0;

    s->keyint = avctx->keyint_min;

    s->pix_fmt = avctx->pix_fmt;

    //set up AVFrames

    s->last_frame.data[0]        = s->pict_bufs[0];

    s->last_frame.linesize[0]    = s->w;

    s->best_frame.data[0]        = s->pict_bufs[1];

    s->best_frame.linesize[0]    = s->w;

    s->scratch_frame.data[0]     = s->pict_bufs[2];

    s->scratch_frame.linesize[0] = s->w;

    if(s->pix_fmt == AV_PIX_FMT_YUV420P) {

        s->last_frame.data[1]        = s->last_frame.data[0] + s->w * s->h;

        s->last_frame.data[2]        = s->last_frame.data[1] + ((s->w * s->h) >> 2);

        s->last_frame.linesize[1]    = s->last_frame.linesize[2] = s->w >> 1;

        s->best_frame.data[1]        = s->best_frame.data[0] + s->w * s->h;

        s->best_frame.data[2]        = s->best_frame.data[1] + ((s->w * s->h) >> 2);

        s->best_frame.linesize[1]    = s->best_frame.linesize[2] = s->w >> 1;

        s->scratch_frame.data[1]     = s->scratch_frame.data[0] + s->w * s->h;

        s->scratch_frame.data[2]     = s->scratch_frame.data[1] + ((s->w * s->h) >> 2);

        s->scratch_frame.linesize[1] = s->scratch_frame.linesize[2] = s->w >> 1;

    }

    s->num_v1_mode = s->num_v4_mode = s->num_mc_mode = s->num_v1_encs = s->num_v4_encs = s->num_skips = 0;

    return 0;

enomem:

    av_free(s->codebook_input);

    av_free(s->codebook_closest);

    av_free(s->strip_buf);

    av_free(s->frame_buf);

    av_free(s->mb);

#ifdef CINEPAKENC_DEBUG

    av_free(s->best_mb);

#endif

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

        av_free(s->pict_bufs[x]);

    return AVERROR(ENOMEM);

}


static int count_contiguous_clusters(int nb_clusters, int cluster_size,

        uint64_t *l2_table, uint64_t stop_flags)

{

    int i;

    uint64_t mask = stop_flags | L2E_OFFSET_MASK | QCOW_OFLAG_COMPRESSED;

    uint64_t first_entry = be64_to_cpu(l2_table[0]);

    uint64_t offset = first_entry & mask;

    if (!offset)

        return 0;

    assert(qcow2_get_cluster_type(first_entry) != QCOW2_CLUSTER_COMPRESSED);

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

        uint64_t l2_entry = be64_to_cpu(l2_table[i]) & mask;

        if (offset + (uint64_t) i * cluster_size != l2_entry) {

            break;

        }

    }

	return i;

}


static PCIDevice *qemu_pci_hot_add_nic(Monitor *mon,

                                       const char *devaddr,

                                       const char *opts_str)

{

    Error *local_err = NULL;

    QemuOpts *opts;

    PCIBus *root = pci_find_primary_bus();

    PCIBus *bus;

    int ret, devfn;

    if (!root) {

        monitor_printf(mon, "no primary PCI bus (if there are multiple"

                       " PCI roots, you must use device_add instead)");

        return NULL;

    }

    bus = pci_get_bus_devfn(&devfn, root, devaddr);

    if (!bus) {

        monitor_printf(mon, "Invalid PCI device address %s\n", devaddr);

        return NULL;

    }

    if (!qbus_is_hotpluggable(BUS(bus))) {

        monitor_printf(mon, "PCI bus doesn't support hotplug\n");

        return NULL;

    }

    opts = qemu_opts_parse(qemu_find_opts("net"), opts_str ? opts_str : "", 0);

    if (!opts) {

        return NULL;

    }

    qemu_opt_set(opts, "type", "nic");

    ret = net_client_init(opts, 0, &local_err);

    if (local_err) {

        qerror_report_err(local_err);

        error_free(local_err);

        return NULL;

    }

    if (nd_table[ret].devaddr) {

        monitor_printf(mon, "Parameter addr not supported\n");

        return NULL;

    }

    return pci_nic_init(&nd_table[ret], root, "rtl8139", devaddr);

}


void rdma_start_outgoing_migration(void *opaque,

                            const char *host_port, Error **errp)

{

    MigrationState *s = opaque;

    Error *local_err = NULL, **temp = &local_err;

    RDMAContext *rdma = qemu_rdma_data_init(host_port, &local_err);

    int ret = 0;

    if (rdma == NULL) {

        ERROR(temp, "Failed to initialize RDMA data structures! %d", ret);

        goto err;

    }

    ret = qemu_rdma_source_init(rdma, &local_err,

        s->enabled_capabilities[MIGRATION_CAPABILITY_RDMA_PIN_ALL]);

    if (ret) {

        goto err;

    }

    trace_rdma_start_outgoing_migration_after_rdma_source_init();

    ret = qemu_rdma_connect(rdma, &local_err);

    if (ret) {

        goto err;

    }

    trace_rdma_start_outgoing_migration_after_rdma_connect();

    s->to_dst_file = qemu_fopen_rdma(rdma, "wb");

    migrate_fd_connect(s);

    return;

err:

    error_propagate(errp, local_err);

    g_free(rdma);

    migrate_fd_error(s);

}


grlib_irqmp_writel(void *opaque, target_phys_addr_t addr, uint32_t value)

{

    IRQMP      *irqmp = opaque;

    IRQMPState *state;

    assert(irqmp != NULL);

    state = irqmp->state;

    assert(state != NULL);

    addr &= 0xff;

    /* global registers */

    switch (addr) {

    case LEVEL_OFFSET:

        value &= 0xFFFF << 1; /* clean up the value */

        state->level = value;

        return;

    case PENDING_OFFSET:

        /* Read Only */

        return;

    case FORCE0_OFFSET:

        /* This register is an "alias" for the force register of CPU 0 */

        value &= 0xFFFE; /* clean up the value */

        state->force[0] = value;

        grlib_irqmp_check_irqs(irqmp->state);

        return;

    case CLEAR_OFFSET:

        value &= ~1; /* clean up the value */

        state->pending &= ~value;

        return;

    case MP_STATUS_OFFSET:

        /* Read Only (no SMP support) */

        return;

    case BROADCAST_OFFSET:

        value &= 0xFFFE; /* clean up the value */

        state->broadcast = value;

        return;

    default:

        break;

    }

    /* mask registers */

    if (addr >= MASK_OFFSET && addr < FORCE_OFFSET) {

        int cpu = (addr - MASK_OFFSET) / 4;

        assert(cpu >= 0 && cpu < IRQMP_MAX_CPU);

        value &= ~1; /* clean up the value */

        state->mask[cpu] = value;

        grlib_irqmp_check_irqs(irqmp->state);

        return;

    }

    /* force registers */

    if (addr >= FORCE_OFFSET && addr < EXTENDED_OFFSET) {

        int cpu = (addr - FORCE_OFFSET) / 4;

        assert(cpu >= 0 && cpu < IRQMP_MAX_CPU);

        uint32_t force = value & 0xFFFE;

        uint32_t clear = (value >> 16) & 0xFFFE;

        uint32_t old   = state->force[cpu];

        state->force[cpu] = (old | force) & ~clear;

        grlib_irqmp_check_irqs(irqmp->state);

        return;

    }

    /* extended (not supported) */

    if (addr >= EXTENDED_OFFSET && addr < IRQMP_REG_SIZE) {

        int cpu = (addr - EXTENDED_OFFSET) / 4;

        assert(cpu >= 0 && cpu < IRQMP_MAX_CPU);

        value &= 0xF; /* clean up the value */

        state->extended[cpu] = value;

        return;

    }

    trace_grlib_irqmp_unknown_register("write", addr);

}


static void qvirtio_pci_queue_select(QVirtioDevice *d, uint16_t index)

{

    QVirtioPCIDevice *dev = (QVirtioPCIDevice *)d;

    qpci_io_writeb(dev->pdev, dev->addr + VIRTIO_PCI_QUEUE_SEL, index);

}


static int cbr_bit_allocation(AC3EncodeContext *s)

{

    int ch;

    int bits_left;

    int snr_offset, snr_incr;

    bits_left = 8 * s->frame_size - (s->frame_bits + s->exponent_bits);

    snr_offset = s->coarse_snr_offset << 4;

    while (snr_offset >= 0 &&

           bit_alloc(s, snr_offset) > bits_left) {

        snr_offset -= 64;

    }

    if (snr_offset < 0)

        return AVERROR(EINVAL);

    FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);

    for (snr_incr = 64; snr_incr > 0; snr_incr >>= 2) {

        while (snr_offset + 64 <= 1023 &&

               bit_alloc(s, snr_offset + snr_incr) <= bits_left) {

            snr_offset += snr_incr;

            FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);

        }

    }

    FFSWAP(uint8_t *, s->bap_buffer, s->bap1_buffer);

    reset_block_bap(s);

    s->coarse_snr_offset = snr_offset >> 4;

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

        s->fine_snr_offset[ch] = snr_offset & 0xF;

    return 0;

}


static int apng_encode_frame(AVCodecContext *avctx, const AVFrame *pict,

                             APNGFctlChunk *best_fctl_chunk, APNGFctlChunk *best_last_fctl_chunk)

{

    PNGEncContext *s = avctx->priv_data;

    int ret;

    unsigned int y;

    AVFrame* diffFrame;

    uint8_t bpp = (s->bits_per_pixel + 7) >> 3;

    uint8_t *original_bytestream, *original_bytestream_end;

    uint8_t *temp_bytestream = 0, *temp_bytestream_end;

    uint32_t best_sequence_number;

    uint8_t *best_bytestream;

    size_t best_bytestream_size = SIZE_MAX;

    APNGFctlChunk last_fctl_chunk = *best_last_fctl_chunk;

    APNGFctlChunk fctl_chunk = *best_fctl_chunk;

    if (avctx->frame_number == 0) {

        best_fctl_chunk->width = pict->width;

        best_fctl_chunk->height = pict->height;

        best_fctl_chunk->x_offset = 0;

        best_fctl_chunk->y_offset = 0;

        best_fctl_chunk->blend_op = APNG_BLEND_OP_SOURCE;

        return encode_frame(avctx, pict);

    }

    diffFrame = av_frame_alloc();

    if (!diffFrame)

        return AVERROR(ENOMEM);

    diffFrame->format = pict->format;

    diffFrame->width = pict->width;

    diffFrame->height = pict->height;

    if ((ret = av_frame_get_buffer(diffFrame, 32)) < 0)

        goto fail;

    original_bytestream = s->bytestream;

    original_bytestream_end = s->bytestream_end;

    temp_bytestream = av_malloc(original_bytestream_end - original_bytestream);

    temp_bytestream_end = temp_bytestream + (original_bytestream_end - original_bytestream);

    if (!temp_bytestream) {

        ret = AVERROR(ENOMEM);

        goto fail;

    }

    for (last_fctl_chunk.dispose_op = 0; last_fctl_chunk.dispose_op < 3; ++last_fctl_chunk.dispose_op) {

        // 0: APNG_DISPOSE_OP_NONE

        // 1: APNG_DISPOSE_OP_BACKGROUND

        // 2: APNG_DISPOSE_OP_PREVIOUS

        for (fctl_chunk.blend_op = 0; fctl_chunk.blend_op < 2; ++fctl_chunk.blend_op) {

            // 0: APNG_BLEND_OP_SOURCE

            // 1: APNG_BLEND_OP_OVER

            uint32_t original_sequence_number = s->sequence_number, sequence_number;

            uint8_t *bytestream_start = s->bytestream;

            size_t bytestream_size;

            // Do disposal

            if (last_fctl_chunk.dispose_op != APNG_DISPOSE_OP_PREVIOUS) {

                diffFrame->width = pict->width;

                diffFrame->height = pict->height;

                av_frame_copy(diffFrame, s->last_frame);

                if (last_fctl_chunk.dispose_op == APNG_DISPOSE_OP_BACKGROUND) {

                    for (y = last_fctl_chunk.y_offset; y < last_fctl_chunk.y_offset + last_fctl_chunk.height; ++y) {

                        size_t row_start = diffFrame->linesize[0] * y + bpp * last_fctl_chunk.x_offset;

                        memset(diffFrame->data[0] + row_start, 0, bpp * last_fctl_chunk.width);

                    }

                }

            } else {

                if (!s->prev_frame)

                    continue;

                diffFrame->width = pict->width;

                diffFrame->height = pict->height;

                av_frame_copy(diffFrame, s->prev_frame);

            }

            // Do inverse blending

            if (apng_do_inverse_blend(diffFrame, pict, &fctl_chunk, bpp) < 0)

                continue;

            // Do encoding

            ret = encode_frame(avctx, diffFrame);

            sequence_number = s->sequence_number;

            s->sequence_number = original_sequence_number;

            bytestream_size = s->bytestream - bytestream_start;

            s->bytestream = bytestream_start;

            if (ret < 0)

                goto fail;

            if (bytestream_size < best_bytestream_size) {

                *best_fctl_chunk = fctl_chunk;

                *best_last_fctl_chunk = last_fctl_chunk;

                best_sequence_number = sequence_number;

                best_bytestream = s->bytestream;

                best_bytestream_size = bytestream_size;

                if (best_bytestream == original_bytestream) {

                    s->bytestream = temp_bytestream;

                    s->bytestream_end = temp_bytestream_end;

                } else {

                    s->bytestream = original_bytestream;

                    s->bytestream_end = original_bytestream_end;

                }

            }

        }

    }

    s->sequence_number = best_sequence_number;

    s->bytestream = original_bytestream + best_bytestream_size;

    s->bytestream_end = original_bytestream_end;

    if (best_bytestream != original_bytestream)

        memcpy(original_bytestream, best_bytestream, best_bytestream_size);

    ret = 0;

fail:

    av_freep(&temp_bytestream);

    av_frame_free(&diffFrame);

    return ret;

}


static inline void transpose4x4(uint8_t *dst, uint8_t *src, x86_reg dst_stride, x86_reg src_stride){

    __asm__ volatile( //FIXME could save 1 instruction if done as 8x4 ...

        "movd  (%1), %%mm0              \n\t"

        "add   %3, %1                   \n\t"

        "movd  (%1), %%mm1              \n\t"

        "movd  (%1,%3,1), %%mm2         \n\t"

        "movd  (%1,%3,2), %%mm3         \n\t"

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

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

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

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

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

        "movd  %%mm0, (%0)              \n\t"

        "add   %2, %0                   \n\t"

        "punpckhdq %%mm0, %%mm0         \n\t"

        "movd  %%mm0, (%0)              \n\t"

        "movd  %%mm1, (%0,%2,1)         \n\t"

        "punpckhdq %%mm1, %%mm1         \n\t"

        "movd  %%mm1, (%0,%2,2)         \n\t"

        :  "+&r" (dst),

           "+&r" (src)

        :  "r" (dst_stride),

           "r" (src_stride)

        :  "memory"

    );

}


uint64_t helper_ld_asi(target_ulong addr, int asi, int size, int sign)

{

    uint64_t ret = 0;

#if defined(DEBUG_ASI)

    target_ulong last_addr = addr;

#endif

    asi &= 0xff;

    if ((asi < 0x80 && (env->pstate & PS_PRIV) == 0)

        || ((env->def->features & CPU_FEATURE_HYPV)

            && asi >= 0x30 && asi < 0x80

            && !(env->hpstate & HS_PRIV)))

        raise_exception(TT_PRIV_ACT);

    helper_check_align(addr, size - 1);

    switch (asi) {

    case 0x82: // Primary no-fault

    case 0x8a: // Primary no-fault LE

    case 0x83: // Secondary no-fault

    case 0x8b: // Secondary no-fault LE

        {

            /* secondary space access has lowest asi bit equal to 1 */

            int access_mmu_idx = ( asi & 1 ) ? MMU_KERNEL_IDX

                                             : MMU_KERNEL_SECONDARY_IDX;

            if (cpu_get_phys_page_nofault(env, addr, access_mmu_idx) == -1ULL) {

#ifdef DEBUG_ASI

                dump_asi("read ", last_addr, asi, size, ret);

#endif

                return 0;

            }

        }

        // Fall through

    case 0x10: // As if user primary

    case 0x11: // As if user secondary

    case 0x18: // As if user primary LE

    case 0x19: // As if user secondary LE

    case 0x80: // Primary

    case 0x81: // Secondary

    case 0x88: // Primary LE

    case 0x89: // Secondary LE

    case 0xe2: // UA2007 Primary block init

    case 0xe3: // UA2007 Secondary block init

        if ((asi & 0x80) && (env->pstate & PS_PRIV)) {

            if ((env->def->features & CPU_FEATURE_HYPV)

                && env->hpstate & HS_PRIV) {

                switch(size) {

                case 1:

                    ret = ldub_hypv(addr);

                    break;

                case 2:

                    ret = lduw_hypv(addr);

                    break;

                case 4:

                    ret = ldl_hypv(addr);

                    break;

                default:

                case 8:

                    ret = ldq_hypv(addr);

                    break;

                }

            } else {

                /* secondary space access has lowest asi bit equal to 1 */

                if (asi & 1) {

                    switch(size) {

                    case 1:

                        ret = ldub_kernel_secondary(addr);

                        break;

                    case 2:

                        ret = lduw_kernel_secondary(addr);

                        break;

                    case 4:

                        ret = ldl_kernel_secondary(addr);

                        break;

                    default:

                    case 8:

                        ret = ldq_kernel_secondary(addr);

                        break;

                    }

                } else {

                    switch(size) {

                    case 1:

                        ret = ldub_kernel(addr);

                        break;

                    case 2:

                        ret = lduw_kernel(addr);

                        break;

                    case 4:

                        ret = ldl_kernel(addr);

                        break;

                    default:

                    case 8:

                        ret = ldq_kernel(addr);

                        break;

                    }

                }

            }

        } else {

            /* secondary space access has lowest asi bit equal to 1 */

            if (asi & 1) {

                switch(size) {

                case 1:

                    ret = ldub_user_secondary(addr);

                    break;

                case 2:

                    ret = lduw_user_secondary(addr);

                    break;

                case 4:

                    ret = ldl_user_secondary(addr);

                    break;

                default:

                case 8:

                    ret = ldq_user_secondary(addr);

                    break;

                }

            } else {

                switch(size) {

                case 1:

                    ret = ldub_user(addr);

                    break;

                case 2:

                    ret = lduw_user(addr);

                    break;

                case 4:

                    ret = ldl_user(addr);

                    break;

                default:

                case 8:

                    ret = ldq_user(addr);

                    break;

                }

            }

        }

        break;

    case 0x14: // Bypass

    case 0x15: // Bypass, non-cacheable

    case 0x1c: // Bypass LE

    case 0x1d: // Bypass, non-cacheable LE

        {

            switch(size) {

            case 1:

                ret = ldub_phys(addr);

                break;

            case 2:

                ret = lduw_phys(addr);

                break;

            case 4:

                ret = ldl_phys(addr);

                break;

            default:

            case 8:

                ret = ldq_phys(addr);

                break;

            }

            break;

        }

    case 0x24: // Nucleus quad LDD 128 bit atomic

    case 0x2c: // Nucleus quad LDD 128 bit atomic LE

        //  Only ldda allowed

        raise_exception(TT_ILL_INSN);

        return 0;

    case 0x04: // Nucleus

    case 0x0c: // Nucleus Little Endian (LE)

    {

        switch(size) {

        case 1:

            ret = ldub_nucleus(addr);

            break;

        case 2:

            ret = lduw_nucleus(addr);

            break;

        case 4:

            ret = ldl_nucleus(addr);

            break;

        default:

        case 8:

            ret = ldq_nucleus(addr);

            break;

        }

        break;

    }

    case 0x4a: // UPA config

        // XXX

        break;

    case 0x45: // LSU

        ret = env->lsu;

        break;

    case 0x50: // I-MMU regs

        {

            int reg = (addr >> 3) & 0xf;

            if (reg == 0) {

                // I-TSB Tag Target register

                ret = ultrasparc_tag_target(env->immu.tag_access);

            } else {

                ret = env->immuregs[reg];

            }

            break;

        }

    case 0x51: // I-MMU 8k TSB pointer

        {

            // env->immuregs[5] holds I-MMU TSB register value

            // env->immuregs[6] holds I-MMU Tag Access register value

            ret = ultrasparc_tsb_pointer(env->immu.tsb, env->immu.tag_access,

                                         8*1024);

            break;

        }

    case 0x52: // I-MMU 64k TSB pointer

        {

            // env->immuregs[5] holds I-MMU TSB register value

            // env->immuregs[6] holds I-MMU Tag Access register value

            ret = ultrasparc_tsb_pointer(env->immu.tsb, env->immu.tag_access,

                                         64*1024);

            break;

        }

    case 0x55: // I-MMU data access

        {

            int reg = (addr >> 3) & 0x3f;

            ret = env->itlb[reg].tte;

            break;

        }

    case 0x56: // I-MMU tag read

        {

            int reg = (addr >> 3) & 0x3f;

            ret = env->itlb[reg].tag;

            break;

        }

    case 0x58: // D-MMU regs

        {

            int reg = (addr >> 3) & 0xf;

            if (reg == 0) {

                // D-TSB Tag Target register

                ret = ultrasparc_tag_target(env->dmmu.tag_access);

            } else {

                ret = env->dmmuregs[reg];

            }

            break;

        }

    case 0x59: // D-MMU 8k TSB pointer

        {

            // env->dmmuregs[5] holds D-MMU TSB register value

            // env->dmmuregs[6] holds D-MMU Tag Access register value

            ret = ultrasparc_tsb_pointer(env->dmmu.tsb, env->dmmu.tag_access,

                                         8*1024);

            break;

        }

    case 0x5a: // D-MMU 64k TSB pointer

        {

            // env->dmmuregs[5] holds D-MMU TSB register value

            // env->dmmuregs[6] holds D-MMU Tag Access register value

            ret = ultrasparc_tsb_pointer(env->dmmu.tsb, env->dmmu.tag_access,

                                         64*1024);

            break;

        }

    case 0x5d: // D-MMU data access

        {

            int reg = (addr >> 3) & 0x3f;

            ret = env->dtlb[reg].tte;

            break;

        }

    case 0x5e: // D-MMU tag read

        {

            int reg = (addr >> 3) & 0x3f;

            ret = env->dtlb[reg].tag;

            break;

        }

    case 0x46: // D-cache data

    case 0x47: // D-cache tag access

    case 0x4b: // E-cache error enable

    case 0x4c: // E-cache asynchronous fault status

    case 0x4d: // E-cache asynchronous fault address

    case 0x4e: // E-cache tag data

    case 0x66: // I-cache instruction access

    case 0x67: // I-cache tag access

    case 0x6e: // I-cache predecode

    case 0x6f: // I-cache LRU etc.

    case 0x76: // E-cache tag

    case 0x7e: // E-cache tag

        break;

    case 0x5b: // D-MMU data pointer

    case 0x48: // Interrupt dispatch, RO

    case 0x49: // Interrupt data receive

    case 0x7f: // Incoming interrupt vector, RO

        // XXX

        break;

    case 0x54: // I-MMU data in, WO

    case 0x57: // I-MMU demap, WO

    case 0x5c: // D-MMU data in, WO

    case 0x5f: // D-MMU demap, WO

    case 0x77: // Interrupt vector, WO

    default:

        do_unassigned_access(addr, 0, 0, 1, size);

        ret = 0;

        break;

    }

    /* Convert from little endian */

    switch (asi) {

    case 0x0c: // Nucleus Little Endian (LE)

    case 0x18: // As if user primary LE

    case 0x19: // As if user secondary LE

    case 0x1c: // Bypass LE

    case 0x1d: // Bypass, non-cacheable LE

    case 0x88: // Primary LE

    case 0x89: // Secondary LE

    case 0x8a: // Primary no-fault LE

    case 0x8b: // Secondary no-fault LE

        switch(size) {

        case 2:

            ret = bswap16(ret);

            break;

        case 4:

            ret = bswap32(ret);

            break;

        case 8:

            ret = bswap64(ret);

            break;

        default:

            break;

        }

    default:

        break;

    }

    /* Convert to signed number */

    if (sign) {

        switch(size) {

        case 1:

            ret = (int8_t) ret;

            break;

        case 2:

            ret = (int16_t) ret;

            break;

        case 4:

            ret = (int32_t) ret;

            break;

        default:

            break;

        }

    }

#ifdef DEBUG_ASI

    dump_asi("read ", last_addr, asi, size, ret);

#endif

    return ret;

}


static AVIOContext * wtvfile_open_sector(int first_sector, uint64_t length, int depth, AVFormatContext *s)

{

    AVIOContext *pb;

    WtvFile *wf;

    uint8_t *buffer;

    if (avio_seek(s->pb, (int64_t)first_sector << WTV_SECTOR_BITS, SEEK_SET) < 0)

        return NULL;

    wf = av_mallocz(sizeof(WtvFile));

    if (!wf)

        return NULL;

    if (depth == 0) {

        wf->sectors = av_malloc(sizeof(uint32_t));

        if (!wf->sectors) {

            av_free(wf);

            return NULL;

        }

        wf->sectors[0]  = first_sector;

        wf->nb_sectors  = 1;

    } else if (depth == 1) {

        wf->sectors = av_malloc(WTV_SECTOR_SIZE);

        if (!wf->sectors) {

            av_free(wf);

            return NULL;

        }

        wf->nb_sectors  = read_ints(s->pb, wf->sectors, WTV_SECTOR_SIZE / 4);

    } else if (depth == 2) {

        uint32_t sectors1[WTV_SECTOR_SIZE / 4];

        int nb_sectors1 = read_ints(s->pb, sectors1, WTV_SECTOR_SIZE / 4);

        int i;

        wf->sectors = av_malloc(nb_sectors1 << WTV_SECTOR_BITS);

        if (!wf->sectors) {

            av_free(wf);

            return NULL;

        }

        wf->nb_sectors = 0;

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

            if (avio_seek(s->pb, (int64_t)sectors1[i] << WTV_SECTOR_BITS, SEEK_SET) < 0)

                break;

            wf->nb_sectors += read_ints(s->pb, wf->sectors + i * WTV_SECTOR_SIZE / 4, WTV_SECTOR_SIZE / 4);

        }

    } else {

        av_log(s, AV_LOG_ERROR, "unsupported file allocation table depth (0x%x)\n", depth);

        av_free(wf);

        return NULL;

    }

    wf->sector_bits = length & (1ULL<<63) ? WTV_SECTOR_BITS : WTV_BIGSECTOR_BITS;

    if (!wf->nb_sectors) {

        av_free(wf->sectors);

        av_free(wf);

        return NULL;

    }

    if (wf->sectors[wf->nb_sectors - 1] << WTV_SECTOR_BITS > avio_tell(s->pb))

        av_log(s, AV_LOG_WARNING, "truncated file\n");

    /* check length */

    length &= 0xFFFFFFFFFFFF;

    if (length > ((int64_t)wf->nb_sectors << wf->sector_bits)) {

        av_log(s, AV_LOG_WARNING, "reported file length (0x%"PRIx64") exceeds number of available sectors (0x%"PRIx64")\n", length, (int64_t)wf->nb_sectors << wf->sector_bits);

        length = (int64_t)wf->nb_sectors <<  wf->sector_bits;

    }

    wf->length = length;

    /* seek to initial sector */

    wf->position = 0;

    if (avio_seek(s->pb, (int64_t)wf->sectors[0] << WTV_SECTOR_BITS, SEEK_SET) < 0) {

        av_free(wf->sectors);

        av_free(wf);

        return NULL;

    }

    wf->pb_filesystem = s->pb;

    buffer = av_malloc(1 << wf->sector_bits);

    if (!buffer) {

        av_free(wf->sectors);

        av_free(wf);

        return NULL;

    }

    pb = avio_alloc_context(buffer, 1 << wf->sector_bits, 0, wf,

                           wtvfile_read_packet, NULL, wtvfile_seek);

    if (!pb) {

        av_free(buffer);

        av_free(wf->sectors);

        av_free(wf);

    }

    return pb;

}


static uint32_t ehci_mem_readb(void *ptr, target_phys_addr_t addr)

{

    EHCIState *s = ptr;

    uint32_t val;

    val = s->mmio[addr];

    return val;

}


static void gen_tlbli_74xx(DisasContext *ctx)

{

#if defined(CONFIG_USER_ONLY)

    gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

#else

    if (unlikely(ctx->pr)) {

        gen_inval_exception(ctx, POWERPC_EXCP_PRIV_OPC);

        return;

    }

    gen_helper_74xx_tlbi(cpu_env, cpu_gpr[rB(ctx->opcode)]);

#endif

}


int av_crc_init(AVCRC *ctx, int le, int bits, uint32_t poly, int ctx_size){

    int i, j;

    uint32_t c;

    if (bits < 8 || bits > 32 || poly >= (1LL<<bits))

        return -1;

    if (ctx_size != sizeof(AVCRC)*257 && ctx_size != sizeof(AVCRC)*1024)

        return -1;

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

        if (le) {

            for (c = i, j = 0; j < 8; j++)

                c = (c>>1)^(poly & (-(c&1)));

            ctx[i] = c;

        } else {

            for (c = i << 24, j = 0; j < 8; j++)

                c = (c<<1) ^ ((poly<<(32-bits)) & (((int32_t)c)>>31) );

            ctx[i] = av_bswap32(c);

        }

    }

    ctx[256]=1;

#if !CONFIG_SMALL

    if(ctx_size >= sizeof(AVCRC)*1024)

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

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

                ctx[256*(j+1) + i]= (ctx[256*j + i]>>8) ^ ctx[ ctx[256*j + i]&0xFF ];

#endif

    return 0;

}


static void sbr_gain_calc(AACContext *ac, SpectralBandReplication *sbr,

                          SBRData *ch_data, const int e_a[2])

{

    int e, k, m;

    // max gain limits : -3dB, 0dB, 3dB, inf dB (limiter off)

    static const SoftFloat limgain[4] = { { 760155524,  0 }, { 0x20000000,  1 },

                                            { 758351638,  1 }, { 625000000, 34 } };

    for (e = 0; e < ch_data->bs_num_env; e++) {

        int delta = !((e == e_a[1]) || (e == e_a[0]));

        for (k = 0; k < sbr->n_lim; k++) {

            SoftFloat gain_boost, gain_max;

            SoftFloat sum[2];

            sum[0] = sum[1] = FLOAT_0;

            for (m = sbr->f_tablelim[k] - sbr->kx[1]; m < sbr->f_tablelim[k + 1] - sbr->kx[1]; m++) {

                const SoftFloat temp = av_div_sf(sbr->e_origmapped[e][m],

                                            av_add_sf(FLOAT_1, sbr->q_mapped[e][m]));

                sbr->q_m[e][m] = av_sqrt_sf(av_mul_sf(temp, sbr->q_mapped[e][m]));

                sbr->s_m[e][m] = av_sqrt_sf(av_mul_sf(temp, av_int2sf(ch_data->s_indexmapped[e + 1][m], 0)));

                if (!sbr->s_mapped[e][m]) {

                    if (delta) {

                      sbr->gain[e][m] = av_sqrt_sf(av_div_sf(sbr->e_origmapped[e][m],

                                            av_mul_sf(av_add_sf(FLOAT_1, sbr->e_curr[e][m]),

                                            av_add_sf(FLOAT_1, sbr->q_mapped[e][m]))));

                    } else {

                      sbr->gain[e][m] = av_sqrt_sf(av_div_sf(sbr->e_origmapped[e][m],

                                            av_add_sf(FLOAT_1, sbr->e_curr[e][m])));

                    }

                } else {

                    sbr->gain[e][m] = av_sqrt_sf(

                                        av_div_sf(

                                            av_mul_sf(sbr->e_origmapped[e][m], sbr->q_mapped[e][m]),

                                            av_mul_sf(

                                                av_add_sf(FLOAT_1, sbr->e_curr[e][m]),

                                                av_add_sf(FLOAT_1, sbr->q_mapped[e][m]))));

                }

            }

            for (m = sbr->f_tablelim[k] - sbr->kx[1]; m < sbr->f_tablelim[k + 1] - sbr->kx[1]; m++) {

                sum[0] = av_add_sf(sum[0], sbr->e_origmapped[e][m]);

                sum[1] = av_add_sf(sum[1], sbr->e_curr[e][m]);

            }

            gain_max = av_mul_sf(limgain[sbr->bs_limiter_gains],

                            av_sqrt_sf(

                                av_div_sf(

                                    av_add_sf(FLOAT_EPSILON, sum[0]),

                                    av_add_sf(FLOAT_EPSILON, sum[1]))));

            if (av_gt_sf(gain_max, FLOAT_100000))

              gain_max = FLOAT_100000;

            for (m = sbr->f_tablelim[k] - sbr->kx[1]; m < sbr->f_tablelim[k + 1] - sbr->kx[1]; m++) {

                SoftFloat q_m_max = av_div_sf(

                                        av_mul_sf(sbr->q_m[e][m], gain_max),

                                        sbr->gain[e][m]);

                if (av_gt_sf(sbr->q_m[e][m], q_m_max))

                  sbr->q_m[e][m] = q_m_max;

                if (av_gt_sf(sbr->gain[e][m], gain_max))

                  sbr->gain[e][m] = gain_max;

            }

            sum[0] = sum[1] = FLOAT_0;

            for (m = sbr->f_tablelim[k] - sbr->kx[1]; m < sbr->f_tablelim[k + 1] - sbr->kx[1]; m++) {

                sum[0] = av_add_sf(sum[0], sbr->e_origmapped[e][m]);

                sum[1] = av_add_sf(sum[1],

                            av_mul_sf(

                                av_mul_sf(sbr->e_curr[e][m],

                                          sbr->gain[e][m]),

                                sbr->gain[e][m]));

                sum[1] = av_add_sf(sum[1],

                            av_mul_sf(sbr->s_m[e][m], sbr->s_m[e][m]));

                if (delta && !sbr->s_m[e][m].mant)

                  sum[1] = av_add_sf(sum[1],

                                av_mul_sf(sbr->q_m[e][m], sbr->q_m[e][m]));

            }

            gain_boost = av_sqrt_sf(

                            av_div_sf(

                                av_add_sf(FLOAT_EPSILON, sum[0]),

                                av_add_sf(FLOAT_EPSILON, sum[1])));

            if (av_gt_sf(gain_boost, FLOAT_1584893192))

              gain_boost = FLOAT_1584893192;

            for (m = sbr->f_tablelim[k] - sbr->kx[1]; m < sbr->f_tablelim[k + 1] - sbr->kx[1]; m++) {

                sbr->gain[e][m] = av_mul_sf(sbr->gain[e][m], gain_boost);

                sbr->q_m[e][m]  = av_mul_sf(sbr->q_m[e][m], gain_boost);

                sbr->s_m[e][m]  = av_mul_sf(sbr->s_m[e][m], gain_boost);

            }

        }

    }

}


void tcg_dump_ops(TCGContext *s)

{

    char buf[128];

    TCGOp *op;

    int oi;

    for (oi = s->gen_op_buf[0].next; oi != 0; oi = op->next) {

        int i, k, nb_oargs, nb_iargs, nb_cargs;

        const TCGOpDef *def;

        TCGOpcode c;

        int col = 0;

        op = &s->gen_op_buf[oi];

        c = op->opc;

        def = &tcg_op_defs[c];

        if (c == INDEX_op_insn_start) {

            col += qemu_log("%s ----", oi != s->gen_op_buf[0].next ? "\n" : "");

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

                target_ulong a;

#if TARGET_LONG_BITS > TCG_TARGET_REG_BITS

                a = deposit64(op->args[i * 2], 32, 32, op->args[i * 2 + 1]);

#else

                a = op->args[i];

#endif

                col += qemu_log(" " TARGET_FMT_lx, a);

            }

        } else if (c == INDEX_op_call) {

            /* variable number of arguments */

            nb_oargs = op->callo;

            nb_iargs = op->calli;

            nb_cargs = def->nb_cargs;

            /* function name, flags, out args */

            col += qemu_log(" %s %s,$0x%" TCG_PRIlx ",$%d", def->name,

                            tcg_find_helper(s, op->args[nb_oargs + nb_iargs]),

                            op->args[nb_oargs + nb_iargs + 1], nb_oargs);

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

                col += qemu_log(",%s", tcg_get_arg_str(s, buf, sizeof(buf),

                                                       op->args[i]));

            }

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

                TCGArg arg = op->args[nb_oargs + i];

                const char *t = "<dummy>";

                if (arg != TCG_CALL_DUMMY_ARG) {

                    t = tcg_get_arg_str(s, buf, sizeof(buf), arg);

                }

                col += qemu_log(",%s", t);

            }

        } else {

            col += qemu_log(" %s ", def->name);

            nb_oargs = def->nb_oargs;

            nb_iargs = def->nb_iargs;

            nb_cargs = def->nb_cargs;

            k = 0;

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

                if (k != 0) {

                    col += qemu_log(",");

                }

                col += qemu_log("%s", tcg_get_arg_str(s, buf, sizeof(buf),

                                                      op->args[k++]));

            }

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

                if (k != 0) {

                    col += qemu_log(",");

                }

                col += qemu_log("%s", tcg_get_arg_str(s, buf, sizeof(buf),

                                                      op->args[k++]));

            }

            switch (c) {

            case INDEX_op_brcond_i32:

            case INDEX_op_setcond_i32:

            case INDEX_op_movcond_i32:

            case INDEX_op_brcond2_i32:

            case INDEX_op_setcond2_i32:

            case INDEX_op_brcond_i64:

            case INDEX_op_setcond_i64:

            case INDEX_op_movcond_i64:

                if (op->args[k] < ARRAY_SIZE(cond_name)

                    && cond_name[op->args[k]]) {

                    col += qemu_log(",%s", cond_name[op->args[k++]]);

                } else {

                    col += qemu_log(",$0x%" TCG_PRIlx, op->args[k++]);

                }

                i = 1;

                break;

            case INDEX_op_qemu_ld_i32:

            case INDEX_op_qemu_st_i32:

            case INDEX_op_qemu_ld_i64:

            case INDEX_op_qemu_st_i64:

                {

                    TCGMemOpIdx oi = op->args[k++];

                    TCGMemOp op = get_memop(oi);

                    unsigned ix = get_mmuidx(oi);

                    if (op & ~(MO_AMASK | MO_BSWAP | MO_SSIZE)) {

                        col += qemu_log(",$0x%x,%u", op, ix);

                    } else {

                        const char *s_al, *s_op;

                        s_al = alignment_name[(op & MO_AMASK) >> MO_ASHIFT];

                        s_op = ldst_name[op & (MO_BSWAP | MO_SSIZE)];

                        col += qemu_log(",%s%s,%u", s_al, s_op, ix);

                    }

                    i = 1;

                }

                break;

            default:

                i = 0;

                break;

            }

            switch (c) {

            case INDEX_op_set_label:

            case INDEX_op_br:

            case INDEX_op_brcond_i32:

            case INDEX_op_brcond_i64:

            case INDEX_op_brcond2_i32:

                col += qemu_log("%s$L%d", k ? "," : "",

                                arg_label(op->args[k])->id);

                i++, k++;

                break;

            default:

                break;

            }

            for (; i < nb_cargs; i++, k++) {

                col += qemu_log("%s$0x%" TCG_PRIlx, k ? "," : "", op->args[k]);

            }

        }

        if (op->life) {

            unsigned life = op->life;

            for (; col < 48; ++col) {

                putc(' ', qemu_logfile);

            }

            if (life & (SYNC_ARG * 3)) {

                qemu_log("  sync:");

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

                    if (life & (SYNC_ARG << i)) {

                        qemu_log(" %d", i);

                    }

                }

            }

            life /= DEAD_ARG;

            if (life) {

                qemu_log("  dead:");

                for (i = 0; life; ++i, life >>= 1) {

                    if (life & 1) {

                        qemu_log(" %d", i);

                    }

                }

            }

        }

        qemu_log("\n");

    }

}


static int vtd_remap_irq_get(IntelIOMMUState *iommu, uint16_t index, VTDIrq *irq)

{

    VTD_IRTE irte = { 0 };

    int ret = 0;

    ret = vtd_irte_get(iommu, index, &irte);

    if (ret) {

        return ret;

    }

    irq->trigger_mode = irte.trigger_mode;

    irq->vector = irte.vector;

    irq->delivery_mode = irte.delivery_mode;

    /* Not support EIM yet: please refer to vt-d 9.10 DST bits */

#define  VTD_IR_APIC_DEST_MASK         (0xff00ULL)

#define  VTD_IR_APIC_DEST_SHIFT        (8)

    irq->dest = (le32_to_cpu(irte.dest_id) & VTD_IR_APIC_DEST_MASK) >> \

        VTD_IR_APIC_DEST_SHIFT;

    irq->dest_mode = irte.dest_mode;

    irq->redir_hint = irte.redir_hint;

    VTD_DPRINTF(IR, "remapping interrupt index %d: trig:%u,vec:%u,"

                "deliver:%u,dest:%u,dest_mode:%u", index,

                irq->trigger_mode, irq->vector, irq->delivery_mode,

                irq->dest, irq->dest_mode);

    return 0;

}


void exynos4210_init_board_irqs(Exynos4210Irq *s)

{

    uint32_t grp, bit, irq_id, n;

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

        s->board_irqs[n] = qemu_irq_split(s->int_combiner_irq[n],

                s->ext_combiner_irq[n]);

        irq_id = 0;

        if (n == EXYNOS4210_COMBINER_GET_IRQ_NUM(1, 4) ||

                n == EXYNOS4210_COMBINER_GET_IRQ_NUM(12, 4)) {

            /* MCT_G0 is passed to External GIC */

            irq_id = EXT_GIC_ID_MCT_G0;

        }

        if (n == EXYNOS4210_COMBINER_GET_IRQ_NUM(1, 5) ||

                n == EXYNOS4210_COMBINER_GET_IRQ_NUM(12, 5)) {

            /* MCT_G1 is passed to External and GIC */

            irq_id = EXT_GIC_ID_MCT_G1;

        }

        if (irq_id) {

            s->board_irqs[n] = qemu_irq_split(s->int_combiner_irq[n],

                    s->ext_gic_irq[irq_id-32]);

        }

    }

    for (; n < EXYNOS4210_MAX_INT_COMBINER_IN_IRQ; n++) {

        /* these IDs are passed to Internal Combiner and External GIC */

        grp = EXYNOS4210_COMBINER_GET_GRP_NUM(n);

        bit = EXYNOS4210_COMBINER_GET_BIT_NUM(n);

        irq_id = combiner_grp_to_gic_id[grp -

                     EXYNOS4210_MAX_EXT_COMBINER_OUT_IRQ][bit];

        if (irq_id) {

            s->board_irqs[n] = qemu_irq_split(s->int_combiner_irq[n],

                    s->ext_gic_irq[irq_id-32]);

        }

    }

}


static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,

                                            int64_t sector_num,

                                            QEMUIOVector *iov,

                                            int nb_sectors,

                                            BlockDriverCompletionFunc *cb,

                                            void *opaque,

                                            int is_write)

{

    VectorTranslationAIOCB *s = qemu_aio_get_pool(&vectored_aio_pool, bs,

                                                  cb, opaque);

    s->iov = iov;

    s->bounce = qemu_memalign(512, nb_sectors * 512);

    s->is_write = is_write;

    if (is_write) {

        qemu_iovec_to_buffer(s->iov, s->bounce);

        s->aiocb = bdrv_aio_write(bs, sector_num, s->bounce, nb_sectors,

                                  bdrv_aio_rw_vector_cb, s);

    } else {

        s->aiocb = bdrv_aio_read(bs, sector_num, s->bounce, nb_sectors,

                                 bdrv_aio_rw_vector_cb, s);

    return &s->common;


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

{

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

        return 0;

    if (ff_mutex_lock(&codec_mutex))

        return -1;

    if (atomic_fetch_add(&entangled_thread_counter, 1)) {

        av_log(log_ctx, AV_LOG_ERROR,

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

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

               atomic_load(&entangled_thread_counter));

        ff_avcodec_locked = 1;

        ff_unlock_avcodec(codec);

        return AVERROR(EINVAL);

    }

    av_assert0(!ff_avcodec_locked);

    ff_avcodec_locked = 1;

    return 0;

}


static void do_mchk_interrupt(CPUS390XState *env)

{

    S390CPU *cpu = s390_env_get_cpu(env);

    uint64_t mask, addr;

    LowCore *lowcore;

    MchkQueue *q;

    int i;

    if (!(env->psw.mask & PSW_MASK_MCHECK)) {

        cpu_abort(CPU(cpu), "Machine check w/o mchk mask\n");

    }

    if (env->mchk_index < 0 || env->mchk_index > MAX_MCHK_QUEUE) {

        cpu_abort(CPU(cpu), "Mchk queue overrun: %d\n", env->mchk_index);

    }

    q = &env->mchk_queue[env->mchk_index];

    if (q->type != 1) {

        /* Don't know how to handle this... */

        cpu_abort(CPU(cpu), "Unknown machine check type %d\n", q->type);

    }

    if (!(env->cregs[14] & (1 << 28))) {

        /* CRW machine checks disabled */

        return;

    }

    lowcore = cpu_map_lowcore(env);

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

        lowcore->floating_pt_save_area[i] = cpu_to_be64(env->fregs[i].ll);

        lowcore->gpregs_save_area[i] = cpu_to_be64(env->regs[i]);

        lowcore->access_regs_save_area[i] = cpu_to_be32(env->aregs[i]);

        lowcore->cregs_save_area[i] = cpu_to_be64(env->cregs[i]);

    }

    lowcore->prefixreg_save_area = cpu_to_be32(env->psa);

    lowcore->fpt_creg_save_area = cpu_to_be32(env->fpc);

    lowcore->tod_progreg_save_area = cpu_to_be32(env->todpr);

    lowcore->cpu_timer_save_area[0] = cpu_to_be32(env->cputm >> 32);

    lowcore->cpu_timer_save_area[1] = cpu_to_be32((uint32_t)env->cputm);

    lowcore->clock_comp_save_area[0] = cpu_to_be32(env->ckc >> 32);

    lowcore->clock_comp_save_area[1] = cpu_to_be32((uint32_t)env->ckc);

    lowcore->mcck_interruption_code[0] = cpu_to_be32(0x00400f1d);

    lowcore->mcck_interruption_code[1] = cpu_to_be32(0x40330000);

    lowcore->mcck_old_psw.mask = cpu_to_be64(get_psw_mask(env));

    lowcore->mcck_old_psw.addr = cpu_to_be64(env->psw.addr);

    mask = be64_to_cpu(lowcore->mcck_new_psw.mask);

    addr = be64_to_cpu(lowcore->mcck_new_psw.addr);

    cpu_unmap_lowcore(lowcore);

    env->mchk_index--;

    if (env->mchk_index == -1) {

        env->pending_int &= ~INTERRUPT_MCHK;

    }

    DPRINTF("%s: %" PRIx64 " %" PRIx64 "\n", __func__,

            env->psw.mask, env->psw.addr);

    load_psw(env, mask, addr);

}


uint16_t acpi_pm1_evt_get_sts(ACPIREGS *ar, int64_t overflow_time)

{

    int64_t d = acpi_pm_tmr_get_clock();

    if (d >= overflow_time) {

        ar->pm1.evt.sts |= ACPI_BITMASK_TIMER_STATUS;

    }

    return ar->pm1.evt.sts;

}


static int ide_drive_pio_post_load(void *opaque, int version_id)

{

    IDEState *s = opaque;

    if (s->end_transfer_fn_idx > ARRAY_SIZE(transfer_end_table)) {

        return -EINVAL;

    }

    s->end_transfer_func = transfer_end_table[s->end_transfer_fn_idx];

    s->data_ptr = s->io_buffer + s->cur_io_buffer_offset;

    s->data_end = s->data_ptr + s->cur_io_buffer_len;

    return 0;

}


int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)

{

    int ret= av_new_packet(pkt, size);

    if(ret<0)

        return ret;

    pkt->pos= avio_tell(s);

    ret= avio_read(s, pkt->data, size);

    if(ret<=0)

        av_free_packet(pkt);

    else

        av_shrink_packet(pkt, ret);

    return ret;

}


void ff_rtp_send_aac(AVFormatContext *s1, const uint8_t *buff, int size)

{

    RTPMuxContext *s = s1->priv_data;

    int len, max_packet_size;

    uint8_t *p;

    /* skip ADTS header, if present */

    if ((s1->streams[0]->codec->extradata_size) == 0) {

        size -= 7;

        buff += 7;

    }

    max_packet_size = s->max_payload_size - MAX_AU_HEADERS_SIZE;

    /* test if the packet must be sent */

    len = (s->buf_ptr - s->buf);

    if ((s->num_frames == MAX_FRAMES_PER_PACKET) || (len && (len + size) > s->max_payload_size)) {

        int au_size = s->num_frames * 2;

        p = s->buf + MAX_AU_HEADERS_SIZE - au_size - 2;

        if (p != s->buf) {

            memmove(p + 2, s->buf + 2, au_size);

        }

        /* Write the AU header size */

        p[0] = ((au_size * 8) & 0xFF) >> 8;

        p[1] = (au_size * 8) & 0xFF;

        ff_rtp_send_data(s1, p, s->buf_ptr - p, 1);

        s->num_frames = 0;

    }

    if (s->num_frames == 0) {

        s->buf_ptr = s->buf + MAX_AU_HEADERS_SIZE;

        s->timestamp = s->cur_timestamp;

    }

    if (size <= max_packet_size) {

        p = s->buf + s->num_frames++ * 2 + 2;

        *p++ = size >> 5;

        *p = (size & 0x1F) << 3;

        memcpy(s->buf_ptr, buff, size);

        s->buf_ptr += size;

    } else {

        if (s->buf_ptr != s->buf + MAX_AU_HEADERS_SIZE) {

            av_log(s1, AV_LOG_ERROR, "Strange...\n");

            av_abort();

        }

        max_packet_size = s->max_payload_size - 4;

        p = s->buf;

        p[0] = 0;

        p[1] = 16;

        while (size > 0) {

            len = FFMIN(size, max_packet_size);

            p[2] = len >> 5;

            p[3] = (size & 0x1F) << 3;

            memcpy(p + 4, buff, len);

            ff_rtp_send_data(s1, p, len + 4, len == size);

            size -= len;

            buff += len;

        }

    }

}