static int encode_picture(MpegEncContext *s, int picture_number)

{

    int i, ret;

    int bits;

    int context_count = s->slice_context_count;

    s->picture_number = picture_number;

    /* Reset the average MB variance */

    s->me.mb_var_sum_temp    =

    s->me.mc_mb_var_sum_temp = 0;

    /* we need to initialize some time vars before we can encode b-frames */

    // RAL: Condition added for MPEG1VIDEO

    if (s->codec_id == AV_CODEC_ID_MPEG1VIDEO || s->codec_id == AV_CODEC_ID_MPEG2VIDEO || (s->h263_pred && !s->msmpeg4_version))

        set_frame_distances(s);

    if(CONFIG_MPEG4_ENCODER && s->codec_id == AV_CODEC_ID_MPEG4)

        ff_set_mpeg4_time(s);

    s->me.scene_change_score=0;

//    s->lambda= s->current_picture_ptr->quality; //FIXME qscale / ... stuff for ME rate distortion

    if(s->pict_type==AV_PICTURE_TYPE_I){

        if(s->msmpeg4_version >= 3) s->no_rounding=1;

        else                        s->no_rounding=0;

    }else if(s->pict_type!=AV_PICTURE_TYPE_B){

        if(s->flipflop_rounding || s->codec_id == AV_CODEC_ID_H263P || s->codec_id == AV_CODEC_ID_MPEG4)

            s->no_rounding ^= 1;

    }

    if(s->flags & CODEC_FLAG_PASS2){

        if (estimate_qp(s,1) < 0)

            return -1;

        ff_get_2pass_fcode(s);

    }else if(!(s->flags & CODEC_FLAG_QSCALE)){

        if(s->pict_type==AV_PICTURE_TYPE_B)

            s->lambda= s->last_lambda_for[s->pict_type];

        else

            s->lambda= s->last_lambda_for[s->last_non_b_pict_type];

        update_qscale(s);

    }

    if(s->codec_id != AV_CODEC_ID_AMV && s->codec_id != AV_CODEC_ID_MJPEG){

        if(s->q_chroma_intra_matrix   != s->q_intra_matrix  ) av_freep(&s->q_chroma_intra_matrix);

        if(s->q_chroma_intra_matrix16 != s->q_intra_matrix16) av_freep(&s->q_chroma_intra_matrix16);

        s->q_chroma_intra_matrix   = s->q_intra_matrix;

        s->q_chroma_intra_matrix16 = s->q_intra_matrix16;

    }

    s->mb_intra=0; //for the rate distortion & bit compare functions

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

        ret = ff_update_duplicate_context(s->thread_context[i], s);

        if (ret < 0)

            return ret;

    }

    if(ff_init_me(s)<0)

        return -1;

    /* Estimate motion for every MB */

    if(s->pict_type != AV_PICTURE_TYPE_I){

        s->lambda = (s->lambda * s->avctx->me_penalty_compensation + 128)>>8;

        s->lambda2= (s->lambda2* (int64_t)s->avctx->me_penalty_compensation + 128)>>8;

        if (s->pict_type != AV_PICTURE_TYPE_B) {

            if((s->avctx->pre_me && s->last_non_b_pict_type==AV_PICTURE_TYPE_I) || s->avctx->pre_me==2){

                s->avctx->execute(s->avctx, pre_estimate_motion_thread, &s->thread_context[0], NULL, context_count, sizeof(void*));

            }

        }

        s->avctx->execute(s->avctx, estimate_motion_thread, &s->thread_context[0], NULL, context_count, sizeof(void*));

    }else /* if(s->pict_type == AV_PICTURE_TYPE_I) */{

        /* I-Frame */

        for(i=0; i<s->mb_stride*s->mb_height; i++)

            s->mb_type[i]= CANDIDATE_MB_TYPE_INTRA;

        if(!s->fixed_qscale){

            /* finding spatial complexity for I-frame rate control */

            s->avctx->execute(s->avctx, mb_var_thread, &s->thread_context[0], NULL, context_count, sizeof(void*));

        }

    }

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

        merge_context_after_me(s, s->thread_context[i]);

    }

    s->current_picture.mc_mb_var_sum= s->current_picture_ptr->mc_mb_var_sum= s->me.mc_mb_var_sum_temp;

    s->current_picture.   mb_var_sum= s->current_picture_ptr->   mb_var_sum= s->me.   mb_var_sum_temp;

    emms_c();

    if(s->me.scene_change_score > s->avctx->scenechange_threshold && s->pict_type == AV_PICTURE_TYPE_P){

        s->pict_type= AV_PICTURE_TYPE_I;

        for(i=0; i<s->mb_stride*s->mb_height; i++)

            s->mb_type[i]= CANDIDATE_MB_TYPE_INTRA;

        if(s->msmpeg4_version >= 3)

            s->no_rounding=1;

        av_dlog(s, "Scene change detected, encoding as I Frame %d %d\n",

                s->current_picture.mb_var_sum, s->current_picture.mc_mb_var_sum);

    }

    if(!s->umvplus){

        if(s->pict_type==AV_PICTURE_TYPE_P || s->pict_type==AV_PICTURE_TYPE_S) {

            s->f_code= ff_get_best_fcode(s, s->p_mv_table, CANDIDATE_MB_TYPE_INTER);

            if(s->flags & CODEC_FLAG_INTERLACED_ME){

                int a,b;

                a= ff_get_best_fcode(s, s->p_field_mv_table[0][0], CANDIDATE_MB_TYPE_INTER_I); //FIXME field_select

                b= ff_get_best_fcode(s, s->p_field_mv_table[1][1], CANDIDATE_MB_TYPE_INTER_I);

                s->f_code= FFMAX3(s->f_code, a, b);

            }

            ff_fix_long_p_mvs(s);

            ff_fix_long_mvs(s, NULL, 0, s->p_mv_table, s->f_code, CANDIDATE_MB_TYPE_INTER, 0);

            if(s->flags & CODEC_FLAG_INTERLACED_ME){

                int j;

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

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

                        ff_fix_long_mvs(s, s->p_field_select_table[i], j,

                                        s->p_field_mv_table[i][j], s->f_code, CANDIDATE_MB_TYPE_INTER_I, 0);

                }

            }

        }

        if(s->pict_type==AV_PICTURE_TYPE_B){

            int a, b;

            a = ff_get_best_fcode(s, s->b_forw_mv_table, CANDIDATE_MB_TYPE_FORWARD);

            b = ff_get_best_fcode(s, s->b_bidir_forw_mv_table, CANDIDATE_MB_TYPE_BIDIR);

            s->f_code = FFMAX(a, b);

            a = ff_get_best_fcode(s, s->b_back_mv_table, CANDIDATE_MB_TYPE_BACKWARD);

            b = ff_get_best_fcode(s, s->b_bidir_back_mv_table, CANDIDATE_MB_TYPE_BIDIR);

            s->b_code = FFMAX(a, b);

            ff_fix_long_mvs(s, NULL, 0, s->b_forw_mv_table, s->f_code, CANDIDATE_MB_TYPE_FORWARD, 1);

            ff_fix_long_mvs(s, NULL, 0, s->b_back_mv_table, s->b_code, CANDIDATE_MB_TYPE_BACKWARD, 1);

            ff_fix_long_mvs(s, NULL, 0, s->b_bidir_forw_mv_table, s->f_code, CANDIDATE_MB_TYPE_BIDIR, 1);

            ff_fix_long_mvs(s, NULL, 0, s->b_bidir_back_mv_table, s->b_code, CANDIDATE_MB_TYPE_BIDIR, 1);

            if(s->flags & CODEC_FLAG_INTERLACED_ME){

                int dir, j;

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

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

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

                            int type= dir ? (CANDIDATE_MB_TYPE_BACKWARD_I|CANDIDATE_MB_TYPE_BIDIR_I)

                                          : (CANDIDATE_MB_TYPE_FORWARD_I |CANDIDATE_MB_TYPE_BIDIR_I);

                            ff_fix_long_mvs(s, s->b_field_select_table[dir][i], j,

                                            s->b_field_mv_table[dir][i][j], dir ? s->b_code : s->f_code, type, 1);

                        }

                    }

                }

            }

        }

    }

    if (estimate_qp(s, 0) < 0)

        return -1;

    if(s->qscale < 3 && s->max_qcoeff<=128 && s->pict_type==AV_PICTURE_TYPE_I && !(s->flags & CODEC_FLAG_QSCALE))

        s->qscale= 3; //reduce clipping problems

    if (s->out_format == FMT_MJPEG) {

        const uint16_t *  luma_matrix = ff_mpeg1_default_intra_matrix;

        const uint16_t *chroma_matrix = ff_mpeg1_default_intra_matrix;

        if (s->avctx->intra_matrix) {

            chroma_matrix =

            luma_matrix = s->avctx->intra_matrix;

        }

        if (s->avctx->chroma_intra_matrix)

            chroma_matrix = s->avctx->chroma_intra_matrix;

        /* for mjpeg, we do include qscale in the matrix */

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

            int j= s->dsp.idct_permutation[i];

            s->chroma_intra_matrix[j] = av_clip_uint8((chroma_matrix[i] * s->qscale) >> 3);

            s->       intra_matrix[j] = av_clip_uint8((  luma_matrix[i] * s->qscale) >> 3);

        }

        s->y_dc_scale_table=

        s->c_dc_scale_table= ff_mpeg2_dc_scale_table[s->intra_dc_precision];

        s->chroma_intra_matrix[0] =

        s->intra_matrix[0] = ff_mpeg2_dc_scale_table[s->intra_dc_precision][8];

        ff_convert_matrix(&s->dsp, s->q_intra_matrix, s->q_intra_matrix16,

                       s->intra_matrix, s->intra_quant_bias, 8, 8, 1);

        ff_convert_matrix(&s->dsp, s->q_chroma_intra_matrix, s->q_chroma_intra_matrix16,

                       s->chroma_intra_matrix, s->intra_quant_bias, 8, 8, 1);

        s->qscale= 8;

    }

    if(s->codec_id == AV_CODEC_ID_AMV){

        static const uint8_t y[32]={13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13};

        static const uint8_t c[32]={14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14};

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

            int j= s->dsp.idct_permutation[ff_zigzag_direct[i]];

            s->intra_matrix[j] = sp5x_quant_table[5*2+0][i];

            s->chroma_intra_matrix[j] = sp5x_quant_table[5*2+1][i];

        }

        s->y_dc_scale_table= y;

        s->c_dc_scale_table= c;

        s->intra_matrix[0] = 13;

        s->chroma_intra_matrix[0] = 14;

        ff_convert_matrix(&s->dsp, s->q_intra_matrix, s->q_intra_matrix16,

                       s->intra_matrix, s->intra_quant_bias, 8, 8, 1);

        ff_convert_matrix(&s->dsp, s->q_chroma_intra_matrix, s->q_chroma_intra_matrix16,

                       s->chroma_intra_matrix, s->intra_quant_bias, 8, 8, 1);

        s->qscale= 8;

    }

    //FIXME var duplication

    s->current_picture_ptr->f.key_frame =

    s->current_picture.f.key_frame = s->pict_type == AV_PICTURE_TYPE_I; //FIXME pic_ptr

    s->current_picture_ptr->f.pict_type =

    s->current_picture.f.pict_type = s->pict_type;

    if (s->current_picture.f.key_frame)

        s->picture_in_gop_number=0;

    s->mb_x = s->mb_y = 0;

    s->last_bits= put_bits_count(&s->pb);

    switch(s->out_format) {

    case FMT_MJPEG:

        if (CONFIG_MJPEG_ENCODER)

            ff_mjpeg_encode_picture_header(s->avctx, &s->pb, &s->intra_scantable,

                                           s->intra_matrix, s->chroma_intra_matrix);

        break;

    case FMT_H261:

        if (CONFIG_H261_ENCODER)

            ff_h261_encode_picture_header(s, picture_number);

        break;

    case FMT_H263:

        if (CONFIG_WMV2_ENCODER && s->codec_id == AV_CODEC_ID_WMV2)

            ff_wmv2_encode_picture_header(s, picture_number);

        else if (CONFIG_MSMPEG4_ENCODER && s->msmpeg4_version)

            ff_msmpeg4_encode_picture_header(s, picture_number);

        else if (CONFIG_MPEG4_ENCODER && s->h263_pred)

            ff_mpeg4_encode_picture_header(s, picture_number);

        else if (CONFIG_RV10_ENCODER && s->codec_id == AV_CODEC_ID_RV10)

            ff_rv10_encode_picture_header(s, picture_number);

        else if (CONFIG_RV20_ENCODER && s->codec_id == AV_CODEC_ID_RV20)

            ff_rv20_encode_picture_header(s, picture_number);

        else if (CONFIG_FLV_ENCODER && s->codec_id == AV_CODEC_ID_FLV1)

            ff_flv_encode_picture_header(s, picture_number);

        else if (CONFIG_H263_ENCODER)

            ff_h263_encode_picture_header(s, picture_number);

        break;

    case FMT_MPEG1:

        if (CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)

            ff_mpeg1_encode_picture_header(s, picture_number);

        break;

    default:

        av_assert0(0);

    }

    bits= put_bits_count(&s->pb);

    s->header_bits= bits - s->last_bits;

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

        update_duplicate_context_after_me(s->thread_context[i], s);

    }

    s->avctx->execute(s->avctx, encode_thread, &s->thread_context[0], NULL, context_count, sizeof(void*));

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

        merge_context_after_encode(s, s->thread_context[i]);

    }

    emms_c();

    return 0;

}


static inline int compare_masked(uint64_t x, uint64_t y, uint64_t mask)

{

    return (x & mask) == (y & mask);

}


