static void extrapolate_isf(float isf[LP_ORDER_16k])

{

    float diff_isf[LP_ORDER - 2], diff_mean;

    float *diff_hi = diff_isf - LP_ORDER + 1; // diff array for extrapolated indexes

    float corr_lag[3];

    float est, scale;

    int i, i_max_corr;

    isf[LP_ORDER_16k - 1] = isf[LP_ORDER - 1];

    /* Calculate the difference vector */

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

        diff_isf[i] = isf[i + 1] - isf[i];

    diff_mean = 0.0;

    for (i = 2; i < LP_ORDER - 2; i++)

        diff_mean += diff_isf[i] * (1.0f / (LP_ORDER - 4));

    /* Find which is the maximum autocorrelation */

    i_max_corr = 0;

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

        corr_lag[i] = auto_correlation(diff_isf, diff_mean, i + 2);

        if (corr_lag[i] > corr_lag[i_max_corr])

            i_max_corr = i;

    }

    i_max_corr++;

    for (i = LP_ORDER - 1; i < LP_ORDER_16k - 1; i++)

        isf[i] = isf[i - 1] + isf[i - 1 - i_max_corr]

                            - isf[i - 2 - i_max_corr];

    /* Calculate an estimate for ISF(18) and scale ISF based on the error */

    est   = 7965 + (isf[2] - isf[3] - isf[4]) / 6.0;

    scale = 0.5 * (FFMIN(est, 7600) - isf[LP_ORDER - 2]) /

            (isf[LP_ORDER_16k - 2] - isf[LP_ORDER - 2]);

    for (i = LP_ORDER - 1; i < LP_ORDER_16k - 1; i++)

        diff_hi[i] = scale * (isf[i] - isf[i - 1]);

    /* Stability insurance */

    for (i = LP_ORDER; i < LP_ORDER_16k - 1; i++)

        if (diff_hi[i] + diff_hi[i - 1] < 5.0) {

            if (diff_hi[i] > diff_hi[i - 1]) {

                diff_hi[i - 1] = 5.0 - diff_hi[i];

            } else

                diff_hi[i] = 5.0 - diff_hi[i - 1];

        }

    for (i = LP_ORDER - 1; i < LP_ORDER_16k - 1; i++)

        isf[i] = isf[i - 1] + diff_hi[i] * (1.0f / (1 << 15));

    /* Scale the ISF vector for 16000 Hz */

    for (i = 0; i < LP_ORDER_16k - 1; i++)

        isf[i] *= 0.8;

}


QString *qobject_to_qstring(const QObject *obj)

{

    if (qobject_type(obj) != QTYPE_QSTRING)

        return NULL;

    return container_of(obj, QString, base);

}


static void gen_mfmsr(DisasContext *ctx)

{

#if defined(CONFIG_USER_ONLY)

    gen_inval_exception(ctx, POWERPC_EXCP_PRIV_REG);

#else

    if (unlikely(ctx->pr)) {

        gen_inval_exception(ctx, POWERPC_EXCP_PRIV_REG);

        return;

    }

    tcg_gen_mov_tl(cpu_gpr[rD(ctx->opcode)], cpu_msr);

#endif

}


static void spapr_add_lmbs(DeviceState *dev, uint64_t addr, uint64_t size,

                           uint32_t node, Error **errp)

{

    sPAPRDRConnector *drc;

    sPAPRDRConnectorClass *drck;

    uint32_t nr_lmbs = size/SPAPR_MEMORY_BLOCK_SIZE;

    int i, fdt_offset, fdt_size;

    void *fdt;

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

        drc = spapr_dr_connector_by_id(SPAPR_DR_CONNECTOR_TYPE_LMB,

                addr/SPAPR_MEMORY_BLOCK_SIZE);

        g_assert(drc);

        fdt = create_device_tree(&fdt_size);

        fdt_offset = spapr_populate_memory_node(fdt, node, addr,

                                                SPAPR_MEMORY_BLOCK_SIZE);

        drck = SPAPR_DR_CONNECTOR_GET_CLASS(drc);

        drck->attach(drc, dev, fdt, fdt_offset, !dev->hotplugged, errp);

        addr += SPAPR_MEMORY_BLOCK_SIZE;

    }

    /* send hotplug notification to the

     * guest only in case of hotplugged memory

     */

    if (dev->hotplugged) {

       spapr_hotplug_req_add_by_count(SPAPR_DR_CONNECTOR_TYPE_LMB, nr_lmbs);

    }

}


static int bdrv_wr_badreq_bytes(BlockDriverState *bs,

                                int64_t offset, int count)

{

    int64_t size = bs->total_sectors << SECTOR_BITS;

    if (count < 0 ||

        offset < 0)

        return 1;

    if (offset > size - count) {

        if (bs->autogrow)

            bs->total_sectors = (offset + count + SECTOR_SIZE - 1) >> SECTOR_BITS;

        else

            return 1;

    }

    return 0;

}


static void spapr_core_plug(HotplugHandler *hotplug_dev, DeviceState *dev,

                            Error **errp)

{

    sPAPRMachineState *spapr = SPAPR_MACHINE(OBJECT(hotplug_dev));

    MachineClass *mc = MACHINE_GET_CLASS(spapr);

    sPAPRMachineClass *smc = SPAPR_MACHINE_CLASS(mc);

    sPAPRCPUCore *core = SPAPR_CPU_CORE(OBJECT(dev));

    CPUCore *cc = CPU_CORE(dev);

    CPUState *cs = CPU(core->threads);

    sPAPRDRConnector *drc;

    Error *local_err = NULL;

    void *fdt = NULL;

    int fdt_offset = 0;

    int smt = kvmppc_smt_threads();

    CPUArchId *core_slot;

    int index;

    bool hotplugged = spapr_drc_hotplugged(dev);

    core_slot = spapr_find_cpu_slot(MACHINE(hotplug_dev), cc->core_id, &index);

    if (!core_slot) {

        error_setg(errp, "Unable to find CPU core with core-id: %d",

                   cc->core_id);

        return;

    }

    drc = spapr_drc_by_id(TYPE_SPAPR_DRC_CPU, index * smt);

    g_assert(drc || !mc->has_hotpluggable_cpus);

    fdt = spapr_populate_hotplug_cpu_dt(cs, &fdt_offset, spapr);

    if (drc) {

        spapr_drc_attach(drc, dev, fdt, fdt_offset, &local_err);

        if (local_err) {

            g_free(fdt);

            error_propagate(errp, local_err);

            return;

        }

        if (hotplugged) {

            /*

             * Send hotplug notification interrupt to the guest only

             * in case of hotplugged CPUs.

             */

            spapr_hotplug_req_add_by_index(drc);

        } else {

            spapr_drc_reset(drc);

        }

    }

    core_slot->cpu = OBJECT(dev);

    if (smc->pre_2_10_has_unused_icps) {

        sPAPRCPUCoreClass *scc = SPAPR_CPU_CORE_GET_CLASS(OBJECT(cc));

        const char *typename = object_class_get_name(scc->cpu_class);

        size_t size = object_type_get_instance_size(typename);

        int i;

        for (i = 0; i < cc->nr_threads; i++) {

            sPAPRCPUCore *sc = SPAPR_CPU_CORE(dev);

            void *obj = sc->threads + i * size;

            cs = CPU(obj);

            pre_2_10_vmstate_unregister_dummy_icp(cs->cpu_index);

        }

    }

}


static void do_video_out(AVFormatContext *s,

                         OutputStream *ost,

                         AVFrame *next_picture,

                         double sync_ipts)

