av_cold int swr_init(struct SwrContext *s){

    int ret;

    clear_context(s);

    if(s-> in_sample_fmt >= AV_SAMPLE_FMT_NB){

        av_log(s, AV_LOG_ERROR, "Requested input sample format %d is invalid\n", s->in_sample_fmt);

        return AVERROR(EINVAL);

    }

    if(s->out_sample_fmt >= AV_SAMPLE_FMT_NB){

        av_log(s, AV_LOG_ERROR, "Requested output sample format %d is invalid\n", s->out_sample_fmt);

        return AVERROR(EINVAL);

    }

    s->out.ch_count  = s-> user_out_ch_count;

    s-> in.ch_count  = s->  user_in_ch_count;

    s->used_ch_count = s->user_used_ch_count;

    s-> in_ch_layout = s-> user_in_ch_layout;

    s->out_ch_layout = s->user_out_ch_layout;

    if(av_get_channel_layout_nb_channels(s-> in_ch_layout) > SWR_CH_MAX) {

        av_log(s, AV_LOG_WARNING, "Input channel layout 0x%"PRIx64" is invalid or unsupported.\n", s-> in_ch_layout);

        s->in_ch_layout = 0;

    }

    if(av_get_channel_layout_nb_channels(s->out_ch_layout) > SWR_CH_MAX) {

        av_log(s, AV_LOG_WARNING, "Output channel layout 0x%"PRIx64" is invalid or unsupported.\n", s->out_ch_layout);

        s->out_ch_layout = 0;

    }

    switch(s->engine){

#if CONFIG_LIBSOXR

        case SWR_ENGINE_SOXR: s->resampler = &swri_soxr_resampler; break;

#endif

        case SWR_ENGINE_SWR : s->resampler = &swri_resampler; break;

        default:

            av_log(s, AV_LOG_ERROR, "Requested resampling engine is unavailable\n");

            return AVERROR(EINVAL);

    }

    if(!s->used_ch_count)

        s->used_ch_count= s->in.ch_count;

    if(s->used_ch_count && s-> in_ch_layout && s->used_ch_count != av_get_channel_layout_nb_channels(s-> in_ch_layout)){

        av_log(s, AV_LOG_WARNING, "Input channel layout has a different number of channels than the number of used channels, ignoring layout\n");

        s-> in_ch_layout= 0;

    }

    if(!s-> in_ch_layout)

        s-> in_ch_layout= av_get_default_channel_layout(s->used_ch_count);

    if(!s->out_ch_layout)

        s->out_ch_layout= av_get_default_channel_layout(s->out.ch_count);

    s->rematrix= s->out_ch_layout  !=s->in_ch_layout || s->rematrix_volume!=1.0 ||

                 s->rematrix_custom;

    if(s->int_sample_fmt == AV_SAMPLE_FMT_NONE){

        if(av_get_planar_sample_fmt(s->in_sample_fmt) <= AV_SAMPLE_FMT_S16P){

            s->int_sample_fmt= AV_SAMPLE_FMT_S16P;

        }else if(   av_get_planar_sample_fmt(s-> in_sample_fmt) == AV_SAMPLE_FMT_S32P

                 && av_get_planar_sample_fmt(s->out_sample_fmt) == AV_SAMPLE_FMT_S32P

                 && !s->rematrix

                 && s->engine != SWR_ENGINE_SOXR){

            s->int_sample_fmt= AV_SAMPLE_FMT_S32P;

        }else if(av_get_planar_sample_fmt(s->in_sample_fmt) <= AV_SAMPLE_FMT_FLTP){

            s->int_sample_fmt= AV_SAMPLE_FMT_FLTP;

        }else{

            av_log(s, AV_LOG_DEBUG, "Using double precision mode\n");

            s->int_sample_fmt= AV_SAMPLE_FMT_DBLP;

        }

    }

    if(   s->int_sample_fmt != AV_SAMPLE_FMT_S16P

        &&s->int_sample_fmt != AV_SAMPLE_FMT_S32P

        &&s->int_sample_fmt != AV_SAMPLE_FMT_FLTP

        &&s->int_sample_fmt != AV_SAMPLE_FMT_DBLP){

        av_log(s, AV_LOG_ERROR, "Requested sample format %s is not supported internally, S16/S32/FLT/DBL is supported\n", av_get_sample_fmt_name(s->int_sample_fmt));

        return AVERROR(EINVAL);

    }

    set_audiodata_fmt(&s-> in, s-> in_sample_fmt);

    set_audiodata_fmt(&s->out, s->out_sample_fmt);

    if (s->firstpts_in_samples != AV_NOPTS_VALUE) {

        if (!s->async && s->min_compensation >= FLT_MAX/2)

            s->async = 1;

        s->firstpts =

        s->outpts   = s->firstpts_in_samples * s->out_sample_rate;

    } else

        s->firstpts = AV_NOPTS_VALUE;

    if (s->async) {

        if (s->min_compensation >= FLT_MAX/2)

            s->min_compensation = 0.001;

        if (s->async > 1.0001) {

            s->max_soft_compensation = s->async / (double) s->in_sample_rate;

        }

    }

    if (s->out_sample_rate!=s->in_sample_rate || (s->flags & SWR_FLAG_RESAMPLE)){

        s->resample = s->resampler->init(s->resample, s->out_sample_rate, s->in_sample_rate, s->filter_size, s->phase_shift, s->linear_interp, s->cutoff, s->int_sample_fmt, s->filter_type, s->kaiser_beta, s->precision, s->cheby);

    }else

        s->resampler->free(&s->resample);

    if(    s->int_sample_fmt != AV_SAMPLE_FMT_S16P

        && s->int_sample_fmt != AV_SAMPLE_FMT_S32P

        && s->int_sample_fmt != AV_SAMPLE_FMT_FLTP

        && s->int_sample_fmt != AV_SAMPLE_FMT_DBLP

        && s->resample){

        av_log(s, AV_LOG_ERROR, "Resampling only supported with internal s16/s32/flt/dbl\n");

        return -1;

    }

#define RSC 1 //FIXME finetune

    if(!s-> in.ch_count)

        s-> in.ch_count= av_get_channel_layout_nb_channels(s-> in_ch_layout);

    if(!s->used_ch_count)

        s->used_ch_count= s->in.ch_count;

    if(!s->out.ch_count)

        s->out.ch_count= av_get_channel_layout_nb_channels(s->out_ch_layout);

    if(!s-> in.ch_count){

        av_assert0(!s->in_ch_layout);

        av_log(s, AV_LOG_ERROR, "Input channel count and layout are unset\n");

        return -1;

    }

    if ((!s->out_ch_layout || !s->in_ch_layout) && s->used_ch_count != s->out.ch_count && !s->rematrix_custom) {

        char l1[1024], l2[1024];

        av_get_channel_layout_string(l1, sizeof(l1), s-> in.ch_count, s-> in_ch_layout);

        av_get_channel_layout_string(l2, sizeof(l2), s->out.ch_count, s->out_ch_layout);

        av_log(s, AV_LOG_ERROR, "Rematrix is needed between %s and %s "

               "but there is not enough information to do it\n", l1, l2);

        return -1;

    }

av_assert0(s->used_ch_count);

av_assert0(s->out.ch_count);

    s->resample_first= RSC*s->out.ch_count/s->in.ch_count - RSC < s->out_sample_rate/(float)s-> in_sample_rate - 1.0;

    s->in_buffer= s->in;

    s->silence  = s->in;

    s->drop_temp= s->out;

    if(!s->resample && !s->rematrix && !s->channel_map && !s->dither.method){

        s->full_convert = swri_audio_convert_alloc(s->out_sample_fmt,

                                                   s-> in_sample_fmt, s-> in.ch_count, NULL, 0);

        return 0;

    }

    s->in_convert = swri_audio_convert_alloc(s->int_sample_fmt,

                                             s-> in_sample_fmt, s->used_ch_count, s->channel_map, 0);

    s->out_convert= swri_audio_convert_alloc(s->out_sample_fmt,

                                             s->int_sample_fmt, s->out.ch_count, NULL, 0);

    if (!s->in_convert || !s->out_convert)

        return AVERROR(ENOMEM);

    s->postin= s->in;

    s->preout= s->out;

    s->midbuf= s->in;

    if(s->channel_map){

        s->postin.ch_count=

        s->midbuf.ch_count= s->used_ch_count;

        if(s->resample)

            s->in_buffer.ch_count= s->used_ch_count;

    }

    if(!s->resample_first){

        s->midbuf.ch_count= s->out.ch_count;

        if(s->resample)

            s->in_buffer.ch_count = s->out.ch_count;

    }

    set_audiodata_fmt(&s->postin, s->int_sample_fmt);

    set_audiodata_fmt(&s->midbuf, s->int_sample_fmt);

    set_audiodata_fmt(&s->preout, s->int_sample_fmt);

    if(s->resample){

        set_audiodata_fmt(&s->in_buffer, s->int_sample_fmt);

    }

    if ((ret = swri_dither_init(s, s->out_sample_fmt, s->int_sample_fmt)) < 0)

        return ret;

    if(s->rematrix || s->dither.method)

        return swri_rematrix_init(s);

    return 0;

}


static void remove_port(VirtIOSerial *vser, uint32_t port_id)

{

    VirtIOSerialPort *port;

    unsigned int i;

    i = port_id / 32;

    vser->ports_map[i] &= ~(1U << (port_id % 32));

    port = find_port_by_id(vser, port_id);

    /*

     * This function is only called from qdev's unplug callback; if we

     * get a NULL port here, we're in trouble.

     */

    assert(port);

    /* Flush out any unconsumed buffers first */

    discard_vq_data(port->ovq, VIRTIO_DEVICE(port->vser));

    send_control_event(vser, port->id, VIRTIO_CONSOLE_PORT_REMOVE, 1);

}


void rgb16tobgr32(const uint8_t *src, uint8_t *dst, unsigned int src_size)

{

	const uint16_t *end;

	uint8_t *d = (uint8_t *)dst;

	const uint16_t *s = (uint16_t *)src;

	end = s + src_size/2;

	while(s < end)

	{

		register uint16_t bgr;

		bgr = *s++;

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

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

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

		*d++ = 0;

	}

}


static int decode_audio_block(AC3DecodeContext *s, int blk)