static int asf_build_simple_index(AVFormatContext *s, int stream_index)
{
    ff_asf_guid g;
    ASFContext *asf     = s->priv_data;
    int64_t current_pos = avio_tell(s->pb);
    int64_t ret;
    if((ret = avio_seek(s->pb, asf->data_object_offset + asf->data_object_size, SEEK_SET)) < 0) {
        return ret;
    if ((ret = ff_get_guid(s->pb, &g)) < 0)
    /* the data object can be followed by other top-level objects,
     * skip them until the simple index object is reached */
    while (ff_guidcmp(&g, &ff_asf_simple_index_header)) {
        int64_t gsize = avio_rl64(s->pb);
        if (gsize < 24 || avio_feof(s->pb)) {
        avio_skip(s->pb, gsize - 24);
        if ((ret = ff_get_guid(s->pb, &g)) < 0)
    {
        int64_t itime, last_pos = -1;
        int pct, ict;
        int i;
        int64_t av_unused gsize = avio_rl64(s->pb);
        if ((ret = ff_get_guid(s->pb, &g)) < 0)
        itime = avio_rl64(s->pb);
        pct   = avio_rl32(s->pb);
        ict   = avio_rl32(s->pb);
        av_log(s, AV_LOG_DEBUG,
               "itime:0x%"PRIx64", pct:%d, ict:%d\n", itime, pct, ict);
        for (i = 0; i < ict; i++) {
            int pktnum        = avio_rl32(s->pb);
            int pktct         = avio_rl16(s->pb);
            int64_t pos       = s->internal->data_offset + s->packet_size * (int64_t)pktnum;
            int64_t index_pts = FFMAX(av_rescale(itime, i, 10000) - asf->hdr.preroll, 0);
            if (pos != last_pos) {
                av_log(s, AV_LOG_DEBUG, "pktnum:%d, pktct:%d  pts: %"PRId64"\n",
                       pktnum, pktct, index_pts);
                av_add_index_entry(s->streams[stream_index], pos, index_pts,
                                   s->packet_size, 0, AVINDEX_KEYFRAME);
                last_pos = pos;
        asf->index_read = ict > 1;
end:
//     if (avio_feof(s->pb)) {
//         ret = 0;
//     }
    avio_seek(s->pb, current_pos, SEEK_SET);
    return ret;


static void ppc_cpu_initfn(Object *obj)

{

    CPUState *cs = CPU(obj);

    PowerPCCPU *cpu = POWERPC_CPU(obj);

    PowerPCCPUClass *pcc = POWERPC_CPU_GET_CLASS(cpu);

    CPUPPCState *env = &cpu->env;

    cs->env_ptr = env;

    cpu_exec_init(env, &error_abort);

    cpu->cpu_dt_id = cs->cpu_index;

    env->msr_mask = pcc->msr_mask;

    env->mmu_model = pcc->mmu_model;

    env->excp_model = pcc->excp_model;

    env->bus_model = pcc->bus_model;

    env->insns_flags = pcc->insns_flags;

    env->insns_flags2 = pcc->insns_flags2;

    env->flags = pcc->flags;

    env->bfd_mach = pcc->bfd_mach;

    env->check_pow = pcc->check_pow;

#if defined(TARGET_PPC64)

    if (pcc->sps) {

        env->sps = *pcc->sps;

    } else if (env->mmu_model & POWERPC_MMU_64) {

        /* Use default sets of page sizes */

        static const struct ppc_segment_page_sizes defsps = {

            .sps = {

                { .page_shift = 12, /* 4K */

                  .slb_enc = 0,

                  .enc = { { .page_shift = 12, .pte_enc = 0 } }

                },

                { .page_shift = 24, /* 16M */

                  .slb_enc = 0x100,

                  .enc = { { .page_shift = 24, .pte_enc = 0 } }

                },

            },

        };

        env->sps = defsps;

    }

#endif /* defined(TARGET_PPC64) */

    if (tcg_enabled()) {

        ppc_translate_init();

    }

}


static void vhost_user_cleanup(NetClientState *nc)

{

    VhostUserState *s = DO_UPCAST(VhostUserState, nc, nc);

    if (s->vhost_net) {

        vhost_net_cleanup(s->vhost_net);

        g_free(s->vhost_net);

        s->vhost_net = NULL;

    if (nc->queue_index == 0) {

        qemu_chr_fe_deinit(&s->chr, true);

    qemu_purge_queued_packets(nc);


int av_base64_decode(uint8_t *out, const char *in, int out_size)

{

    int i, v;

    uint8_t *dst = out;

    v = 0;

    for (i = 0; in[i] && in[i] != '='; i++) {

        unsigned int index= in[i]-43;

        if (index>=FF_ARRAY_ELEMS(map2) || map2[index] == 0xff)

            return -1;

        v = (v << 6) + map2[index];

        if (i & 3) {

            if (dst - out < out_size) {

                *dst++ = v >> (6 - 2 * (i & 3));

            }

        }

    }

    return dst - out;

}


static int process_input(int file_index)

{

    InputFile *ifile = input_files[file_index];

    AVFormatContext *is;

    InputStream *ist;

    AVPacket pkt;

    int ret, i, j;

    is  = ifile->ctx;

    ret = get_input_packet(ifile, &pkt);

    if (ret == AVERROR(EAGAIN)) {

        ifile->eagain = 1;

        return ret;

    }

    if (ret < 0) {

        if (ret != AVERROR_EOF) {

            print_error(is->filename, ret);

            if (exit_on_error)

                exit_program(1);

        }

        ifile->eof_reached = 1;

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

            ist = input_streams[ifile->ist_index + i];

            if (ist->decoding_needed)

                output_packet(ist, NULL);

            /* mark all outputs that don't go through lavfi as finished */

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

                OutputStream *ost = output_streams[j];

                if (ost->source_index == ifile->ist_index + i &&

                    (ost->stream_copy || ost->enc->type == AVMEDIA_TYPE_SUBTITLE))

                    close_output_stream(ost);

            }

        }

        return AVERROR(EAGAIN);

    }

    reset_eagain();

    if (do_pkt_dump) {

        av_pkt_dump_log2(NULL, AV_LOG_DEBUG, &pkt, do_hex_dump,

                         is->streams[pkt.stream_index]);

    }

    /* the following test is needed in case new streams appear

       dynamically in stream : we ignore them */

    if (pkt.stream_index >= ifile->nb_streams) {

        report_new_stream(file_index, &pkt);

        goto discard_packet;

    }

    ist = input_streams[ifile->ist_index + pkt.stream_index];

    if (ist->discard)

        goto discard_packet;

    if(!ist->wrap_correction_done && input_files[file_index]->ctx->start_time != AV_NOPTS_VALUE && ist->st->pts_wrap_bits < 64){

        uint64_t stime = av_rescale_q(input_files[file_index]->ctx->start_time, AV_TIME_BASE_Q, ist->st->time_base);

        uint64_t stime2= stime + (1LL<<ist->st->pts_wrap_bits);

        ist->wrap_correction_done = 1;

        if(pkt.dts != AV_NOPTS_VALUE && pkt.dts > stime && pkt.dts - stime > stime2 - pkt.dts) {

            pkt.dts -= 1LL<<ist->st->pts_wrap_bits;

            ist->wrap_correction_done = 0;

        }

        if(pkt.pts != AV_NOPTS_VALUE && pkt.pts > stime && pkt.pts - stime > stime2 - pkt.pts) {

            pkt.pts -= 1LL<<ist->st->pts_wrap_bits;

            ist->wrap_correction_done = 0;

        }

    }

    if (pkt.dts != AV_NOPTS_VALUE)

        pkt.dts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);

    if (pkt.pts != AV_NOPTS_VALUE)

        pkt.pts += av_rescale_q(ifile->ts_offset, AV_TIME_BASE_Q, ist->st->time_base);

    if (pkt.pts != AV_NOPTS_VALUE)

        pkt.pts *= ist->ts_scale;

    if (pkt.dts != AV_NOPTS_VALUE)

        pkt.dts *= ist->ts_scale;

    if (debug_ts) {

        av_log(NULL, AV_LOG_INFO, "demuxer -> ist_index:%d type:%s "

                "next_dts:%s next_dts_time:%s next_pts:%s next_pts_time:%s  pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s off:%"PRId64"\n",

                ifile->ist_index + pkt.stream_index, av_get_media_type_string(ist->st->codec->codec_type),

                av_ts2str(ist->next_dts), av_ts2timestr(ist->next_dts, &AV_TIME_BASE_Q),

                av_ts2str(ist->next_pts), av_ts2timestr(ist->next_pts, &AV_TIME_BASE_Q),

                av_ts2str(pkt.pts), av_ts2timestr(pkt.pts, &ist->st->time_base),

                av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &ist->st->time_base),

                input_files[ist->file_index]->ts_offset);

    }

    if (pkt.dts != AV_NOPTS_VALUE && ist->next_dts != AV_NOPTS_VALUE &&

        !copy_ts) {

        int64_t pkt_dts = av_rescale_q(pkt.dts, ist->st->time_base, AV_TIME_BASE_Q);

        int64_t delta   = pkt_dts - ist->next_dts;

        if (is->iformat->flags & AVFMT_TS_DISCONT) {

        if(delta < -1LL*dts_delta_threshold*AV_TIME_BASE ||

            (delta > 1LL*dts_delta_threshold*AV_TIME_BASE &&

                ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE) ||

            pkt_dts+1<ist->pts){

            ifile->ts_offset -= delta;

            av_log(NULL, AV_LOG_DEBUG,

                   "timestamp discontinuity %"PRId64", new offset= %"PRId64"\n",

                   delta, ifile->ts_offset);

            pkt.dts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);

            if (pkt.pts != AV_NOPTS_VALUE)

                pkt.pts -= av_rescale_q(delta, AV_TIME_BASE_Q, ist->st->time_base);

        }

        } else {

            if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||

                (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)

               ) {

                av_log(NULL, AV_LOG_WARNING, "DTS %"PRId64", next:%"PRId64" st:%d invalid dropping\n", pkt.dts, ist->next_dts, pkt.stream_index);

                pkt.dts = AV_NOPTS_VALUE;

            }

            if (pkt.pts != AV_NOPTS_VALUE){

                int64_t pkt_pts = av_rescale_q(pkt.pts, ist->st->time_base, AV_TIME_BASE_Q);

                delta   = pkt_pts - ist->next_dts;

                if ( delta < -1LL*dts_error_threshold*AV_TIME_BASE ||

                    (delta > 1LL*dts_error_threshold*AV_TIME_BASE && ist->st->codec->codec_type != AVMEDIA_TYPE_SUBTITLE)

                   ) {

                    av_log(NULL, AV_LOG_WARNING, "PTS %"PRId64", next:%"PRId64" invalid dropping st:%d\n", pkt.pts, ist->next_dts, pkt.stream_index);

                    pkt.pts = AV_NOPTS_VALUE;

                }

            }

        }

    }

    sub2video_heartbeat(ist, pkt.pts);

    ret = output_packet(ist, &pkt);

    if (ret < 0) {

        char buf[128];

        av_strerror(ret, buf, sizeof(buf));

        av_log(NULL, AV_LOG_ERROR, "Error while decoding stream #%d:%d: %s\n",

                ist->file_index, ist->st->index, buf);

        if (exit_on_error)

            exit_program(1);

    }

discard_packet:

    av_free_packet(&pkt);

    return 0;

}


void visit_type_int8(Visitor *v, int8_t *obj, const char *name, Error **errp)

{

    int64_t value;

    if (!error_is_set(errp)) {

        if (v->type_int8) {

            v->type_int8(v, obj, name, errp);

        } else {

            value = *obj;

            v->type_int(v, &value, name, errp);

            if (value < INT8_MIN || value > INT8_MAX) {

                error_set(errp, QERR_INVALID_PARAMETER_VALUE, name ? name : "null",

                          "int8_t");

                return;

            }

            *obj = value;

        }

    }

}


static void roq_encode_video(RoqContext *enc)

{

    RoqTempdata *tempData = enc->tmpData;

    int i;

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

    create_cel_evals(enc, tempData);

    generate_new_codebooks(enc, tempData);

    if (enc->framesSinceKeyframe >= 1) {

        motion_search(enc, 8);

        motion_search(enc, 4);

    }

 retry_encode:

    for (i=0; i<enc->width*enc->height/64; i++)

        gather_data_for_cel(tempData->cel_evals + i, enc, tempData);

    /* Quake 3 can't handle chunks bigger than 65536 bytes */

    if (tempData->mainChunkSize/8 > 65536) {

        enc->lambda *= .8;

        goto retry_encode;

    }

    remap_codebooks(enc, tempData);

    write_codebooks(enc, tempData);

    reconstruct_and_encode_image(enc, tempData, enc->width, enc->height,

                                 enc->width*enc->height/64);

    enc->avctx->coded_frame = enc->current_frame;

    /* Rotate frame history */

    FFSWAP(AVFrame *, enc->current_frame, enc->last_frame);

    FFSWAP(motion_vect *, enc->last_motion4, enc->this_motion4);

    FFSWAP(motion_vect *, enc->last_motion8, enc->this_motion8);

    av_free(tempData->cel_evals);

    av_free(tempData->closest_cb2);

    enc->framesSinceKeyframe++;

}


static int packet_alloc(AVBufferRef **buf, int size)

{

    int ret;

    if ((unsigned)size >= (unsigned)size + AV_INPUT_BUFFER_PADDING_SIZE)

        return AVERROR(EINVAL);

    ret = av_buffer_realloc(buf, size + AV_INPUT_BUFFER_PADDING_SIZE);

    if (ret < 0)

        return ret;

    memset((*buf)->data + size, 0, AV_INPUT_BUFFER_PADDING_SIZE);

    return 0;

}


static void m4sl_cb(MpegTSFilter *filter, const uint8_t *section,

                    int section_len)

{

    MpegTSContext *ts = filter->u.section_filter.opaque;

    MpegTSSectionFilter *tssf = &filter->u.section_filter;

    SectionHeader h;

    const uint8_t *p, *p_end;

    AVIOContext pb;

    int mp4_descr_count = 0;

    Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = { { 0 } };

    int i, pid;

    AVFormatContext *s = ts->stream;

    p_end = section + section_len - 4;

    p = section;

    if (parse_section_header(&h, &p, p_end) < 0)

        return;

    if (h.tid != M4OD_TID)

        return;

    if (h.version == tssf->last_ver)

        return;

    tssf->last_ver = h.version;

    mp4_read_od(s, p, (unsigned) (p_end - p), mp4_descr, &mp4_descr_count,

                MAX_MP4_DESCR_COUNT);

    for (pid = 0; pid < NB_PID_MAX; pid++) {

        if (!ts->pids[pid])

            continue;

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

            PESContext *pes;

            AVStream *st;

            if (ts->pids[pid]->es_id != mp4_descr[i].es_id)

                continue;

            if (ts->pids[pid]->type != MPEGTS_PES) {

                av_log(s, AV_LOG_ERROR, "pid %x is not PES\n", pid);

                continue;

            }

            pes = ts->pids[pid]->u.pes_filter.opaque;

            st  = pes->st;

            if (!st)

                continue;

            pes->sl = mp4_descr[i].sl;

            ffio_init_context(&pb, mp4_descr[i].dec_config_descr,

                              mp4_descr[i].dec_config_descr_len, 0,

                              NULL, NULL, NULL, NULL);

            ff_mp4_read_dec_config_descr(s, st, &pb);

            if (st->codec->codec_id == AV_CODEC_ID_AAC &&

                st->codec->extradata_size > 0)

                st->need_parsing = 0;

            if (st->codec->codec_id == AV_CODEC_ID_H264 &&

                st->codec->extradata_size > 0)

                st->need_parsing = 0;

            if (st->codec->codec_id <= AV_CODEC_ID_NONE) {

                // do nothing

            } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_AUDIO)

                st->codec->codec_type = AVMEDIA_TYPE_VIDEO;

            else if (st->codec->codec_id < AV_CODEC_ID_FIRST_SUBTITLE)

                st->codec->codec_type = AVMEDIA_TYPE_AUDIO;

            else if (st->codec->codec_id < AV_CODEC_ID_FIRST_UNKNOWN)

                st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;

        }

    }

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

        av_free(mp4_descr[i].dec_config_descr);

}


static int ffat_encode(AVCodecContext *avctx, AVPacket *avpkt,

                       const AVFrame *frame, int *got_packet_ptr)

{

    ATDecodeContext *at = avctx->priv_data;

    OSStatus ret;

    AudioBufferList out_buffers = {

        .mNumberBuffers = 1,

        .mBuffers = {

            {

                .mNumberChannels = avctx->channels,

                .mDataByteSize = at->pkt_size,

            }

        }

    };

    AudioStreamPacketDescription out_pkt_desc = {0};

    if ((ret = ff_alloc_packet2(avctx, avpkt, at->pkt_size, 0)) < 0)

        return ret;

    av_frame_unref(&at->new_in_frame);

    if (frame) {

        if ((ret = ff_af_queue_add(&at->afq, frame)) < 0)

            return ret;

        if ((ret = av_frame_ref(&at->new_in_frame, frame)) < 0)

            return ret;

    } else {

        at->eof = 1;

    }

    out_buffers.mBuffers[0].mData = avpkt->data;

    *got_packet_ptr = avctx->frame_size / at->frame_size;

    ret = AudioConverterFillComplexBuffer(at->converter, ffat_encode_callback, avctx,

                                          got_packet_ptr, &out_buffers,

                                          (avctx->frame_size > at->frame_size) ? NULL : &out_pkt_desc);

    if ((!ret || ret == 1) && *got_packet_ptr) {

        avpkt->size = out_buffers.mBuffers[0].mDataByteSize;

        ff_af_queue_remove(&at->afq, out_pkt_desc.mVariableFramesInPacket ?

                                     out_pkt_desc.mVariableFramesInPacket :

                                     avctx->frame_size,

                           &avpkt->pts,

                           &avpkt->duration);

    } else if (ret && ret != 1) {

        av_log(avctx, AV_LOG_WARNING, "Encode error: %i\n", ret);

    }

    return 0;

}


static int open_url(AVFormatContext *s, AVIOContext **pb, const char *url,

                    AVDictionary *opts, AVDictionary *opts2)

{

    HLSContext *c = s->priv_data;

    AVDictionary *tmp = NULL;

    const char *proto_name = avio_find_protocol_name(url);

    int ret;

    av_dict_copy(&tmp, opts, 0);

    av_dict_copy(&tmp, opts2, 0);

    if (!proto_name)

        return AVERROR_INVALIDDATA;

    // only http(s) & file are allowed

    if (!av_strstart(proto_name, "http", NULL) && !av_strstart(proto_name, "file", NULL))

        return AVERROR_INVALIDDATA;

    if (!strncmp(proto_name, url, strlen(proto_name)) && url[strlen(proto_name)] == ':')

        ;

    else if (strcmp(proto_name, "file") || !strncmp(url, "file,", 5))

        return AVERROR_INVALIDDATA;

    ret = s->io_open(s, pb, url, AVIO_FLAG_READ, &tmp);

    if (ret >= 0) {

        // update cookies on http response with setcookies.

        void *u = (s->flags & AVFMT_FLAG_CUSTOM_IO) ? NULL : s->pb;

        update_options(&c->cookies, "cookies", u);

        av_dict_set(&opts, "cookies", c->cookies, 0);

    }

    av_dict_free(&tmp);

    return ret;

}


static int nvdec_mpeg12_end_frame(AVCodecContext *avctx)

{

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

    int ret = ff_nvdec_end_frame(avctx);

    ctx->bitstream = NULL;

    return ret;

}


static void setup_rt_frame(int sig, struct target_sigaction *ka,

                           target_siginfo_t *info,

			   target_sigset_t *set, CPUX86State *env)

{

        abi_ulong frame_addr, addr;

	struct rt_sigframe *frame;

	int i, err = 0;

	frame_addr = get_sigframe(ka, env, sizeof(*frame));

	if (!lock_user_struct(VERIFY_WRITE, frame, frame_addr, 0))

		goto give_sigsegv;

    __put_user(current_exec_domain_sig(sig), &frame->sig);

        addr = frame_addr + offsetof(struct rt_sigframe, info);

    __put_user(addr, &frame->pinfo);

        addr = frame_addr + offsetof(struct rt_sigframe, uc);

    __put_user(addr, &frame->puc);

	err |= copy_siginfo_to_user(&frame->info, info);

	if (err)

		goto give_sigsegv;

	/* Create the ucontext.  */

    __put_user(0, &frame->uc.tuc_flags);

    __put_user(0, &frame->uc.tuc_link);

    __put_user(target_sigaltstack_used.ss_sp, &frame->uc.tuc_stack.ss_sp);

    __put_user(sas_ss_flags(get_sp_from_cpustate(env)),

               &frame->uc.tuc_stack.ss_flags);

    __put_user(target_sigaltstack_used.ss_size,

               &frame->uc.tuc_stack.ss_size);

	err |= setup_sigcontext(&frame->uc.tuc_mcontext, &frame->fpstate,

			        env, set->sig[0],

                                frame_addr + offsetof(struct rt_sigframe, fpstate));

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

            if (__put_user(set->sig[i], &frame->uc.tuc_sigmask.sig[i]))

                goto give_sigsegv;

        }

	/* Set up to return from userspace.  If provided, use a stub

	   already in userspace.  */

	if (ka->sa_flags & TARGET_SA_RESTORER) {

        __put_user(ka->sa_restorer, &frame->pretcode);

	} else {

                uint16_t val16;

                addr = frame_addr + offsetof(struct rt_sigframe, retcode);

        __put_user(addr, &frame->pretcode);

		/* This is movl $,%eax ; int $0x80 */

        __put_user(0xb8, (char *)(frame->retcode+0));

        __put_user(TARGET_NR_rt_sigreturn, (int *)(frame->retcode+1));

                val16 = 0x80cd;

        __put_user(val16, (uint16_t *)(frame->retcode+5));

	}

	if (err)

		goto give_sigsegv;

	/* Set up registers for signal handler */

	env->regs[R_ESP] = frame_addr;

	env->eip = ka->_sa_handler;

        cpu_x86_load_seg(env, R_DS, __USER_DS);

        cpu_x86_load_seg(env, R_ES, __USER_DS);

        cpu_x86_load_seg(env, R_SS, __USER_DS);

        cpu_x86_load_seg(env, R_CS, __USER_CS);

	env->eflags &= ~TF_MASK;

	unlock_user_struct(frame, frame_addr, 1);

	return;

give_sigsegv:

	unlock_user_struct(frame, frame_addr, 1);

	if (sig == TARGET_SIGSEGV)

		ka->_sa_handler = TARGET_SIG_DFL;

	force_sig(TARGET_SIGSEGV /* , current */);

}


static void pci_qdev_realize(DeviceState *qdev, Error **errp)

{

    PCIDevice *pci_dev = (PCIDevice *)qdev;

    PCIDeviceClass *pc = PCI_DEVICE_GET_CLASS(pci_dev);

    Error *local_err = NULL;

    PCIBus *bus;

    bool is_default_rom;

    /* initialize cap_present for pci_is_express() and pci_config_size() */

    if (pc->is_express) {

        pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS;

    }

    bus = PCI_BUS(qdev_get_parent_bus(qdev));

    pci_dev = do_pci_register_device(pci_dev, bus,

                                     object_get_typename(OBJECT(qdev)),

                                     pci_dev->devfn, errp);

    if (pci_dev == NULL)

        return;

    if (pc->realize) {

        pc->realize(pci_dev, &local_err);

        if (local_err) {

            error_propagate(errp, local_err);

            do_pci_unregister_device(pci_dev);

            return;

        }

    }

    /* rom loading */

    is_default_rom = false;

    if (pci_dev->romfile == NULL && pc->romfile != NULL) {

        pci_dev->romfile = g_strdup(pc->romfile);

        is_default_rom = true;

    }

    pci_add_option_rom(pci_dev, is_default_rom, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        pci_qdev_unrealize(DEVICE(pci_dev), NULL);

        return;

    }

}


int check_migratable(Object *obj, Error **err)

{

    return 0;

}


static av_cold int vp8_free(AVCodecContext *avctx)

{

    VP8Context *ctx = avctx->priv_data;

    vpx_codec_destroy(&ctx->encoder);

    av_freep(&ctx->twopass_stats.buf);

    av_freep(&avctx->coded_frame);

    av_freep(&avctx->stats_out);

    free_frame_list(ctx->coded_frame_list);

    return 0;

}


static void exynos4210_fimd_write(void *opaque, target_phys_addr_t offset,

                              uint64_t val, unsigned size)

{

    Exynos4210fimdState *s = (Exynos4210fimdState *)opaque;

    unsigned w, i;

    uint32_t old_value;

    DPRINT_L2("write offset 0x%08x, value=%llu(0x%08llx)\n", offset,

            (long long unsigned int)val, (long long unsigned int)val);

    switch (offset) {

    case FIMD_VIDCON0:

        if ((val & FIMD_VIDCON0_ENVID_MASK) == FIMD_VIDCON0_ENVID_MASK) {

            exynos4210_fimd_enable(s, true);

        } else {

            if ((val & FIMD_VIDCON0_ENVID) == 0) {

                exynos4210_fimd_enable(s, false);

            }

        }

        s->vidcon[0] = val;

        break;

    case FIMD_VIDCON1:

        /* Leave read-only bits as is */

        val = (val & (~FIMD_VIDCON1_ROMASK)) |

                (s->vidcon[1] & FIMD_VIDCON1_ROMASK);

        s->vidcon[1] = val;

        break;

    case FIMD_VIDCON2 ... FIMD_VIDCON3:

        s->vidcon[(offset) >> 2] = val;

        break;

    case FIMD_VIDTCON_START ... FIMD_VIDTCON_END:

        s->vidtcon[(offset - FIMD_VIDTCON_START) >> 2] = val;

        break;

    case FIMD_WINCON_START ... FIMD_WINCON_END:

        w = (offset - FIMD_WINCON_START) >> 2;

        /* Window's current buffer ID */

        i = fimd_get_buffer_id(&s->window[w]);

        old_value = s->window[w].wincon;

        val = (val & ~FIMD_WINCON_ROMASK) |

                (s->window[w].wincon & FIMD_WINCON_ROMASK);

        if (w == 0) {

            /* Window 0 wincon ALPHA_MUL bit must always be 0 */

            val &= ~FIMD_WINCON_ALPHA_MUL;

        }

        exynos4210_fimd_trace_bppmode(s, w, val);

        switch (val & FIMD_WINCON_BUFSELECT) {

        case FIMD_WINCON_BUF0_SEL:

            val &= ~FIMD_WINCON_BUFSTATUS;

            break;

        case FIMD_WINCON_BUF1_SEL:

            val = (val & ~FIMD_WINCON_BUFSTAT_H) | FIMD_WINCON_BUFSTAT_L;

            break;

        case FIMD_WINCON_BUF2_SEL:

            if (val & FIMD_WINCON_BUFMODE) {

                val = (val & ~FIMD_WINCON_BUFSTAT_L) | FIMD_WINCON_BUFSTAT_H;

            }

            break;

        default:

            break;

        }

        s->window[w].wincon = val;

        exynos4210_fimd_update_win_bppmode(s, w);

        fimd_update_get_alpha(s, w);

        if ((i != fimd_get_buffer_id(&s->window[w])) ||

                (!(old_value & FIMD_WINCON_ENWIN) && (s->window[w].wincon &

                        FIMD_WINCON_ENWIN))) {

            fimd_update_memory_section(s, w);

        }

        break;

    case FIMD_SHADOWCON:

        old_value = s->shadowcon;

        s->shadowcon = val;

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

            if (FIMD_WINDOW_PROTECTED(old_value, w) &&

                    !FIMD_WINDOW_PROTECTED(s->shadowcon, w)) {

                fimd_update_memory_section(s, w);

            }

        }

        break;

    case FIMD_WINCHMAP:

        s->winchmap = val;

        break;

    case FIMD_VIDOSD_START ... FIMD_VIDOSD_END:

        w = (offset - FIMD_VIDOSD_START) >> 4;

        i = ((offset - FIMD_VIDOSD_START) & 0xF) >> 2;

        switch (i) {

        case 0:

            old_value = s->window[w].lefttop_y;

            s->window[w].lefttop_x = (val >> FIMD_VIDOSD_HOR_SHIFT) &

                                      FIMD_VIDOSD_COORD_MASK;

            s->window[w].lefttop_y = (val >> FIMD_VIDOSD_VER_SHIFT) &

                                      FIMD_VIDOSD_COORD_MASK;

            if (s->window[w].lefttop_y != old_value) {

                fimd_update_memory_section(s, w);

            }

            break;

        case 1:

            old_value = s->window[w].rightbot_y;

            s->window[w].rightbot_x = (val >> FIMD_VIDOSD_HOR_SHIFT) &

                                       FIMD_VIDOSD_COORD_MASK;

            s->window[w].rightbot_y = (val >> FIMD_VIDOSD_VER_SHIFT) &

                                       FIMD_VIDOSD_COORD_MASK;

            if (s->window[w].rightbot_y != old_value) {

                fimd_update_memory_section(s, w);

            }

            break;

        case 2:

            if (w == 0) {

                s->window[w].osdsize = val;

            } else {

                s->window[w].alpha_val[0] =

                    unpack_upper_4((val & FIMD_VIDOSD_ALPHA_AEN0) >>

                    FIMD_VIDOSD_AEN0_SHIFT) |

                    (s->window[w].alpha_val[0] & FIMD_VIDALPHA_ALPHA_LOWER);

                s->window[w].alpha_val[1] =

                    unpack_upper_4(val & FIMD_VIDOSD_ALPHA_AEN1) |

                    (s->window[w].alpha_val[1] & FIMD_VIDALPHA_ALPHA_LOWER);

            }

            break;

        case 3:

            if (w != 1 && w != 2) {

                DPRINT_ERROR("Bad write offset 0x%08x\n", offset);

                return;

            }

            s->window[w].osdsize = val;

            break;

        }

        break;

    case FIMD_VIDWADD0_START ... FIMD_VIDWADD0_END:

        w = (offset - FIMD_VIDWADD0_START) >> 3;

        i = ((offset - FIMD_VIDWADD0_START) >> 2) & 1;

        if (i == fimd_get_buffer_id(&s->window[w]) &&

                s->window[w].buf_start[i] != val) {

            s->window[w].buf_start[i] = val;

            fimd_update_memory_section(s, w);

            break;

        }

        s->window[w].buf_start[i] = val;

        break;

    case FIMD_VIDWADD1_START ... FIMD_VIDWADD1_END:

        w = (offset - FIMD_VIDWADD1_START) >> 3;

        i = ((offset - FIMD_VIDWADD1_START) >> 2) & 1;

        s->window[w].buf_end[i] = val;

        break;

    case FIMD_VIDWADD2_START ... FIMD_VIDWADD2_END:

        w = (offset - FIMD_VIDWADD2_START) >> 2;

        if (((val & FIMD_VIDWADD2_PAGEWIDTH) != s->window[w].virtpage_width) ||

            (((val >> FIMD_VIDWADD2_OFFSIZE_SHIFT) & FIMD_VIDWADD2_OFFSIZE) !=

                        s->window[w].virtpage_offsize)) {

            s->window[w].virtpage_width = val & FIMD_VIDWADD2_PAGEWIDTH;

            s->window[w].virtpage_offsize =

                (val >> FIMD_VIDWADD2_OFFSIZE_SHIFT) & FIMD_VIDWADD2_OFFSIZE;

            fimd_update_memory_section(s, w);

        }

        break;

    case FIMD_VIDINTCON0:

        s->vidintcon[0] = val;

        break;

    case FIMD_VIDINTCON1:

        s->vidintcon[1] &= ~(val & 7);

        exynos4210_fimd_update_irq(s);

        break;

    case FIMD_WKEYCON_START ... FIMD_WKEYCON_END:

        w = ((offset - FIMD_WKEYCON_START) >> 3) + 1;

        i = ((offset - FIMD_WKEYCON_START) >> 2) & 1;

        s->window[w].keycon[i] = val;

        break;

    case FIMD_WKEYALPHA_START ... FIMD_WKEYALPHA_END:

        w = ((offset - FIMD_WKEYALPHA_START) >> 2) + 1;

        s->window[w].keyalpha = val;

        break;

    case FIMD_DITHMODE:

        s->dithmode = val;

        break;

    case FIMD_WINMAP_START ... FIMD_WINMAP_END:

        w = (offset - FIMD_WINMAP_START) >> 2;

        old_value = s->window[w].winmap;

        s->window[w].winmap = val;

        if ((val & FIMD_WINMAP_EN) ^ (old_value & FIMD_WINMAP_EN)) {

            exynos4210_fimd_invalidate(s);

            exynos4210_fimd_update_win_bppmode(s, w);

            exynos4210_fimd_trace_bppmode(s, w, 0xFFFFFFFF);

            exynos4210_fimd_update(s);

        }

        break;

    case FIMD_WPALCON_HIGH ... FIMD_WPALCON_LOW:

        i = (offset - FIMD_WPALCON_HIGH) >> 2;

        s->wpalcon[i] = val;

        if (s->wpalcon[1] & FIMD_WPALCON_UPDATEEN) {

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

                exynos4210_fimd_update_win_bppmode(s, w);

                fimd_update_get_alpha(s, w);

            }

        }

        break;

    case FIMD_TRIGCON:

        val = (val & ~FIMD_TRIGCON_ROMASK) | (s->trigcon & FIMD_TRIGCON_ROMASK);

        s->trigcon = val;

        break;

    case FIMD_I80IFCON_START ... FIMD_I80IFCON_END:

        s->i80ifcon[(offset - FIMD_I80IFCON_START) >> 2] = val;

        break;

    case FIMD_COLORGAINCON:

        s->colorgaincon = val;

        break;

    case FIMD_LDI_CMDCON0 ... FIMD_LDI_CMDCON1:

        s->ldi_cmdcon[(offset - FIMD_LDI_CMDCON0) >> 2] = val;

        break;

    case FIMD_SIFCCON0 ... FIMD_SIFCCON2:

        i = (offset - FIMD_SIFCCON0) >> 2;

        if (i != 2) {

            s->sifccon[i] = val;

        }

        break;

    case FIMD_HUECOEFCR_START ... FIMD_HUECOEFCR_END:

        i = (offset - FIMD_HUECOEFCR_START) >> 2;

        s->huecoef_cr[i] = val;

        break;

    case FIMD_HUECOEFCB_START ... FIMD_HUECOEFCB_END:

        i = (offset - FIMD_HUECOEFCB_START) >> 2;

        s->huecoef_cb[i] = val;

        break;

    case FIMD_HUEOFFSET:

        s->hueoffset = val;

        break;

    case FIMD_VIDWALPHA_START ... FIMD_VIDWALPHA_END:

        w = ((offset - FIMD_VIDWALPHA_START) >> 3);

        i = ((offset - FIMD_VIDWALPHA_START) >> 2) & 1;

        if (w == 0) {

            s->window[w].alpha_val[i] = val;

        } else {

            s->window[w].alpha_val[i] = (val & FIMD_VIDALPHA_ALPHA_LOWER) |

                (s->window[w].alpha_val[i] & FIMD_VIDALPHA_ALPHA_UPPER);

        }

        break;

    case FIMD_BLENDEQ_START ... FIMD_BLENDEQ_END:

        s->window[(offset - FIMD_BLENDEQ_START) >> 2].blendeq = val;

        break;

    case FIMD_BLENDCON:

        old_value = s->blendcon;

        s->blendcon = val;

        if ((s->blendcon & FIMD_ALPHA_8BIT) != (old_value & FIMD_ALPHA_8BIT)) {

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

                fimd_update_get_alpha(s, w);

            }

        }

        break;

    case FIMD_WRTQOSCON_START ... FIMD_WRTQOSCON_END:

        s->window[(offset - FIMD_WRTQOSCON_START) >> 2].rtqoscon = val;

        break;

    case FIMD_I80IFCMD_START ... FIMD_I80IFCMD_END:

        s->i80ifcmd[(offset - FIMD_I80IFCMD_START) >> 2] = val;

        break;

    case FIMD_VIDW0ADD0_B2 ... FIMD_VIDW4ADD0_B2:

        if (offset & 0x0004) {

            DPRINT_ERROR("bad write offset 0x%08x\n", offset);

            break;

        }

        w = (offset - FIMD_VIDW0ADD0_B2) >> 3;

        if (fimd_get_buffer_id(&s->window[w]) == 2 &&

                s->window[w].buf_start[2] != val) {

            s->window[w].buf_start[2] = val;

            fimd_update_memory_section(s, w);

            break;

        }

        s->window[w].buf_start[2] = val;

        break;

    case FIMD_SHD_ADD0_START ... FIMD_SHD_ADD0_END:

        if (offset & 0x0004) {

            DPRINT_ERROR("bad write offset 0x%08x\n", offset);

            break;

        }

        s->window[(offset - FIMD_SHD_ADD0_START) >> 3].shadow_buf_start = val;

        break;

    case FIMD_SHD_ADD1_START ... FIMD_SHD_ADD1_END:

        if (offset & 0x0004) {

            DPRINT_ERROR("bad write offset 0x%08x\n", offset);

            break;

        }

        s->window[(offset - FIMD_SHD_ADD1_START) >> 3].shadow_buf_end = val;

        break;

    case FIMD_SHD_ADD2_START ... FIMD_SHD_ADD2_END:

        s->window[(offset - FIMD_SHD_ADD2_START) >> 2].shadow_buf_size = val;

        break;

    case FIMD_PAL_MEM_START ... FIMD_PAL_MEM_END:

        w = (offset - FIMD_PAL_MEM_START) >> 10;

        i = ((offset - FIMD_PAL_MEM_START) >> 2) & 0xFF;

        s->window[w].palette[i] = val;

        break;

    case FIMD_PALMEM_AL_START ... FIMD_PALMEM_AL_END:

        /* Palette memory aliases for windows 0 and 1 */

        w = (offset - FIMD_PALMEM_AL_START) >> 10;

        i = ((offset - FIMD_PALMEM_AL_START) >> 2) & 0xFF;

        s->window[w].palette[i] = val;

        break;

    default:

        DPRINT_ERROR("bad write offset 0x%08x\n", offset);

        break;

    }

}