{

    int ret, format_video_sync;

    AVPacket pkt;

    AVCodecContext *enc = ost->enc_ctx;

    AVCodecContext *mux_enc = ost->st->codec;

    int nb_frames, nb0_frames, i;

    double delta, delta0;

    double duration = 0;

    int frame_size = 0;

    InputStream *ist = NULL;

    AVFilterContext *filter = ost->filter->filter;

    if (ost->source_index >= 0)

        ist = input_streams[ost->source_index];

    if (filter->inputs[0]->frame_rate.num > 0 &&

        filter->inputs[0]->frame_rate.den > 0)

        duration = 1/(av_q2d(filter->inputs[0]->frame_rate) * av_q2d(enc->time_base));

    if(ist && ist->st->start_time != AV_NOPTS_VALUE && ist->st->first_dts != AV_NOPTS_VALUE && ost->frame_rate.num)

        duration = FFMIN(duration, 1/(av_q2d(ost->frame_rate) * av_q2d(enc->time_base)));

    if (!ost->filters_script &&

        !ost->filters &&

        next_picture &&

        ist &&

        lrintf(av_frame_get_pkt_duration(next_picture) * av_q2d(ist->st->time_base) / av_q2d(enc->time_base)) > 0) {

        duration = lrintf(av_frame_get_pkt_duration(next_picture) * av_q2d(ist->st->time_base) / av_q2d(enc->time_base));

    }

    if (!next_picture) {

        //end, flushing

        nb0_frames = nb_frames = mid_pred(ost->last_nb0_frames[0],

                                          ost->last_nb0_frames[1],

                                          ost->last_nb0_frames[2]);

    } else {

        delta0 = sync_ipts - ost->sync_opts;

        delta  = delta0 + duration;

        /* by default, we output a single frame */

        nb0_frames = 0;

        nb_frames = 1;

        format_video_sync = video_sync_method;

        if (format_video_sync == VSYNC_AUTO) {

            if(!strcmp(s->oformat->name, "avi")) {

                format_video_sync = VSYNC_VFR;

            } else

                format_video_sync = (s->oformat->flags & AVFMT_VARIABLE_FPS) ? ((s->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH : VSYNC_VFR) : VSYNC_CFR;

            if (   ist

                && format_video_sync == VSYNC_CFR

                && input_files[ist->file_index]->ctx->nb_streams == 1

                && input_files[ist->file_index]->input_ts_offset == 0) {

                format_video_sync = VSYNC_VSCFR;

            }

            if (format_video_sync == VSYNC_CFR && copy_ts) {

                format_video_sync = VSYNC_VSCFR;

            }

        }

        if (delta0 < 0 &&

            delta > 0 &&

            format_video_sync != VSYNC_PASSTHROUGH &&

            format_video_sync != VSYNC_DROP) {

            double cor = FFMIN(-delta0, duration);

            if (delta0 < -0.6) {

                av_log(NULL, AV_LOG_WARNING, "Past duration %f too large\n", -delta0);

            } else

                av_log(NULL, AV_LOG_DEBUG, "Cliping frame in rate conversion by %f\n", -delta0);

            sync_ipts += cor;

            duration -= cor;

            delta0 += cor;

        }

        switch (format_video_sync) {

        case VSYNC_VSCFR:

            if (ost->frame_number == 0 && delta - duration >= 0.5) {

                av_log(NULL, AV_LOG_DEBUG, "Not duplicating %d initial frames\n", (int)lrintf(delta - duration));

                delta = duration;

                delta0 = 0;

                ost->sync_opts = lrint(sync_ipts);

            }

        case VSYNC_CFR:

            // FIXME set to 0.5 after we fix some dts/pts bugs like in avidec.c

            if (frame_drop_threshold && delta < frame_drop_threshold && ost->frame_number) {

                nb_frames = 0;

            } else if (delta < -1.1)

                nb_frames = 0;

            else if (delta > 1.1) {

                nb_frames = lrintf(delta);

                if (delta0 > 1.1)

                    nb0_frames = lrintf(delta0 - 0.6);

            }

            break;

        case VSYNC_VFR:

            if (delta <= -0.6)

                nb_frames = 0;

            else if (delta > 0.6)

                ost->sync_opts = lrint(sync_ipts);

            break;

        case VSYNC_DROP:

        case VSYNC_PASSTHROUGH:

            ost->sync_opts = lrint(sync_ipts);

            break;

        default:

            av_assert0(0);

        }

    }

    nb_frames = FFMIN(nb_frames, ost->max_frames - ost->frame_number);

    nb0_frames = FFMIN(nb0_frames, nb_frames);

    memmove(ost->last_nb0_frames + 1,

            ost->last_nb0_frames,

            sizeof(ost->last_nb0_frames[0]) * (FF_ARRAY_ELEMS(ost->last_nb0_frames) - 1));

    ost->last_nb0_frames[0] = nb0_frames;

    if (nb0_frames == 0 && ost->last_droped) {

        nb_frames_drop++;

        av_log(NULL, AV_LOG_VERBOSE,

               "*** dropping frame %d from stream %d at ts %"PRId64"\n",

               ost->frame_number, ost->st->index, ost->last_frame->pts);

    }

    if (nb_frames > (nb0_frames && ost->last_droped) + (nb_frames > nb0_frames)) {

        if (nb_frames > dts_error_threshold * 30) {

            av_log(NULL, AV_LOG_ERROR, "%d frame duplication too large, skipping\n", nb_frames - 1);

            nb_frames_drop++;

            return;

        }

        nb_frames_dup += nb_frames - (nb0_frames && ost->last_droped) - (nb_frames > nb0_frames);

        av_log(NULL, AV_LOG_VERBOSE, "*** %d dup!\n", nb_frames - 1);

    }

    ost->last_droped = nb_frames == nb0_frames && next_picture;

  /* duplicates frame if needed */

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

    AVFrame *in_picture;

    av_init_packet(&pkt);

    pkt.data = NULL;

    pkt.size = 0;

    if (i < nb0_frames && ost->last_frame) {

        in_picture = ost->last_frame;

    } else

        in_picture = next_picture;

    if (!in_picture)

        return;

    in_picture->pts = ost->sync_opts;

#if 1

    if (!check_recording_time(ost))

#else

    if (ost->frame_number >= ost->max_frames)

#endif

        return;

    if (s->oformat->flags & AVFMT_RAWPICTURE &&

        enc->codec->id == AV_CODEC_ID_RAWVIDEO) {

        /* raw pictures are written as AVPicture structure to

           avoid any copies. We support temporarily the older

           method. */

        if (in_picture->interlaced_frame)

            mux_enc->field_order = in_picture->top_field_first ? AV_FIELD_TB:AV_FIELD_BT;

        else

            mux_enc->field_order = AV_FIELD_PROGRESSIVE;

        pkt.data   = (uint8_t *)in_picture;

        pkt.size   =  sizeof(AVPicture);

        pkt.pts    = av_rescale_q(in_picture->pts, enc->time_base, ost->st->time_base);

        pkt.flags |= AV_PKT_FLAG_KEY;

        write_frame(s, &pkt, ost);

    } else {

        int got_packet, forced_keyframe = 0;

        double pts_time;

        if (enc->flags & (AV_CODEC_FLAG_INTERLACED_DCT | AV_CODEC_FLAG_INTERLACED_ME) &&

            ost->top_field_first >= 0)

            in_picture->top_field_first = !!ost->top_field_first;

        if (in_picture->interlaced_frame) {

            if (enc->codec->id == AV_CODEC_ID_MJPEG)

                mux_enc->field_order = in_picture->top_field_first ? AV_FIELD_TT:AV_FIELD_BB;

            else

                mux_enc->field_order = in_picture->top_field_first ? AV_FIELD_TB:AV_FIELD_BT;

        } else

            mux_enc->field_order = AV_FIELD_PROGRESSIVE;

        in_picture->quality = enc->global_quality;

        in_picture->pict_type = 0;

        pts_time = in_picture->pts != AV_NOPTS_VALUE ?

            in_picture->pts * av_q2d(enc->time_base) : NAN;

        if (ost->forced_kf_index < ost->forced_kf_count &&

            in_picture->pts >= ost->forced_kf_pts[ost->forced_kf_index]) {

            ost->forced_kf_index++;

            forced_keyframe = 1;

        } else if (ost->forced_keyframes_pexpr) {

            double res;

            ost->forced_keyframes_expr_const_values[FKF_T] = pts_time;

            res = av_expr_eval(ost->forced_keyframes_pexpr,

                               ost->forced_keyframes_expr_const_values, NULL);

            ff_dlog(NULL, "force_key_frame: n:%f n_forced:%f prev_forced_n:%f t:%f prev_forced_t:%f -> res:%f\n",

                    ost->forced_keyframes_expr_const_values[FKF_N],

                    ost->forced_keyframes_expr_const_values[FKF_N_FORCED],

                    ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N],

                    ost->forced_keyframes_expr_const_values[FKF_T],

                    ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T],

                    res);

            if (res) {

                forced_keyframe = 1;

                ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_N] =

                    ost->forced_keyframes_expr_const_values[FKF_N];

                ost->forced_keyframes_expr_const_values[FKF_PREV_FORCED_T] =

                    ost->forced_keyframes_expr_const_values[FKF_T];

                ost->forced_keyframes_expr_const_values[FKF_N_FORCED] += 1;

            }

            ost->forced_keyframes_expr_const_values[FKF_N] += 1;

        } else if (   ost->forced_keyframes

                   && !strncmp(ost->forced_keyframes, "source", 6)

                   && in_picture->key_frame==1) {

            forced_keyframe = 1;

        }

        if (forced_keyframe) {

            in_picture->pict_type = AV_PICTURE_TYPE_I;

            av_log(NULL, AV_LOG_DEBUG, "Forced keyframe at time %f\n", pts_time);

        }

        update_benchmark(NULL);

        if (debug_ts) {

            av_log(NULL, AV_LOG_INFO, "encoder <- type:video "

                   "frame_pts:%s frame_pts_time:%s time_base:%d/%d\n",

                   av_ts2str(in_picture->pts), av_ts2timestr(in_picture->pts, &enc->time_base),

                   enc->time_base.num, enc->time_base.den);

        }

        ost->frames_encoded++;

        ret = avcodec_encode_video2(enc, &pkt, in_picture, &got_packet);

        update_benchmark("encode_video %d.%d", ost->file_index, ost->index);

        if (ret < 0) {

            av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");

            exit_program(1);

        }

        if (got_packet) {

            if (debug_ts) {

                av_log(NULL, AV_LOG_INFO, "encoder -> type:video "

                       "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",

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

                       av_ts2str(pkt.dts), av_ts2timestr(pkt.dts, &enc->time_base));

            }

            if (pkt.pts == AV_NOPTS_VALUE && !(enc->codec->capabilities & AV_CODEC_CAP_DELAY))

                pkt.pts = ost->sync_opts;

            av_packet_rescale_ts(&pkt, enc->time_base, ost->st->time_base);

            if (debug_ts) {

                av_log(NULL, AV_LOG_INFO, "encoder -> type:video "

                    "pkt_pts:%s pkt_pts_time:%s pkt_dts:%s pkt_dts_time:%s\n",

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

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

            }

            frame_size = pkt.size;

            write_frame(s, &pkt, ost);

            /* if two pass, output log */

            if (ost->logfile && enc->stats_out) {

                fprintf(ost->logfile, "%s", enc->stats_out);

            }

        }

    }

    ost->sync_opts++;

    /*

     * For video, number of frames in == number of packets out.

     * But there may be reordering, so we can't throw away frames on encoder

     * flush, we need to limit them here, before they go into encoder.

     */

    ost->frame_number++;

    if (vstats_filename && frame_size)

        do_video_stats(ost, frame_size);

  }

    if (!ost->last_frame)

        ost->last_frame = av_frame_alloc();

    av_frame_unref(ost->last_frame);

    if (next_picture && ost->last_frame)

        av_frame_ref(ost->last_frame, next_picture);

    else

        av_frame_free(&ost->last_frame);

}


static int vqa_decode_frame(AVCodecContext *avctx,

                            void *data, int *data_size,

                            AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    VqaContext *s = avctx->priv_data;

    s->buf = buf;

    s->size = buf_size;

    if (s->frame.data[0])

        avctx->release_buffer(avctx, &s->frame);

    if (avctx->get_buffer(avctx, &s->frame)) {

        av_log(s->avctx, AV_LOG_ERROR, "  VQA Video: get_buffer() failed\n");

        return -1;

    }

    vqa_decode_chunk(s);

    /* make the palette available on the way out */

    memcpy(s->frame.data[1], s->palette, PALETTE_COUNT * 4);

    s->frame.palette_has_changed = 1;

    *data_size = sizeof(AVFrame);

    *(AVFrame*)data = s->frame;

    /* report that the buffer was completely consumed */

    return buf_size;

}


static int check_write_unsafe(BlockDriverState *bs, int64_t sector_num,

                              const uint8_t *buf, int nb_sectors)

{

    /* assume that if the user specifies the format explicitly, then assume

       that they will continue to do so and provide no safety net */

    if (!bs->probed) {

        return 0;

    }

    if (sector_num == 0 && nb_sectors > 0) {

        return check_for_block_signature(bs, buf);

    }

    return 0;

}


static void search_for_quantizers_faac(AVCodecContext *avctx, AACEncContext *s,

                                       SingleChannelElement *sce,

                                       const float lambda)

{

    int start = 0, i, w, w2, g;

    float uplim[128], maxq[128];

    int minq, maxsf;

    float distfact = ((sce->ics.num_windows > 1) ? 85.80 : 147.84) / lambda;

    int last = 0, lastband = 0, curband = 0;

    float avg_energy = 0.0;

    if (sce->ics.num_windows == 1) {

        start = 0;

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

            if (i - start >= sce->ics.swb_sizes[curband]) {

                start += sce->ics.swb_sizes[curband];

                curband++;

            }

            if (sce->coeffs[i]) {

                avg_energy += sce->coeffs[i] * sce->coeffs[i];

                last = i;

                lastband = curband;

            }

        }

    } else {

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

            const float *coeffs = sce->coeffs + w*128;

            curband = start = 0;

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

                if (i - start >= sce->ics.swb_sizes[curband]) {

                    start += sce->ics.swb_sizes[curband];

                    curband++;

                }

                if (coeffs[i]) {

                    avg_energy += coeffs[i] * coeffs[i];

                    last = FFMAX(last, i);

                    lastband = FFMAX(lastband, curband);

                }

            }

        }

    }

    last++;

    avg_energy /= last;

    if (avg_energy == 0.0f) {

        for (i = 0; i < FF_ARRAY_ELEMS(sce->sf_idx); i++)

            sce->sf_idx[i] = SCALE_ONE_POS;

        return;

    }

    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {

        start = w*128;

        for (g = 0; g < sce->ics.num_swb; g++) {

            float *coefs   = sce->coeffs + start;

            const int size = sce->ics.swb_sizes[g];

            int start2 = start, end2 = start + size, peakpos = start;

            float maxval = -1, thr = 0.0f, t;

            maxq[w*16+g] = 0.0f;

            if (g > lastband) {

                maxq[w*16+g] = 0.0f;

                start += size;

                for (w2 = 0; w2 < sce->ics.group_len[w]; w2++)

                    memset(coefs + w2*128, 0, sizeof(coefs[0])*size);

                continue;

            }

            for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {

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

                    float t = coefs[w2*128+i]*coefs[w2*128+i];

                    maxq[w*16+g] = FFMAX(maxq[w*16+g], fabsf(coefs[w2*128 + i]));

                    thr += t;

                    if (sce->ics.num_windows == 1 && maxval < t) {

                        maxval  = t;

                        peakpos = start+i;

                    }

                }

            }

            if (sce->ics.num_windows == 1) {

                start2 = FFMAX(peakpos - 2, start2);

                end2   = FFMIN(peakpos + 3, end2);

            } else {

                start2 -= start;

                end2   -= start;

            }

            start += size;

            thr = pow(thr / (avg_energy * (end2 - start2)), 0.3 + 0.1*(lastband - g) / lastband);

            t   = 1.0 - (1.0 * start2 / last);

            uplim[w*16+g] = distfact / (1.4 * thr + t*t*t + 0.075);

        }

    }

    memset(sce->sf_idx, 0, sizeof(sce->sf_idx));

    abs_pow34_v(s->scoefs, sce->coeffs, 1024);

    for (w = 0; w < sce->ics.num_windows; w += sce->ics.group_len[w]) {

        start = w*128;

        for (g = 0;  g < sce->ics.num_swb; g++) {

            const float *coefs  = sce->coeffs + start;

            const float *scaled = s->scoefs   + start;

            const int size      = sce->ics.swb_sizes[g];

            int scf, prev_scf, step;

            int min_scf = -1, max_scf = 256;

            float curdiff;

            if (maxq[w*16+g] < 21.544) {

                sce->zeroes[w*16+g] = 1;

                start += size;

                continue;

            }

            sce->zeroes[w*16+g] = 0;

            scf  = prev_scf = av_clip(SCALE_ONE_POS - SCALE_DIV_512 - log2f(1/maxq[w*16+g])*16/3, 60, 218);

            for (;;) {

                float dist = 0.0f;

                int quant_max;

                for (w2 = 0; w2 < sce->ics.group_len[w]; w2++) {

                    int b;

                    dist += quantize_band_cost(s, coefs + w2*128,

                                               scaled + w2*128,

                                               sce->ics.swb_sizes[g],

                                               scf,

                                               ESC_BT,

                                               lambda,

                                               INFINITY,

                                               &b,

                                               0);

                    dist -= b;

                }

                dist *= 1.0f / 512.0f / lambda;

                quant_max = quant(maxq[w*16+g], ff_aac_pow2sf_tab[POW_SF2_ZERO - scf + SCALE_ONE_POS - SCALE_DIV_512], ROUND_STANDARD);

                if (quant_max >= 8191) { // too much, return to the previous quantizer

                    sce->sf_idx[w*16+g] = prev_scf;

                    break;

                }

                prev_scf = scf;

                curdiff = fabsf(dist - uplim[w*16+g]);

                if (curdiff <= 1.0f)

                    step = 0;

                else

                    step = log2f(curdiff);

                if (dist > uplim[w*16+g])

                    step = -step;

                scf += step;

                scf = av_clip_uint8(scf);

                step = scf - prev_scf;

                if (FFABS(step) <= 1 || (step > 0 && scf >= max_scf) || (step < 0 && scf <= min_scf)) {

                    sce->sf_idx[w*16+g] = av_clip(scf, min_scf, max_scf);

                    break;

                }

                if (step > 0)

                    min_scf = prev_scf;

                else

                    max_scf = prev_scf;

            }

            start += size;

        }

    }

    minq = sce->sf_idx[0] ? sce->sf_idx[0] : INT_MAX;

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

        if (!sce->sf_idx[i])

            sce->sf_idx[i] = sce->sf_idx[i-1];

        else

            minq = FFMIN(minq, sce->sf_idx[i]);

    }

    if (minq == INT_MAX)

        minq = 0;

    minq = FFMIN(minq, SCALE_MAX_POS);

    maxsf = FFMIN(minq + SCALE_MAX_DIFF, SCALE_MAX_POS);

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

        if (!sce->sf_idx[i])

            sce->sf_idx[i] = sce->sf_idx[i+1];

        sce->sf_idx[i] = av_clip(sce->sf_idx[i], minq, maxsf);

    }

}