{

    int fbw_channels = s->fbw_channels;

    int channel_mode = s->channel_mode;

    int i, bnd, seg, ch, ret;

    int different_transforms;

    int downmix_output;

    int cpl_in_use;

    GetBitContext *gbc = &s->gbc;

    uint8_t bit_alloc_stages[AC3_MAX_CHANNELS] = { 0 };

    /* block switch flags */

    different_transforms = 0;

    if (s->block_switch_syntax) {

        for (ch = 1; ch <= fbw_channels; ch++) {

            s->block_switch[ch] = get_bits1(gbc);

            if (ch > 1 && s->block_switch[ch] != s->block_switch[1])

                different_transforms = 1;

        }

    }

    /* dithering flags */

    if (s->dither_flag_syntax) {

        for (ch = 1; ch <= fbw_channels; ch++) {

            s->dither_flag[ch] = get_bits1(gbc);

        }

    }

    /* dynamic range */

    i = !s->channel_mode;

    do {

        if (get_bits1(gbc)) {

            /* Allow asymmetric application of DRC when drc_scale > 1.

               Amplification of quiet sounds is enhanced */

            int range_bits = get_bits(gbc, 8);

            INTFLOAT range = AC3_RANGE(range_bits);

            if (range_bits <= 127 || s->drc_scale <= 1.0)

                s->dynamic_range[i] = AC3_DYNAMIC_RANGE(range);

            else

                s->dynamic_range[i] = range;

        } else if (blk == 0) {

            s->dynamic_range[i] = AC3_DYNAMIC_RANGE1;

        }

    } while (i--);

    /* spectral extension strategy */

    if (s->eac3 && (!blk || get_bits1(gbc))) {

        s->spx_in_use = get_bits1(gbc);

        if (s->spx_in_use) {

            if ((ret = spx_strategy(s, blk)) < 0)

                return ret;

        }

    }

    if (!s->eac3 || !s->spx_in_use) {

        s->spx_in_use = 0;

        for (ch = 1; ch <= fbw_channels; ch++) {

            s->channel_uses_spx[ch] = 0;

            s->first_spx_coords[ch] = 1;

        }

    }

    /* spectral extension coordinates */

    if (s->spx_in_use)

        spx_coordinates(s);

    /* coupling strategy */

    if (s->eac3 ? s->cpl_strategy_exists[blk] : get_bits1(gbc)) {

        if ((ret = coupling_strategy(s, blk, bit_alloc_stages)) < 0)

            return ret;

    } else if (!s->eac3) {

        if (!blk) {

            av_log(s->avctx, AV_LOG_ERROR, "new coupling strategy must "

                   "be present in block 0\n");

            return AVERROR_INVALIDDATA;

        } else {

            s->cpl_in_use[blk] = s->cpl_in_use[blk-1];

        }

    }

    cpl_in_use = s->cpl_in_use[blk];

    /* coupling coordinates */

    if (cpl_in_use) {

        if ((ret = coupling_coordinates(s, blk)) < 0)

            return ret;

    }

    /* stereo rematrixing strategy and band structure */

    if (channel_mode == AC3_CHMODE_STEREO) {

        if ((s->eac3 && !blk) || get_bits1(gbc)) {

            s->num_rematrixing_bands = 4;

            if (cpl_in_use && s->start_freq[CPL_CH] <= 61) {

                s->num_rematrixing_bands -= 1 + (s->start_freq[CPL_CH] == 37);

            } else if (s->spx_in_use && s->spx_src_start_freq <= 61) {

                s->num_rematrixing_bands--;

            }

            for (bnd = 0; bnd < s->num_rematrixing_bands; bnd++)

                s->rematrixing_flags[bnd] = get_bits1(gbc);

        } else if (!blk) {

            av_log(s->avctx, AV_LOG_WARNING, "Warning: "

                   "new rematrixing strategy not present in block 0\n");

            s->num_rematrixing_bands = 0;

        }

    }

    /* exponent strategies for each channel */

    for (ch = !cpl_in_use; ch <= s->channels; ch++) {

        if (!s->eac3)

            s->exp_strategy[blk][ch] = get_bits(gbc, 2 - (ch == s->lfe_ch));

        if (s->exp_strategy[blk][ch] != EXP_REUSE)

            bit_alloc_stages[ch] = 3;

    }

    /* channel bandwidth */

    for (ch = 1; ch <= fbw_channels; ch++) {

        s->start_freq[ch] = 0;

        if (s->exp_strategy[blk][ch] != EXP_REUSE) {

            int group_size;

            int prev = s->end_freq[ch];

            if (s->channel_in_cpl[ch])

                s->end_freq[ch] = s->start_freq[CPL_CH];

            else if (s->channel_uses_spx[ch])

                s->end_freq[ch] = s->spx_src_start_freq;

            else {

                int bandwidth_code = get_bits(gbc, 6);

                if (bandwidth_code > 60) {

                    av_log(s->avctx, AV_LOG_ERROR, "bandwidth code = %d > 60\n", bandwidth_code);

                    return AVERROR_INVALIDDATA;

                }

                s->end_freq[ch] = bandwidth_code * 3 + 73;

            }

            group_size = 3 << (s->exp_strategy[blk][ch] - 1);

            s->num_exp_groups[ch] = (s->end_freq[ch] + group_size-4) / group_size;

            if (blk > 0 && s->end_freq[ch] != prev)

                memset(bit_alloc_stages, 3, AC3_MAX_CHANNELS);

        }

    }

    if (cpl_in_use && s->exp_strategy[blk][CPL_CH] != EXP_REUSE) {

        s->num_exp_groups[CPL_CH] = (s->end_freq[CPL_CH] - s->start_freq[CPL_CH]) /

                                    (3 << (s->exp_strategy[blk][CPL_CH] - 1));

    }

    /* decode exponents for each channel */

    for (ch = !cpl_in_use; ch <= s->channels; ch++) {

        if (s->exp_strategy[blk][ch] != EXP_REUSE) {

            s->dexps[ch][0] = get_bits(gbc, 4) << !ch;

            if (decode_exponents(s, gbc, s->exp_strategy[blk][ch],

                                 s->num_exp_groups[ch], s->dexps[ch][0],

                                 &s->dexps[ch][s->start_freq[ch]+!!ch])) {

                return AVERROR_INVALIDDATA;

            }

            if (ch != CPL_CH && ch != s->lfe_ch)

                skip_bits(gbc, 2); /* skip gainrng */

        }

    }

    /* bit allocation information */

    if (s->bit_allocation_syntax) {

        if (get_bits1(gbc)) {

            s->bit_alloc_params.slow_decay = ff_ac3_slow_decay_tab[get_bits(gbc, 2)] >> s->bit_alloc_params.sr_shift;

            s->bit_alloc_params.fast_decay = ff_ac3_fast_decay_tab[get_bits(gbc, 2)] >> s->bit_alloc_params.sr_shift;

            s->bit_alloc_params.slow_gain  = ff_ac3_slow_gain_tab[get_bits(gbc, 2)];

            s->bit_alloc_params.db_per_bit = ff_ac3_db_per_bit_tab[get_bits(gbc, 2)];

            s->bit_alloc_params.floor  = ff_ac3_floor_tab[get_bits(gbc, 3)];

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

                bit_alloc_stages[ch] = FFMAX(bit_alloc_stages[ch], 2);

        } else if (!blk) {

            av_log(s->avctx, AV_LOG_ERROR, "new bit allocation info must "

                   "be present in block 0\n");

            return AVERROR_INVALIDDATA;

        }

    }

    /* signal-to-noise ratio offsets and fast gains (signal-to-mask ratios) */

    if (!s->eac3 || !blk) {

        if (s->snr_offset_strategy && get_bits1(gbc)) {

            int snr = 0;

            int csnr;

            csnr = (get_bits(gbc, 6) - 15) << 4;

            for (i = ch = !cpl_in_use; ch <= s->channels; ch++) {

                /* snr offset */

                if (ch == i || s->snr_offset_strategy == 2)

                    snr = (csnr + get_bits(gbc, 4)) << 2;

                /* run at least last bit allocation stage if snr offset changes */

                if (blk && s->snr_offset[ch] != snr) {

                    bit_alloc_stages[ch] = FFMAX(bit_alloc_stages[ch], 1);

                }

                s->snr_offset[ch] = snr;

                /* fast gain (normal AC-3 only) */

                if (!s->eac3) {

                    int prev = s->fast_gain[ch];

                    s->fast_gain[ch] = ff_ac3_fast_gain_tab[get_bits(gbc, 3)];

                    /* run last 2 bit allocation stages if fast gain changes */

                    if (blk && prev != s->fast_gain[ch])

                        bit_alloc_stages[ch] = FFMAX(bit_alloc_stages[ch], 2);

                }

            }

        } else if (!s->eac3 && !blk) {

            av_log(s->avctx, AV_LOG_ERROR, "new snr offsets must be present in block 0\n");

            return AVERROR_INVALIDDATA;

        }

    }

    /* fast gain (E-AC-3 only) */

    if (s->fast_gain_syntax && get_bits1(gbc)) {

        for (ch = !cpl_in_use; ch <= s->channels; ch++) {

            int prev = s->fast_gain[ch];

            s->fast_gain[ch] = ff_ac3_fast_gain_tab[get_bits(gbc, 3)];

            /* run last 2 bit allocation stages if fast gain changes */

            if (blk && prev != s->fast_gain[ch])

                bit_alloc_stages[ch] = FFMAX(bit_alloc_stages[ch], 2);

        }

    } else if (s->eac3 && !blk) {

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

            s->fast_gain[ch] = ff_ac3_fast_gain_tab[4];

    }

    /* E-AC-3 to AC-3 converter SNR offset */

    if (s->frame_type == EAC3_FRAME_TYPE_INDEPENDENT && get_bits1(gbc)) {

        skip_bits(gbc, 10); // skip converter snr offset

    }

    /* coupling leak information */

    if (cpl_in_use) {

        if (s->first_cpl_leak || get_bits1(gbc)) {

            int fl = get_bits(gbc, 3);

            int sl = get_bits(gbc, 3);

            /* run last 2 bit allocation stages for coupling channel if

               coupling leak changes */

            if (blk && (fl != s->bit_alloc_params.cpl_fast_leak ||

                sl != s->bit_alloc_params.cpl_slow_leak)) {

                bit_alloc_stages[CPL_CH] = FFMAX(bit_alloc_stages[CPL_CH], 2);

            }

            s->bit_alloc_params.cpl_fast_leak = fl;

            s->bit_alloc_params.cpl_slow_leak = sl;

        } else if (!s->eac3 && !blk) {

            av_log(s->avctx, AV_LOG_ERROR, "new coupling leak info must "

                   "be present in block 0\n");

            return AVERROR_INVALIDDATA;

        }

        s->first_cpl_leak = 0;

    }

    /* delta bit allocation information */

    if (s->dba_syntax && get_bits1(gbc)) {

        /* delta bit allocation exists (strategy) */

        for (ch = !cpl_in_use; ch <= fbw_channels; ch++) {

            s->dba_mode[ch] = get_bits(gbc, 2);

            if (s->dba_mode[ch] == DBA_RESERVED) {

                av_log(s->avctx, AV_LOG_ERROR, "delta bit allocation strategy reserved\n");

                return AVERROR_INVALIDDATA;

            }

            bit_alloc_stages[ch] = FFMAX(bit_alloc_stages[ch], 2);

        }

        /* channel delta offset, len and bit allocation */

        for (ch = !cpl_in_use; ch <= fbw_channels; ch++) {

            if (s->dba_mode[ch] == DBA_NEW) {

                s->dba_nsegs[ch] = get_bits(gbc, 3) + 1;

                for (seg = 0; seg < s->dba_nsegs[ch]; seg++) {

                    s->dba_offsets[ch][seg] = get_bits(gbc, 5);

                    s->dba_lengths[ch][seg] = get_bits(gbc, 4);

                    s->dba_values[ch][seg]  = get_bits(gbc, 3);

                }

                /* run last 2 bit allocation stages if new dba values */

                bit_alloc_stages[ch] = FFMAX(bit_alloc_stages[ch], 2);

            }

        }

    } else if (blk == 0) {

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

            s->dba_mode[ch] = DBA_NONE;

        }

    }

    /* Bit allocation */

    for (ch = !cpl_in_use; ch <= s->channels; ch++) {

        if (bit_alloc_stages[ch] > 2) {

            /* Exponent mapping into PSD and PSD integration */

            ff_ac3_bit_alloc_calc_psd(s->dexps[ch],

                                      s->start_freq[ch], s->end_freq[ch],

                                      s->psd[ch], s->band_psd[ch]);

        }

        if (bit_alloc_stages[ch] > 1) {

            /* Compute excitation function, Compute masking curve, and

               Apply delta bit allocation */

            if (ff_ac3_bit_alloc_calc_mask(&s->bit_alloc_params, s->band_psd[ch],

                                           s->start_freq[ch],  s->end_freq[ch],

                                           s->fast_gain[ch],   (ch == s->lfe_ch),

                                           s->dba_mode[ch],    s->dba_nsegs[ch],

                                           s->dba_offsets[ch], s->dba_lengths[ch],

                                           s->dba_values[ch],  s->mask[ch])) {

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

                return AVERROR_INVALIDDATA;

            }

        }

        if (bit_alloc_stages[ch] > 0) {

            /* Compute bit allocation */

            const uint8_t *bap_tab = s->channel_uses_aht[ch] ?

                                     ff_eac3_hebap_tab : ff_ac3_bap_tab;

            s->ac3dsp.bit_alloc_calc_bap(s->mask[ch], s->psd[ch],

                                      s->start_freq[ch], s->end_freq[ch],

                                      s->snr_offset[ch],

                                      s->bit_alloc_params.floor,

                                      bap_tab, s->bap[ch]);

        }

    }

    /* unused dummy data */

    if (s->skip_syntax && get_bits1(gbc)) {

        int skipl = get_bits(gbc, 9);

        skip_bits_long(gbc, 8 * skipl);

    }

    /* unpack the transform coefficients

       this also uncouples channels if coupling is in use. */

    decode_transform_coeffs(s, blk);

    /* TODO: generate enhanced coupling coordinates and uncouple */

    /* recover coefficients if rematrixing is in use */

    if (s->channel_mode == AC3_CHMODE_STEREO)

        do_rematrixing(s);

    /* apply scaling to coefficients (headroom, dynrng) */

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

        int audio_channel = 0;

        INTFLOAT gain;

        if (s->channel_mode == AC3_CHMODE_DUALMONO)

            audio_channel = 2-ch;

        if (s->heavy_compression && s->compression_exists[audio_channel])

            gain = s->heavy_dynamic_range[audio_channel];

        else

            gain = s->dynamic_range[audio_channel];