static int usb_wacom_initfn(USBDevice *dev)

{

    USBWacomState *s = DO_UPCAST(USBWacomState, dev, dev);

    s->dev.speed = USB_SPEED_FULL;

    s->changed = 1;

    return 0;

}


void bdrv_register(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;

        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;

        } else if (!bdrv->bdrv_read) {

            /* add synchronous IO emulation layer */

            bdrv->bdrv_read = bdrv_read_em;

            bdrv->bdrv_write = bdrv_write_em;

        }

    }

    if (!bdrv->bdrv_aio_flush)

        bdrv->bdrv_aio_flush = bdrv_aio_flush_em;

    QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);

}


void socket_listen_cleanup(int fd, Error **errp)

{

    SocketAddress *addr;

    addr = socket_local_address(fd, errp);

    if (addr->type == SOCKET_ADDRESS_KIND_UNIX

        && addr->u.q_unix.data->path) {

        if (unlink(addr->u.q_unix.data->path) < 0 && errno != ENOENT) {

            error_setg_errno(errp, errno,

                             "Failed to unlink socket %s",

                             addr->u.q_unix.data->path);

        }

    }

    qapi_free_SocketAddress(addr);

}


static void test_nested_struct(gconstpointer opaque)

{

    TestArgs *args = (TestArgs *) opaque;

    const SerializeOps *ops = args->ops;

    UserDefNested *udnp = nested_struct_create();

    UserDefNested *udnp_copy = NULL;

    Error *err = NULL;

    void *serialize_data;

    ops->serialize(udnp, &serialize_data, visit_nested_struct, &err);

    ops->deserialize((void **)&udnp_copy, serialize_data, visit_nested_struct, &err);

    g_assert(err == NULL);

    nested_struct_compare(udnp, udnp_copy);

    nested_struct_cleanup(udnp);

    nested_struct_cleanup(udnp_copy);

    ops->cleanup(serialize_data);

    g_free(args);

}