static av_cold int jpg_init(AVCodecContext *avctx, JPGContext *c)

{

    int ret;

    ret = build_vlc(&c->dc_vlc[0], avpriv_mjpeg_bits_dc_luminance,

                    avpriv_mjpeg_val_dc, 12, 0);

    if (ret)

        return ret;

    ret = build_vlc(&c->dc_vlc[1], avpriv_mjpeg_bits_dc_chrominance,

                    avpriv_mjpeg_val_dc, 12, 0);

    if (ret)

        return ret;

    ret = build_vlc(&c->ac_vlc[0], avpriv_mjpeg_bits_ac_luminance,

                    avpriv_mjpeg_val_ac_luminance, 251, 1);

    if (ret)

        return ret;

    ret = build_vlc(&c->ac_vlc[1], avpriv_mjpeg_bits_ac_chrominance,

                    avpriv_mjpeg_val_ac_chrominance, 251, 1);

    if (ret)

        return ret;

    ff_blockdsp_init(&c->bdsp, avctx);

    ff_idctdsp_init(&c->idsp, avctx);

    ff_init_scantable(c->idsp.idct_permutation, &c->scantable,

                      ff_zigzag_direct);

    return 0;

}


static int ffm_read_header(AVFormatContext *s, AVFormatParameters *ap)

{

    FFMContext *ffm = s->priv_data;

    AVStream *st;

    ByteIOContext *pb = s->pb;

    AVCodecContext *codec;

    int i, nb_streams;

    uint32_t tag;

    /* header */

    tag = get_le32(pb);

    if (tag != MKTAG('F', 'F', 'M', '1'))

        goto fail;

    ffm->packet_size = get_be32(pb);

    if (ffm->packet_size != FFM_PACKET_SIZE)

        goto fail;

    ffm->write_index = get_be64(pb);

    /* get also filesize */

    if (!url_is_streamed(pb)) {

        ffm->file_size = url_fsize(pb);

        if (ffm->write_index)

            adjust_write_index(s);

    } else {

        ffm->file_size = (UINT64_C(1) << 63) - 1;

    }

    nb_streams = get_be32(pb);

    get_be32(pb); /* total bitrate */

    /* read each stream */

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

        char rc_eq_buf[128];

        st = av_new_stream(s, 0);

        if (!st)

            goto fail;

        av_set_pts_info(st, 64, 1, 1000000);

        codec = st->codec;

        /* generic info */

        codec->codec_id = get_be32(pb);

        codec->codec_type = get_byte(pb); /* codec_type */

        codec->bit_rate = get_be32(pb);

        st->quality = get_be32(pb);

        codec->flags = get_be32(pb);

        codec->flags2 = get_be32(pb);

        codec->debug = get_be32(pb);

        /* specific info */

        switch(codec->codec_type) {

        case CODEC_TYPE_VIDEO:

            codec->time_base.num = get_be32(pb);

            codec->time_base.den = get_be32(pb);

            codec->width = get_be16(pb);

            codec->height = get_be16(pb);

            codec->gop_size = get_be16(pb);

            codec->pix_fmt = get_be32(pb);

            codec->qmin = get_byte(pb);

            codec->qmax = get_byte(pb);

            codec->max_qdiff = get_byte(pb);

            codec->qcompress = get_be16(pb) / 10000.0;

            codec->qblur = get_be16(pb) / 10000.0;

            codec->bit_rate_tolerance = get_be32(pb);

            codec->rc_eq = av_strdup(get_strz(pb, rc_eq_buf, sizeof(rc_eq_buf)));

            codec->rc_max_rate = get_be32(pb);

            codec->rc_min_rate = get_be32(pb);

            codec->rc_buffer_size = get_be32(pb);

            codec->i_quant_factor = av_int2dbl(get_be64(pb));

            codec->b_quant_factor = av_int2dbl(get_be64(pb));

            codec->i_quant_offset = av_int2dbl(get_be64(pb));

            codec->b_quant_offset = av_int2dbl(get_be64(pb));

            codec->dct_algo = get_be32(pb);

            codec->strict_std_compliance = get_be32(pb);

            codec->max_b_frames = get_be32(pb);

            codec->luma_elim_threshold = get_be32(pb);

            codec->chroma_elim_threshold = get_be32(pb);

            codec->mpeg_quant = get_be32(pb);

            codec->intra_dc_precision = get_be32(pb);

            codec->me_method = get_be32(pb);

            codec->mb_decision = get_be32(pb);

            codec->nsse_weight = get_be32(pb);

            codec->frame_skip_cmp = get_be32(pb);

            codec->rc_buffer_aggressivity = av_int2dbl(get_be64(pb));

            codec->codec_tag = get_be32(pb);

            codec->thread_count = get_byte(pb);

            codec->coder_type = get_be32(pb);

            codec->me_cmp = get_be32(pb);

            codec->partitions = get_be32(pb);

            codec->me_subpel_quality = get_be32(pb);

            codec->me_range = get_be32(pb);

            codec->keyint_min = get_be32(pb);

            codec->scenechange_threshold = get_be32(pb);

            codec->b_frame_strategy = get_be32(pb);

            codec->qcompress = av_int2dbl(get_be64(pb));

            codec->qblur = av_int2dbl(get_be64(pb));

            codec->max_qdiff = get_be32(pb);

            codec->refs = get_be32(pb);

            codec->directpred = get_be32(pb);

            break;

        case CODEC_TYPE_AUDIO:

            codec->sample_rate = get_be32(pb);

            codec->channels = get_le16(pb);

            codec->frame_size = get_le16(pb);

            codec->sample_fmt = get_le16(pb);

            break;

        default:

            goto fail;

        }

        if (codec->flags & CODEC_FLAG_GLOBAL_HEADER) {

            codec->extradata_size = get_be32(pb);

            codec->extradata = av_malloc(codec->extradata_size);

            if (!codec->extradata)

                return AVERROR(ENOMEM);

            get_buffer(pb, codec->extradata, codec->extradata_size);

        }

    }

    /* get until end of block reached */

    while ((url_ftell(pb) % ffm->packet_size) != 0)

        get_byte(pb);

    /* init packet demux */

    ffm->packet_ptr = ffm->packet;

    ffm->packet_end = ffm->packet;

    ffm->frame_offset = 0;

    ffm->dts = 0;

    ffm->read_state = READ_HEADER;

    ffm->first_packet = 1;

    return 0;

 fail:

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

        st = s->streams[i];

        if (st) {

            av_free(st);

        }

    }

    return -1;

}


static av_cold int msvideo1_decode_init(AVCodecContext *avctx)

{

    Msvideo1Context *s = avctx->priv_data;

    s->avctx = avctx;

    /* figure out the colorspace based on the presence of a palette */

    if (s->avctx->bits_per_coded_sample == 8) {

        s->mode_8bit = 1;

        avctx->pix_fmt = AV_PIX_FMT_PAL8;

    } else {

        s->mode_8bit = 0;

        avctx->pix_fmt = AV_PIX_FMT_RGB555;

    }

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

    return 0;

}


static void avc_luma_hv_qrt_16w_msa(const uint8_t *src_x, const uint8_t *src_y,

                                    int32_t src_stride, uint8_t *dst,

                                    int32_t dst_stride, int32_t height)

{

    uint32_t multiple8_cnt;

    for (multiple8_cnt = 2; multiple8_cnt--;) {

        avc_luma_hv_qrt_8w_msa(src_x, src_y, src_stride, dst, dst_stride,

                               height);

        src_x += 8;

        src_y += 8;

        dst += 8;

    }

}


int udp_output(struct socket *so, struct mbuf *m,

               struct sockaddr_in *addr)

{

    struct sockaddr_in saddr, daddr;

    saddr = *addr;

    if ((so->so_faddr.s_addr & htonl(0xffffff00)) == special_addr.s_addr) {

        if ((so->so_faddr.s_addr & htonl(0x000000ff)) == htonl(0xff))

            saddr.sin_addr.s_addr = alias_addr.s_addr;

        else if (addr->sin_addr.s_addr == loopback_addr.s_addr ||

                 ((so->so_faddr.s_addr & htonl(CTL_DNS)) == htonl(CTL_DNS)))

            saddr.sin_addr.s_addr = so->so_faddr.s_addr;

    }

    daddr.sin_addr = so->so_laddr;

    daddr.sin_port = so->so_lport;

    return udp_output2(so, m, &saddr, &daddr, so->so_iptos);

}


void qemu_chr_add_handlers(CharDriverState *s,

                           IOCanReadHandler *fd_can_read,

                           IOReadHandler *fd_read,

                           IOEventHandler *fd_event,

                           void *opaque)

{

    if (!opaque) {

        /* chr driver being released. */

        ++s->avail_connections;

    }

    s->chr_can_read = fd_can_read;

    s->chr_read = fd_read;

    s->chr_event = fd_event;

    s->handler_opaque = opaque;

    if (s->chr_update_read_handler)

        s->chr_update_read_handler(s);

    /* We're connecting to an already opened device, so let's make sure we

       also get the open event */

    if (s->opened) {

        qemu_chr_generic_open(s);

    }

}


static void guest_fsfreeze_init(void)

{

    guest_fsfreeze_state.status = GUEST_FSFREEZE_STATUS_THAWED;

}


static int bdrv_rw_co(BlockDriverState *bs, int64_t sector_num, uint8_t *buf,

                      int nb_sectors, bool is_write, BdrvRequestFlags flags)

{

    QEMUIOVector qiov;

    struct iovec iov = {

        .iov_base = (void *)buf,

        .iov_len = nb_sectors * BDRV_SECTOR_SIZE,

    };

    if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) {

        return -EINVAL;

    }

    qemu_iovec_init_external(&qiov, &iov, 1);

    return bdrv_prwv_co(bs, sector_num << BDRV_SECTOR_BITS,

                        &qiov, is_write, flags);

}