#if USE_FIXED

        scale_coefs(s->transform_coeffs[ch], s->fixed_coeffs[ch], gain, 256);

#else

        if (s->target_level != 0)

          gain = gain * s->level_gain[audio_channel];

        gain *= 1.0 / 4194304.0f;

        s->fmt_conv.int32_to_float_fmul_scalar(s->transform_coeffs[ch],

                                               s->fixed_coeffs[ch], gain, 256);

#endif

    }

    /* apply spectral extension to high frequency bins */

    if (CONFIG_EAC3_DECODER && s->spx_in_use) {

        ff_eac3_apply_spectral_extension(s);

    }

    /* downmix and MDCT. order depends on whether block switching is used for

       any channel in this block. this is because coefficients for the long

       and short transforms cannot be mixed. */

    downmix_output = s->channels != s->out_channels &&

                     !((s->output_mode & AC3_OUTPUT_LFEON) &&

                     s->fbw_channels == s->out_channels);

    if (different_transforms) {

        /* the delay samples have already been downmixed, so we upmix the delay

           samples in order to reconstruct all channels before downmixing. */

        if (s->downmixed) {

            s->downmixed = 0;

            ac3_upmix_delay(s);

        }

        do_imdct(s, s->channels);

        if (downmix_output) {

#if USE_FIXED

            ac3_downmix_c_fixed16(s->outptr, s->downmix_coeffs,

                              s->out_channels, s->fbw_channels, 256);

#else

            ff_ac3dsp_downmix(&s->ac3dsp, s->outptr, s->downmix_coeffs,

                              s->out_channels, s->fbw_channels, 256);

#endif

        }

    } else {

        if (downmix_output) {

            AC3_RENAME(ff_ac3dsp_downmix)(&s->ac3dsp, s->xcfptr + 1, s->downmix_coeffs,

                                          s->out_channels, s->fbw_channels, 256);

        }

        if (downmix_output && !s->downmixed) {

            s->downmixed = 1;

            AC3_RENAME(ff_ac3dsp_downmix)(&s->ac3dsp, s->dlyptr, s->downmix_coeffs,

                                          s->out_channels, s->fbw_channels, 128);

        }

        do_imdct(s, s->out_channels);

    }

    return 0;

}


static void write_header(AVFormatContext *s)

{

    double min_buffer_time = 1.0;

    avio_printf(s->pb, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");

    avio_printf(s->pb, "<MPD\n");

    avio_printf(s->pb, "  xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n");

    avio_printf(s->pb, "  xmlns=\"urn:mpeg:DASH:schema:MPD:2011\"\n");

    avio_printf(s->pb, "  xsi:schemaLocation=\"urn:mpeg:DASH:schema:MPD:2011\"\n");

    avio_printf(s->pb, "  type=\"static\"\n");

    avio_printf(s->pb, "  mediaPresentationDuration=\"PT%gS\"\n",

                get_duration(s));

    avio_printf(s->pb, "  minBufferTime=\"PT%gS\"\n",

                min_buffer_time);

    avio_printf(s->pb, "  profiles=\"urn:webm:dash:profile:webm-on-demand:2012\"");

    avio_printf(s->pb, ">\n");

}


static void opt_input_file(void *optctx, const char *arg)

{

    if (input_filename) {

        fprintf(stderr,

                "Argument '%s' provided as input filename, but '%s' was already specified.\n",

                arg, input_filename);

        exit(1);

    }

    if (!strcmp(arg, "-"))

        arg = "pipe:";

    input_filename = arg;

}


static void gen_rlwinm(DisasContext *ctx)

{

    uint32_t mb, me, sh;

    sh = SH(ctx->opcode);

    mb = MB(ctx->opcode);

    me = ME(ctx->opcode);

    if (likely(mb == 0 && me == (31 - sh))) {

        if (likely(sh == 0)) {

            tcg_gen_ext32u_tl(cpu_gpr[rA(ctx->opcode)], cpu_gpr[rS(ctx->opcode)]);

        } else {

            TCGv t0 = tcg_temp_new();

            tcg_gen_ext32u_tl(t0, cpu_gpr[rS(ctx->opcode)]);

            tcg_gen_shli_tl(t0, t0, sh);

            tcg_gen_ext32u_tl(cpu_gpr[rA(ctx->opcode)], t0);

            tcg_temp_free(t0);

        }

    } else if (likely(sh != 0 && me == 31 && sh == (32 - mb))) {

        TCGv t0 = tcg_temp_new();

        tcg_gen_ext32u_tl(t0, cpu_gpr[rS(ctx->opcode)]);

        tcg_gen_shri_tl(t0, t0, mb);

        tcg_gen_ext32u_tl(cpu_gpr[rA(ctx->opcode)], t0);

        tcg_temp_free(t0);

    } else if (likely(mb == 0 && me == 31)) {

        TCGv_i32 t0 = tcg_temp_new_i32();

        tcg_gen_trunc_tl_i32(t0, cpu_gpr[rS(ctx->opcode)]);

        tcg_gen_rotli_i32(t0, t0, sh);

        tcg_gen_extu_i32_tl(cpu_gpr[rA(ctx->opcode)], t0);

        tcg_temp_free_i32(t0);

    } else {

        TCGv t0 = tcg_temp_new();

#if defined(TARGET_PPC64)

        tcg_gen_deposit_i64(t0, cpu_gpr[rS(ctx->opcode)],

            cpu_gpr[rS(ctx->opcode)], 32, 32);

        tcg_gen_rotli_i64(t0, t0, sh);

#else

        tcg_gen_rotli_i32(t0, cpu_gpr[rS(ctx->opcode)], sh);

#endif

#if defined(TARGET_PPC64)

        mb += 32;

        me += 32;

#endif

        tcg_gen_andi_tl(cpu_gpr[rA(ctx->opcode)], t0, MASK(mb, me));

        tcg_temp_free(t0);

    }

    if (unlikely(Rc(ctx->opcode) != 0))

        gen_set_Rc0(ctx, cpu_gpr[rA(ctx->opcode)]);

}


static int transcode_subtitles(InputStream *ist, AVPacket *pkt, int *got_output)

{

    AVSubtitle subtitle;

    int i, ret = avcodec_decode_subtitle2(ist->dec_ctx,

                                          &subtitle, got_output, pkt);

    if (ret < 0)

        return ret;

    if (!*got_output)

        return ret;

    ist->frames_decoded++;

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

        OutputStream *ost = output_streams[i];

        if (!check_output_constraints(ist, ost) || !ost->encoding_needed)

            continue;

        do_subtitle_out(output_files[ost->file_index]->ctx, ost, ist, &subtitle, pkt->pts);

    }

    avsubtitle_free(&subtitle);

    return ret;

}


void bdrv_setup_io_funcs(BlockDriver *bdrv)