static int usb_net_initfn(USBDevice *dev)

{

    USBNetState *s = DO_UPCAST(USBNetState, dev, dev);

    s->dev.speed  = USB_SPEED_FULL;

    s->rndis = 1;

    s->rndis_state = RNDIS_UNINITIALIZED;

    QTAILQ_INIT(&s->rndis_resp);

    s->medium = 0;	/* NDIS_MEDIUM_802_3 */

    s->speed = 1000000; /* 100MBps, in 100Bps units */

    s->media_state = 0;	/* NDIS_MEDIA_STATE_CONNECTED */;

    s->filter = 0;

    s->vendorid = 0x1234;

    qemu_macaddr_default_if_unset(&s->conf.macaddr);

    s->nic = qemu_new_nic(&net_usbnet_info, &s->conf,

                          s->dev.qdev.info->name, s->dev.qdev.id, s);

    qemu_format_nic_info_str(&s->nic->nc, s->conf.macaddr.a);

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

             "%02x%02x%02x%02x%02x%02x",

             0x40,

             s->conf.macaddr.a[1],

             s->conf.macaddr.a[2],

             s->conf.macaddr.a[3],

             s->conf.macaddr.a[4],

             s->conf.macaddr.a[5]);

    usb_desc_set_string(dev, STRING_ETHADDR, s->usbstring_mac);

    add_boot_device_path(s->conf.bootindex, &dev->qdev, "/ethernet@0");

    return 0;

}