static uint32_t stellaris_enet_read(void *opaque, target_phys_addr_t offset)

{

    stellaris_enet_state *s = (stellaris_enet_state *)opaque;

    uint32_t val;

    switch (offset) {

    case 0x00: /* RIS */

        DPRINTF("IRQ status %02x\n", s->ris);

        return s->ris;

    case 0x04: /* IM */

        return s->im;

    case 0x08: /* RCTL */

        return s->rctl;

    case 0x0c: /* TCTL */

        return s->tctl;

    case 0x10: /* DATA */

        if (s->rx_fifo_len == 0) {

            if (s->np == 0) {

                BADF("RX underflow\n");

                return 0;

            }

            s->rx_fifo_len = s->rx[s->next_packet].len;

            s->rx_fifo = s->rx[s->next_packet].data;

            DPRINTF("RX FIFO start packet len=%d\n", s->rx_fifo_len);

        }

        val = s->rx_fifo[0] | (s->rx_fifo[1] << 8) | (s->rx_fifo[2] << 16)

              | (s->rx_fifo[3] << 24);

        s->rx_fifo += 4;

        s->rx_fifo_len -= 4;

        if (s->rx_fifo_len <= 0) {

            s->rx_fifo_len = 0;

            s->next_packet++;

            if (s->next_packet >= 31)

                s->next_packet = 0;

            s->np--;

            DPRINTF("RX done np=%d\n", s->np);

        }

        return val;

    case 0x14: /* IA0 */

        return s->macaddr[0] | (s->macaddr[1] << 8)

               | (s->macaddr[2] << 16) | (s->macaddr[3] << 24);

    case 0x18: /* IA1 */

        return s->macaddr[4] | (s->macaddr[5] << 8);

    case 0x1c: /* THR */

        return s->thr;

    case 0x20: /* MCTL */

        return s->mctl;

    case 0x24: /* MDV */

        return s->mdv;

    case 0x28: /* MADD */

        return 0;

    case 0x2c: /* MTXD */

        return s->mtxd;

    case 0x30: /* MRXD */

        return s->mrxd;

    case 0x34: /* NP */

        return s->np;

    case 0x38: /* TR */

        return 0;

    case 0x3c: /* Undocuented: Timestamp? */

        return 0;

    default:

        hw_error("stellaris_enet_read: Bad offset %x\n", (int)offset);

        return 0;

    }

}


static void ide_reset(IDEState *s)

{

    if (s->is_cf)

        s->mult_sectors = 0;

    else

        s->mult_sectors = MAX_MULT_SECTORS;

    s->cur_drive = s;

    s->select = 0xa0;

    s->status = READY_STAT;

    ide_set_signature(s);

    /* init the transfer handler so that 0xffff is returned on data

       accesses */

    s->end_transfer_func = ide_dummy_transfer_stop;

    ide_dummy_transfer_stop(s);

    s->media_changed = 0;

}


int monitor_read_password(Monitor *mon, ReadLineFunc *readline_func,

                          void *opaque)

{

    if (monitor_ctrl_mode(mon)) {

        qerror_report(QERR_MISSING_PARAMETER, "password");

        return -EINVAL;

    } else if (mon->rs) {

        readline_start(mon->rs, "Password: ", 1, readline_func, opaque);

        /* prompt is printed on return from the command handler */

        return 0;

    } else {

        monitor_printf(mon, "terminal does not support password prompting\n");

        return -ENOTTY;

    }

}


static void openrisc_sim_net_init(MemoryRegion *address_space,

                                  hwaddr base,

                                  hwaddr descriptors,

                                  qemu_irq irq, NICInfo *nd)

{

    DeviceState *dev;

    SysBusDevice *s;

    dev = qdev_create(NULL, "open_eth");

    qdev_set_nic_properties(dev, nd);

    qdev_init_nofail(dev);

    s = SYS_BUS_DEVICE(dev);

    sysbus_connect_irq(s, 0, irq);

    memory_region_add_subregion(address_space, base,

                                sysbus_mmio_get_region(s, 0));

    memory_region_add_subregion(address_space, descriptors,

                                sysbus_mmio_get_region(s, 1));

}


build_srat(GArray *table_data, GArray *linker, MachineState *machine)

{

    AcpiSystemResourceAffinityTable *srat;

    AcpiSratProcessorAffinity *core;

    AcpiSratMemoryAffinity *numamem;

    int i;

    uint64_t curnode;

    int srat_start, numa_start, slots;

    uint64_t mem_len, mem_base, next_base;

    MachineClass *mc = MACHINE_GET_CLASS(machine);

    CPUArchIdList *apic_ids = mc->possible_cpu_arch_ids(machine);

    PCMachineState *pcms = PC_MACHINE(machine);

    ram_addr_t hotplugabble_address_space_size =

        object_property_get_int(OBJECT(pcms), PC_MACHINE_MEMHP_REGION_SIZE,

                                NULL);

    srat_start = table_data->len;

    srat = acpi_data_push(table_data, sizeof *srat);

    srat->reserved1 = cpu_to_le32(1);

    for (i = 0; i < apic_ids->len; i++) {

        int apic_id = apic_ids->cpus[i].arch_id;

        core = acpi_data_push(table_data, sizeof *core);

        core->type = ACPI_SRAT_PROCESSOR_APIC;

        core->length = sizeof(*core);

        core->local_apic_id = apic_id;

        curnode = pcms->node_cpu[apic_id];

        core->proximity_lo = curnode;

        memset(core->proximity_hi, 0, 3);

        core->local_sapic_eid = 0;

        core->flags = cpu_to_le32(1);

    }

    /* the memory map is a bit tricky, it contains at least one hole

     * from 640k-1M and possibly another one from 3.5G-4G.

     */

    next_base = 0;

    numa_start = table_data->len;

    numamem = acpi_data_push(table_data, sizeof *numamem);

    build_srat_memory(numamem, 0, 640 * 1024, 0, MEM_AFFINITY_ENABLED);

    next_base = 1024 * 1024;

    for (i = 1; i < pcms->numa_nodes + 1; ++i) {

        mem_base = next_base;

        mem_len = pcms->node_mem[i - 1];

        if (i == 1) {

            mem_len -= 1024 * 1024;

        }

        next_base = mem_base + mem_len;

        /* Cut out the ACPI_PCI hole */

        if (mem_base <= pcms->below_4g_mem_size &&

            next_base > pcms->below_4g_mem_size) {

            mem_len -= next_base - pcms->below_4g_mem_size;

            if (mem_len > 0) {

                numamem = acpi_data_push(table_data, sizeof *numamem);

                build_srat_memory(numamem, mem_base, mem_len, i - 1,

                                  MEM_AFFINITY_ENABLED);

            }

            mem_base = 1ULL << 32;

            mem_len = next_base - pcms->below_4g_mem_size;

            next_base += (1ULL << 32) - pcms->below_4g_mem_size;

        }

        numamem = acpi_data_push(table_data, sizeof *numamem);

        build_srat_memory(numamem, mem_base, mem_len, i - 1,

                          MEM_AFFINITY_ENABLED);

    }

    slots = (table_data->len - numa_start) / sizeof *numamem;

    for (; slots < pcms->numa_nodes + 2; slots++) {

        numamem = acpi_data_push(table_data, sizeof *numamem);

        build_srat_memory(numamem, 0, 0, 0, MEM_AFFINITY_NOFLAGS);

    }

    /*

     * Entry is required for Windows to enable memory hotplug in OS.

     * Memory devices may override proximity set by this entry,

     * providing _PXM method if necessary.

     */

    if (hotplugabble_address_space_size) {

        numamem = acpi_data_push(table_data, sizeof *numamem);

        build_srat_memory(numamem, pcms->hotplug_memory.base,

                          hotplugabble_address_space_size, 0,

                          MEM_AFFINITY_HOTPLUGGABLE | MEM_AFFINITY_ENABLED);

    }

    build_header(linker, table_data,

                 (void *)(table_data->data + srat_start),

                 "SRAT",

                 table_data->len - srat_start, 1, NULL, NULL);

    g_free(apic_ids);

}


static MaltaFPGAState *malta_fpga_init(MemoryRegion *address_space,

         target_phys_addr_t base, qemu_irq uart_irq, CharDriverState *uart_chr)

{

    MaltaFPGAState *s;

    s = (MaltaFPGAState *)g_malloc0(sizeof(MaltaFPGAState));

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

                          "malta-fpga", 0x100000);

    memory_region_init_alias(&s->iomem_lo, "malta-fpga",

                             &s->iomem, 0, 0x900);

    memory_region_init_alias(&s->iomem_hi, "malta-fpga",

                             &s->iomem, 0xa00, 0x10000-0xa00);

    memory_region_add_subregion(address_space, base, &s->iomem_lo);

    memory_region_add_subregion(address_space, base + 0xa00, &s->iomem_hi);

    s->display = qemu_chr_new("fpga", "vc:320x200", malta_fpga_led_init);

    s->uart = serial_mm_init(address_space, base + 0x900, 3, uart_irq,

                             230400, uart_chr, DEVICE_NATIVE_ENDIAN);

    malta_fpga_reset(s);

    qemu_register_reset(malta_fpga_reset, s);

    return s;

}


static void tcg_reg_alloc_start(TCGContext *s)

{

    int i;

    TCGTemp *ts;

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

        ts = &s->temps[i];

        if (ts->fixed_reg) {

            ts->val_type = TEMP_VAL_REG;

        } else {

            ts->val_type = TEMP_VAL_MEM;

        }

    }

    for(i = s->nb_globals; i < s->nb_temps; i++) {

        ts = &s->temps[i];

        ts->val_type = TEMP_VAL_DEAD;

        ts->mem_allocated = 0;

        ts->fixed_reg = 0;

    }

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

        s->reg_to_temp[i] = -1;

    }

}


static int coroutine_fn bdrv_driver_preadv(BlockDriverState *bs,

                                           uint64_t offset, uint64_t bytes,

                                           QEMUIOVector *qiov, int flags)

{

    BlockDriver *drv = bs->drv;

    int64_t sector_num = offset >> BDRV_SECTOR_BITS;

    unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS;

    assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);

    assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);

    assert((bytes >> BDRV_SECTOR_BITS) <= BDRV_REQUEST_MAX_SECTORS);

    return drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);

}


SCSIDevice *scsi_bus_legacy_add_drive(SCSIBus *bus, BlockDriverState *bdrv,

                                      int unit, bool removable, int bootindex,

                                      const char *serial, Error **errp)

{

    const char *driver;

    DeviceState *dev;

    Error *err = NULL;

    driver = bdrv_is_sg(bdrv) ? "scsi-generic" : "scsi-disk";

    dev = qdev_create(&bus->qbus, driver);

    qdev_prop_set_uint32(dev, "scsi-id", unit);

    if (bootindex >= 0) {

        object_property_set_int(OBJECT(dev), bootindex, "bootindex",

                                &error_abort);

    }

    if (object_property_find(OBJECT(dev), "removable", NULL)) {

        qdev_prop_set_bit(dev, "removable", removable);

    }

    if (serial && object_property_find(OBJECT(dev), "serial", NULL)) {

        qdev_prop_set_string(dev, "serial", serial);

    }

    if (qdev_prop_set_drive(dev, "drive", bdrv) < 0) {

        error_setg(errp, "Setting drive property failed");

        object_unparent(OBJECT(dev));

        return NULL;

    }

    object_property_set_bool(OBJECT(dev), true, "realized", &err);

    if (err != NULL) {

        error_propagate(errp, err);

        object_unparent(OBJECT(dev));

        return NULL;

    }

    return SCSI_DEVICE(dev);

}


static void check_exception(PowerPCCPU *cpu, sPAPRMachineState *spapr,

                            uint32_t token, uint32_t nargs,

                            target_ulong args,

                            uint32_t nret, target_ulong rets)