{

    /* Block drivers without coroutine functions need emulation */

    if (!bdrv->bdrv_co_readv) {

        bdrv->bdrv_co_readv = bdrv_co_readv_em;

        bdrv->bdrv_co_writev = bdrv_co_writev_em;

        /* bdrv_co_readv_em()/brdv_co_writev_em() work in terms of aio, so if

         * the block driver lacks aio we need to emulate that too.

         */

        if (!bdrv->bdrv_aio_readv) {

            /* add AIO emulation layer */

            bdrv->bdrv_aio_readv = bdrv_aio_readv_em;

            bdrv->bdrv_aio_writev = bdrv_aio_writev_em;

        }

    }

}


static void ff_h264_idct8_add4_mmx(uint8_t *dst, const int *block_offset, DCTELEM *block, int stride, const uint8_t nnzc[6*8]){

    int i;

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

        if(nnzc[ scan8[i] ])

            ff_h264_idct8_add_mmx(dst + block_offset[i], block + i*16, stride);

    }

}


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

{

    char tmp_key[5];

    char str[1024], key2[32], language[4] = {0};

    const char *key = NULL;

    uint16_t langcode = 0;

    uint32_t data_type = 0, str_size;

    int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL;

    switch (atom.type) {

    case MKTAG(0xa9,'n','a','m'): key = "title";     break;

    case MKTAG(0xa9,'a','u','t'):

    case MKTAG(0xa9,'A','R','T'): key = "artist";    break;

    case MKTAG( 'a','A','R','T'): key = "album_artist";    break;

    case MKTAG(0xa9,'w','r','t'): key = "composer";  break;

    case MKTAG( 'c','p','r','t'):

    case MKTAG(0xa9,'c','p','y'): key = "copyright"; break;

    case MKTAG(0xa9,'c','m','t'):

    case MKTAG(0xa9,'i','n','f'): key = "comment";   break;

    case MKTAG(0xa9,'a','l','b'): key = "album";     break;

    case MKTAG(0xa9,'d','a','y'): key = "date";      break;

    case MKTAG(0xa9,'g','e','n'): key = "genre";     break;

    case MKTAG( 'g','n','r','e'): key = "genre";

        parse = mov_metadata_gnre; break;

    case MKTAG(0xa9,'t','o','o'):

    case MKTAG(0xa9,'s','w','r'): key = "encoder";   break;

    case MKTAG(0xa9,'e','n','c'): key = "encoder";   break;

    case MKTAG(0xa9,'x','y','z'): key = "location";  break;

    case MKTAG( 'd','e','s','c'): key = "description";break;

    case MKTAG( 'l','d','e','s'): key = "synopsis";  break;

    case MKTAG( 't','v','s','h'): key = "show";      break;

    case MKTAG( 't','v','e','n'): key = "episode_id";break;

    case MKTAG( 't','v','n','n'): key = "network";   break;

    case MKTAG( 't','r','k','n'): key = "track";

        parse = mov_metadata_track_or_disc_number; break;

    case MKTAG( 'd','i','s','k'): key = "disc";

        parse = mov_metadata_track_or_disc_number; break;

    case MKTAG( 't','v','e','s'): key = "episode_sort";

        parse = mov_metadata_int8_bypass_padding; break;

    case MKTAG( 't','v','s','n'): key = "season_number";

        parse = mov_metadata_int8_bypass_padding; break;

    case MKTAG( 's','t','i','k'): key = "media_type";

        parse = mov_metadata_int8_no_padding; break;

    case MKTAG( 'h','d','v','d'): key = "hd_video";

        parse = mov_metadata_int8_no_padding; break;

    case MKTAG( 'p','g','a','p'): key = "gapless_playback";

        parse = mov_metadata_int8_no_padding; break;

    case MKTAG( 'l','o','c','i'):

        return mov_metadata_loci(c, pb, atom.size);

    }

    if (c->itunes_metadata && atom.size > 8) {

        int data_size = avio_rb32(pb);

        int tag = avio_rl32(pb);

        if (tag == MKTAG('d','a','t','a')) {

            data_type = avio_rb32(pb); // type

            avio_rb32(pb); // unknown

            str_size = data_size - 16;

            atom.size -= 16;

            if (atom.type == MKTAG('c', 'o', 'v', 'r')) {

                int ret = mov_read_covr(c, pb, data_type, str_size);

                if (ret < 0) {

                    av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n");

                    return ret;

                }

            }

        } else return 0;

    } else if (atom.size > 4 && key && !c->itunes_metadata) {

        str_size = avio_rb16(pb); // string length

        langcode = avio_rb16(pb);

        ff_mov_lang_to_iso639(langcode, language);

        atom.size -= 4;

    } else

        str_size = atom.size;

    if (c->export_all && !key) {

        snprintf(tmp_key, 5, "%.4s", (char*)&atom.type);

        key = tmp_key;

    }

    if (!key)

        return 0;

    if (atom.size < 0)

        return AVERROR_INVALIDDATA;

    str_size = FFMIN3(sizeof(str)-1, str_size, atom.size);

    if (parse)

        parse(c, pb, str_size, key);

    else {

        if (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff))) { // MAC Encoded

            mov_read_mac_string(c, pb, str_size, str, sizeof(str));

        } else {

            avio_read(pb, str, str_size);

            str[str_size] = 0;

        }

        c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;

        av_dict_set(&c->fc->metadata, key, str, 0);

        if (*language && strcmp(language, "und")) {

            snprintf(key2, sizeof(key2), "%s-%s", key, language);

            av_dict_set(&c->fc->metadata, key2, str, 0);

        }

    }

    av_dlog(c->fc, "lang \"%3s\" ", language);

    av_dlog(c->fc, "tag \"%s\" value \"%s\" atom \"%.4s\" %d %"PRId64"\n",

            key, str, (char*)&atom.type, str_size, atom.size);

    return 0;

}


size_t virtio_serial_guest_ready(VirtIOSerialPort *port)

{

    VirtQueue *vq = port->ivq;

    unsigned int bytes;

    if (!virtio_queue_ready(vq) ||

        !(port->vser->vdev.status & VIRTIO_CONFIG_S_DRIVER_OK) ||

        virtio_queue_empty(vq)) {

        return 0;

    }

    if (use_multiport(port->vser) && !port->guest_connected) {

        return 0;

    }

    virtqueue_get_avail_bytes(vq, &bytes, NULL);

    return bytes;

}


DriveInfo *add_init_drive(const char *optstr)

{

    DriveInfo *dinfo;

    QemuOpts *opts;

    opts = drive_def(optstr);

    if (!opts)

        return NULL;

    dinfo = drive_init(opts, current_machine->use_scsi);

    if (!dinfo) {

        qemu_opts_del(opts);

        return NULL;

    }

    return dinfo;

}


static BusState *qbus_find_recursive(BusState *bus, const char *name,

                                     const char *bus_typename)

{

    BusChild *kid;

    BusState *child, *ret;

    int match = 1;

    if (name && (strcmp(bus->name, name) != 0)) {

        match = 0;

    }

    if (bus_typename &&

        (strcmp(object_get_typename(OBJECT(bus)), bus_typename) != 0)) {

        match = 0;

    }

    if (match) {

        return bus;

    }

    QTAILQ_FOREACH(kid, &bus->children, sibling) {

        DeviceState *dev = kid->child;

        QLIST_FOREACH(child, &dev->child_bus, sibling) {

            ret = qbus_find_recursive(child, name, bus_typename);

            if (ret) {

                return ret;

            }

        }

    }

    return NULL;

}


void qemu_input_event_sync(void)

{

    QemuInputHandlerState *s;

    if (!runstate_is_running() && !runstate_check(RUN_STATE_SUSPENDED)) {

        return;

    }

    trace_input_event_sync();

    QTAILQ_FOREACH(s, &handlers, node) {

        if (!s->events) {

            continue;

        }

        if (s->handler->sync) {

            s->handler->sync(s->dev);

        }

        s->events = 0;

    }

}


static int nvdec_h264_decode_init(AVCodecContext *avctx)

{

    const H264Context *h = avctx->priv_data;

    const SPS       *sps = h->ps.sps;

    return ff_nvdec_decode_init(avctx, sps->ref_frame_count + sps->num_reorder_frames);

}


static void mxf_free_metadataset(MXFMetadataSet **ctx, int freectx)

{

    MXFIndexTableSegment *seg;

    switch ((*ctx)->type) {

    case Descriptor:

        av_freep(&((MXFDescriptor *)*ctx)->extradata);

        break;

    case MultipleDescriptor:

        av_freep(&((MXFDescriptor *)*ctx)->sub_descriptors_refs);

        break;

    case Sequence:

        av_freep(&((MXFSequence *)*ctx)->structural_components_refs);

        break;

    case EssenceGroup:

        av_freep(&((MXFEssenceGroup *)*ctx)->structural_components_refs);

        break;

    case SourcePackage:

    case MaterialPackage:

        av_freep(&((MXFPackage *)*ctx)->tracks_refs);

        av_freep(&((MXFPackage *)*ctx)->name);

        break;

    case TaggedValue:

        av_freep(&((MXFTaggedValue *)*ctx)->name);

        av_freep(&((MXFTaggedValue *)*ctx)->value);

        break;

    case IndexTableSegment:

        seg = (MXFIndexTableSegment *)*ctx;

        av_freep(&seg->temporal_offset_entries);

        av_freep(&seg->flag_entries);

        av_freep(&seg->stream_offset_entries);

    default:

        break;

    }

    if (freectx)

    av_freep(ctx);

}


static void test_visitor_in_native_list_int64(TestInputVisitorData *data,

                                              const void *unused)

{

    test_native_list_integer_helper(data, unused,

                                    USER_DEF_NATIVE_LIST_UNION_KIND_S64);

}


static void qint_destroy_obj(QObject *obj)

{

    assert(obj != NULL);

    g_free(qobject_to_qint(obj));

}


int ioinst_handle_tsch(S390CPU *cpu, uint64_t reg1, uint32_t ipb)

{

    CPUS390XState *env = &cpu->env;

    int cssid, ssid, schid, m;

    SubchDev *sch;

    IRB irb;

    uint64_t addr;

    int cc, irb_len;

    uint8_t ar;

    if (ioinst_disassemble_sch_ident(reg1, &m, &cssid, &ssid, &schid)) {

        program_interrupt(env, PGM_OPERAND, 2);

        return -EIO;

    }

    trace_ioinst_sch_id("tsch", cssid, ssid, schid);

    addr = decode_basedisp_s(env, ipb, &ar);

    if (addr & 3) {

        program_interrupt(env, PGM_SPECIFICATION, 2);

        return -EIO;

    }

    sch = css_find_subch(m, cssid, ssid, schid);

    if (sch && css_subch_visible(sch)) {

        cc = css_do_tsch_get_irb(sch, &irb, &irb_len);

    } else {

        cc = 3;

    }

    /* 0 - status pending, 1 - not status pending, 3 - not operational */

    if (cc != 3) {

        if (s390_cpu_virt_mem_write(cpu, addr, ar, &irb, irb_len) != 0) {

            return -EFAULT;

        }

        css_do_tsch_update_subch(sch);

    } else {

        irb_len = sizeof(irb) - sizeof(irb.emw);

        /* Access exceptions have a higher priority than cc3 */

        if (s390_cpu_virt_mem_check_write(cpu, addr, ar, irb_len) != 0) {

            return -EFAULT;

        }

    }

    setcc(cpu, cc);

    return 0;

}