static void curses_setup(void)

{

    int i, colour_default[8] = {

        COLOR_BLACK, COLOR_BLUE, COLOR_GREEN, COLOR_CYAN,

        COLOR_RED, COLOR_MAGENTA, COLOR_YELLOW, COLOR_WHITE,

    };

    /* input as raw as possible, let everything be interpreted

     * by the guest system */

    initscr(); noecho(); intrflush(stdscr, FALSE);

    nodelay(stdscr, TRUE); nonl(); keypad(stdscr, TRUE);

    start_color(); raw(); scrollok(stdscr, FALSE);

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

        init_pair(i, colour_default[i & 7], colour_default[i >> 3]);

    }

    /* Set default color for more than 64. (monitor uses 0x74xx for example) */

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

        init_pair(i, COLOR_WHITE, COLOR_BLACK);

    }

    /*

     * Setup mapping for vga to curses line graphics.

     * FIXME: for better font, have to use ncursesw and setlocale()

     */

#if 0

    /* FIXME: map from where? */

    ACS_S1;

    ACS_S3;

    ACS_S7;

    ACS_S9;

#endif

    /* ACS_* is not constant. So, we can't initialize statically. */

    vga_to_curses['\0'] = ' ';

    vga_to_curses[0x04] = ACS_DIAMOND;

    vga_to_curses[0x0a] = ACS_RARROW;

    vga_to_curses[0x0b] = ACS_LARROW;

    vga_to_curses[0x18] = ACS_UARROW;

    vga_to_curses[0x19] = ACS_DARROW;

    vga_to_curses[0x9c] = ACS_STERLING;

    vga_to_curses[0xb0] = ACS_BOARD;

    vga_to_curses[0xb1] = ACS_CKBOARD;

    vga_to_curses[0xb3] = ACS_VLINE;

    vga_to_curses[0xb4] = ACS_RTEE;

    vga_to_curses[0xbf] = ACS_URCORNER;

    vga_to_curses[0xc0] = ACS_LLCORNER;

    vga_to_curses[0xc1] = ACS_BTEE;

    vga_to_curses[0xc2] = ACS_TTEE;

    vga_to_curses[0xc3] = ACS_LTEE;

    vga_to_curses[0xc4] = ACS_HLINE;

    vga_to_curses[0xc5] = ACS_PLUS;

    vga_to_curses[0xce] = ACS_LANTERN;

    vga_to_curses[0xd8] = ACS_NEQUAL;

    vga_to_curses[0xd9] = ACS_LRCORNER;

    vga_to_curses[0xda] = ACS_ULCORNER;

    vga_to_curses[0xdb] = ACS_BLOCK;

    vga_to_curses[0xe3] = ACS_PI;

    vga_to_curses[0xf1] = ACS_PLMINUS;

    vga_to_curses[0xf2] = ACS_GEQUAL;

    vga_to_curses[0xf3] = ACS_LEQUAL;

    vga_to_curses[0xf8] = ACS_DEGREE;

    vga_to_curses[0xfe] = ACS_BULLET;

}


static bool send_gradient_rect(VncState *vs, int w, int h)

{

    int stream = 3;

    int level = tight_conf[vs->tight_compression].gradient_zlib_level;

    size_t bytes;

    if (vs->clientds.pf.bytes_per_pixel == 1)

        return send_full_color_rect(vs, w, h);

    vnc_write_u8(vs, (stream | VNC_TIGHT_EXPLICIT_FILTER) << 4);

    vnc_write_u8(vs, VNC_TIGHT_FILTER_GRADIENT);

    buffer_reserve(&vs->tight_gradient, w * 3 * sizeof (int));

    if (vs->tight_pixel24) {

        tight_filter_gradient24(vs, vs->tight.buffer, w, h);

        bytes = 3;

    } else if (vs->clientds.pf.bytes_per_pixel == 4) {

        tight_filter_gradient32(vs, (uint32_t *)vs->tight.buffer, w, h);

        bytes = 4;

    } else {

        tight_filter_gradient16(vs, (uint16_t *)vs->tight.buffer, w, h);

        bytes = 2;

    }

    buffer_reset(&vs->tight_gradient);

    bytes = w * h * bytes;

    vs->tight.offset = bytes;

    bytes = tight_compress_data(vs, stream, bytes,

                                level, Z_FILTERED);

    return (bytes >= 0);

}


int bdrv_get_flags(BlockDriverState *bs)

{

    return bs->open_flags;

}


static int filter_frame(AVFilterLink *inlink, AVFrame *insamples)

{

    AVFilterContext *ctx = inlink->dst;

    ASNSContext *asns = ctx->priv;

    AVFilterLink *outlink = ctx->outputs[0];

    int ret;

    int nb_samples = insamples->nb_samples;

    if (av_audio_fifo_space(asns->fifo) < nb_samples) {

        av_log(ctx, AV_LOG_DEBUG, "No space for %d samples, stretching audio fifo\n", nb_samples);

        ret = av_audio_fifo_realloc(asns->fifo, av_audio_fifo_size(asns->fifo) + nb_samples);

        if (ret < 0) {

            av_log(ctx, AV_LOG_ERROR,

                   "Stretching audio fifo failed, discarded %d samples\n", nb_samples);

            return -1;

        }

    }

    av_audio_fifo_write(asns->fifo, (void **)insamples->extended_data, nb_samples);

    if (asns->next_out_pts == AV_NOPTS_VALUE)

        asns->next_out_pts = insamples->pts;

    av_frame_free(&insamples);

    while (av_audio_fifo_size(asns->fifo) >= asns->nb_out_samples)

        push_samples(outlink);

    return 0;

}


long do_rt_sigreturn(CPUState *env)

{

	struct rt_sigframe *frame;

        sigset_t host_set;

	/*

	 * Since we stacked the signal on a 64-bit boundary,

	 * then 'sp' should be word aligned here.  If it's

	 * not, then the user is trying to mess with us.

	 */

	if (env->regs[13] & 7)

		goto badframe;

	frame = (struct rt_sigframe *)env->regs[13];

#if 0

	if (verify_area(VERIFY_READ, frame, sizeof (*frame)))

		goto badframe;

#endif

        target_to_host_sigset(&host_set, &frame->uc.tuc_sigmask);

        sigprocmask(SIG_SETMASK, &host_set, NULL);

	if (restore_sigcontext(env, &frame->uc.tuc_mcontext))

		goto badframe;

	if (do_sigaltstack(h2g(&frame->uc.tuc_stack), 0, get_sp_from_cpustate(env)) == -EFAULT)

		goto badframe;

#if 0

	/* Send SIGTRAP if we're single-stepping */

	if (ptrace_cancel_bpt(current))

		send_sig(SIGTRAP, current, 1);

#endif

	return env->regs[0];

badframe:

        force_sig(SIGSEGV /* , current */);

	return 0;

}


static PCIDevice *find_dev(sPAPREnvironment *spapr, uint64_t buid,

                           uint32_t config_addr)

{

    sPAPRPHBState *sphb = find_phb(spapr, buid);

    PCIHostState *phb = PCI_HOST_BRIDGE(sphb);

    int bus_num = (config_addr >> 16) & 0xFF;

    int devfn = (config_addr >> 8) & 0xFF;

    if (!phb) {

        return NULL;

    }

    return pci_find_device(phb->bus, bus_num, devfn);

}


void *pci_assign_dev_load_option_rom(PCIDevice *dev, struct Object *owner,

                                     int *size, unsigned int domain,

                                     unsigned int bus, unsigned int slot,

                                     unsigned int function)

{

    char name[32], rom_file[64];

    FILE *fp;

    uint8_t val;

    struct stat st;

    void *ptr = NULL;

    /* If loading ROM from file, pci handles it */

    if (dev->romfile || !dev->rom_bar) {

        return NULL;

    }

    snprintf(rom_file, sizeof(rom_file),

             "/sys/bus/pci/devices/%04x:%02x:%02x.%01x/rom",

             domain, bus, slot, function);

    if (stat(rom_file, &st)) {

        if (errno != ENOENT) {

            error_report("pci-assign: Invalid ROM.");

        }

        return NULL;

    }

    /* Write "1" to the ROM file to enable it */

    fp = fopen(rom_file, "r+");

    if (fp == NULL) {

        error_report("pci-assign: Cannot open %s: %s", rom_file, strerror(errno));

        return NULL;

    }

    val = 1;

    if (fwrite(&val, 1, 1, fp) != 1) {

        goto close_rom;

    }

    fseek(fp, 0, SEEK_SET);

    snprintf(name, sizeof(name), "%s.rom", object_get_typename(owner));

    memory_region_init_ram(&dev->rom, owner, name, st.st_size, &error_abort);

    vmstate_register_ram(&dev->rom, &dev->qdev);

    ptr = memory_region_get_ram_ptr(&dev->rom);

    memset(ptr, 0xff, st.st_size);

    if (!fread(ptr, 1, st.st_size, fp)) {

        error_report("pci-assign: Cannot read from host %s", rom_file);

        error_printf("Device option ROM contents are probably invalid "

                     "(check dmesg).\nSkip option ROM probe with rombar=0, "

                     "or load from file with romfile=\n");

        goto close_rom;

    }

    pci_register_bar(dev, PCI_ROM_SLOT, 0, &dev->rom);

    dev->has_rom = true;

    *size = st.st_size;

close_rom:

    /* Write "0" to disable ROM */

    fseek(fp, 0, SEEK_SET);

    val = 0;

    if (!fwrite(&val, 1, 1, fp)) {

        DEBUG("%s\n", "Failed to disable pci-sysfs rom file");

    }

    fclose(fp);

    return ptr;

}


void cpu_unregister_map_client(void *_client)

{

    MapClient *client = (MapClient *)_client;

    LIST_REMOVE(client, link);

    qemu_free(client);

}


static inline void gen_intermediate_code_internal(PowerPCCPU *cpu,

                                                  TranslationBlock *tb,

                                                  bool search_pc)