{

    uint32_t mask, buf, len, event_len;

    uint64_t xinfo;

    sPAPREventLogEntry *event;

    struct rtas_error_log *hdr;

    if ((nargs < 6) || (nargs > 7) || nret != 1) {

        rtas_st(rets, 0, RTAS_OUT_PARAM_ERROR);

        return;

    }

    xinfo = rtas_ld(args, 1);

    mask = rtas_ld(args, 2);

    buf = rtas_ld(args, 4);

    len = rtas_ld(args, 5);

    if (nargs == 7) {

        xinfo |= (uint64_t)rtas_ld(args, 6) << 32;

    }

    event = rtas_event_log_dequeue(mask, true);

    if (!event) {

        goto out_no_events;

    }

    hdr = event->data;

    event_len = be32_to_cpu(hdr->extended_length) + sizeof(*hdr);

    if (event_len < len) {

        len = event_len;

    }

    cpu_physical_memory_write(buf, event->data, len);

    rtas_st(rets, 0, RTAS_OUT_SUCCESS);

    g_free(event->data);

    g_free(event);

    /* according to PAPR+, the IRQ must be left asserted, or re-asserted, if

     * there are still pending events to be fetched via check-exception. We

     * do the latter here, since our code relies on edge-triggered

     * interrupts.

     */

    if (rtas_event_log_contains(mask, true)) {

        qemu_irq_pulse(xics_get_qirq(spapr->xics, spapr->check_exception_irq));

    }

    return;

out_no_events:

    rtas_st(rets, 0, RTAS_OUT_NO_ERRORS_FOUND);

}


static void test_qemu_strtoull_full_correct(void)

{

    const char *str = "18446744073709551614";

    uint64_t res = 999;

    int err;

    err = qemu_strtoull(str, NULL, 0, &res);

    g_assert_cmpint(err, ==, 0);

    g_assert_cmpint(res, ==, 18446744073709551614LLU);

}


QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)

{

    QEMUBH *bh;

    bh = qemu_malloc(sizeof(*bh));

    bh->cb = cb;

    bh->opaque = opaque;

    return bh;

}


static void omap_mcbsp_sink_tick(void *opaque)

{

    struct omap_mcbsp_s *s = (struct omap_mcbsp_s *) opaque;

    static const int bps[8] = { 0, 1, 1, 2, 2, 2, -255, -255 };

    if (!s->tx_rate)

        return;

    if (s->tx_req)

        printf("%s: Tx FIFO underrun\n", __FUNCTION__);

    s->tx_req = s->tx_rate << bps[(s->xcr[0] >> 5) & 7];

    omap_mcbsp_tx_newdata(s);

    timer_mod(s->sink_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +

                   NANOSECONDS_PER_SECOND);

}


static av_always_inline void hl_decode_mb_idct_luma(H264Context *h, int mb_type,

                                                    int is_h264, int simple,

                                                    int transform_bypass,

                                                    int pixel_shift,

                                                    int *block_offset,

                                                    int linesize,

                                                    uint8_t *dest_y, int p)

{

    void (*idct_add)(uint8_t *dst, int16_t *block, int stride);

    int i;

    block_offset += 16 * p;

    if (!IS_INTRA4x4(mb_type)) {

        if (is_h264) {

            if (IS_INTRA16x16(mb_type)) {

                if (transform_bypass) {

                    if (h->sps.profile_idc == 244 &&

                        (h->intra16x16_pred_mode == VERT_PRED8x8 ||

                         h->intra16x16_pred_mode == HOR_PRED8x8)) {

                        h->hpc.pred16x16_add[h->intra16x16_pred_mode](dest_y, block_offset,

                                                                      h->mb + (p * 256 << pixel_shift),

                                                                      linesize);

                    } else {

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

                            if (h->non_zero_count_cache[scan8[i + p * 16]] ||

                                dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))

                                h->h264dsp.h264_add_pixels4(dest_y + block_offset[i],

                                                            h->mb + (i * 16 + p * 256 << pixel_shift),

                                                            linesize);

                    }

                } else {

                    h->h264dsp.h264_idct_add16intra(dest_y, block_offset,

                                                    h->mb + (p * 256 << pixel_shift),

                                                    linesize,

                                                    h->non_zero_count_cache + p * 5 * 8);

                }

            } else if (h->cbp & 15) {

                if (transform_bypass) {

                    const int di = IS_8x8DCT(mb_type) ? 4 : 1;

                    idct_add = IS_8x8DCT(mb_type) ? h->h264dsp.h264_add_pixels8

                                                  : h->h264dsp.h264_add_pixels4;

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

                        if (h->non_zero_count_cache[scan8[i + p * 16]])

                            idct_add(dest_y + block_offset[i],

                                     h->mb + (i * 16 + p * 256 << pixel_shift),

                                     linesize);

                } else {

                    if (IS_8x8DCT(mb_type))

                        h->h264dsp.h264_idct8_add4(dest_y, block_offset,

                                                   h->mb + (p * 256 << pixel_shift),

                                                   linesize,

                                                   h->non_zero_count_cache + p * 5 * 8);

                    else

                        h->h264dsp.h264_idct_add16(dest_y, block_offset,

                                                   h->mb + (p * 256 << pixel_shift),

                                                   linesize,

                                                   h->non_zero_count_cache + p * 5 * 8);

                }

            }

        } else if (CONFIG_SVQ3_DECODER) {

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

                if (h->non_zero_count_cache[scan8[i + p * 16]] || h->mb[i * 16 + p * 256]) {

                    // FIXME benchmark weird rule, & below

                    uint8_t *const ptr = dest_y + block_offset[i];

                    ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize,

                                       h->qscale, IS_INTRA(mb_type) ? 1 : 0);

                }

        }

    }

}


int kvm_insert_breakpoint(CPUState *current_env, target_ulong addr,

                          target_ulong len, int type)

{

    struct kvm_sw_breakpoint *bp;

    CPUState *env;

    int err;

    if (type == GDB_BREAKPOINT_SW) {

        bp = kvm_find_sw_breakpoint(current_env, addr);

        if (bp) {

            bp->use_count++;

            return 0;

        }

        bp = qemu_malloc(sizeof(struct kvm_sw_breakpoint));

        if (!bp)

            return -ENOMEM;

        bp->pc = addr;

        bp->use_count = 1;

        err = kvm_arch_insert_sw_breakpoint(current_env, bp);

        if (err) {

            free(bp);

            return err;

        }

        QTAILQ_INSERT_HEAD(&current_env->kvm_state->kvm_sw_breakpoints,

                          bp, entry);

    } else {

        err = kvm_arch_insert_hw_breakpoint(addr, len, type);

        if (err)

            return err;

    }

    for (env = first_cpu; env != NULL; env = env->next_cpu) {

        err = kvm_update_guest_debug(env, 0);

        if (err)

            return err;

    }

    return 0;

}


static uint32_t nvic_readl(NVICState *s, uint32_t offset, MemTxAttrs attrs)

{

    ARMCPU *cpu = s->cpu;

    uint32_t val;

    switch (offset) {

    case 4: /* Interrupt Control Type.  */

        return ((s->num_irq - NVIC_FIRST_IRQ) / 32) - 1;

    case 0xd00: /* CPUID Base.  */

        return cpu->midr;

    case 0xd04: /* Interrupt Control State.  */

        /* VECTACTIVE */

        val = cpu->env.v7m.exception;

        /* VECTPENDING */

        val |= (s->vectpending & 0xff) << 12;

        /* ISRPENDING - set if any external IRQ is pending */

        if (nvic_isrpending(s)) {

            val |= (1 << 22);

        }

        /* RETTOBASE - set if only one handler is active */

        if (nvic_rettobase(s)) {

            val |= (1 << 11);

        }

        /* PENDSTSET */

        if (s->vectors[ARMV7M_EXCP_SYSTICK].pending) {

            val |= (1 << 26);

        }

        /* PENDSVSET */

        if (s->vectors[ARMV7M_EXCP_PENDSV].pending) {

            val |= (1 << 28);

        }

        /* NMIPENDSET */

        if (s->vectors[ARMV7M_EXCP_NMI].pending) {

            val |= (1 << 31);

        }

        /* ISRPREEMPT not implemented */

        return val;

    case 0xd08: /* Vector Table Offset.  */

        return cpu->env.v7m.vecbase[attrs.secure];

    case 0xd0c: /* Application Interrupt/Reset Control.  */

        return 0xfa050000 | (s->prigroup << 8);

    case 0xd10: /* System Control.  */

        /* TODO: Implement SLEEPONEXIT.  */

        return 0;

    case 0xd14: /* Configuration Control.  */

        return cpu->env.v7m.ccr;

    case 0xd24: /* System Handler Status.  */

        val = 0;

        if (s->vectors[ARMV7M_EXCP_MEM].active) {

            val |= (1 << 0);

        }

        if (s->vectors[ARMV7M_EXCP_BUS].active) {

            val |= (1 << 1);

        }

        if (s->vectors[ARMV7M_EXCP_USAGE].active) {

            val |= (1 << 3);

        }

        if (s->vectors[ARMV7M_EXCP_SVC].active) {

            val |= (1 << 7);

        }

        if (s->vectors[ARMV7M_EXCP_DEBUG].active) {

            val |= (1 << 8);

        }

        if (s->vectors[ARMV7M_EXCP_PENDSV].active) {

            val |= (1 << 10);

        }

        if (s->vectors[ARMV7M_EXCP_SYSTICK].active) {

            val |= (1 << 11);

        }

        if (s->vectors[ARMV7M_EXCP_USAGE].pending) {

            val |= (1 << 12);

        }

        if (s->vectors[ARMV7M_EXCP_MEM].pending) {

            val |= (1 << 13);

        }

        if (s->vectors[ARMV7M_EXCP_BUS].pending) {

            val |= (1 << 14);

        }

        if (s->vectors[ARMV7M_EXCP_SVC].pending) {

            val |= (1 << 15);

        }

        if (s->vectors[ARMV7M_EXCP_MEM].enabled) {

            val |= (1 << 16);

        }

        if (s->vectors[ARMV7M_EXCP_BUS].enabled) {

            val |= (1 << 17);

        }

        if (s->vectors[ARMV7M_EXCP_USAGE].enabled) {

            val |= (1 << 18);

        }

        return val;

    case 0xd28: /* Configurable Fault Status.  */

        return cpu->env.v7m.cfsr;

    case 0xd2c: /* Hard Fault Status.  */

        return cpu->env.v7m.hfsr;

    case 0xd30: /* Debug Fault Status.  */

        return cpu->env.v7m.dfsr;

    case 0xd34: /* MMFAR MemManage Fault Address */

        return cpu->env.v7m.mmfar;

    case 0xd38: /* Bus Fault Address.  */

        return cpu->env.v7m.bfar;

    case 0xd3c: /* Aux Fault Status.  */

        /* TODO: Implement fault status registers.  */

        qemu_log_mask(LOG_UNIMP,

                      "Aux Fault status registers unimplemented\n");

        return 0;

    case 0xd40: /* PFR0.  */

        return 0x00000030;

    case 0xd44: /* PRF1.  */

        return 0x00000200;

    case 0xd48: /* DFR0.  */

        return 0x00100000;

    case 0xd4c: /* AFR0.  */

        return 0x00000000;

    case 0xd50: /* MMFR0.  */

        return 0x00000030;

    case 0xd54: /* MMFR1.  */

        return 0x00000000;

    case 0xd58: /* MMFR2.  */

        return 0x00000000;

    case 0xd5c: /* MMFR3.  */

        return 0x00000000;

    case 0xd60: /* ISAR0.  */

        return 0x01141110;

    case 0xd64: /* ISAR1.  */

        return 0x02111000;

    case 0xd68: /* ISAR2.  */

        return 0x21112231;

    case 0xd6c: /* ISAR3.  */

        return 0x01111110;

    case 0xd70: /* ISAR4.  */

        return 0x01310102;

    /* TODO: Implement debug registers.  */

    case 0xd90: /* MPU_TYPE */

        /* Unified MPU; if the MPU is not present this value is zero */

        return cpu->pmsav7_dregion << 8;

        break;

    case 0xd94: /* MPU_CTRL */

        return cpu->env.v7m.mpu_ctrl;

    case 0xd98: /* MPU_RNR */

        return cpu->env.pmsav7.rnr[attrs.secure];

    case 0xd9c: /* MPU_RBAR */

    case 0xda4: /* MPU_RBAR_A1 */

    case 0xdac: /* MPU_RBAR_A2 */

    case 0xdb4: /* MPU_RBAR_A3 */

    {

        int region = cpu->env.pmsav7.rnr[attrs.secure];

        if (arm_feature(&cpu->env, ARM_FEATURE_V8)) {

            /* PMSAv8M handling of the aliases is different from v7M:

             * aliases A1, A2, A3 override the low two bits of the region

             * number in MPU_RNR, and there is no 'region' field in the

             * RBAR register.

             */

            int aliasno = (offset - 0xd9c) / 8; /* 0..3 */

            if (aliasno) {

                region = deposit32(region, 0, 2, aliasno);

            }

            if (region >= cpu->pmsav7_dregion) {

                return 0;

            }

            return cpu->env.pmsav8.rbar[attrs.secure][region];

        }

        if (region >= cpu->pmsav7_dregion) {

            return 0;

        }

        return (cpu->env.pmsav7.drbar[region] & 0x1f) | (region & 0xf);

    }

    case 0xda0: /* MPU_RASR (v7M), MPU_RLAR (v8M) */

    case 0xda8: /* MPU_RASR_A1 (v7M), MPU_RLAR_A1 (v8M) */

    case 0xdb0: /* MPU_RASR_A2 (v7M), MPU_RLAR_A2 (v8M) */

    case 0xdb8: /* MPU_RASR_A3 (v7M), MPU_RLAR_A3 (v8M) */

    {

        int region = cpu->env.pmsav7.rnr[attrs.secure];

        if (arm_feature(&cpu->env, ARM_FEATURE_V8)) {

            /* PMSAv8M handling of the aliases is different from v7M:

             * aliases A1, A2, A3 override the low two bits of the region

             * number in MPU_RNR.

             */

            int aliasno = (offset - 0xda0) / 8; /* 0..3 */

            if (aliasno) {

                region = deposit32(region, 0, 2, aliasno);

            }

            if (region >= cpu->pmsav7_dregion) {

                return 0;

            }

            return cpu->env.pmsav8.rlar[attrs.secure][region];

        }

        if (region >= cpu->pmsav7_dregion) {

            return 0;

        }

        return ((cpu->env.pmsav7.dracr[region] & 0xffff) << 16) |

            (cpu->env.pmsav7.drsr[region] & 0xffff);

    }

    case 0xdc0: /* MPU_MAIR0 */

        if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {

            goto bad_offset;

        }

        return cpu->env.pmsav8.mair0[attrs.secure];

    case 0xdc4: /* MPU_MAIR1 */

        if (!arm_feature(&cpu->env, ARM_FEATURE_V8)) {

            goto bad_offset;

        }

        return cpu->env.pmsav8.mair1[attrs.secure];

    default:

    bad_offset:

        qemu_log_mask(LOG_GUEST_ERROR, "NVIC: Bad read offset 0x%x\n", offset);

        return 0;

    }

}