static int lag_decode_arith_plane(LagarithContext *l, uint8_t *dst,

                                  int width, int height, int stride,

                                  const uint8_t *src, int src_size)

{

    int i = 0;

    int read = 0;

    uint32_t length;

    uint32_t offset = 1;

    int esc_count;

    GetBitContext gb;

    lag_rac rac;

    const uint8_t *src_end = src + src_size;

    rac.avctx = l->avctx;

    l->zeros = 0;

    if(src_size < 2)

        return AVERROR_INVALIDDATA;

    esc_count = src[0];

    if (esc_count < 4) {

        length = width * height;

        if(src_size < 5)

            return AVERROR_INVALIDDATA;

        if (esc_count && AV_RL32(src + 1) < length) {

            length = AV_RL32(src + 1);

            offset += 4;

        }

        init_get_bits8(&gb, src + offset, src_size - offset);

        if (lag_read_prob_header(&rac, &gb) < 0)

            return -1;

        ff_lag_rac_init(&rac, &gb, length - stride);

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

            read += lag_decode_line(l, &rac, dst + (i * stride), width,

                                    stride, esc_count);

        if (read > length)

            av_log(l->avctx, AV_LOG_WARNING,

                   "Output more bytes than length (%d of %d)\n", read,

                   length);

    } else if (esc_count < 8) {

        esc_count -= 4;

        src ++;

        src_size --;

        if (esc_count > 0) {

            /* Zero run coding only, no range coding. */

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

                int res = lag_decode_zero_run_line(l, dst + (i * stride), src,

                                                   src_end, width, esc_count);

                if (res < 0)

                    return res;

                src += res;

            }

        } else {

            if (src_size < width * height)

                return AVERROR_INVALIDDATA; // buffer not big enough

            /* Plane is stored uncompressed */

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

                memcpy(dst + (i * stride), src, width);

                src += width;

            }

        }

    } else if (esc_count == 0xff) {

        /* Plane is a solid run of given value */

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

            memset(dst + i * stride, src[1], width);

        /* Do not apply prediction.

           Note: memset to 0 above, setting first value to src[1]

           and applying prediction gives the same result. */

        return 0;

    } else {

        av_log(l->avctx, AV_LOG_ERROR,

               "Invalid zero run escape code! (%#x)\n", esc_count);

        return -1;

    }

    if (l->avctx->pix_fmt != AV_PIX_FMT_YUV422P) {

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

            lag_pred_line(l, dst, width, stride, i);

            dst += stride;

        }

    } else {

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

            lag_pred_line_yuy2(l, dst, width, stride, i,

                               width == l->avctx->width);

            dst += stride;

        }

    }

    return 0;

}


static ssize_t v9fs_synth_pwritev(FsContext *ctx, V9fsFidOpenState *fs,

                                  const struct iovec *iov,

                                  int iovcnt, off_t offset)

{

    int i, count = 0, wcount;

    V9fsSynthOpenState *synth_open = fs->private;

    V9fsSynthNode *node = synth_open->node;

    if (!node->attr->write) {

        errno = EPERM;

        return -1;

    }

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

        wcount = node->attr->write(iov[i].iov_base, iov[i].iov_len,

                                   offset, node->private);

        offset += wcount;

        count  += wcount;

        /* If we wrote less than requested. we are done */

        if (wcount < iov[i].iov_len) {

            break;

        }

    }

    return count;

}


static void piix4_device_unplug_request_cb(HotplugHandler *hotplug_dev,

                                           DeviceState *dev, Error **errp)

{

    PIIX4PMState *s = PIIX4_PM(hotplug_dev);

    if (s->acpi_memory_hotplug.is_enabled &&

        object_dynamic_cast(OBJECT(dev), TYPE_PC_DIMM)) {

        acpi_memory_unplug_request_cb(hotplug_dev, &s->acpi_memory_hotplug,

                                      dev, errp);

    } else if (object_dynamic_cast(OBJECT(dev), TYPE_PCI_DEVICE)) {

        acpi_pcihp_device_unplug_cb(hotplug_dev, &s->acpi_pci_hotplug, dev,

                                    errp);

    } else if (object_dynamic_cast(OBJECT(dev), TYPE_CPU) &&

               !s->cpu_hotplug_legacy) {

        acpi_cpu_unplug_request_cb(hotplug_dev, &s->cpuhp_state, dev, errp);

    } else {

        error_setg(errp, "acpi: device unplug request for not supported device"

                   " type: %s", object_get_typename(OBJECT(dev)));

    }

}


static av_cold int smc_decode_init(AVCodecContext *avctx)

{

    SmcContext *s = avctx->priv_data;

    s->avctx = avctx;

    avctx->pix_fmt = AV_PIX_FMT_PAL8;

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

    return 0;

}


static void ohci_td_pkt(const char *msg, const uint8_t *buf, size_t len)

{

    bool print16 = !!trace_event_get_state(TRACE_USB_OHCI_TD_PKT_SHORT);

    bool printall = !!trace_event_get_state(TRACE_USB_OHCI_TD_PKT_FULL);

    const int width = 16;

    int i;

    char tmp[3 * width + 1];

    char *p = tmp;

    if (!printall && !print16) {

        return;

    }

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

        if (i && (!(i % width) || (i == len))) {

            if (!printall) {

                trace_usb_ohci_td_pkt_short(msg, tmp);

                break;

            }

            trace_usb_ohci_td_pkt_full(msg, tmp);

            p = tmp;

            *p = 0;

        }

        if (i == len) {

            break;

        }

        p += sprintf(p, " %.2x", buf[i]);

    }

}


void ff_set_fixed_vector(float *out, const AMRFixed *in, float scale, int size)

{

    int i;

    for (i=0; i < in->n; i++) {

        int x   = in->x[i], repeats = !((in->no_repeat_mask >> i) & 1);

        float y = in->y[i] * scale;

        do {

            out[x] += y;

            y *= in->pitch_fac;

            x += in->pitch_lag;

        } while (x < size && repeats);

    }

}


int do_subchannel_work_virtual(SubchDev *sch)

{

    SCSW *s = &sch->curr_status.scsw;

    if (s->ctrl & SCSW_FCTL_CLEAR_FUNC) {

        sch_handle_clear_func(sch);

    } else if (s->ctrl & SCSW_FCTL_HALT_FUNC) {

        sch_handle_halt_func(sch);

    } else if (s->ctrl & SCSW_FCTL_START_FUNC) {

        /* Triggered by both ssch and rsch. */

        sch_handle_start_func_virtual(sch);

    } else {

        /* Cannot happen. */

        return 0;

    }

    css_inject_io_interrupt(sch);

    return 0;

}


static inline uint64_t ldq_phys_internal(target_phys_addr_t addr,

                                         enum device_endian endian)

{

    uint8_t *ptr;

    uint64_t val;

    MemoryRegionSection *section;

    section = phys_page_find(address_space_memory.dispatch, addr >> TARGET_PAGE_BITS);

    if (!(memory_region_is_ram(section->mr) ||

          memory_region_is_romd(section->mr))) {

        /* I/O case */

        addr = memory_region_section_addr(section, addr);

        /* XXX This is broken when device endian != cpu endian.

               Fix and add "endian" variable check */

#ifdef TARGET_WORDS_BIGENDIAN

        val = io_mem_read(section->mr, addr, 4) << 32;

        val |= io_mem_read(section->mr, addr + 4, 4);

#else

        val = io_mem_read(section->mr, addr, 4);

        val |= io_mem_read(section->mr, addr + 4, 4) << 32;

#endif

    } else {

        /* RAM case */

        ptr = qemu_get_ram_ptr((memory_region_get_ram_addr(section->mr)

                                & TARGET_PAGE_MASK)

                               + memory_region_section_addr(section, addr));

        switch (endian) {

        case DEVICE_LITTLE_ENDIAN:

            val = ldq_le_p(ptr);

            break;

        case DEVICE_BIG_ENDIAN:

            val = ldq_be_p(ptr);

            break;

        default:

            val = ldq_p(ptr);

            break;

        }

    }

    return val;

}


static int raw_reopen_prepare(BDRVReopenState *reopen_state,

                              BlockReopenQueue *queue, Error **errp)

{

    assert(reopen_state != NULL);

    assert(reopen_state->bs != NULL);

    reopen_state->opaque = g_new0(BDRVRawState, 1);

    return raw_read_options(

        reopen_state->options,

        reopen_state->bs,

        reopen_state->opaque,

        errp);

}


static void nfs_refresh_filename(BlockDriverState *bs, QDict *options)

{

    NFSClient *client = bs->opaque;

    QDict *opts = qdict_new();

    QObject *server_qdict;

    Visitor *ov;

    qdict_put(opts, "driver", qstring_from_str("nfs"));

    if (client->uid && !client->gid) {

        snprintf(bs->exact_filename, sizeof(bs->exact_filename),

                 "nfs://%s%s?uid=%" PRId64, client->server->host, client->path,

                 client->uid);

    } else if (!client->uid && client->gid) {

        snprintf(bs->exact_filename, sizeof(bs->exact_filename),

                 "nfs://%s%s?gid=%" PRId64, client->server->host, client->path,

                 client->gid);

    } else if (client->uid && client->gid) {

        snprintf(bs->exact_filename, sizeof(bs->exact_filename),

                 "nfs://%s%s?uid=%" PRId64 "&gid=%" PRId64,

                 client->server->host, client->path, client->uid, client->gid);

    } else {

        snprintf(bs->exact_filename, sizeof(bs->exact_filename),

                 "nfs://%s%s", client->server->host, client->path);

    }

    ov = qobject_output_visitor_new(&server_qdict);

    visit_type_NFSServer(ov, NULL, &client->server, &error_abort);

    visit_complete(ov, &server_qdict);

    assert(qobject_type(server_qdict) == QTYPE_QDICT);

    qdict_put_obj(opts, "server", server_qdict);

    qdict_put(opts, "path", qstring_from_str(client->path));

    if (client->uid) {

        qdict_put(opts, "uid", qint_from_int(client->uid));

    }

    if (client->gid) {

        qdict_put(opts, "gid", qint_from_int(client->gid));

    }

    if (client->tcp_syncnt) {

        qdict_put(opts, "tcp-syncnt",

                      qint_from_int(client->tcp_syncnt));

    }

    if (client->readahead) {

        qdict_put(opts, "readahead",

                      qint_from_int(client->readahead));

    }

    if (client->pagecache) {

        qdict_put(opts, "pagecache",

                      qint_from_int(client->pagecache));

    }

    if (client->debug) {

        qdict_put(opts, "debug", qint_from_int(client->debug));

    }

    visit_free(ov);

    qdict_flatten(opts);

    bs->full_open_options = opts;

}