{

    CPUState *cs = CPU(cpu);

    CPUPPCState *env = &cpu->env;

    DisasContext ctx, *ctxp = &ctx;

    opc_handler_t **table, *handler;

    target_ulong pc_start;

    uint16_t *gen_opc_end;

    CPUBreakpoint *bp;

    int j, lj = -1;

    int num_insns;

    int max_insns;

    pc_start = tb->pc;

    gen_opc_end = tcg_ctx.gen_opc_buf + OPC_MAX_SIZE;

    ctx.nip = pc_start;

    ctx.tb = tb;

    ctx.exception = POWERPC_EXCP_NONE;

    ctx.spr_cb = env->spr_cb;

    ctx.pr = msr_pr;

    ctx.hv = !msr_pr && msr_hv;

    ctx.mem_idx = env->mmu_idx;

    ctx.insns_flags = env->insns_flags;

    ctx.insns_flags2 = env->insns_flags2;

    ctx.access_type = -1;

    ctx.le_mode = env->hflags & (1 << MSR_LE) ? 1 : 0;

    ctx.default_tcg_memop_mask = ctx.le_mode ? MO_LE : MO_BE;

#if defined(TARGET_PPC64)

    ctx.sf_mode = msr_is_64bit(env, env->msr);

    ctx.has_cfar = !!(env->flags & POWERPC_FLAG_CFAR);

#endif

    ctx.fpu_enabled = msr_fp;

    if ((env->flags & POWERPC_FLAG_SPE) && msr_spe)

        ctx.spe_enabled = msr_spe;

    else

        ctx.spe_enabled = 0;

    if ((env->flags & POWERPC_FLAG_VRE) && msr_vr)

        ctx.altivec_enabled = msr_vr;

    else

        ctx.altivec_enabled = 0;

    if ((env->flags & POWERPC_FLAG_VSX) && msr_vsx) {

        ctx.vsx_enabled = msr_vsx;

    } else {

        ctx.vsx_enabled = 0;

    }

    if ((env->flags & POWERPC_FLAG_SE) && msr_se)

        ctx.singlestep_enabled = CPU_SINGLE_STEP;

    else

        ctx.singlestep_enabled = 0;

    if ((env->flags & POWERPC_FLAG_BE) && msr_be)

        ctx.singlestep_enabled |= CPU_BRANCH_STEP;

    if (unlikely(cs->singlestep_enabled)) {

        ctx.singlestep_enabled |= GDBSTUB_SINGLE_STEP;

    }

#if defined (DO_SINGLE_STEP) && 0

    /* Single step trace mode */

    msr_se = 1;

#endif

    num_insns = 0;

    max_insns = tb->cflags & CF_COUNT_MASK;

    if (max_insns == 0)

        max_insns = CF_COUNT_MASK;

    gen_tb_start();

    tcg_clear_temp_count();

    /* Set env in case of segfault during code fetch */

    while (ctx.exception == POWERPC_EXCP_NONE

            && tcg_ctx.gen_opc_ptr < gen_opc_end) {

        if (unlikely(!QTAILQ_EMPTY(&cs->breakpoints))) {

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

                if (bp->pc == ctx.nip) {

                    gen_debug_exception(ctxp);

                    break;

                }

            }

        }

        if (unlikely(search_pc)) {

            j = tcg_ctx.gen_opc_ptr - tcg_ctx.gen_opc_buf;

            if (lj < j) {

                lj++;

                while (lj < j)

                    tcg_ctx.gen_opc_instr_start[lj++] = 0;

            }

            tcg_ctx.gen_opc_pc[lj] = ctx.nip;

            tcg_ctx.gen_opc_instr_start[lj] = 1;

            tcg_ctx.gen_opc_icount[lj] = num_insns;

        }

        LOG_DISAS("----------------\n");

        LOG_DISAS("nip=" TARGET_FMT_lx " super=%d ir=%d\n",

                  ctx.nip, ctx.mem_idx, (int)msr_ir);

        if (num_insns + 1 == max_insns && (tb->cflags & CF_LAST_IO))

            gen_io_start();

        if (unlikely(need_byteswap(&ctx))) {

            ctx.opcode = bswap32(cpu_ldl_code(env, ctx.nip));

        } else {

            ctx.opcode = cpu_ldl_code(env, ctx.nip);

        }

        LOG_DISAS("translate opcode %08x (%02x %02x %02x) (%s)\n",

                    ctx.opcode, opc1(ctx.opcode), opc2(ctx.opcode),

                    opc3(ctx.opcode), ctx.le_mode ? "little" : "big");

        if (unlikely(qemu_loglevel_mask(CPU_LOG_TB_OP | CPU_LOG_TB_OP_OPT))) {

            tcg_gen_debug_insn_start(ctx.nip);

        }

        ctx.nip += 4;

        table = env->opcodes;

        num_insns++;

        handler = table[opc1(ctx.opcode)];

        if (is_indirect_opcode(handler)) {

            table = ind_table(handler);

            handler = table[opc2(ctx.opcode)];

            if (is_indirect_opcode(handler)) {

                table = ind_table(handler);

                handler = table[opc3(ctx.opcode)];

            }

        }

        /* Is opcode *REALLY* valid ? */

        if (unlikely(handler->handler == &gen_invalid)) {

            if (qemu_log_enabled()) {

                qemu_log("invalid/unsupported opcode: "

                         "%02x - %02x - %02x (%08x) " TARGET_FMT_lx " %d\n",

                         opc1(ctx.opcode), opc2(ctx.opcode),

                         opc3(ctx.opcode), ctx.opcode, ctx.nip - 4, (int)msr_ir);

            }

        } else {

            uint32_t inval;

            if (unlikely(handler->type & (PPC_SPE | PPC_SPE_SINGLE | PPC_SPE_DOUBLE) && Rc(ctx.opcode))) {

                inval = handler->inval2;

            } else {

                inval = handler->inval1;

            }

            if (unlikely((ctx.opcode & inval) != 0)) {

                if (qemu_log_enabled()) {

                    qemu_log("invalid bits: %08x for opcode: "

                             "%02x - %02x - %02x (%08x) " TARGET_FMT_lx "\n",

                             ctx.opcode & inval, opc1(ctx.opcode),

                             opc2(ctx.opcode), opc3(ctx.opcode),

                             ctx.opcode, ctx.nip - 4);

                }

                gen_inval_exception(ctxp, POWERPC_EXCP_INVAL_INVAL);

                break;

            }

        }

        (*(handler->handler))(&ctx);

#if defined(DO_PPC_STATISTICS)

        handler->count++;

#endif

        /* Check trace mode exceptions */

        if (unlikely(ctx.singlestep_enabled & CPU_SINGLE_STEP &&

                     (ctx.nip <= 0x100 || ctx.nip > 0xF00) &&

                     ctx.exception != POWERPC_SYSCALL &&

                     ctx.exception != POWERPC_EXCP_TRAP &&

                     ctx.exception != POWERPC_EXCP_BRANCH)) {

            gen_exception(ctxp, POWERPC_EXCP_TRACE);

        } else if (unlikely(((ctx.nip & (TARGET_PAGE_SIZE - 1)) == 0) ||

                            (cs->singlestep_enabled) ||

                            singlestep ||

                            num_insns >= max_insns)) {

            /* if we reach a page boundary or are single stepping, stop

             * generation

             */

            break;

        }

        if (tcg_check_temp_count()) {

            fprintf(stderr, "Opcode %02x %02x %02x (%08x) leaked temporaries\n",

                    opc1(ctx.opcode), opc2(ctx.opcode), opc3(ctx.opcode),

                    ctx.opcode);

            exit(1);

        }

    }

    if (tb->cflags & CF_LAST_IO)

        gen_io_end();

    if (ctx.exception == POWERPC_EXCP_NONE) {

        gen_goto_tb(&ctx, 0, ctx.nip);

    } else if (ctx.exception != POWERPC_EXCP_BRANCH) {

        if (unlikely(cs->singlestep_enabled)) {

            gen_debug_exception(ctxp);

        }

        /* Generate the return instruction */

        tcg_gen_exit_tb(0);

    }

    gen_tb_end(tb, num_insns);

    *tcg_ctx.gen_opc_ptr = INDEX_op_end;

    if (unlikely(search_pc)) {

        j = tcg_ctx.gen_opc_ptr - tcg_ctx.gen_opc_buf;

        lj++;

        while (lj <= j)

            tcg_ctx.gen_opc_instr_start[lj++] = 0;

    } else {

        tb->size = ctx.nip - pc_start;

        tb->icount = num_insns;

    }

#if defined(DEBUG_DISAS)

    if (qemu_loglevel_mask(CPU_LOG_TB_IN_ASM)) {

        int flags;

        flags = env->bfd_mach;

        flags |= ctx.le_mode << 16;

        qemu_log("IN: %s\n", lookup_symbol(pc_start));

        log_target_disas(env, pc_start, ctx.nip - pc_start, flags);

        qemu_log("\n");

    }

#endif

}


static void dma_aio_cancel(BlockDriverAIOCB *acb)

{

    DMAAIOCB *dbs = container_of(acb, DMAAIOCB, common);

    if (dbs->acb) {

        bdrv_aio_cancel(dbs->acb);

    }

}


int32_t idiv32(int32_t *q_ptr, int64_t num, int32_t den)

{

    *q_ptr = num / den;

    return num % den;

}


void qmp_nbd_server_add(const char *device, bool has_writable, bool writable,

                        Error **errp)

{

    BlockDriverState *bs;

    NBDExport *exp;

    NBDCloseNotifier *n;

    if (server_fd == -1) {

        error_setg(errp, "NBD server not running");

        return;

    }

    if (nbd_export_find(device)) {

        error_setg(errp, "NBD server already exporting device '%s'", device);

        return;

    }

    bs = bdrv_find(device);

    if (!bs) {

        error_set(errp, QERR_DEVICE_NOT_FOUND, device);

        return;

    }

    if (!bdrv_is_inserted(bs)) {

        error_set(errp, QERR_DEVICE_HAS_NO_MEDIUM, device);

        return;

    }

    if (!has_writable) {

        writable = false;

    }

    if (bdrv_is_read_only(bs)) {

        writable = false;

    }

    exp = nbd_export_new(bs, 0, -1, writable ? 0 : NBD_FLAG_READ_ONLY, NULL);

    nbd_export_set_name(exp, device);

    n = g_malloc0(sizeof(NBDCloseNotifier));

    n->n.notify = nbd_close_notifier;

    n->exp = exp;

    bdrv_add_close_notifier(bs, &n->n);

    QTAILQ_INSERT_TAIL(&close_notifiers, n, next);

}


static void xbr3x(AVFrame *input, AVFrame *output, const uint32_t *r2y)

{

    const int nl = output->linesize[0]>>2;

    const int nl1 = nl + nl;

    uint32_t pprev;

    uint32_t pprev2;

    int x,y;

    for (y = 0; y < input->height; y++) {

        uint32_t * E = (uint32_t *)(output->data[0] + y * output->linesize[0] * 3);

        /* middle. Offset of -8 is given */

        uint32_t * sa2 = (uint32_t *)(input->data[0] + y * input->linesize[0] - 8);

        /* up one */

        uint32_t * sa1 = sa2 - (input->linesize[0]>>2);

        /* up two */

        uint32_t * sa0 = sa1 - (input->linesize[0]>>2);

        /* down one */

        uint32_t * sa3 = sa2 + (input->linesize[0]>>2);

        /* down two */

        uint32_t * sa4 = sa3 + (input->linesize[0]>>2);

        if (y <= 1){

            sa0 = sa1;

            if (y == 0){

                sa0 = sa1 = sa2;

            }

        }

        if (y >= input->height - 2){

            sa4 = sa3;

            if (y == input->height - 1){

                sa4 = sa3 = sa2;

            }

        }

        pprev = pprev2 = 2;

        for (x = 0; x < input->width; x++){

            uint32_t B1 = sa0[2];

            uint32_t PB = sa1[2];

            uint32_t PE = sa2[2];

            uint32_t PH = sa3[2];

            uint32_t H5 = sa4[2];

            uint32_t A1 = sa0[pprev];

            uint32_t PA = sa1[pprev];

            uint32_t PD = sa2[pprev];

            uint32_t PG = sa3[pprev];

            uint32_t G5 = sa4[pprev];

            uint32_t A0 = sa1[pprev2];

            uint32_t D0 = sa2[pprev2];

            uint32_t G0 = sa3[pprev2];

            uint32_t C1 = 0;

            uint32_t PC = 0;

            uint32_t PF = 0;

            uint32_t PI = 0;

            uint32_t I5 = 0;

            uint32_t C4 = 0;

            uint32_t F4 = 0;

            uint32_t I4 = 0;

            if (x >= input->width - 2){

                if (x == input->width - 1){

                    C1 = sa0[2];

                    PC = sa1[2];

                    PF = sa2[2];

                    PI = sa3[2];

                    I5 = sa4[2];

                    C4 = sa1[2];

                    F4 = sa2[2];

                    I4 = sa3[2];

                } else {

                    C1 = sa0[3];

                    PC = sa1[3];

                    PF = sa2[3];

                    PI = sa3[3];

                    I5 = sa4[3];

                    C4 = sa1[3];

                    F4 = sa2[3];

                    I4 = sa3[3];

                }

            } else {

                C1 = sa0[3];

                PC = sa1[3];

                PF = sa2[3];

                PI = sa3[3];

                I5 = sa4[3];

                C4 = sa1[4];

                F4 = sa2[4];

                I4 = sa3[4];

            }

            E[0]   = E[1]     = E[2]     = PE;

            E[nl]  = E[nl+1]  = E[nl+2]  = PE; // 3, 4, 5

            E[nl1] = E[nl1+1] = E[nl1+2] = PE; // 6, 7, 8

            FILT3(PE, PI, PH, PF, PG, PC, PD, PB, PA, G5, C4, G0, D0, C1, B1, F4, I4, H5, I5, A0, A1, 0, 1, 2, nl, nl+1, nl+2, nl1, nl1+1, nl1+2);

            FILT3(PE, PC, PF, PB, PI, PA, PH, PD, PG, I4, A1, I5, H5, A0, D0, B1, C1, F4, C4, G5, G0, nl1, nl, 0, nl1+1, nl+1, 1, nl1+2, nl+2, 2);

            FILT3(PE, PA, PB, PD, PC, PG, PF, PH, PI, C1, G0, C4, F4, G5, H5, D0, A0, B1, A1, I4, I5, nl1+2, nl1+1, nl1, nl+2, nl+1, nl, 2, 1, 0);

            FILT3(PE, PG, PD, PH, PA, PI, PB, PF, PC, A0, I5, A1, B1, I4, F4, H5, G5, D0, G0, C1, C4, 2, nl+2, nl1+2, 1, nl+1, nl1+1, 0, nl, nl1);

            sa0 += 1;

            sa1 += 1;

            sa2 += 1;

            sa3 += 1;

            sa4 += 1;

            E += 3;

            if (pprev2){

                pprev2--;

                pprev = 1;

            }

        }

    }

}


qio_channel_websock_source_prepare(GSource *source,

                                   gint *timeout)

{

    QIOChannelWebsockSource *wsource = (QIOChannelWebsockSource *)source;

    GIOCondition cond = 0;

    *timeout = -1;

    if (wsource->wioc->rawinput.offset) {

        cond |= G_IO_IN;

    }

    if (wsource->wioc->rawoutput.offset < QIO_CHANNEL_WEBSOCK_MAX_BUFFER) {

        cond |= G_IO_OUT;

    }

    return cond & wsource->condition;

}


static uint_fast8_t vorbis_floor1_decode(vorbis_context *vc,

                                         vorbis_floor_data *vfu, float *vec)

{

    vorbis_floor1 *vf = &vfu->t1;

    GetBitContext *gb = &vc->gb;

    uint_fast16_t range_v[4] = { 256, 128, 86, 64 };

    uint_fast16_t range = range_v[vf->multiplier-1];

    uint_fast16_t floor1_Y[258];

    uint_fast16_t floor1_Y_final[258];

    int floor1_flag[258];

    uint_fast8_t class_;

    uint_fast8_t cdim;

    uint_fast8_t cbits;

    uint_fast8_t csub;

    uint_fast8_t cval;

    int_fast16_t book;

    uint_fast16_t offset;

    uint_fast16_t i,j;

    /*u*/int_fast16_t adx, ady, off, predicted; // WTF ? dy/adx =  (unsigned)dy/adx ?

    int_fast16_t dy, err;

    if (!get_bits1(gb)) // silence

        return 1;

// Read values (or differences) for the floor's points

    floor1_Y[0] = get_bits(gb, ilog(range - 1));

    floor1_Y[1] = get_bits(gb, ilog(range - 1));

    AV_DEBUG("floor 0 Y %d floor 1 Y %d \n", floor1_Y[0], floor1_Y[1]);

    offset = 2;

    for (i = 0; i < vf->partitions; ++i) {

        class_ = vf->partition_class[i];

        cdim   = vf->class_dimensions[class_];

        cbits  = vf->class_subclasses[class_];

        csub = (1 << cbits) - 1;

        cval = 0;

        AV_DEBUG("Cbits %d \n", cbits);

        if (cbits) // this reads all subclasses for this partition's class

            cval = get_vlc2(gb, vc->codebooks[vf->class_masterbook[class_]].vlc.table,

                            vc->codebooks[vf->class_masterbook[class_]].nb_bits, 3);

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

            book = vf->subclass_books[class_][cval & csub];

            AV_DEBUG("book %d Cbits %d cval %d  bits:%d \n", book, cbits, cval, get_bits_count(gb));

            cval = cval >> cbits;

            if (book > -1) {

                floor1_Y[offset+j] = get_vlc2(gb, vc->codebooks[book].vlc.table,

                vc->codebooks[book].nb_bits, 3);

            } else {

                floor1_Y[offset+j] = 0;

            }

            AV_DEBUG(" floor(%d) = %d \n", vf->list[offset+j].x, floor1_Y[offset+j]);

        }

        offset+=cdim;

    }