static gboolean vtd_hash_remove_by_page(gpointer key, gpointer value,

                                        gpointer user_data)

{

    VTDIOTLBEntry *entry = (VTDIOTLBEntry *)value;

    VTDIOTLBPageInvInfo *info = (VTDIOTLBPageInvInfo *)user_data;

    uint64_t gfn = info->gfn & info->mask;

    return (entry->domain_id == info->domain_id) &&

            ((entry->gfn & info->mask) == gfn);

}


int coroutine_fn bdrv_co_pwritev(BdrvChild *child,

    int64_t offset, unsigned int bytes, QEMUIOVector *qiov,

    BdrvRequestFlags flags)

{

    BlockDriverState *bs = child->bs;

    BdrvTrackedRequest req;

    uint64_t align = bs->bl.request_alignment;

    uint8_t *head_buf = NULL;

    uint8_t *tail_buf = NULL;

    QEMUIOVector local_qiov;

    bool use_local_qiov = false;

    int ret;

    if (!bs->drv) {

        return -ENOMEDIUM;

    }

    if (bs->read_only) {

        return -EPERM;

    }

    assert(!(bs->open_flags & BDRV_O_INACTIVE));

    ret = bdrv_check_byte_request(bs, offset, bytes);

    if (ret < 0) {

        return ret;

    }

    bdrv_inc_in_flight(bs);

    /*

     * Align write if necessary by performing a read-modify-write cycle.

     * Pad qiov with the read parts and be sure to have a tracked request not

     * only for bdrv_aligned_pwritev, but also for the reads of the RMW cycle.

     */

    tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_WRITE);

    if (!qiov) {

        ret = bdrv_co_do_zero_pwritev(bs, offset, bytes, flags, &req);

        goto out;

    }

    if (offset & (align - 1)) {

        QEMUIOVector head_qiov;

        struct iovec head_iov;

        mark_request_serialising(&req, align);

        wait_serialising_requests(&req);

        head_buf = qemu_blockalign(bs, align);

        head_iov = (struct iovec) {

            .iov_base   = head_buf,

            .iov_len    = align,

        };

        qemu_iovec_init_external(&head_qiov, &head_iov, 1);

        bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_HEAD);

        ret = bdrv_aligned_preadv(bs, &req, offset & ~(align - 1), align,

                                  align, &head_qiov, 0);

        if (ret < 0) {

            goto fail;

        }

        bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD);

        qemu_iovec_init(&local_qiov, qiov->niov + 2);

        qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));

        qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);

        use_local_qiov = true;

        bytes += offset & (align - 1);

        offset = offset & ~(align - 1);

        /* We have read the tail already if the request is smaller

         * than one aligned block.

         */

        if (bytes < align) {

            qemu_iovec_add(&local_qiov, head_buf + bytes, align - bytes);

            bytes = align;

        }

    }

    if ((offset + bytes) & (align - 1)) {

        QEMUIOVector tail_qiov;

        struct iovec tail_iov;

        size_t tail_bytes;

        bool waited;

        mark_request_serialising(&req, align);

        waited = wait_serialising_requests(&req);

        assert(!waited || !use_local_qiov);

        tail_buf = qemu_blockalign(bs, align);

        tail_iov = (struct iovec) {

            .iov_base   = tail_buf,

            .iov_len    = align,

        };

        qemu_iovec_init_external(&tail_qiov, &tail_iov, 1);

        bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_TAIL);

        ret = bdrv_aligned_preadv(bs, &req, (offset + bytes) & ~(align - 1), align,

                                  align, &tail_qiov, 0);

        if (ret < 0) {

            goto fail;

        }

        bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);

        if (!use_local_qiov) {

            qemu_iovec_init(&local_qiov, qiov->niov + 1);

            qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);

            use_local_qiov = true;

        }

        tail_bytes = (offset + bytes) & (align - 1);

        qemu_iovec_add(&local_qiov, tail_buf + tail_bytes, align - tail_bytes);

        bytes = ROUND_UP(bytes, align);

    }

    ret = bdrv_aligned_pwritev(bs, &req, offset, bytes, align,

                               use_local_qiov ? &local_qiov : qiov,

                               flags);

fail:

    if (use_local_qiov) {

        qemu_iovec_destroy(&local_qiov);

    }

    qemu_vfree(head_buf);

    qemu_vfree(tail_buf);

out:

    tracked_request_end(&req);

    bdrv_dec_in_flight(bs);

    return ret;

}


int kvm_init_vcpu(CPUState *env)

{

    KVMState *s = kvm_state;

    long mmap_size;

    int ret;

    DPRINTF("kvm_init_vcpu\n");

    ret = kvm_vm_ioctl(s, KVM_CREATE_VCPU, env->cpu_index);

    if (ret < 0) {

        DPRINTF("kvm_create_vcpu failed\n");

        goto err;

    }

    env->kvm_fd = ret;

    env->kvm_state = s;

    mmap_size = kvm_ioctl(s, KVM_GET_VCPU_MMAP_SIZE, 0);

    if (mmap_size < 0) {

        DPRINTF("KVM_GET_VCPU_MMAP_SIZE failed\n");

        goto err;

    }

    env->kvm_run = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED,

                        env->kvm_fd, 0);

    if (env->kvm_run == MAP_FAILED) {

        ret = -errno;

        DPRINTF("mmap'ing vcpu state failed\n");

        goto err;

    }

#ifdef KVM_CAP_COALESCED_MMIO

    if (s->coalesced_mmio && !s->coalesced_mmio_ring)

        s->coalesced_mmio_ring = (void *) env->kvm_run +

		s->coalesced_mmio * PAGE_SIZE;

#endif

    ret = kvm_arch_init_vcpu(env);

    if (ret == 0) {

        qemu_register_reset(kvm_reset_vcpu, env);

        kvm_arch_reset_vcpu(env);

    }

err:

    return ret;

}


void bdrv_disable_copy_on_read(BlockDriverState *bs)

{

    assert(bs->copy_on_read > 0);

    bs->copy_on_read--;

}


void sdl_display_init(DisplayState *ds, int full_screen, int no_frame)

{

    int flags;

    uint8_t data = 0;

#if defined(__APPLE__)

    /* always use generic keymaps */

    if (!keyboard_layout)

        keyboard_layout = "en-us";

#endif

    if(keyboard_layout) {

        kbd_layout = init_keyboard_layout(keyboard_layout);

        if (!kbd_layout)

            exit(1);

    }

    if (no_frame)

        gui_noframe = 1;

    flags = SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE;

    if (SDL_Init (flags)) {

        fprintf(stderr, "Could not initialize SDL - exiting\n");

        exit(1);

    }

#ifndef _WIN32

    /* NOTE: we still want Ctrl-C to work, so we undo the SDL redirections */

    signal(SIGINT, SIG_DFL);

    signal(SIGQUIT, SIG_DFL);

#endif

    ds->dpy_update = sdl_update;

    ds->dpy_resize = sdl_resize;

    ds->dpy_refresh = sdl_refresh;

    ds->dpy_fill = sdl_fill;

    ds->mouse_set = sdl_mouse_warp;

    ds->cursor_define = sdl_mouse_define;

    sdl_resize(ds, 640, 400);

    sdl_update_caption();

    SDL_EnableKeyRepeat(250, 50);

    gui_grab = 0;

    sdl_cursor_hidden = SDL_CreateCursor(&data, &data, 8, 1, 0, 0);

    sdl_cursor_normal = SDL_GetCursor();

    atexit(sdl_cleanup);

    if (full_screen) {

        gui_fullscreen = 1;

        gui_fullscreen_initial_grab = 1;

        sdl_grab_start();

    }

}


int nbd_trip(BlockDriverState *bs, int csock, off_t size, uint64_t dev_offset,

             off_t *offset, uint32_t nbdflags, uint8_t *data, int data_size)

{

    struct nbd_request request;

    struct nbd_reply reply;

    TRACE("Reading request.");

    if (nbd_receive_request(csock, &request) == -1)

        return -1;

    if (request.len + NBD_REPLY_SIZE > data_size) {

        LOG("len (%u) is larger than max len (%u)",

            request.len + NBD_REPLY_SIZE, data_size);

        errno = EINVAL;

        return -1;

    }

    if ((request.from + request.len) < request.from) {

        LOG("integer overflow detected! "

            "you're probably being attacked");

        errno = EINVAL;

        return -1;

    }

    if ((request.from + request.len) > size) {

            LOG("From: %" PRIu64 ", Len: %u, Size: %" PRIu64

            ", Offset: %" PRIu64 "\n",

                    request.from, request.len, (uint64_t)size, dev_offset);

        LOG("requested operation past EOF--bad client?");

        errno = EINVAL;

        return -1;

    }

    TRACE("Decoding type");

    reply.handle = request.handle;

    reply.error = 0;

    switch (request.type) {

    case NBD_CMD_READ:

        TRACE("Request type is READ");

        if (bdrv_read(bs, (request.from + dev_offset) / 512,

                  data + NBD_REPLY_SIZE,

                  request.len / 512) == -1) {

            LOG("reading from file failed");

            errno = EINVAL;

            return -1;

        }

        *offset += request.len;

        TRACE("Read %u byte(s)", request.len);

        /* Reply

           [ 0 ..  3]    magic   (NBD_REPLY_MAGIC)

           [ 4 ..  7]    error   (0 == no error)

           [ 7 .. 15]    handle

         */

        cpu_to_be32w((uint32_t*)data, NBD_REPLY_MAGIC);

        cpu_to_be32w((uint32_t*)(data + 4), reply.error);

        cpu_to_be64w((uint64_t*)(data + 8), reply.handle);

        TRACE("Sending data to client");

        if (write_sync(csock, data,

                   request.len + NBD_REPLY_SIZE) !=

                   request.len + NBD_REPLY_SIZE) {

            LOG("writing to socket failed");

            errno = EINVAL;

            return -1;

        }

        break;

    case NBD_CMD_WRITE:

        TRACE("Request type is WRITE");

        TRACE("Reading %u byte(s)", request.len);

        if (read_sync(csock, data, request.len) != request.len) {

            LOG("reading from socket failed");

            errno = EINVAL;

            return -1;

        }

        if (nbdflags & NBD_FLAG_READ_ONLY) {

            TRACE("Server is read-only, return error");

            reply.error = 1;

        } else {

            TRACE("Writing to device");

            if (bdrv_write(bs, (request.from + dev_offset) / 512,

                       data, request.len / 512) == -1) {

                LOG("writing to file failed");

                errno = EINVAL;

                return -1;

            }

            *offset += request.len;

        }

        if (nbd_send_reply(csock, &reply) == -1)

            return -1;

        break;

    case NBD_CMD_DISC:

        TRACE("Request type is DISCONNECT");

        errno = 0;

        return 1;

    default:

        LOG("invalid request type (%u) received", request.type);

        errno = EINVAL;

        return -1;

    }

    TRACE("Request/Reply complete");

    return 0;

}