iscsi_readcapacity16_cb(struct iscsi_context *iscsi, int status,

                        void *command_data, void *opaque)

{

    struct IscsiTask *itask = opaque;

    struct scsi_readcapacity16 *rc16;

    struct scsi_task *task = command_data;

    if (status != 0) {

        error_report("iSCSI: Failed to read capacity of iSCSI lun. %s",

                     iscsi_get_error(iscsi));

        itask->status   = 1;

        itask->complete = 1;

        scsi_free_scsi_task(task);

        return;

    }

    rc16 = scsi_datain_unmarshall(task);

    if (rc16 == NULL) {

        error_report("iSCSI: Failed to unmarshall readcapacity16 data.");

        itask->status   = 1;

        itask->complete = 1;

        scsi_free_scsi_task(task);

        return;

    }

    itask->iscsilun->block_size = rc16->block_length;

    itask->iscsilun->num_blocks = rc16->returned_lba + 1;

    itask->bs->total_sectors    = itask->iscsilun->num_blocks *

                               itask->iscsilun->block_size / BDRV_SECTOR_SIZE ;

    itask->status   = 0;

    itask->complete = 1;

    scsi_free_scsi_task(task);

}


static void fill_scaling_lists(const AVCodecContext *avctx, AVDXVAContext *ctx, const H264Context *h, DXVA_Qmatrix_H264 *qm)

{

    unsigned i, j;

    memset(qm, 0, sizeof(*qm));

    if (DXVA_CONTEXT_WORKAROUND(avctx, ctx) & FF_DXVA2_WORKAROUND_SCALING_LIST_ZIGZAG) {

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

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

                qm->bScalingLists4x4[i][j] = h->pps.scaling_matrix4[i][j];

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

            qm->bScalingLists8x8[0][i] = h->pps.scaling_matrix8[0][i];

            qm->bScalingLists8x8[1][i] = h->pps.scaling_matrix8[3][i];

        }

    } else {

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

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

                qm->bScalingLists4x4[i][j] = h->pps.scaling_matrix4[i][ff_zigzag_scan[j]];

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

            qm->bScalingLists8x8[0][i] = h->pps.scaling_matrix8[0][ff_zigzag_direct[i]];

            qm->bScalingLists8x8[1][i] = h->pps.scaling_matrix8[3][ff_zigzag_direct[i]];

        }

    }

}


uint64_t helper_fnmsub(CPUPPCState *env, uint64_t arg1, uint64_t arg2,

                       uint64_t arg3)

{

    CPU_DoubleU farg1, farg2, farg3;

    farg1.ll = arg1;

    farg2.ll = arg2;

    farg3.ll = arg3;

    if (unlikely((float64_is_infinity(farg1.d) && float64_is_zero(farg2.d)) ||

                 (float64_is_zero(farg1.d) &&

                  float64_is_infinity(farg2.d)))) {

        /* Multiplication of zero by infinity */

        farg1.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXIMZ);

    } else {

        if (unlikely(float64_is_signaling_nan(farg1.d) ||

                     float64_is_signaling_nan(farg2.d) ||

                     float64_is_signaling_nan(farg3.d))) {

            /* sNaN operation */

            fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXSNAN);

        }

        /* This is the way the PowerPC specification defines it */

        float128 ft0_128, ft1_128;

        ft0_128 = float64_to_float128(farg1.d, &env->fp_status);

        ft1_128 = float64_to_float128(farg2.d, &env->fp_status);

        ft0_128 = float128_mul(ft0_128, ft1_128, &env->fp_status);

        if (unlikely(float128_is_infinity(ft0_128) &&

                     float64_is_infinity(farg3.d) &&

                     float128_is_neg(ft0_128) == float64_is_neg(farg3.d))) {

            /* Magnitude subtraction of infinities */

            farg1.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXISI);

        } else {

            ft1_128 = float64_to_float128(farg3.d, &env->fp_status);

            ft0_128 = float128_sub(ft0_128, ft1_128, &env->fp_status);

            farg1.d = float128_to_float64(ft0_128, &env->fp_status);

        }

        if (likely(!float64_is_any_nan(farg1.d))) {

            farg1.d = float64_chs(farg1.d);

        }

    }

    return farg1.ll;

}


static int decode_tag(AVCodecContext * avctx,

                      void *data, int *data_size,

                      AVPacket *avpkt) {

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    NellyMoserDecodeContext *s = avctx->priv_data;

    int blocks, i;

    int16_t* samples;

    *data_size = 0;

    samples = (int16_t*)data;

    if (buf_size < avctx->block_align)

        return buf_size;

    if (buf_size % 64) {

        av_log(avctx, AV_LOG_ERROR, "Tag size %d.\n", buf_size);

        return buf_size;

    }

    blocks = buf_size / 64;

    /* Normal numbers of blocks for sample rates:

     *  8000 Hz - 1

     * 11025 Hz - 2

     * 16000 Hz - 3

     * 22050 Hz - 4

     * 44100 Hz - 8

     */

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

        nelly_decode_block(s, &buf[i*NELLY_BLOCK_LEN], s->float_buf);

        s->fmt_conv.float_to_int16(&samples[i*NELLY_SAMPLES], s->float_buf, NELLY_SAMPLES);

        *data_size += NELLY_SAMPLES*sizeof(int16_t);

    }

    return buf_size;

}


static int megasas_map_dcmd(MegasasState *s, MegasasCmd *cmd)

{

    dma_addr_t iov_pa, iov_size;

    cmd->flags = le16_to_cpu(cmd->frame->header.flags);

    if (!cmd->frame->header.sge_count) {

        trace_megasas_dcmd_zero_sge(cmd->index);

        cmd->iov_size = 0;

        return 0;

    } else if (cmd->frame->header.sge_count > 1) {

        trace_megasas_dcmd_invalid_sge(cmd->index,

                                       cmd->frame->header.sge_count);

        cmd->iov_size = 0;

        return -1;

    }

    iov_pa = megasas_sgl_get_addr(cmd, &cmd->frame->dcmd.sgl);

    iov_size = megasas_sgl_get_len(cmd, &cmd->frame->dcmd.sgl);

    pci_dma_sglist_init(&cmd->qsg, PCI_DEVICE(s), 1);

    qemu_sglist_add(&cmd->qsg, iov_pa, iov_size);

    cmd->iov_size = iov_size;

    return cmd->iov_size;

}


static void cdrom_change_cb(void *opaque, int reason)

{

    IDEState *s = opaque;

    uint64_t nb_sectors;

    if (!(reason & CHANGE_MEDIA)) {

        return;

    }

    bdrv_get_geometry(s->bs, &nb_sectors);

    s->nb_sectors = nb_sectors;

    s->sense_key = SENSE_UNIT_ATTENTION;

    s->asc = ASC_MEDIUM_MAY_HAVE_CHANGED;

    s->cdrom_changed = 1;

    s->events.new_media = true;

    ide_set_irq(s->bus);

}


static int gdb_handle_packet(GDBState *s, const char *line_buf)