// Amplitude calculation from the differences

    floor1_flag[0] = 1;

    floor1_flag[1] = 1;

    floor1_Y_final[0] = floor1_Y[0];

    floor1_Y_final[1] = floor1_Y[1];

    for (i = 2; i < vf->x_list_dim; ++i) {

        uint_fast16_t val, highroom, lowroom, room;

        uint_fast16_t high_neigh_offs;

        uint_fast16_t low_neigh_offs;

        low_neigh_offs  = vf->list[i].low;

        high_neigh_offs = vf->list[i].high;

        dy  = floor1_Y_final[high_neigh_offs] - floor1_Y_final[low_neigh_offs];  // render_point begin

        adx = vf->list[high_neigh_offs].x - vf->list[low_neigh_offs].x;

        ady = FFABS(dy);

        err = ady * (vf->list[i].x - vf->list[low_neigh_offs].x);

        off = (int16_t)err / (int16_t)adx;

        if (dy < 0) {

            predicted = floor1_Y_final[low_neigh_offs] - off;

        } else {

            predicted = floor1_Y_final[low_neigh_offs] + off;

        } // render_point end

        val = floor1_Y[i];

        highroom = range-predicted;

        lowroom  = predicted;

        if (highroom < lowroom) {

            room = highroom * 2;

        } else {

            room = lowroom * 2;   // SPEC mispelling

        }

        if (val) {

            floor1_flag[low_neigh_offs]  = 1;

            floor1_flag[high_neigh_offs] = 1;

            floor1_flag[i]               = 1;

            if (val >= room) {

                if (highroom > lowroom) {

                    floor1_Y_final[i] = val - lowroom + predicted;

                } else {

                    floor1_Y_final[i] = predicted - val + highroom - 1;

                }

            } else {

                if (val & 1) {

                    floor1_Y_final[i] = predicted - (val + 1) / 2;

                } else {

                    floor1_Y_final[i] = predicted + val / 2;

                }

            }

        } else {

            floor1_flag[i]    = 0;

            floor1_Y_final[i] = predicted;

        }

        AV_DEBUG(" Decoded floor(%d) = %d / val %d \n", vf->list[i].x, floor1_Y_final[i], val);

    }

// Curve synth - connect the calculated dots and convert from dB scale FIXME optimize ?

    ff_vorbis_floor1_render_list(vf->list, vf->x_list_dim, floor1_Y_final, floor1_flag, vf->multiplier, vec, vf->list[1].x);

    AV_DEBUG(" Floor decoded\n");

    return 0;

}


static void qemu_add_data_dir(const char *path)

{

    int i;

    if (path == NULL) {

        return;

    }

    if (data_dir_idx == ARRAY_SIZE(data_dir)) {

        return;

    }

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

        if (strcmp(data_dir[i], path) == 0) {

            return; /* duplicate */

        }

    }

    data_dir[data_dir_idx++] = path;

}


void *ff_schro_queue_pop(FFSchroQueue *queue)

{

    FFSchroQueueElement *top = queue->p_head;

    if (top) {

        void *data = top->data;

        queue->p_head = queue->p_head->next;

        --queue->size;

        av_freep(&top);

        return data;

    }

    return NULL;

}


static void virtio_net_vhost_status(VirtIONet *n, uint8_t status)

{

    VirtIODevice *vdev = VIRTIO_DEVICE(n);

    NetClientState *nc = qemu_get_queue(n->nic);

    int queues = n->multiqueue ? n->max_queues : 1;

    if (!get_vhost_net(nc->peer)) {

        return;

    }

    if ((virtio_net_started(n, status) && !nc->peer->link_down) ==

        !!n->vhost_started) {

        return;

    }

    if (!n->vhost_started) {

        int r, i;

        if (!vhost_net_query(get_vhost_net(nc->peer), vdev)) {

            return;

        }

        /* Any packets outstanding? Purge them to avoid touching rings

         * when vhost is running.

         */

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

            NetClientState *qnc = qemu_get_subqueue(n->nic, i);

            /* Purge both directions: TX and RX. */

            qemu_net_queue_purge(qnc->peer->incoming_queue, qnc);

            qemu_net_queue_purge(qnc->incoming_queue, qnc->peer);

        }

        n->vhost_started = 1;

        r = vhost_net_start(vdev, n->nic->ncs, queues);

        if (r < 0) {

            error_report("unable to start vhost net: %d: "

                         "falling back on userspace virtio", -r);

            n->vhost_started = 0;

        }

    } else {

        vhost_net_stop(vdev, n->nic->ncs, queues);

        n->vhost_started = 0;

    }

}


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

                             int *got_frame_ptr, AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    AVFrame *frame     = data;

    EVRCContext *e     = avctx->priv_data;

    int buf_size       = avpkt->size;

    float ilspf[FILTER_ORDER], ilpc[FILTER_ORDER], idelay[NB_SUBFRAMES];

    float *samples;

    int   i, j, ret, error_flag = 0;

    frame->nb_samples = 160;

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

        return ret;

    samples = (float *)frame->data[0];

    if ((e->bitrate = determine_bitrate(avctx, &buf_size, &buf)) == RATE_ERRS) {

        warn_insufficient_frame_quality(avctx, "bitrate cannot be determined.");

        goto erasure;

    }

    if (e->bitrate <= SILENCE || e->bitrate == RATE_QUARTER)

        goto erasure;

    if (e->bitrate == RATE_QUANT && e->last_valid_bitrate == RATE_FULL

                                 && !e->prev_error_flag)

        goto erasure;

    init_get_bits(&e->gb, buf, 8 * buf_size);

    memset(&e->frame, 0, sizeof(EVRCAFrame));

    unpack_frame(e);

    if (e->bitrate != RATE_QUANT) {

        uint8_t *p = (uint8_t *) &e->frame;

        for (i = 0; i < sizeof(EVRCAFrame); i++) {

            if (p[i])

                break;

        }

        if (i == sizeof(EVRCAFrame))

            goto erasure;

    } else if (e->frame.lsp[0] == 0xf &&

               e->frame.lsp[1] == 0xf &&

               e->frame.energy_gain == 0xff) {

        goto erasure;

    }

    if (decode_lspf(e) < 0)

        goto erasure;

    if (e->bitrate == RATE_FULL || e->bitrate == RATE_HALF) {

        /* Pitch delay parameter checking as per TIA/IS-127 5.1.5.1 */

        if (e->frame.pitch_delay > MAX_DELAY - MIN_DELAY)

            goto erasure;

        e->pitch_delay = e->frame.pitch_delay + MIN_DELAY;

        /* Delay diff parameter checking as per TIA/IS-127 5.1.5.2 */

        if (e->frame.delay_diff) {

            int p = e->pitch_delay - e->frame.delay_diff + 16;

            if (p < MIN_DELAY || p > MAX_DELAY)

                goto erasure;

        }

        /* Delay contour reconstruction as per TIA/IS-127 5.2.2.2 */

        if (e->frame.delay_diff &&

            e->bitrate == RATE_FULL && e->prev_error_flag) {

            float delay;

            memcpy(e->pitch, e->pitch_back, ACB_SIZE * sizeof(float));

            delay = e->prev_pitch_delay;

            e->prev_pitch_delay = delay - e->frame.delay_diff + 16.0;

            if (fabs(e->pitch_delay - delay) > 15)

                delay = e->pitch_delay;

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

                int subframe_size = subframe_sizes[i];

                interpolate_delay(idelay, delay, e->prev_pitch_delay, i);

                acb_excitation(e, e->pitch + ACB_SIZE, e->avg_acb_gain, idelay, subframe_size);

                memcpy(e->pitch, e->pitch + subframe_size, ACB_SIZE * sizeof(float));

            }

        }

        /* Smoothing of the decoded delay as per TIA/IS-127 5.2.2.5 */

        if (fabs(e->pitch_delay - e->prev_pitch_delay) > 15)

            e->prev_pitch_delay = e->pitch_delay;

        e->avg_acb_gain = e->avg_fcb_gain = 0.0;

    } else {

        idelay[0] = idelay[1] = idelay[2] = MIN_DELAY;

        /* Decode frame energy vectors as per TIA/IS-127 5.7.2 */

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

            e->energy_vector[i] = pow(10, evrc_energy_quant[e->frame.energy_gain][i]);

        e->prev_energy_gain = e->frame.energy_gain;

    }

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

        float tmp[SUBFRAME_SIZE + 6] = { 0 };

        int subframe_size = subframe_sizes[i];

        int pitch_lag;

        interpolate_lsp(ilspf, e->lspf, e->prev_lspf, i);

        if (e->bitrate != RATE_QUANT)

            interpolate_delay(idelay, e->pitch_delay, e->prev_pitch_delay, i);

        pitch_lag = lrintf((idelay[1] + idelay[0]) / 2.0);

        decode_predictor_coeffs(ilspf, ilpc);

        /* Bandwidth expansion as per TIA/IS-127 5.2.3.3 */

        if (e->frame.lpc_flag && e->prev_error_flag)

            bandwidth_expansion(ilpc, ilpc, 0.75);

        if (e->bitrate != RATE_QUANT) {

            float acb_sum, f;

            f = exp((e->bitrate == RATE_HALF ? 0.5 : 0.25)

                         * (e->frame.fcb_gain[i] + 1));

            acb_sum = pitch_gain_vq[e->frame.acb_gain[i]];

            e->avg_acb_gain += acb_sum / NB_SUBFRAMES;

            e->avg_fcb_gain += f / NB_SUBFRAMES;

            acb_excitation(e, e->pitch + ACB_SIZE,

                           acb_sum, idelay, subframe_size);

            fcb_excitation(e, e->frame.fcb_shape[i], tmp,

                           acb_sum, pitch_lag, subframe_size);

            /* Total excitation generation as per TIA/IS-127 5.2.3.9 */

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

                e->pitch[ACB_SIZE + j] += f * tmp[j];

            e->fade_scale = FFMIN(e->fade_scale + 0.2, 1.0);

        } else {

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

                e->pitch[ACB_SIZE + j] = e->energy_vector[i];

        }

        memcpy(e->pitch, e->pitch + subframe_size, ACB_SIZE * sizeof(float));

        synthesis_filter(e->pitch + ACB_SIZE, ilpc,

                         e->synthesis, subframe_size, tmp);

        postfilter(e, tmp, ilpc, samples, pitch_lag,

                   &postfilter_coeffs[e->bitrate], subframe_size);

        samples += subframe_size;

    }

    if (error_flag) {

erasure:

        error_flag = 1;

        av_log(avctx, AV_LOG_WARNING, "frame erasure\n");

        frame_erasure(e, samples);

    }

    memcpy(e->prev_lspf, e->lspf, sizeof(e->prev_lspf));

    e->prev_error_flag    = error_flag;

    e->last_valid_bitrate = e->bitrate;

    if (e->bitrate != RATE_QUANT)

        e->prev_pitch_delay = e->pitch_delay;

    samples = (float *)frame->data[0];

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

        samples[i] /= 32768;

    *got_frame_ptr   = 1;

    return avpkt->size;

}


static int _do_rematrixing(AC3DecodeContext *ctx, int start, int end)

{

    float tmp0, tmp1;

    while (start < end) {

        tmp0 = ctx->samples[start];

        tmp1 = (ctx->samples + 256)[start];

        ctx->samples[start] = tmp0 + tmp1;

        (ctx->samples + 256)[start] = tmp0 - tmp1;

        start++;

    }

    return 0;

}


const DVprofile* avpriv_dv_frame_profile(const DVprofile *sys,

                                  const uint8_t* frame, unsigned buf_size)

{

   int i;

   int dsf = (frame[3] & 0x80) >> 7;

   int stype = frame[80*5 + 48 + 3] & 0x1f;

   /* 576i50 25Mbps 4:1:1 is a special case */

   if (dsf == 1 && stype == 0 && frame[4] & 0x07 /* the APT field */) {

       return &dv_profiles[2];

   }

   for (i=0; i<FF_ARRAY_ELEMS(dv_profiles); i++)

       if (dsf == dv_profiles[i].dsf && stype == dv_profiles[i].video_stype)

           return &dv_profiles[i];

   /* check if old sys matches and assumes corrupted input */

   if (sys && buf_size == sys->frame_size)

       return sys;

   return NULL;

}


static int do_fork(CPUState *env, unsigned int flags, abi_ulong newsp,

                   abi_ulong parent_tidptr, target_ulong newtls,

                   abi_ulong child_tidptr)