static inline void reloc_pc19(tcg_insn_unit *code_ptr, tcg_insn_unit *target)

{

    ptrdiff_t offset = target - code_ptr;

    assert(offset == sextract64(offset, 0, 19));

    *code_ptr = deposit32(*code_ptr, 5, 19, offset);

}


void json_end_object(QJSON *json)

{

    qstring_append(json->str, " }");

    json->omit_comma = false;

}


void timerlist_free(QEMUTimerList *timer_list)

{

    assert(!timerlist_has_timers(timer_list));

    if (timer_list->clock) {

        QLIST_REMOVE(timer_list, list);

    }

    qemu_mutex_destroy(&timer_list->active_timers_lock);

    g_free(timer_list);

}


static AioContext *thread_pool_get_aio_context(BlockAIOCB *acb)

{

    ThreadPoolElement *elem = (ThreadPoolElement *)acb;

    ThreadPool *pool = elem->pool;

    return pool->ctx;

}


static BlockDriverAIOCB *dma_bdrv_io(

    BlockDriverState *bs, QEMUSGList *sg, uint64_t sector_num,

    BlockDriverCompletionFunc *cb, void *opaque,

    int is_write)

{

    DMABlockState *dbs = qemu_malloc(sizeof(*dbs));

    dbs->bs = bs;

    dbs->acb = qemu_aio_get(bs, cb, opaque);

    dbs->sg = sg;

    dbs->sector_num = sector_num;

    dbs->sg_cur_index = 0;

    dbs->sg_cur_byte = 0;

    dbs->is_write = is_write;

    dbs->bh = NULL;

    qemu_iovec_init(&dbs->iov, sg->nsg);

    dma_bdrv_cb(dbs, 0);

    return dbs->acb;

}


static uint64_t watch_mem_read(void *opaque, target_phys_addr_t addr,

                               unsigned size)

{

    check_watchpoint(addr & ~TARGET_PAGE_MASK, ~(size - 1), BP_MEM_READ);

    switch (size) {

    case 1: return ldub_phys(addr);

    case 2: return lduw_phys(addr);

    case 4: return ldl_phys(addr);

    default: abort();

    }

}


print_syscall_ret(int num, abi_long ret)

{

    int i;

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

        if( scnames[i].nr == num ) {

            if( scnames[i].result != NULL ) {

                scnames[i].result(&scnames[i],ret);

            } else {

                if( ret < 0 ) {

                    gemu_log(" = -1 errno=" TARGET_ABI_FMT_ld " (%s)\n", -ret, target_strerror(-ret));

                } else {

                    gemu_log(" = " TARGET_ABI_FMT_ld "\n", ret);

                }

            }

            break;

        }

}


struct pxa2xx_state_s *pxa270_init(unsigned int sdram_size,

                DisplayState *ds, const char *revision)

{

    struct pxa2xx_state_s *s;

    struct pxa2xx_ssp_s *ssp;

    int iomemtype, i;

    s = (struct pxa2xx_state_s *) qemu_mallocz(sizeof(struct pxa2xx_state_s));

    if (revision && strncmp(revision, "pxa27", 5)) {

        fprintf(stderr, "Machine requires a PXA27x processor.\n");

        exit(1);

    }

    s->env = cpu_init();

    cpu_arm_set_model(s->env, revision ?: "pxa270");

    register_savevm("cpu", 0, 0, cpu_save, cpu_load, s->env);

    /* SDRAM & Internal Memory Storage */

    cpu_register_physical_memory(PXA2XX_SDRAM_BASE,

                    sdram_size, qemu_ram_alloc(sdram_size) | IO_MEM_RAM);

    cpu_register_physical_memory(PXA2XX_INTERNAL_BASE,

                    0x40000, qemu_ram_alloc(0x40000) | IO_MEM_RAM);

    s->pic = pxa2xx_pic_init(0x40d00000, s->env);

    s->dma = pxa27x_dma_init(0x40000000, s->pic[PXA2XX_PIC_DMA]);

    pxa27x_timer_init(0x40a00000, &s->pic[PXA2XX_PIC_OST_0],

                    s->pic[PXA27X_PIC_OST_4_11]);

    s->gpio = pxa2xx_gpio_init(0x40e00000, s->env, s->pic, 121);

    s->mmc = pxa2xx_mmci_init(0x41100000, s->pic[PXA2XX_PIC_MMC], s->dma);

    for (i = 0; pxa270_serial[i].io_base; i ++)

        if (serial_hds[i])

            serial_mm_init(pxa270_serial[i].io_base, 2,

                            s->pic[pxa270_serial[i].irqn], serial_hds[i], 1);

        else

            break;

    if (serial_hds[i])

        s->fir = pxa2xx_fir_init(0x40800000, s->pic[PXA2XX_PIC_ICP],

                        s->dma, serial_hds[i]);

    if (ds)

        s->lcd = pxa2xx_lcdc_init(0x44000000, s->pic[PXA2XX_PIC_LCD], ds);

    s->cm_base = 0x41300000;

    s->cm_regs[CCCR >> 4] = 0x02000210;	/* 416.0 MHz */

    s->clkcfg = 0x00000009;		/* Turbo mode active */

    iomemtype = cpu_register_io_memory(0, pxa2xx_cm_readfn,

                    pxa2xx_cm_writefn, s);

    cpu_register_physical_memory(s->cm_base, 0xfff, iomemtype);

    register_savevm("pxa2xx_cm", 0, 0, pxa2xx_cm_save, pxa2xx_cm_load, s);

    cpu_arm_set_cp_io(s->env, 14, pxa2xx_cp14_read, pxa2xx_cp14_write, s);

    s->mm_base = 0x48000000;

    s->mm_regs[MDMRS >> 2] = 0x00020002;

    s->mm_regs[MDREFR >> 2] = 0x03ca4000;

    s->mm_regs[MECR >> 2] = 0x00000001;	/* Two PC Card sockets */

    iomemtype = cpu_register_io_memory(0, pxa2xx_mm_readfn,

                    pxa2xx_mm_writefn, s);

    cpu_register_physical_memory(s->mm_base, 0xfff, iomemtype);

    register_savevm("pxa2xx_mm", 0, 0, pxa2xx_mm_save, pxa2xx_mm_load, s);

    s->pm_base = 0x40f00000;

    iomemtype = cpu_register_io_memory(0, pxa2xx_pm_readfn,

                    pxa2xx_pm_writefn, s);

    cpu_register_physical_memory(s->pm_base, 0xff, iomemtype);

    register_savevm("pxa2xx_pm", 0, 0, pxa2xx_pm_save, pxa2xx_pm_load, s);

    for (i = 0; pxa27x_ssp[i].io_base; i ++);

    s->ssp = (struct pxa2xx_ssp_s **)

            qemu_mallocz(sizeof(struct pxa2xx_ssp_s *) * i);

    ssp = (struct pxa2xx_ssp_s *)

            qemu_mallocz(sizeof(struct pxa2xx_ssp_s) * i);

    for (i = 0; pxa27x_ssp[i].io_base; i ++) {

        s->ssp[i] = &ssp[i];

        ssp[i].base = pxa27x_ssp[i].io_base;

        ssp[i].irq = s->pic[pxa27x_ssp[i].irqn];

        iomemtype = cpu_register_io_memory(0, pxa2xx_ssp_readfn,

                        pxa2xx_ssp_writefn, &ssp[i]);

        cpu_register_physical_memory(ssp[i].base, 0xfff, iomemtype);

        register_savevm("pxa2xx_ssp", i, 0,

                        pxa2xx_ssp_save, pxa2xx_ssp_load, s);

    }

    if (usb_enabled) {

        usb_ohci_init_pxa(0x4c000000, 3, -1, s->pic[PXA2XX_PIC_USBH1]);

    }

    s->pcmcia[0] = pxa2xx_pcmcia_init(0x20000000);

    s->pcmcia[1] = pxa2xx_pcmcia_init(0x30000000);

    s->rtc_base = 0x40900000;

    iomemtype = cpu_register_io_memory(0, pxa2xx_rtc_readfn,

                    pxa2xx_rtc_writefn, s);

    cpu_register_physical_memory(s->rtc_base, 0xfff, iomemtype);

    pxa2xx_rtc_init(s);

    register_savevm("pxa2xx_rtc", 0, 0, pxa2xx_rtc_save, pxa2xx_rtc_load, s);

    s->i2c[0] = pxa2xx_i2c_init(0x40301600, s->pic[PXA2XX_PIC_I2C], 0xffff);

    s->i2c[1] = pxa2xx_i2c_init(0x40f00100, s->pic[PXA2XX_PIC_PWRI2C], 0xff);

    s->i2s = pxa2xx_i2s_init(0x40400000, s->pic[PXA2XX_PIC_I2S], s->dma);

    /* GPIO1 resets the processor */

    /* The handler can be overriden by board-specific code */

    pxa2xx_gpio_handler_set(s->gpio, 1, pxa2xx_reset, s);

    return s;

}


static void apc_init(target_phys_addr_t power_base, qemu_irq cpu_halt)

{

    DeviceState *dev;

    SysBusDevice *s;

    dev = qdev_create(NULL, "apc");

    qdev_init(dev);

    s = sysbus_from_qdev(dev);

    /* Power management (APC) XXX: not a Slavio device */

    sysbus_mmio_map(s, 0, power_base);

    sysbus_connect_irq(s, 0, cpu_halt);

}


static int wc3_read_header(AVFormatContext *s,

                           AVFormatParameters *ap)