{

    CPUArchState *env;

    const char *p;

    uint32_t thread;

    int ch, reg_size, type, res;

    char buf[MAX_PACKET_LENGTH];

    uint8_t mem_buf[MAX_PACKET_LENGTH];

    uint8_t *registers;

    target_ulong addr, len;

#ifdef DEBUG_GDB

    printf("command='%s'\n", line_buf);

#endif

    p = line_buf;

    ch = *p++;

    switch(ch) {

    case '?':

        /* TODO: Make this return the correct value for user-mode.  */

        snprintf(buf, sizeof(buf), "T%02xthread:%02x;", GDB_SIGNAL_TRAP,

                 cpu_index(ENV_GET_CPU(s->c_cpu)));

        put_packet(s, buf);

        /* Remove all the breakpoints when this query is issued,

         * because gdb is doing and initial connect and the state

         * should be cleaned up.

         */

        gdb_breakpoint_remove_all();

        break;

    case 'c':

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

            addr = strtoull(p, (char **)&p, 16);

            gdb_set_cpu_pc(s, addr);

        }

        s->signal = 0;

        gdb_continue(s);

	return RS_IDLE;

    case 'C':

        s->signal = gdb_signal_to_target (strtoul(p, (char **)&p, 16));

        if (s->signal == -1)

            s->signal = 0;

        gdb_continue(s);

        return RS_IDLE;

    case 'v':

        if (strncmp(p, "Cont", 4) == 0) {

            int res_signal, res_thread;

            p += 4;

            if (*p == '?') {

                put_packet(s, "vCont;c;C;s;S");

                break;

            }

            res = 0;

            res_signal = 0;

            res_thread = 0;

            while (*p) {

                int action, signal;

                if (*p++ != ';') {

                    res = 0;

                    break;

                }

                action = *p++;

                signal = 0;

                if (action == 'C' || action == 'S') {

                    signal = strtoul(p, (char **)&p, 16);

                } else if (action != 'c' && action != 's') {

                    res = 0;

                    break;

                }

                thread = 0;

                if (*p == ':') {

                    thread = strtoull(p+1, (char **)&p, 16);

                }

                action = tolower(action);

                if (res == 0 || (res == 'c' && action == 's')) {

                    res = action;

                    res_signal = signal;

                    res_thread = thread;

                }

            }

            if (res) {

                if (res_thread != -1 && res_thread != 0) {

                    env = find_cpu(res_thread);

                    if (env == NULL) {

                        put_packet(s, "E22");

                        break;

                    }

                    s->c_cpu = env;

                }

                if (res == 's') {

                    cpu_single_step(s->c_cpu, sstep_flags);

                }

                s->signal = res_signal;

                gdb_continue(s);

                return RS_IDLE;

            }

            break;

        } else {

            goto unknown_command;

        }

    case 'k':

#ifdef CONFIG_USER_ONLY

        /* Kill the target */

        fprintf(stderr, "\nQEMU: Terminated via GDBstub\n");

        exit(0);

#endif

    case 'D':

        /* Detach packet */

        gdb_breakpoint_remove_all();

        gdb_syscall_mode = GDB_SYS_DISABLED;

        gdb_continue(s);

        put_packet(s, "OK");

        break;

    case 's':

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

            addr = strtoull(p, (char **)&p, 16);

            gdb_set_cpu_pc(s, addr);

        }

        cpu_single_step(s->c_cpu, sstep_flags);

        gdb_continue(s);

	return RS_IDLE;

    case 'F':

        {

            target_ulong ret;

            target_ulong err;

            ret = strtoull(p, (char **)&p, 16);

            if (*p == ',') {

                p++;

                err = strtoull(p, (char **)&p, 16);

            } else {

                err = 0;

            }

            if (*p == ',')

                p++;

            type = *p;

            if (s->current_syscall_cb) {

                s->current_syscall_cb(s->c_cpu, ret, err);

                s->current_syscall_cb = NULL;

            }

            if (type == 'C') {

                put_packet(s, "T02");

            } else {

                gdb_continue(s);

            }

        }

        break;

    case 'g':

        cpu_synchronize_state(ENV_GET_CPU(s->g_cpu));

        env = s->g_cpu;

        len = 0;

        for (addr = 0; addr < num_g_regs; addr++) {

            reg_size = gdb_read_register(s->g_cpu, mem_buf + len, addr);

            len += reg_size;

        }

        memtohex(buf, mem_buf, len);

        put_packet(s, buf);

        break;

    case 'G':

        cpu_synchronize_state(ENV_GET_CPU(s->g_cpu));

        env = s->g_cpu;

        registers = mem_buf;

        len = strlen(p) / 2;

        hextomem((uint8_t *)registers, p, len);

        for (addr = 0; addr < num_g_regs && len > 0; addr++) {

            reg_size = gdb_write_register(s->g_cpu, registers, addr);

            len -= reg_size;

            registers += reg_size;

        }

        put_packet(s, "OK");

        break;

    case 'm':

        addr = strtoull(p, (char **)&p, 16);

        if (*p == ',')

            p++;

        len = strtoull(p, NULL, 16);

        if (target_memory_rw_debug(s->g_cpu, addr, mem_buf, len, 0) != 0) {

            put_packet (s, "E14");

        } else {

            memtohex(buf, mem_buf, len);

            put_packet(s, buf);

        }

        break;

    case 'M':

        addr = strtoull(p, (char **)&p, 16);

        if (*p == ',')

            p++;

        len = strtoull(p, (char **)&p, 16);

        if (*p == ':')

            p++;

        hextomem(mem_buf, p, len);

        if (target_memory_rw_debug(s->g_cpu, addr, mem_buf, len, 1) != 0) {

            put_packet(s, "E14");

        } else {

            put_packet(s, "OK");

        }

        break;

    case 'p':

        /* Older gdb are really dumb, and don't use 'g' if 'p' is avaialable.

           This works, but can be very slow.  Anything new enough to

           understand XML also knows how to use this properly.  */

        if (!gdb_has_xml)

            goto unknown_command;

        addr = strtoull(p, (char **)&p, 16);

        reg_size = gdb_read_register(s->g_cpu, mem_buf, addr);

        if (reg_size) {

            memtohex(buf, mem_buf, reg_size);

            put_packet(s, buf);

        } else {

            put_packet(s, "E14");

        }

        break;

    case 'P':

        if (!gdb_has_xml)

            goto unknown_command;

        addr = strtoull(p, (char **)&p, 16);

        if (*p == '=')

            p++;

        reg_size = strlen(p) / 2;

        hextomem(mem_buf, p, reg_size);

        gdb_write_register(s->g_cpu, mem_buf, addr);

        put_packet(s, "OK");

        break;

    case 'Z':

    case 'z':

        type = strtoul(p, (char **)&p, 16);

        if (*p == ',')

            p++;

        addr = strtoull(p, (char **)&p, 16);

        if (*p == ',')

            p++;

        len = strtoull(p, (char **)&p, 16);

        if (ch == 'Z')

            res = gdb_breakpoint_insert(addr, len, type);

        else

            res = gdb_breakpoint_remove(addr, len, type);

        if (res >= 0)

             put_packet(s, "OK");

        else if (res == -ENOSYS)

            put_packet(s, "");

        else

            put_packet(s, "E22");

        break;

    case 'H':

        type = *p++;

        thread = strtoull(p, (char **)&p, 16);

        if (thread == -1 || thread == 0) {

            put_packet(s, "OK");

            break;

        }

        env = find_cpu(thread);

        if (env == NULL) {

            put_packet(s, "E22");

            break;

        }

        switch (type) {

        case 'c':

            s->c_cpu = env;

            put_packet(s, "OK");

            break;

        case 'g':

            s->g_cpu = env;

            put_packet(s, "OK");

            break;

        default:

             put_packet(s, "E22");

             break;

        }

        break;

    case 'T':

        thread = strtoull(p, (char **)&p, 16);

        env = find_cpu(thread);

        if (env != NULL) {

            put_packet(s, "OK");

        } else {

            put_packet(s, "E22");

        }

        break;

    case 'q':

    case 'Q':

        /* parse any 'q' packets here */

        if (!strcmp(p,"qemu.sstepbits")) {

            /* Query Breakpoint bit definitions */

            snprintf(buf, sizeof(buf), "ENABLE=%x,NOIRQ=%x,NOTIMER=%x",

                     SSTEP_ENABLE,

                     SSTEP_NOIRQ,

                     SSTEP_NOTIMER);

            put_packet(s, buf);

            break;

        } else if (strncmp(p,"qemu.sstep",10) == 0) {

            /* Display or change the sstep_flags */

            p += 10;

            if (*p != '=') {

                /* Display current setting */

                snprintf(buf, sizeof(buf), "0x%x", sstep_flags);

                put_packet(s, buf);

                break;

            }

            p++;

            type = strtoul(p, (char **)&p, 16);

            sstep_flags = type;

            put_packet(s, "OK");

            break;

        } else if (strcmp(p,"C") == 0) {

            /* "Current thread" remains vague in the spec, so always return

             *  the first CPU (gdb returns the first thread). */

            put_packet(s, "QC1");

            break;

        } else if (strcmp(p,"fThreadInfo") == 0) {

            s->query_cpu = first_cpu->env_ptr;

            goto report_cpuinfo;

        } else if (strcmp(p,"sThreadInfo") == 0) {

        report_cpuinfo:

            if (s->query_cpu) {

                snprintf(buf, sizeof(buf), "m%x",

                         cpu_index(ENV_GET_CPU(s->query_cpu)));

                put_packet(s, buf);

                s->query_cpu = ENV_GET_CPU(s->query_cpu)->next_cpu->env_ptr;

            } else

                put_packet(s, "l");

            break;

        } else if (strncmp(p,"ThreadExtraInfo,", 16) == 0) {

            thread = strtoull(p+16, (char **)&p, 16);

            env = find_cpu(thread);

            if (env != NULL) {

                CPUState *cpu = ENV_GET_CPU(env);

                cpu_synchronize_state(cpu);

                len = snprintf((char *)mem_buf, sizeof(mem_buf),

                               "CPU#%d [%s]", cpu->cpu_index,

                               cpu->halted ? "halted " : "running");

                memtohex(buf, mem_buf, len);

                put_packet(s, buf);

            }

            break;

        }

#ifdef CONFIG_USER_ONLY

        else if (strncmp(p, "Offsets", 7) == 0) {

            TaskState *ts = s->c_cpu->opaque;

            snprintf(buf, sizeof(buf),

                     "Text=" TARGET_ABI_FMT_lx ";Data=" TARGET_ABI_FMT_lx

                     ";Bss=" TARGET_ABI_FMT_lx,

                     ts->info->code_offset,

                     ts->info->data_offset,

                     ts->info->data_offset);

            put_packet(s, buf);

            break;

        }

#else /* !CONFIG_USER_ONLY */

        else if (strncmp(p, "Rcmd,", 5) == 0) {

            int len = strlen(p + 5);

            if ((len % 2) != 0) {

                put_packet(s, "E01");

                break;

            }

            hextomem(mem_buf, p + 5, len);

            len = len / 2;

            mem_buf[len++] = 0;

            qemu_chr_be_write(s->mon_chr, mem_buf, len);

            put_packet(s, "OK");

            break;

        }

#endif /* !CONFIG_USER_ONLY */

        if (strncmp(p, "Supported", 9) == 0) {

            snprintf(buf, sizeof(buf), "PacketSize=%x", MAX_PACKET_LENGTH);

#ifdef GDB_CORE_XML

            pstrcat(buf, sizeof(buf), ";qXfer:features:read+");

#endif

            put_packet(s, buf);

            break;

        }

#ifdef GDB_CORE_XML

        if (strncmp(p, "Xfer:features:read:", 19) == 0) {

            const char *xml;

            target_ulong total_len;

            gdb_has_xml = 1;

            p += 19;

            xml = get_feature_xml(p, &p);

            if (!xml) {

                snprintf(buf, sizeof(buf), "E00");

                put_packet(s, buf);

                break;

            }

            if (*p == ':')

                p++;

            addr = strtoul(p, (char **)&p, 16);

            if (*p == ',')

                p++;

            len = strtoul(p, (char **)&p, 16);

            total_len = strlen(xml);

            if (addr > total_len) {

                snprintf(buf, sizeof(buf), "E00");

                put_packet(s, buf);

                break;

            }

            if (len > (MAX_PACKET_LENGTH - 5) / 2)

                len = (MAX_PACKET_LENGTH - 5) / 2;

            if (len < total_len - addr) {

                buf[0] = 'm';

                len = memtox(buf + 1, xml + addr, len);

            } else {

                buf[0] = 'l';

                len = memtox(buf + 1, xml + addr, total_len - addr);

            }

            put_packet_binary(s, buf, len + 1);

            break;

        }

#endif

        /* Unrecognised 'q' command.  */

        goto unknown_command;

    default:

    unknown_command:

        /* put empty packet */

        buf[0] = '\0';

        put_packet(s, buf);

        break;

    }

    return RS_IDLE;

}


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

                        const char *hoststr, const char *auth,

                        const char *proxyauth, int *new_location)

{

    HTTPContext *s = h->priv_data;

    int post, err;

    char headers[HTTP_HEADERS_SIZE] = "";

    char *authstr = NULL, *proxyauthstr = NULL;

    uint64_t off = s->off;

    int len = 0;

    const char *method;

    int send_expect_100 = 0;

    /* send http header */

    post = h->flags & AVIO_FLAG_WRITE;

    if (s->post_data) {

        /* force POST method and disable chunked encoding when

         * custom HTTP post data is set */

        post            = 1;

        s->chunked_post = 0;

    }

    if (s->method)

        method = s->method;

    else

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

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

                                                local_path, method);

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

                                                local_path, method);

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

        send_expect_100 = s->send_expect_100;

        /* The user has supplied authentication but we don't know the auth type,

         * send Expect: 100-continue to get the 401 response including the

         * WWW-Authenticate header, or an 100 continue if no auth actually

         * is needed. */

        if (auth && *auth &&

            s->auth_state.auth_type == HTTP_AUTH_NONE &&

            s->http_code != 401)

            send_expect_100 = 1;

    }