{

    int ret;

    TaskState *ts;

    uint8_t *new_stack;

    CPUState *new_env;

#if defined(CONFIG_USE_NPTL)

    unsigned int nptl_flags;

    sigset_t sigmask;

#endif

    /* Emulate vfork() with fork() */

    if (flags & CLONE_VFORK)

        flags &= ~(CLONE_VFORK | CLONE_VM);

    if (flags & CLONE_VM) {

        TaskState *parent_ts = (TaskState *)env->opaque;

#if defined(CONFIG_USE_NPTL)

        new_thread_info info;

        pthread_attr_t attr;

#endif

        ts = qemu_mallocz(sizeof(TaskState) + NEW_STACK_SIZE);

        init_task_state(ts);

        new_stack = ts->stack;

        /* we create a new CPU instance. */

        new_env = cpu_copy(env);

#if defined(TARGET_I386) || defined(TARGET_SPARC) || defined(TARGET_PPC)

        cpu_reset(new_env);

#endif

        /* Init regs that differ from the parent.  */

        cpu_clone_regs(new_env, newsp);

        new_env->opaque = ts;

        ts->bprm = parent_ts->bprm;

        ts->info = parent_ts->info;

#if defined(CONFIG_USE_NPTL)

        nptl_flags = flags;

        flags &= ~CLONE_NPTL_FLAGS2;

        if (nptl_flags & CLONE_CHILD_CLEARTID) {

            ts->child_tidptr = child_tidptr;

        }

        if (nptl_flags & CLONE_SETTLS)

            cpu_set_tls (new_env, newtls);

        /* Grab a mutex so that thread setup appears atomic.  */

        pthread_mutex_lock(&clone_lock);

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

        pthread_mutex_init(&info.mutex, NULL);

        pthread_mutex_lock(&info.mutex);

        pthread_cond_init(&info.cond, NULL);

        info.env = new_env;

        if (nptl_flags & CLONE_CHILD_SETTID)

            info.child_tidptr = child_tidptr;

        if (nptl_flags & CLONE_PARENT_SETTID)

            info.parent_tidptr = parent_tidptr;

        ret = pthread_attr_init(&attr);

        ret = pthread_attr_setstack(&attr, new_stack, NEW_STACK_SIZE);

        /* It is not safe to deliver signals until the child has finished

           initializing, so temporarily block all signals.  */

        sigfillset(&sigmask);

        sigprocmask(SIG_BLOCK, &sigmask, &info.sigmask);

        ret = pthread_create(&info.thread, &attr, clone_func, &info);

        /* TODO: Free new CPU state if thread creation failed.  */

        sigprocmask(SIG_SETMASK, &info.sigmask, NULL);

        pthread_attr_destroy(&attr);

        if (ret == 0) {

            /* Wait for the child to initialize.  */

            pthread_cond_wait(&info.cond, &info.mutex);

            ret = info.tid;

            if (flags & CLONE_PARENT_SETTID)

                put_user_u32(ret, parent_tidptr);

        } else {

            ret = -1;

        }

        pthread_mutex_unlock(&info.mutex);

        pthread_cond_destroy(&info.cond);

        pthread_mutex_destroy(&info.mutex);

        pthread_mutex_unlock(&clone_lock);

#else

        if (flags & CLONE_NPTL_FLAGS2)

            return -EINVAL;

        /* This is probably going to die very quickly, but do it anyway.  */

#ifdef __ia64__

        ret = __clone2(clone_func, new_stack, NEW_STACK_SIZE, flags, new_env);

#else

	ret = clone(clone_func, new_stack + NEW_STACK_SIZE, flags, new_env);

#endif

#endif

    } else {

        /* if no CLONE_VM, we consider it is a fork */

        if ((flags & ~(CSIGNAL | CLONE_NPTL_FLAGS2)) != 0)

            return -EINVAL;

        fork_start();

        ret = fork();

        if (ret == 0) {

            /* Child Process.  */

            cpu_clone_regs(env, newsp);

            fork_end(1);

#if defined(CONFIG_USE_NPTL)

            /* There is a race condition here.  The parent process could

               theoretically read the TID in the child process before the child

               tid is set.  This would require using either ptrace

               (not implemented) or having *_tidptr to point at a shared memory

               mapping.  We can't repeat the spinlock hack used above because

               the child process gets its own copy of the lock.  */

            if (flags & CLONE_CHILD_SETTID)

                put_user_u32(gettid(), child_tidptr);

            if (flags & CLONE_PARENT_SETTID)

                put_user_u32(gettid(), parent_tidptr);

            ts = (TaskState *)env->opaque;

            if (flags & CLONE_SETTLS)

                cpu_set_tls (env, newtls);

            if (flags & CLONE_CHILD_CLEARTID)

                ts->child_tidptr = child_tidptr;

#endif

        } else {

            fork_end(0);

        }

    }

    return ret;

}


static inline void decode(DisasContext *dc, uint32_t ir)

{

    if (unlikely(qemu_loglevel_mask(CPU_LOG_TB_OP | CPU_LOG_TB_OP_OPT))) {

        tcg_gen_debug_insn_start(dc->pc);

    }

    dc->ir = ir;

    LOG_DIS("%8.8x\t", dc->ir);

    /* try guessing 'empty' instruction memory, although it may be a valid

     * instruction sequence (eg. srui r0, r0, 0) */

    if (dc->ir) {

        dc->nr_nops = 0;

    } else {

        LOG_DIS("nr_nops=%d\t", dc->nr_nops);

        dc->nr_nops++;

        if (dc->nr_nops > 4) {

            cpu_abort(dc->env, "fetching nop sequence\n");

        }

    }

    dc->opcode = EXTRACT_FIELD(ir, 26, 31);

    dc->imm5 = EXTRACT_FIELD(ir, 0, 4);

    dc->imm16 = EXTRACT_FIELD(ir, 0, 15);

    dc->imm26 = EXTRACT_FIELD(ir, 0, 25);

    dc->csr = EXTRACT_FIELD(ir, 21, 25);

    dc->r0 = EXTRACT_FIELD(ir, 21, 25);

    dc->r1 = EXTRACT_FIELD(ir, 16, 20);

    dc->r2 = EXTRACT_FIELD(ir, 11, 15);

    /* bit 31 seems to indicate insn type.  */

    if (ir & (1 << 31)) {

        dc->format = OP_FMT_RR;

    } else {

        dc->format = OP_FMT_RI;

    }

    assert(ARRAY_SIZE(decinfo) == 64);

    assert(dc->opcode < 64);

    decinfo[dc->opcode](dc);

}


static int decode_zbuf(AVBPrint *bp, const uint8_t *data,

                       const uint8_t *data_end)

{

    z_stream zstream;

    unsigned char *buf;

    unsigned buf_size;

    int ret;

    zstream.zalloc = ff_png_zalloc;

    zstream.zfree  = ff_png_zfree;

    zstream.opaque = NULL;

    if (inflateInit(&zstream) != Z_OK)

        return AVERROR_EXTERNAL;

    zstream.next_in  = (unsigned char *)data;

    zstream.avail_in = data_end - data;

    av_bprint_init(bp, 0, -1);

    while (zstream.avail_in > 0) {

        av_bprint_get_buffer(bp, 1, &buf, &buf_size);

        if (!buf_size) {

            ret = AVERROR(ENOMEM);

            goto fail;

        }

        zstream.next_out  = buf;

        zstream.avail_out = buf_size;

        ret = inflate(&zstream, Z_PARTIAL_FLUSH);

        if (ret != Z_OK && ret != Z_STREAM_END) {

            ret = AVERROR_EXTERNAL;

            goto fail;

        }

        bp->len += zstream.next_out - buf;

        if (ret == Z_STREAM_END)

            break;

    }

    inflateEnd(&zstream);

    bp->str[bp->len] = 0;

    return 0;

fail:

    inflateEnd(&zstream);

    av_bprint_finalize(bp, NULL);

    return ret;

}


static int write_extradata(FFV1Context *f)

{

    RangeCoder *const c = &f->c;

    uint8_t state[CONTEXT_SIZE];

    int i, j, k;

    uint8_t state2[32][CONTEXT_SIZE];

    unsigned v;

    memset(state2, 128, sizeof(state2));

    memset(state, 128, sizeof(state));

    f->avctx->extradata_size = 10000 + 4 +

                                    (11 * 11 * 5 * 5 * 5 + 11 * 11 * 11) * 32;

    f->avctx->extradata = av_malloc(f->avctx->extradata_size);

    ff_init_range_encoder(c, f->avctx->extradata, f->avctx->extradata_size);

    ff_build_rac_states(c, 0.05 * (1LL << 32), 256 - 8);

    put_symbol(c, state, f->version, 0);

    if (f->version > 2) {

        if (f->version == 3)

            f->minor_version = 4;

        put_symbol(c, state, f->minor_version, 0);

    }

    put_symbol(c, state, f->ac, 0);

    if (f->ac > 1)

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

            put_symbol(c, state, f->state_transition[i] - c->one_state[i], 1);

    put_symbol(c, state, f->colorspace, 0); // YUV cs type

    put_symbol(c, state, f->bits_per_raw_sample, 0);

    put_rac(c, state, f->chroma_planes);

    put_symbol(c, state, f->chroma_h_shift, 0);

    put_symbol(c, state, f->chroma_v_shift, 0);

    put_rac(c, state, f->transparency);

    put_symbol(c, state, f->num_h_slices - 1, 0);

    put_symbol(c, state, f->num_v_slices - 1, 0);

    put_symbol(c, state, f->quant_table_count, 0);

    for (i = 0; i < f->quant_table_count; i++)

        write_quant_tables(c, f->quant_tables[i]);

    for (i = 0; i < f->quant_table_count; i++) {

        for (j = 0; j < f->context_count[i] * CONTEXT_SIZE; j++)

            if (f->initial_states[i] && f->initial_states[i][0][j] != 128)

                break;

        if (j < f->context_count[i] * CONTEXT_SIZE) {

            put_rac(c, state, 1);

            for (j = 0; j < f->context_count[i]; j++)

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

                    int pred = j ? f->initial_states[i][j - 1][k] : 128;

                    put_symbol(c, state2[k],

                               (int8_t)(f->initial_states[i][j][k] - pred), 1);

                }

        } else {

            put_rac(c, state, 0);

        }

    }

    if (f->version > 2) {

        put_symbol(c, state, f->ec, 0);

        put_symbol(c, state, f->intra = (f->avctx->gop_size < 2), 0);

    }

    f->avctx->extradata_size = ff_rac_terminate(c);

    v = av_crc(av_crc_get_table(AV_CRC_32_IEEE), 0, f->avctx->extradata, f->avctx->extradata_size);

    AV_WL32(f->avctx->extradata + f->avctx->extradata_size, v);

    f->avctx->extradata_size += 4;

    return 0;

}


int qemu_strtol(const char *nptr, const char **endptr, int base,

                long *result)

{

    char *p;

    int err = 0;

    if (!nptr) {

        if (endptr) {

            *endptr = nptr;

        }

        err = -EINVAL;

    } else {

        errno = 0;

        *result = strtol(nptr, &p, base);

        err = check_strtox_error(endptr, p, errno);

    }

    return err;

}


static void spapr_set_vsmt_mode(sPAPRMachineState *spapr, Error **errp)

{

    Error *local_err = NULL;

    bool vsmt_user = !!spapr->vsmt;

    int kvm_smt = kvmppc_smt_threads();

    int ret;

    if (!kvm_enabled() && (smp_threads > 1)) {

        error_setg(&local_err, "TCG cannot support more than 1 thread/core "

                     "on a pseries machine");

        goto out;

    }

    if (!is_power_of_2(smp_threads)) {

        error_setg(&local_err, "Cannot support %d threads/core on a pseries "

                     "machine because it must be a power of 2", smp_threads);

        goto out;

    }

    /* Detemine the VSMT mode to use: */

    if (vsmt_user) {

        if (spapr->vsmt < smp_threads) {

            error_setg(&local_err, "Cannot support VSMT mode %d"

                         " because it must be >= threads/core (%d)",

                         spapr->vsmt, smp_threads);

            goto out;

        }

        /* In this case, spapr->vsmt has been set by the command line */

    } else {

        /* Choose a VSMT mode that may be higher than necessary but is

         * likely to be compatible with hosts that don't have VSMT. */

        spapr->vsmt = MAX(kvm_smt, smp_threads);

    }

    /* KVM: If necessary, set the SMT mode: */

    if (kvm_enabled() && (spapr->vsmt != kvm_smt)) {

        ret = kvmppc_set_smt_threads(spapr->vsmt);

        if (ret) {

            /* Looks like KVM isn't able to change VSMT mode */

            error_setg(&local_err,

                       "Failed to set KVM's VSMT mode to %d (errno %d)",

                       spapr->vsmt, ret);

            /* We can live with that if the default one is big enough

             * for the number of threads, and a submultiple of the one

             * we want.  In this case we'll waste some vcpu ids, but

             * behaviour will be correct */

            if ((kvm_smt >= smp_threads) && ((spapr->vsmt % kvm_smt) == 0)) {

                warn_report_err(local_err);

                local_err = NULL;

                goto out;

            } else {

                if (!vsmt_user) {

                    error_append_hint(&local_err,

                                      "On PPC, a VM with %d threads/core"

                                      " on a host with %d threads/core"

                                      " requires the use of VSMT mode %d.\n",

                                      smp_threads, kvm_smt, spapr->vsmt);

                }

                kvmppc_hint_smt_possible(&local_err);

                goto out;

            }

        }

    }

    /* else TCG: nothing to do currently */

out:

    error_propagate(errp, local_err);

}


static void pci_bridge_update_mappings(PCIBridge *br)

{

    /* Make updates atomic to: handle the case of one VCPU updating the bridge

     * while another accesses an unaffected region. */

    memory_region_transaction_begin();

    pci_bridge_region_cleanup(br);

    pci_bridge_region_init(br);

    memory_region_transaction_commit();

}


static struct omap_sysctl_s *omap_sysctl_init(struct omap_target_agent_s *ta,

                omap_clk iclk, struct omap_mpu_state_s *mpu)

{

    struct omap_sysctl_s *s = (struct omap_sysctl_s *)

            g_malloc0(sizeof(struct omap_sysctl_s));

    s->mpu = mpu;

    omap_sysctl_reset(s);

    memory_region_init_io(&s->iomem, NULL, &omap_sysctl_ops, s, "omap.sysctl",

                          omap_l4_region_size(ta, 0));

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

    return s;

}