{

    Wc3DemuxContext *wc3 = s->priv_data;

    ByteIOContext *pb = s->pb;

    unsigned int fourcc_tag;

    unsigned int size;

    AVStream *st;

    int ret = 0;

    int current_palette = 0;

    char *buffer;

    int i;

    /* default context members */

    wc3->width = WC3_DEFAULT_WIDTH;

    wc3->height = WC3_DEFAULT_HEIGHT;

    wc3->palettes = NULL;

    wc3->palette_count = 0;

    wc3->pts = 0;

    wc3->video_stream_index = wc3->audio_stream_index = 0;

    /* skip the first 3 32-bit numbers */

    url_fseek(pb, 12, SEEK_CUR);

    /* traverse through the chunks and load the header information before

     * the first BRCH tag */

    fourcc_tag = get_le32(pb);

    size = (get_be32(pb) + 1) & (~1);

    do {

        switch (fourcc_tag) {

        case SOND_TAG:

        case INDX_TAG:

            /* SOND unknown, INDX unnecessary; ignore both */

            url_fseek(pb, size, SEEK_CUR);

            break;

        case PC__TAG:

            /* need the number of palettes */

            url_fseek(pb, 8, SEEK_CUR);

            wc3->palette_count = get_le32(pb);

            if((unsigned)wc3->palette_count >= UINT_MAX / PALETTE_SIZE){

                wc3->palette_count= 0;

                return -1;

            }

            wc3->palettes = av_malloc(wc3->palette_count * PALETTE_SIZE);

            break;

        case BNAM_TAG:

            /* load up the name */

            buffer = av_malloc(size+1);

            if (!buffer)

                return AVERROR(ENOMEM);

            if ((ret = get_buffer(pb, buffer, size)) != size)

                return AVERROR(EIO);

            buffer[size] = 0;

            av_metadata_set2(&s->metadata, "title", buffer,

                                   AV_METADATA_DONT_STRDUP_VAL);

            break;

        case SIZE_TAG:

            /* video resolution override */

            wc3->width  = get_le32(pb);

            wc3->height = get_le32(pb);

            break;

        case PALT_TAG:

            /* one of several palettes */

            if ((unsigned)current_palette >= wc3->palette_count)

                return AVERROR_INVALIDDATA;

            if ((ret = get_buffer(pb,

                &wc3->palettes[current_palette * PALETTE_SIZE],

                PALETTE_SIZE)) != PALETTE_SIZE)

                return AVERROR(EIO);

            /* transform the current palette in place */

            for (i = current_palette * PALETTE_SIZE;

                 i < (current_palette + 1) * PALETTE_SIZE; i++) {

                wc3->palettes[i] = wc3_pal_lookup[wc3->palettes[i]];

            }

            current_palette++;

            break;

        default:

            av_log(s, AV_LOG_ERROR, "  unrecognized WC3 chunk: %c%c%c%c (0x%02X%02X%02X%02X)\n",

                (uint8_t)fourcc_tag, (uint8_t)(fourcc_tag >> 8), (uint8_t)(fourcc_tag >> 16), (uint8_t)(fourcc_tag >> 24),

                (uint8_t)fourcc_tag, (uint8_t)(fourcc_tag >> 8), (uint8_t)(fourcc_tag >> 16), (uint8_t)(fourcc_tag >> 24));

            return AVERROR_INVALIDDATA;

            break;

        }

        fourcc_tag = get_le32(pb);

        /* chunk sizes are 16-bit aligned */

        size = (get_be32(pb) + 1) & (~1);

        if (url_feof(pb))

            return AVERROR(EIO);

    } while (fourcc_tag != BRCH_TAG);

    /* initialize the decoder streams */

    st = av_new_stream(s, 0);

    if (!st)

        return AVERROR(ENOMEM);

    av_set_pts_info(st, 33, 1, WC3_FRAME_FPS);

    wc3->video_stream_index = st->index;

    st->codec->codec_type = AVMEDIA_TYPE_VIDEO;

    st->codec->codec_id = CODEC_ID_XAN_WC3;

    st->codec->codec_tag = 0;  /* no fourcc */

    st->codec->width = wc3->width;

    st->codec->height = wc3->height;

    /* palette considerations */

    st->codec->palctrl = &wc3->palette_control;

    st = av_new_stream(s, 0);

    if (!st)

        return AVERROR(ENOMEM);

    av_set_pts_info(st, 33, 1, WC3_FRAME_FPS);

    wc3->audio_stream_index = st->index;

    st->codec->codec_type = AVMEDIA_TYPE_AUDIO;

    st->codec->codec_id = CODEC_ID_PCM_S16LE;

    st->codec->codec_tag = 1;

    st->codec->channels = WC3_AUDIO_CHANNELS;

    st->codec->bits_per_coded_sample = WC3_AUDIO_BITS;

    st->codec->sample_rate = WC3_SAMPLE_RATE;

    st->codec->bit_rate = st->codec->channels * st->codec->sample_rate *

        st->codec->bits_per_coded_sample;

    st->codec->block_align = WC3_AUDIO_BITS * WC3_AUDIO_CHANNELS;

    return 0;

}


struct icp_state *xics_system_init(int nr_irqs)

{

    CPUPPCState *env;

    CPUState *cpu;

    int max_server_num;

    struct icp_state *icp;

    struct ics_state *ics;

    max_server_num = -1;

    for (env = first_cpu; env != NULL; env = env->next_cpu) {

        cpu = CPU(ppc_env_get_cpu(env));

        if (cpu->cpu_index > max_server_num) {

            max_server_num = cpu->cpu_index;

        }

    }

    icp = g_malloc0(sizeof(*icp));

    icp->nr_servers = max_server_num + 1;

    icp->ss = g_malloc0(icp->nr_servers*sizeof(struct icp_server_state));

    for (env = first_cpu; env != NULL; env = env->next_cpu) {

        cpu = CPU(ppc_env_get_cpu(env));

        struct icp_server_state *ss = &icp->ss[cpu->cpu_index];

        switch (PPC_INPUT(env)) {

        case PPC_FLAGS_INPUT_POWER7:

            ss->output = env->irq_inputs[POWER7_INPUT_INT];

            break;

        case PPC_FLAGS_INPUT_970:

            ss->output = env->irq_inputs[PPC970_INPUT_INT];

            break;

        default:

            hw_error("XICS interrupt model does not support this CPU bus "

                     "model\n");

            exit(1);

        }

    }

    ics = g_malloc0(sizeof(*ics));

    ics->nr_irqs = nr_irqs;

    ics->offset = XICS_IRQ_BASE;

    ics->irqs = g_malloc0(nr_irqs * sizeof(struct ics_irq_state));

    ics->islsi = g_malloc0(nr_irqs * sizeof(bool));

    icp->ics = ics;

    ics->icp = icp;

    ics->qirqs = qemu_allocate_irqs(ics_set_irq, ics, nr_irqs);

    spapr_register_hypercall(H_CPPR, h_cppr);

    spapr_register_hypercall(H_IPI, h_ipi);

    spapr_register_hypercall(H_XIRR, h_xirr);

    spapr_register_hypercall(H_EOI, h_eoi);

    spapr_rtas_register("ibm,set-xive", rtas_set_xive);

    spapr_rtas_register("ibm,get-xive", rtas_get_xive);

    spapr_rtas_register("ibm,int-off", rtas_int_off);

    spapr_rtas_register("ibm,int-on", rtas_int_on);

    qemu_register_reset(xics_reset, icp);

    return icp;

}


static uint16_t nvme_write_zeros(NvmeCtrl *n, NvmeNamespace *ns, NvmeCmd *cmd,

    NvmeRequest *req)

{

    NvmeRwCmd *rw = (NvmeRwCmd *)cmd;

    const uint8_t lba_index = NVME_ID_NS_FLBAS_INDEX(ns->id_ns.flbas);

    const uint8_t data_shift = ns->id_ns.lbaf[lba_index].ds;

    uint64_t slba = le64_to_cpu(rw->slba);

    uint32_t nlb  = le16_to_cpu(rw->nlb) + 1;

    uint64_t aio_slba = slba << (data_shift - BDRV_SECTOR_BITS);

    uint32_t aio_nlb = nlb << (data_shift - BDRV_SECTOR_BITS);

    if (slba + nlb > ns->id_ns.nsze) {

        return NVME_LBA_RANGE | NVME_DNR;

    }

    req->has_sg = false;

    block_acct_start(blk_get_stats(n->conf.blk), &req->acct, 0,

                     BLOCK_ACCT_WRITE);

    req->aiocb = blk_aio_pwrite_zeroes(n->conf.blk, aio_slba, aio_nlb,

                                        BDRV_REQ_MAY_UNMAP, nvme_rw_cb, req);

    return NVME_NO_COMPLETE;

}


static int decode_packet(AVCodecContext *avctx, void *data, int *got_frame_ptr,
                         AVPacket* avpkt)
{
    WmallDecodeCtx *s = avctx->priv_data;
    GetBitContext* gb  = &s->pgb;
    const uint8_t* buf = avpkt->data;
    int buf_size       = avpkt->size;
    int num_bits_prev_frame, packet_sequence_number, spliced_packet;
    s->frame->nb_samples = 0;
    if (!buf_size && s->num_saved_bits > get_bits_count(&s->gb)) {
        s->packet_done = 0;
        if (!decode_frame(s))
            s->num_saved_bits = 0;
    } else if (s->packet_done || s->packet_loss) {
        s->packet_done = 0;
        if (!buf_size)
            return 0;
        s->next_packet_start = buf_size - FFMIN(avctx->block_align, buf_size);
        buf_size             = FFMIN(avctx->block_align, buf_size);
        s->buf_bit_size      = buf_size << 3;
        /* parse packet header */
        init_get_bits(gb, buf, s->buf_bit_size);
        packet_sequence_number = get_bits(gb, 4);
        skip_bits(gb, 1);   // Skip seekable_frame_in_packet, currently unused
        spliced_packet = get_bits1(gb);
        if (spliced_packet)
            avpriv_request_sample(avctx, "Bitstream splicing");
        /* get number of bits that need to be added to the previous frame */
        num_bits_prev_frame = get_bits(gb, s->log2_frame_size);
        /* check for packet loss */
        if (!s->packet_loss &&
            ((s->packet_sequence_number + 1) & 0xF) != packet_sequence_number) {
            av_log(avctx, AV_LOG_ERROR,
                   "Packet loss detected! seq %"PRIx8" vs %x\n",
                   s->packet_sequence_number, packet_sequence_number);
        s->packet_sequence_number = packet_sequence_number;
        if (num_bits_prev_frame > 0) {
            int remaining_packet_bits = s->buf_bit_size - get_bits_count(gb);
            if (num_bits_prev_frame >= remaining_packet_bits) {
                num_bits_prev_frame = remaining_packet_bits;
                s->packet_done = 1;
            /* Append the previous frame data to the remaining data from the
             * previous packet to create a full frame. */
            save_bits(s, gb, num_bits_prev_frame, 1);
            /* decode the cross packet frame if it is valid */
            if (num_bits_prev_frame < remaining_packet_bits && !s->packet_loss)
                decode_frame(s);
        } else if (s->num_saved_bits - s->frame_offset) {
            ff_dlog(avctx, "ignoring %x previously saved bits\n",
                    s->num_saved_bits - s->frame_offset);
        if (s->packet_loss) {
            /* Reset number of saved bits so that the decoder does not start
             * to decode incomplete frames in the s->len_prefix == 0 case. */
            s->num_saved_bits = 0;
            s->packet_loss    = 0;
            init_put_bits(&s->pb, s->frame_data, s->max_frame_size);
    } else {
        int frame_size;
        s->buf_bit_size = (avpkt->size - s->next_packet_start) << 3;
        init_get_bits(gb, avpkt->data, s->buf_bit_size);
        skip_bits(gb, s->packet_offset);
        if (s->len_prefix && remaining_bits(s, gb) > s->log2_frame_size &&
            (frame_size = show_bits(gb, s->log2_frame_size)) &&
            frame_size <= remaining_bits(s, gb)) {
            save_bits(s, gb, frame_size, 0);
            s->packet_done = !decode_frame(s);
        } else if (!s->len_prefix
                   && s->num_saved_bits > get_bits_count(&s->gb)) {
            /* when the frames do not have a length prefix, we don't know the
             * compressed length of the individual frames however, we know what
             * part of a new packet belongs to the previous frame therefore we
             * save the incoming packet first, then we append the "previous
             * frame" data from the next packet so that we get a buffer that
             * only contains full frames */
            s->packet_done = !decode_frame(s);
        } else {
            s->packet_done = 1;
    if (s->packet_done && !s->packet_loss &&
        remaining_bits(s, gb) > 0) {
        /* save the rest of the data so that it can be decoded
         * with the next packet */
        save_bits(s, gb, remaining_bits(s, gb), 0);
    *got_frame_ptr   = s->frame->nb_samples > 0;
    av_frame_move_ref(data, s->frame);
    s->packet_offset = get_bits_count(gb) & 7;
    return (s->packet_loss) ? AVERROR_INVALIDDATA : buf_size ? get_bits_count(gb) >> 3 : 0;


int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)

{

    int size, l;

    if (f->is_write) {

        abort();

    }

    size = size1;

    while (size > 0) {

        l = f->buf_size - f->buf_index;

        if (l == 0) {

            qemu_fill_buffer(f);

            l = f->buf_size - f->buf_index;

            if (l == 0) {

                break;

            }

        }

        if (l > size) {

            l = size;

        }

        memcpy(buf, f->buf + f->buf_index, l);

        f->buf_index += l;

        buf += l;

        size -= l;

    }

    return size1 - size;

}