#if FF_API_HTTP_USER_AGENT

    if (strcmp(s->user_agent_deprecated, DEFAULT_USER_AGENT)) {

        av_log(s, AV_LOG_WARNING, "the user-agent option is deprecated, please use user_agent option\n");

        s->user_agent = av_strdup(s->user_agent_deprecated);

    }

#endif

    /* set default headers if needed */

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

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

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

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

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

                          sizeof(headers) - len);

    // Note: we send this on purpose even when s->off is 0 when we're probing,

    // since it allows us to detect more reliably if a (non-conforming)

    // server supports seeking by analysing the reply headers.

    if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) {

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

                           "Range: bytes=%"PRIu64"-", s->off);

        if (s->end_off)

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

                               "%"PRId64, s->end_off - 1);

        len += av_strlcpy(headers + len, "\r\n",

                          sizeof(headers) - len);

    }

    if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))

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

                           "Expect: 100-continue\r\n");

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

        if (s->multiple_requests)

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

                              sizeof(headers) - len);

        else

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

                              sizeof(headers) - len);

    }

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

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

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

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

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

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

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

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

                           "Content-Type: %s\r\n", s->content_type);

    if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {

        char *cookies = NULL;

        if (!get_cookies(s, &cookies, path, hoststr) && cookies) {

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

                               "Cookie: %s\r\n", cookies);

            av_free(cookies);

        }

    }

    if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy)

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

                           "Icy-MetaData: %d\r\n", 1);

    /* now add in custom headers */

    if (s->headers)

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

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

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

             "%s"

             "%s"

             "%s"

             "%s%s"

             "\r\n",

             method,

             path,

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

             headers,

             authstr ? authstr : "",

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

    av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer);

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

        goto done;

    if (s->post_data)

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

            goto done;

    /* init input buffer */

    s->buf_ptr          = s->buffer;

    s->buf_end          = s->buffer;

    s->line_count       = 0;

    s->off              = 0;

    s->icy_data_read    = 0;

    s->filesize         = UINT64_MAX;

    s->willclose        = 0;

    s->end_chunked_post = 0;

    s->end_header       = 0;

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

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

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

         * function will check http_code after we return. */

        s->http_code = 200;

        err = 0;

        goto done;

    }

    /* wait for header */

    err = http_read_header(h, new_location);

    if (err < 0)

        goto done;

    if (*new_location)

        s->off = off;

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

done:

    av_freep(&authstr);

    av_freep(&proxyauthstr);

    return err;

}


static int xen_host_pci_sysfs_path(const XenHostPCIDevice *d,

                                   const char *name, char *buf, ssize_t size)

{

    int rc;

    rc = snprintf(buf, size, "/sys/bus/pci/devices/%04x:%02x:%02x.%d/%s",

                  d->domain, d->bus, d->dev, d->func, name);

    if (rc >= size || rc < 0) {

        /* The output is truncated, or some other error was encountered */

        return -ENODEV;

    }

    return 0;

}


static void test_validate_fail_union_native_list(TestInputVisitorData *data,

                                                 const void *unused)

{

    UserDefNativeListUnion *tmp = NULL;

    Error *err = NULL;

    Visitor *v;

    v = validate_test_init(data,

                           "{ 'type': 'integer', 'data' : [ 'string' ] }");

    visit_type_UserDefNativeListUnion(v, NULL, &tmp, &err);

    error_free_or_abort(&err);

    g_assert(!tmp);

}


static int colo_do_checkpoint_transaction(MigrationState *s,

                                          QIOChannelBuffer *bioc,

                                          QEMUFile *fb)

{

    Error *local_err = NULL;

    int ret = -1;

    colo_send_message(s->to_dst_file, COLO_MESSAGE_CHECKPOINT_REQUEST,

                      &local_err);

    if (local_err) {

    colo_receive_check_message(s->rp_state.from_dst_file,

                    COLO_MESSAGE_CHECKPOINT_REPLY, &local_err);

    if (local_err) {

    /* Reset channel-buffer directly */

    qio_channel_io_seek(QIO_CHANNEL(bioc), 0, 0, NULL);

    bioc->usage = 0;

    qemu_mutex_lock_iothread();

    vm_stop_force_state(RUN_STATE_COLO);

    trace_colo_vm_state_change("run", "stop");

    /* Disable block migration */

    s->params.blk = 0;

    s->params.shared = 0;

    qemu_savevm_state_header(fb);

    qemu_savevm_state_begin(fb, &s->params);

    qemu_mutex_lock_iothread();

    qemu_savevm_state_complete_precopy(fb, false);

    qemu_fflush(fb);

    colo_send_message(s->to_dst_file, COLO_MESSAGE_VMSTATE_SEND, &local_err);

    if (local_err) {

     * We need the size of the VMstate data in Secondary side,

     * With which we can decide how much data should be read.

    colo_send_message_value(s->to_dst_file, COLO_MESSAGE_VMSTATE_SIZE,

                            bioc->usage, &local_err);

    if (local_err) {

    qemu_put_buffer(s->to_dst_file, bioc->data, bioc->usage);

    qemu_fflush(s->to_dst_file);

    ret = qemu_file_get_error(s->to_dst_file);

    if (ret < 0) {

    colo_receive_check_message(s->rp_state.from_dst_file,

                       COLO_MESSAGE_VMSTATE_RECEIVED, &local_err);

    if (local_err) {

    colo_receive_check_message(s->rp_state.from_dst_file,

                       COLO_MESSAGE_VMSTATE_LOADED, &local_err);

    if (local_err) {

    ret = 0;

    qemu_mutex_lock_iothread();

    vm_start();

    trace_colo_vm_state_change("stop", "run");

out:

    if (local_err) {

        error_report_err(local_err);

    return ret;


void qpci_msix_disable(QPCIDevice *dev)

{

    uint8_t addr;

    uint16_t val;

    g_assert(dev->msix_enabled);

    addr = qpci_find_capability(dev, PCI_CAP_ID_MSIX);

    g_assert_cmphex(addr, !=, 0);

    val = qpci_config_readw(dev, addr + PCI_MSIX_FLAGS);

    qpci_config_writew(dev, addr + PCI_MSIX_FLAGS,

                                                val & ~PCI_MSIX_FLAGS_ENABLE);

    qpci_iounmap(dev, dev->msix_table);

    qpci_iounmap(dev, dev->msix_pba);

    dev->msix_enabled = 0;

    dev->msix_table = NULL;

    dev->msix_pba = NULL;

}


static struct omap_rtc_s *omap_rtc_init(MemoryRegion *system_memory,

                                        target_phys_addr_t base,

                                        qemu_irq timerirq, qemu_irq alarmirq,

                                        omap_clk clk)

{

    struct omap_rtc_s *s = (struct omap_rtc_s *)

            g_malloc0(sizeof(struct omap_rtc_s));

    s->irq = timerirq;

    s->alarm = alarmirq;

    s->clk = qemu_new_timer_ms(rtc_clock, omap_rtc_tick, s);

    omap_rtc_reset(s);

    memory_region_init_io(&s->iomem, &omap_rtc_ops, s,

                          "omap-rtc", 0x800);

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

    return s;

}


static ssize_t qio_channel_socket_writev(QIOChannel *ioc,

                                         const struct iovec *iov,

                                         size_t niov,

                                         int *fds,

                                         size_t nfds,

                                         Error **errp)

{

    QIOChannelSocket *sioc = QIO_CHANNEL_SOCKET(ioc);

    ssize_t ret;

    struct msghdr msg = { NULL, };

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

    size_t fdsize = sizeof(int) * nfds;

    struct cmsghdr *cmsg;

    msg.msg_iov = (struct iovec *)iov;

    msg.msg_iovlen = niov;

    if (nfds) {

        if (nfds > SOCKET_MAX_FDS) {

            error_setg_errno(errp, EINVAL,

                             "Only %d FDs can be sent, got %zu",

                             SOCKET_MAX_FDS, nfds);

            return -1;

        }

        msg.msg_control = control;

        msg.msg_controllen = CMSG_SPACE(sizeof(int) * nfds);

        cmsg = CMSG_FIRSTHDR(&msg);

        cmsg->cmsg_len = CMSG_LEN(fdsize);

        cmsg->cmsg_level = SOL_SOCKET;

        cmsg->cmsg_type = SCM_RIGHTS;

        memcpy(CMSG_DATA(cmsg), fds, fdsize);

    }

 retry:

    ret = sendmsg(sioc->fd, &msg, 0);

    if (ret <= 0) {

        if (socket_error() == EAGAIN ||

            socket_error() == EWOULDBLOCK) {

            return QIO_CHANNEL_ERR_BLOCK;

        }

        if (socket_error() == EINTR) {

            goto retry;

        }

        error_setg_errno(errp, socket_error(),

                         "Unable to write to socket");

        return -1;

    }

    return ret;

}


void *lsi_scsi_init(PCIBus *bus, int devfn)

{

    LSIState *s;

    s = (LSIState *)pci_register_device(bus, "LSI53C895A SCSI HBA",

                                        sizeof(*s), devfn, NULL, NULL);

    if (s == NULL) {

        fprintf(stderr, "lsi-scsi: Failed to register PCI device\n");

        return NULL;

    }

    s->pci_dev.config[0x00] = 0x00;

    s->pci_dev.config[0x01] = 0x10;

    s->pci_dev.config[0x02] = 0x12;

    s->pci_dev.config[0x03] = 0x00;

    s->pci_dev.config[0x0b] = 0x01;

    s->pci_dev.config[0x3d] = 0x01; /* interrupt pin 1 */

    s->mmio_io_addr = cpu_register_io_memory(0, lsi_mmio_readfn,

                                             lsi_mmio_writefn, s);

    s->ram_io_addr = cpu_register_io_memory(0, lsi_ram_readfn,

                                            lsi_ram_writefn, s);

    pci_register_io_region((struct PCIDevice *)s, 0, 256,

                           PCI_ADDRESS_SPACE_IO, lsi_io_mapfunc);

    pci_register_io_region((struct PCIDevice *)s, 1, 0x400,

                           PCI_ADDRESS_SPACE_MEM, lsi_mmio_mapfunc);

    pci_register_io_region((struct PCIDevice *)s, 2, 0x2000,

                           PCI_ADDRESS_SPACE_MEM, lsi_ram_mapfunc);

    s->queue = qemu_malloc(sizeof(lsi_queue));

    s->queue_len = 1;

    s->active_commands = 0;

    lsi_soft_reset(s);

    return s;

}