static int kvm_get_sregs(CPUState *env)

{

    struct kvm_sregs sregs;

    uint32_t hflags;

    int ret;

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

    if (ret < 0)

        return ret;

    memcpy(env->interrupt_bitmap,

           sregs.interrupt_bitmap,

           sizeof(sregs.interrupt_bitmap));

    get_seg(&env->segs[R_CS], &sregs.cs);

    get_seg(&env->segs[R_DS], &sregs.ds);

    get_seg(&env->segs[R_ES], &sregs.es);

    get_seg(&env->segs[R_FS], &sregs.fs);

    get_seg(&env->segs[R_GS], &sregs.gs);

    get_seg(&env->segs[R_SS], &sregs.ss);

    get_seg(&env->tr, &sregs.tr);

    get_seg(&env->ldt, &sregs.ldt);

    env->idt.limit = sregs.idt.limit;

    env->idt.base = sregs.idt.base;

    env->gdt.limit = sregs.gdt.limit;

    env->gdt.base = sregs.gdt.base;

    env->cr[0] = sregs.cr0;

    env->cr[2] = sregs.cr2;

    env->cr[3] = sregs.cr3;

    env->cr[4] = sregs.cr4;

    cpu_set_apic_base(env, sregs.apic_base);

    env->efer = sregs.efer;

    //cpu_set_apic_tpr(env, sregs.cr8);

#define HFLAG_COPY_MASK ~( \

			HF_CPL_MASK | HF_PE_MASK | HF_MP_MASK | HF_EM_MASK | \

			HF_TS_MASK | HF_TF_MASK | HF_VM_MASK | HF_IOPL_MASK | \

			HF_OSFXSR_MASK | HF_LMA_MASK | HF_CS32_MASK | \

			HF_SS32_MASK | HF_CS64_MASK | HF_ADDSEG_MASK)

    hflags = (env->segs[R_CS].flags >> DESC_DPL_SHIFT) & HF_CPL_MASK;

    hflags |= (env->cr[0] & CR0_PE_MASK) << (HF_PE_SHIFT - CR0_PE_SHIFT);

    hflags |= (env->cr[0] << (HF_MP_SHIFT - CR0_MP_SHIFT)) &

	    (HF_MP_MASK | HF_EM_MASK | HF_TS_MASK);

    hflags |= (env->eflags & (HF_TF_MASK | HF_VM_MASK | HF_IOPL_MASK));

    hflags |= (env->cr[4] & CR4_OSFXSR_MASK) <<

	    (HF_OSFXSR_SHIFT - CR4_OSFXSR_SHIFT);

    if (env->efer & MSR_EFER_LMA) {

        hflags |= HF_LMA_MASK;

    }

    if ((hflags & HF_LMA_MASK) && (env->segs[R_CS].flags & DESC_L_MASK)) {

        hflags |= HF_CS32_MASK | HF_SS32_MASK | HF_CS64_MASK;

    } else {

        hflags |= (env->segs[R_CS].flags & DESC_B_MASK) >>

		(DESC_B_SHIFT - HF_CS32_SHIFT);

        hflags |= (env->segs[R_SS].flags & DESC_B_MASK) >>

		(DESC_B_SHIFT - HF_SS32_SHIFT);

        if (!(env->cr[0] & CR0_PE_MASK) ||

                   (env->eflags & VM_MASK) ||

                   !(hflags & HF_CS32_MASK)) {

                hflags |= HF_ADDSEG_MASK;

            } else {

                hflags |= ((env->segs[R_DS].base |

                                env->segs[R_ES].base |

                                env->segs[R_SS].base) != 0) <<

                    HF_ADDSEG_SHIFT;

            }

    }

    env->hflags = (env->hflags & HFLAG_COPY_MASK) | hflags;

    env->cc_src = env->eflags & (CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C);

    env->df = 1 - (2 * ((env->eflags >> 10) & 1));

    env->cc_op = CC_OP_EFLAGS;

    env->eflags &= ~(DF_MASK | CC_O | CC_S | CC_Z | CC_A | CC_P | CC_C);

    return 0;

}


int qemu_opt_set_bool(QemuOpts *opts, const char *name, bool val)

{

    QemuOpt *opt;

    const QemuOptDesc *desc = opts->list->desc;

    int i;

    for (i = 0; desc[i].name != NULL; i++) {

        if (strcmp(desc[i].name, name) == 0) {

            break;

        }

    }

    if (desc[i].name == NULL) {

        if (i == 0) {

            /* empty list -> allow any */;

        } else {

            qerror_report(QERR_INVALID_PARAMETER, name);

            return -1;

        }

    }

    opt = g_malloc0(sizeof(*opt));

    opt->name = g_strdup(name);

    opt->opts = opts;

    QTAILQ_INSERT_TAIL(&opts->head, opt, next);

    if (desc[i].name != NULL) {

        opt->desc = desc+i;

    }

    opt->value.boolean = !!val;

    return 0;

}


static int vc1_decode_init(AVCodecContext *avctx)

{

    VC1Context *v = avctx->priv_data;

    MpegEncContext *s = &v->s;

    GetBitContext gb;

    if (!avctx->extradata_size || !avctx->extradata) return -1;

    if (!(avctx->flags & CODEC_FLAG_GRAY))

        avctx->pix_fmt = PIX_FMT_YUV420P;

    else

        avctx->pix_fmt = PIX_FMT_GRAY8;

    v->s.avctx = avctx;

    avctx->flags |= CODEC_FLAG_EMU_EDGE;

    v->s.flags |= CODEC_FLAG_EMU_EDGE;

    if(avctx->idct_algo==FF_IDCT_AUTO){

        avctx->idct_algo=FF_IDCT_WMV2;

    }

    if(ff_h263_decode_init(avctx) < 0)

        return -1;

    if (vc1_init_common(v) < 0) return -1;

    avctx->coded_width = avctx->width;

    avctx->coded_height = avctx->height;

    if (avctx->codec_id == CODEC_ID_WMV3)

    {

        int count = 0;

        // looks like WMV3 has a sequence header stored in the extradata

        // advanced sequence header may be before the first frame

        // the last byte of the extradata is a version number, 1 for the

        // samples we can decode

        init_get_bits(&gb, avctx->extradata, avctx->extradata_size*8);

        if (decode_sequence_header(avctx, &gb) < 0)

          return -1;

        count = avctx->extradata_size*8 - get_bits_count(&gb);

        if (count>0)

        {

            av_log(avctx, AV_LOG_INFO, "Extra data: %i bits left, value: %X\n",

                   count, get_bits(&gb, count));

        }

        else if (count < 0)

        {

            av_log(avctx, AV_LOG_INFO, "Read %i bits in overflow\n", -count);

        }

    } else { // VC1/WVC1

        const uint8_t *start = avctx->extradata;

        uint8_t *end = avctx->extradata + avctx->extradata_size;

        const uint8_t *next;

        int size, buf2_size;

        uint8_t *buf2 = NULL;

        int seq_inited = 0, ep_inited = 0;

        if(avctx->extradata_size < 16) {

            av_log(avctx, AV_LOG_ERROR, "Extradata size too small: %i\n", avctx->extradata_size);

            return -1;

        }

        buf2 = av_mallocz(avctx->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);

        if(start[0]) start++; // in WVC1 extradata first byte is its size

        next = start;

        for(; next < end; start = next){

            next = find_next_marker(start + 4, end);

            size = next - start - 4;

            if(size <= 0) continue;

            buf2_size = vc1_unescape_buffer(start + 4, size, buf2);

            init_get_bits(&gb, buf2, buf2_size * 8);

            switch(AV_RB32(start)){

            case VC1_CODE_SEQHDR:

                if(decode_sequence_header(avctx, &gb) < 0){

                    av_free(buf2);

                    return -1;

                }

                seq_inited = 1;

                break;

            case VC1_CODE_ENTRYPOINT:

                if(decode_entry_point(avctx, &gb) < 0){

                    av_free(buf2);

                    return -1;

                }

                ep_inited = 1;

                break;

            }

        }

        av_free(buf2);

        if(!seq_inited || !ep_inited){

            av_log(avctx, AV_LOG_ERROR, "Incomplete extradata\n");

            return -1;

        }

    }

    avctx->has_b_frames= !!(avctx->max_b_frames);

    s->low_delay = !avctx->has_b_frames;

    s->mb_width = (avctx->coded_width+15)>>4;

    s->mb_height = (avctx->coded_height+15)>>4;

    /* Allocate mb bitplanes */

    v->mv_type_mb_plane = av_malloc(s->mb_stride * s->mb_height);

    v->direct_mb_plane = av_malloc(s->mb_stride * s->mb_height);

    v->acpred_plane = av_malloc(s->mb_stride * s->mb_height);

    v->over_flags_plane = av_malloc(s->mb_stride * s->mb_height);

    /* allocate block type info in that way so it could be used with s->block_index[] */

    v->mb_type_base = av_malloc(s->b8_stride * (s->mb_height * 2 + 1) + s->mb_stride * (s->mb_height + 1) * 2);

    v->mb_type[0] = v->mb_type_base + s->b8_stride + 1;

    v->mb_type[1] = v->mb_type_base + s->b8_stride * (s->mb_height * 2 + 1) + s->mb_stride + 1;

    v->mb_type[2] = v->mb_type[1] + s->mb_stride * (s->mb_height + 1);

    /* Init coded blocks info */

    if (v->profile == PROFILE_ADVANCED)

    {

//        if (alloc_bitplane(&v->over_flags_plane, s->mb_width, s->mb_height) < 0)

//            return -1;

//        if (alloc_bitplane(&v->ac_pred_plane, s->mb_width, s->mb_height) < 0)

//            return -1;

    }

    ff_intrax8_common_init(&v->x8,s);

    return 0;

}


static CharDriverState *qemu_chr_open_pp_fd(int fd)

{

    CharDriverState *chr;

    ParallelCharDriver *drv;

    if (ioctl(fd, PPCLAIM) < 0) {

        close(fd);

        return NULL;

    }

    drv = g_malloc0(sizeof(ParallelCharDriver));

    drv->fd = fd;

    drv->mode = IEEE1284_MODE_COMPAT;

    chr = qemu_chr_alloc();

    chr->chr_write = null_chr_write;

    chr->chr_ioctl = pp_ioctl;

    chr->chr_close = pp_close;

    chr->opaque = drv;

    return chr;

}


av_cold void ff_vp9dsp_init(VP9DSPContext *dsp)

{

    vp9dsp_intrapred_init(dsp);

    vp9dsp_itxfm_init(dsp);

    vp9dsp_loopfilter_init(dsp);

    vp9dsp_mc_init(dsp);

    if (ARCH_X86)

        ff_vp9dsp_init_x86(dsp);

}


static int flv_write_header(AVFormatContext *s)

{

    AVIOContext *pb = s->pb;

    FLVContext *flv = s->priv_data;

    AVCodecContext *audio_enc = NULL, *video_enc = NULL;

    int i, metadata_count = 0;

    double framerate = 0.0;

    int64_t metadata_size_pos, data_size, metadata_count_pos;

    AVDictionaryEntry *tag = NULL;

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

        AVCodecContext *enc = s->streams[i]->codec;

        if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {

            if (s->streams[i]->r_frame_rate.den && s->streams[i]->r_frame_rate.num) {

                framerate = av_q2d(s->streams[i]->r_frame_rate);

            } else {

                framerate = 1/av_q2d(s->streams[i]->codec->time_base);

            }

            video_enc = enc;

            if(enc->codec_tag == 0) {

                av_log(enc, AV_LOG_ERROR, "video codec not compatible with flv\n");

                return -1;

            }

        } else {

            audio_enc = enc;

            if(get_audio_flags(enc)<0)

                return -1;

        }

        av_set_pts_info(s->streams[i], 32, 1, 1000); /* 32 bit pts in ms */

    }

    avio_write(pb, "FLV", 3);

    avio_w8(pb,1);

    avio_w8(pb,   FLV_HEADER_FLAG_HASAUDIO * !!audio_enc

                 + FLV_HEADER_FLAG_HASVIDEO * !!video_enc);

    avio_wb32(pb,9);

    avio_wb32(pb,0);

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

        if(s->streams[i]->codec->codec_tag == 5){

            avio_w8(pb,8); // message type

            avio_wb24(pb,0); // include flags

            avio_wb24(pb,0); // time stamp

            avio_wb32(pb,0); // reserved

            avio_wb32(pb,11); // size

            flv->reserved=5;

        }

    }

    flv->last_video_ts = -1;

    /* write meta_tag */

    avio_w8(pb, 18);         // tag type META

    metadata_size_pos= avio_tell(pb);

    avio_wb24(pb, 0);          // size of data part (sum of all parts below)

    avio_wb24(pb, 0);          // time stamp

    avio_wb32(pb, 0);          // reserved

    /* now data of data_size size */

    /* first event name as a string */

    avio_w8(pb, AMF_DATA_TYPE_STRING);

    put_amf_string(pb, "onMetaData"); // 12 bytes

    /* mixed array (hash) with size and string/type/data tuples */

    avio_w8(pb, AMF_DATA_TYPE_MIXEDARRAY);

    metadata_count_pos = avio_tell(pb);

    metadata_count = 5*!!video_enc + 5*!!audio_enc + 2; // +2 for duration and file size

    avio_wb32(pb, metadata_count);

    put_amf_string(pb, "duration");

    flv->duration_offset= avio_tell(pb);

    put_amf_double(pb, s->duration / AV_TIME_BASE); // fill in the guessed duration, it'll be corrected later if incorrect

    if(video_enc){

        put_amf_string(pb, "width");

        put_amf_double(pb, video_enc->width);

        put_amf_string(pb, "height");

        put_amf_double(pb, video_enc->height);

        put_amf_string(pb, "videodatarate");

        put_amf_double(pb, video_enc->bit_rate / 1024.0);

        put_amf_string(pb, "framerate");

        put_amf_double(pb, framerate);

        put_amf_string(pb, "videocodecid");

        put_amf_double(pb, video_enc->codec_tag);

    }

    if(audio_enc){

        put_amf_string(pb, "audiodatarate");

        put_amf_double(pb, audio_enc->bit_rate / 1024.0);

        put_amf_string(pb, "audiosamplerate");

        put_amf_double(pb, audio_enc->sample_rate);

        put_amf_string(pb, "audiosamplesize");

        put_amf_double(pb, audio_enc->codec_id == CODEC_ID_PCM_U8 ? 8 : 16);

        put_amf_string(pb, "stereo");

        put_amf_bool(pb, audio_enc->channels == 2);

        put_amf_string(pb, "audiocodecid");

        put_amf_double(pb, audio_enc->codec_tag);

    }

    while ((tag = av_dict_get(s->metadata, "", tag, AV_DICT_IGNORE_SUFFIX))) {

        put_amf_string(pb, tag->key);

        avio_w8(pb, AMF_DATA_TYPE_STRING);

        put_amf_string(pb, tag->value);

        metadata_count++;

    }

    put_amf_string(pb, "filesize");

    flv->filesize_offset= avio_tell(pb);

    put_amf_double(pb, 0); // delayed write

    put_amf_string(pb, "");

    avio_w8(pb, AMF_END_OF_OBJECT);

    /* write total size of tag */

    data_size= avio_tell(pb) - metadata_size_pos - 10;

    avio_seek(pb, metadata_count_pos, SEEK_SET);

    avio_wb32(pb, metadata_count);

    avio_seek(pb, metadata_size_pos, SEEK_SET);

    avio_wb24(pb, data_size);

    avio_skip(pb, data_size + 10 - 3);

    avio_wb32(pb, data_size + 11);

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

        AVCodecContext *enc = s->streams[i]->codec;

        if (enc->codec_id == CODEC_ID_AAC || enc->codec_id == CODEC_ID_H264) {

            int64_t pos;

            avio_w8(pb, enc->codec_type == AVMEDIA_TYPE_VIDEO ?

                     FLV_TAG_TYPE_VIDEO : FLV_TAG_TYPE_AUDIO);

            avio_wb24(pb, 0); // size patched later

            avio_wb24(pb, 0); // ts

            avio_w8(pb, 0); // ts ext

            avio_wb24(pb, 0); // streamid

            pos = avio_tell(pb);

            if (enc->codec_id == CODEC_ID_AAC) {

                avio_w8(pb, get_audio_flags(enc));

                avio_w8(pb, 0); // AAC sequence header

                avio_write(pb, enc->extradata, enc->extradata_size);

            } else {

                avio_w8(pb, enc->codec_tag | FLV_FRAME_KEY); // flags

                avio_w8(pb, 0); // AVC sequence header

                avio_wb24(pb, 0); // composition time

                ff_isom_write_avcc(pb, enc->extradata, enc->extradata_size);

            }

            data_size = avio_tell(pb) - pos;

            avio_seek(pb, -data_size - 10, SEEK_CUR);

            avio_wb24(pb, data_size);

            avio_skip(pb, data_size + 10 - 3);

            avio_wb32(pb, data_size + 11); // previous tag size

        }

    }

    return 0;

}


void qdev_prop_set_globals(DeviceState *dev)

{

    ObjectClass *class = object_get_class(OBJECT(dev));

    do {

        qdev_prop_set_globals_for_type(dev, object_class_get_name(class));

        class = object_class_get_parent(class);

    } while (class);

}


BlockDriverState *bdrv_new(const char *device_name, Error **errp)

{

    BlockDriverState *bs;

    int i;

    if (bdrv_find(device_name)) {

        error_setg(errp, "Device with id '%s' already exists",

                   device_name);

        return NULL;

    }

    if (bdrv_find_node(device_name)) {

        error_setg(errp, "Device with node-name '%s' already exists",

                   device_name);

        return NULL;

    }

    bs = g_malloc0(sizeof(BlockDriverState));

    QLIST_INIT(&bs->dirty_bitmaps);

    pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);

    if (device_name[0] != '\0') {

        QTAILQ_INSERT_TAIL(&bdrv_states, bs, device_list);

    }

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

        QLIST_INIT(&bs->op_blockers[i]);

    }

    bdrv_iostatus_disable(bs);

    notifier_list_init(&bs->close_notifiers);

    notifier_with_return_list_init(&bs->before_write_notifiers);

    qemu_co_queue_init(&bs->throttled_reqs[0]);

    qemu_co_queue_init(&bs->throttled_reqs[1]);

    bs->refcnt = 1;

    bs->aio_context = qemu_get_aio_context();

    return bs;

}


static void filter_edges(void *dst1, void *prev1, void *cur1, void *next1,

                         int w, int prefs, int mrefs, int parity, int mode)

{

    uint8_t *dst  = dst1;

    uint8_t *prev = prev1;

    uint8_t *cur  = cur1;

    uint8_t *next = next1;

    int x;

    uint8_t *prev2 = parity ? prev : cur ;

    uint8_t *next2 = parity ? cur  : next;

    /* Only edge pixels need to be processed here.  A constant value of false

     * for is_not_edge should let the compiler ignore the whole branch. */

    FILTER(0, 3, 0)

    dst  = (uint8_t*)dst1  + w - 3;

    prev = (uint8_t*)prev1 + w - 3;

    cur  = (uint8_t*)cur1  + w - 3;

    next = (uint8_t*)next1 + w - 3;

    prev2 = (uint8_t*)(parity ? prev : cur);

    next2 = (uint8_t*)(parity ? cur  : next);

    FILTER(w - 3, w, 0)

}


static int kvm_set_user_memory_region(KVMState *s, KVMSlot *slot)

{

    struct kvm_userspace_memory_region mem;

    mem.slot = slot->slot;

    mem.guest_phys_addr = slot->start_addr;

    mem.userspace_addr = (unsigned long)slot->ram;

    mem.flags = slot->flags;

    if (s->migration_log) {

        mem.flags |= KVM_MEM_LOG_DIRTY_PAGES;

    }

    if (mem.flags & KVM_MEM_READONLY) {

        /* Set the slot size to 0 before setting the slot to the desired

         * value. This is needed based on KVM commit 75d61fbc. */

        mem.memory_size = 0;

        kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);

    }

    mem.memory_size = slot->memory_size;

    return kvm_vm_ioctl(s, KVM_SET_USER_MEMORY_REGION, &mem);

}


static int decode_frame(AVCodecContext *avctx, void *data, int *data_size,

                        AVPacket *avpkt)

{

    V210DecContext *s = avctx->priv_data;

    int h, w, stride, aligned_input;

    AVFrame *pic = avctx->coded_frame;

    const uint8_t *psrc = avpkt->data;

    uint16_t *y, *u, *v;

    if (s->custom_stride )

        stride = s->custom_stride;

    else {

        int aligned_width = ((avctx->width + 47) / 48) * 48;

        stride = aligned_width * 8 / 3;

    }

    aligned_input = !((uintptr_t)psrc & 0xf) && !(stride & 0xf);

    if (aligned_input != s->aligned_input) {

        s->aligned_input = aligned_input;

        if (HAVE_MMX)

            v210_x86_init(s);

    }

    if (pic->data[0])

        avctx->release_buffer(avctx, pic);

    if (avpkt->size < stride * avctx->height) {

        av_log(avctx, AV_LOG_ERROR, "packet too small\n");

        return -1;

    }

    pic->reference = 0;

    if (avctx->get_buffer(avctx, pic) < 0)

        return -1;

    y = (uint16_t*)pic->data[0];

    u = (uint16_t*)pic->data[1];

    v = (uint16_t*)pic->data[2];

    pic->pict_type = AV_PICTURE_TYPE_I;

    pic->key_frame = 1;

    for (h = 0; h < avctx->height; h++) {

        const uint32_t *src = (const uint32_t*)psrc;

        uint32_t val;

        w = (avctx->width / 6) * 6;

        s->unpack_frame(src, y, u, v, w);

        y += w;

        u += w >> 1;

        v += w >> 1;

        src += (w << 1) / 3;

        if (w < avctx->width - 1) {

            READ_PIXELS(u, y, v);

            val  = av_le2ne32(*src++);

            *y++ =  val & 0x3FF;

        }

        if (w < avctx->width - 3) {

            *u++ = (val >> 10) & 0x3FF;

            *y++ = (val >> 20) & 0x3FF;

            val  = av_le2ne32(*src++);

            *v++ =  val & 0x3FF;

            *y++ = (val >> 10) & 0x3FF;

        }

        psrc += stride;

        y += pic->linesize[0] / 2 - avctx->width;

        u += pic->linesize[1] / 2 - avctx->width / 2;

        v += pic->linesize[2] / 2 - avctx->width / 2;

    }

    *data_size = sizeof(AVFrame);

    *(AVFrame*)data = *avctx->coded_frame;

    return avpkt->size;

}


void cpu_exec_init(CPUState *cpu, Error **errp)

{

    CPUClass *cc ATTRIBUTE_UNUSED = CPU_GET_CLASS(cpu);

    cpu_list_add(cpu);

#ifndef CONFIG_USER_ONLY

    if (qdev_get_vmsd(DEVICE(cpu)) == NULL) {

        vmstate_register(NULL, cpu->cpu_index, &vmstate_cpu_common, cpu);

    }

    if (cc->vmsd != NULL) {

        vmstate_register(NULL, cpu->cpu_index, cc->vmsd, cpu);

    }

#endif

}


static int read_shape_from_file(int *cols, int *rows, int **values, const char *filename,

                                void *log_ctx)

{

    uint8_t *buf, *p, *pend;

    size_t size;

    int ret, i, j, w;

    if ((ret = av_file_map(filename, &buf, &size, 0, log_ctx)) < 0)

        return ret;

    /* prescan file to get the number of lines and the maximum width */

    w = 0;

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

        if (buf[i] == '\n') {

            if (*rows == INT_MAX) {

                av_log(log_ctx, AV_LOG_ERROR, "Overflow on the number of rows in the file\n");

                return AVERROR_INVALIDDATA;

            }

            ++(*rows);

            *cols = FFMAX(*cols, w);

            w = 0;

        } else if (w == INT_MAX) {

            av_log(log_ctx, AV_LOG_ERROR, "Overflow on the number of columns in the file\n");

            return AVERROR_INVALIDDATA;

        }

        w++;

    }

    if (*rows > (SIZE_MAX / sizeof(int) / *cols)) {

        av_log(log_ctx, AV_LOG_ERROR, "File with size %dx%d is too big\n",

               *rows, *cols);

        return AVERROR_INVALIDDATA;

    }

    if (!(*values = av_mallocz_array(sizeof(int) * *rows, *cols)))

        return AVERROR(ENOMEM);

    /* fill *values */

    p    = buf;

    pend = buf + size-1;

    for (i = 0; i < *rows; i++) {

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

            if (p > pend || *p == '\n') {

                p++;

                break;

            } else

                (*values)[*cols*i + j] = !!av_isgraph(*(p++));

        }

    }

    av_file_unmap(buf, size);

#ifdef DEBUG

    {

        char *line;

        if (!(line = av_malloc(*cols + 1)))

            return AVERROR(ENOMEM);

        for (i = 0; i < *rows; i++) {

            for (j = 0; j < *cols; j++)

                line[j] = (*values)[i * *cols + j] ? '@' : ' ';

            line[j] = 0;

            av_log(log_ctx, AV_LOG_DEBUG, "%3d: %s\n", i, line);

        }

        av_free(line);

    }

#endif

    return 0;

}


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

{

	const uint16_t *end;

#ifdef HAVE_MMX

	const uint16_t *mm_end;

#endif

	uint8_t *d = (uint8_t *)dst;

	const uint16_t *s = (uint16_t *)src;

	end = s + src_size/2;

#ifdef HAVE_MMX

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

	__asm __volatile("pxor	%%mm7,%%mm7\n\t":::"memory");

	mm_end = end - 3;

	while(s < mm_end)

	{

	    __asm __volatile(

		PREFETCH" 32%1\n\t"

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

		:"=m"(*d)

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

		:"memory");

		d += 16;

		s += 4;

	}

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

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

#endif

	while(s < end)

	{

		register uint16_t bgr;

		bgr = *s++;

#ifdef WORDS_BIGENDIAN

		*d++ = 0;

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

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

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

#else

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

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

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

		*d++ = 0;

#endif

	}

}


int ff_packet_split_and_drop_side_data(AVPacket *pkt){

    if (!pkt->side_data_elems && pkt->size >12 && AV_RB64(pkt->data + pkt->size - 8) == FF_MERGE_MARKER){

        int i;

        unsigned int size;

        uint8_t *p;

        p = pkt->data + pkt->size - 8 - 5;

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

            size = AV_RB32(p);

            if (size>INT_MAX - 5 || p - pkt->data < size)

            if (p[4]&128)

                break;

            if (p - pkt->data < size + 5)

            p-= size+5;

        }

        pkt->size = p - pkt->data - size;

        av_assert0(pkt->size >= 0);

        return 1;

    }

}


static bool aio_dispatch(AioContext *ctx)

{

    AioHandler *node;

    bool progress = false;

    /*

     * We have to walk very carefully in case qemu_aio_set_fd_handler is

     * called while we're walking.

     */

    node = QLIST_FIRST(&ctx->aio_handlers);

    while (node) {

        AioHandler *tmp;

        int revents;

        ctx->walking_handlers++;

        revents = node->pfd.revents & node->pfd.events;

        node->pfd.revents = 0;

        if (!node->deleted &&

            (revents & (G_IO_IN | G_IO_HUP | G_IO_ERR)) &&

            node->io_read) {

            node->io_read(node->opaque);

            progress = true;

        }

        if (!node->deleted &&

            (revents & (G_IO_OUT | G_IO_ERR)) &&

            node->io_write) {

            node->io_write(node->opaque);

            progress = true;

        }

        tmp = node;

        node = QLIST_NEXT(node, node);

        ctx->walking_handlers--;

        if (!ctx->walking_handlers && tmp->deleted) {

            QLIST_REMOVE(tmp, node);

            g_free(tmp);

        }

    }

    return progress;

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);

    k->no_hotplug = 1;

    k->init = pci_piix_ide_initfn;

    k->exit = pci_piix_ide_exitfn;

    k->vendor_id = PCI_VENDOR_ID_INTEL;

    k->device_id = PCI_DEVICE_ID_INTEL_82371AB;

    k->class_id = PCI_CLASS_STORAGE_IDE;

    set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);

    dc->no_user = 1;

}


static float get_band_cost_SPAIR_mips(struct AACEncContext *s,

                                      PutBitContext *pb, const float *in,

                                      const float *scaled, int size, int scale_idx,

                                      int cb, const float lambda, const float uplim,

                                      int *bits)

{

    const float Q34 = ff_aac_pow34sf_tab[POW_SF2_ZERO - scale_idx + SCALE_ONE_POS - SCALE_DIV_512];

    const float IQ  = ff_aac_pow2sf_tab [POW_SF2_ZERO + scale_idx - SCALE_ONE_POS + SCALE_DIV_512];

    int i;

    float cost = 0;

    int qc1, qc2, qc3, qc4;

    int curbits = 0;

    uint8_t *p_bits  = (uint8_t *)ff_aac_spectral_bits[cb-1];

    float   *p_codes = (float   *)ff_aac_codebook_vectors[cb-1];

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

        const float *vec, *vec2;

        int curidx, curidx2;

        int   *in_int = (int   *)&in[i];

        float *in_pos = (float *)&in[i];

        float di0, di1, di2, di3;

        int t0, t1, t2, t3, t4, t5, t6, t7;

        qc1 = scaled[i  ] * Q34 + ROUND_STANDARD;

        qc2 = scaled[i+1] * Q34 + ROUND_STANDARD;

        qc3 = scaled[i+2] * Q34 + ROUND_STANDARD;

        qc4 = scaled[i+3] * Q34 + ROUND_STANDARD;

        __asm__ volatile (

            ".set push                                  \n\t"

            ".set noreorder                             \n\t"

            "ori        %[t4],  $zero,  4               \n\t"

            "slt        %[t0],  %[t4],  %[qc1]          \n\t"

            "slt        %[t1],  %[t4],  %[qc2]          \n\t"

            "slt        %[t2],  %[t4],  %[qc3]          \n\t"

            "slt        %[t3],  %[t4],  %[qc4]          \n\t"

            "movn       %[qc1], %[t4],  %[t0]           \n\t"

            "movn       %[qc2], %[t4],  %[t1]           \n\t"

            "movn       %[qc3], %[t4],  %[t2]           \n\t"

            "movn       %[qc4], %[t4],  %[t3]           \n\t"

            "lw         %[t0],  0(%[in_int])            \n\t"

            "lw         %[t1],  4(%[in_int])            \n\t"

            "lw         %[t2],  8(%[in_int])            \n\t"

            "lw         %[t3],  12(%[in_int])           \n\t"

            "srl        %[t0],  %[t0],  31              \n\t"

            "srl        %[t1],  %[t1],  31              \n\t"

            "srl        %[t2],  %[t2],  31              \n\t"

            "srl        %[t3],  %[t3],  31              \n\t"

            "subu       %[t4],  $zero,  %[qc1]          \n\t"

            "subu       %[t5],  $zero,  %[qc2]          \n\t"

            "subu       %[t6],  $zero,  %[qc3]          \n\t"

            "subu       %[t7],  $zero,  %[qc4]          \n\t"

            "movn       %[qc1], %[t4],  %[t0]           \n\t"

            "movn       %[qc2], %[t5],  %[t1]           \n\t"

            "movn       %[qc3], %[t6],  %[t2]           \n\t"

            "movn       %[qc4], %[t7],  %[t3]           \n\t"

            ".set pop                                   \n\t"

            : [qc1]"+r"(qc1), [qc2]"+r"(qc2),

              [qc3]"+r"(qc3), [qc4]"+r"(qc4),

              [t0]"=&r"(t0), [t1]"=&r"(t1), [t2]"=&r"(t2), [t3]"=&r"(t3),

              [t4]"=&r"(t4), [t5]"=&r"(t5), [t6]"=&r"(t6), [t7]"=&r"(t7)

            : [in_int]"r"(in_int)

            : "memory"

        );

        curidx = 9 * qc1;

        curidx += qc2 + 40;

        curidx2 = 9 * qc3;

        curidx2 += qc4 + 40;

        curbits += p_bits[curidx];

        curbits += p_bits[curidx2];

        vec     = &p_codes[curidx*2];

        vec2    = &p_codes[curidx2*2];

        __asm__ volatile (

            ".set push                                  \n\t"

            ".set noreorder                             \n\t"

            "lwc1       $f0,    0(%[in_pos])            \n\t"

            "lwc1       $f1,    0(%[vec])               \n\t"

            "lwc1       $f2,    4(%[in_pos])            \n\t"

            "lwc1       $f3,    4(%[vec])               \n\t"

            "lwc1       $f4,    8(%[in_pos])            \n\t"

            "lwc1       $f5,    0(%[vec2])              \n\t"

            "lwc1       $f6,    12(%[in_pos])           \n\t"

            "lwc1       $f7,    4(%[vec2])              \n\t"

            "nmsub.s    %[di0], $f0,    $f1,    %[IQ]   \n\t"

            "nmsub.s    %[di1], $f2,    $f3,    %[IQ]   \n\t"

            "nmsub.s    %[di2], $f4,    $f5,    %[IQ]   \n\t"

            "nmsub.s    %[di3], $f6,    $f7,    %[IQ]   \n\t"

            ".set pop                                   \n\t"

            : [di0]"=&f"(di0), [di1]"=&f"(di1),

              [di2]"=&f"(di2), [di3]"=&f"(di3)

            : [in_pos]"r"(in_pos), [vec]"r"(vec),

              [vec2]"r"(vec2), [IQ]"f"(IQ)

            : "$f0", "$f1", "$f2", "$f3",

              "$f4", "$f5", "$f6", "$f7",

              "memory"

        );

        cost += di0 * di0 + di1 * di1

                + di2 * di2 + di3 * di3;

    }

    if (bits)

        *bits = curbits;

    return cost * lambda + curbits;

}


static void qdict_add_key(const char *key, QObject *obj, void *opaque)

{

    GHashTable *h = opaque;

    g_hash_table_insert(h, (gpointer) key, NULL);

}


static void eject_device(BlockDriverState *bs, int force, Error **errp)

{

    if (bdrv_in_use(bs)) {

        error_set(errp, QERR_DEVICE_IN_USE, bdrv_get_device_name(bs));

        return;

    }

    if (!bdrv_dev_has_removable_media(bs)) {

        error_setg(errp, "Device '%s' is not removable",

                   bdrv_get_device_name(bs));

        return;

    }

    if (bdrv_dev_is_medium_locked(bs) && !bdrv_dev_is_tray_open(bs)) {

        bdrv_dev_eject_request(bs, force);

        if (!force) {

            error_setg(errp, "Device '%s' is locked",

                       bdrv_get_device_name(bs));

            return;

        }

    }

    bdrv_close(bs);

}


void ff_rm_free_rmstream (RMStream *rms)

{

    av_free(rms->videobuf);

    av_free(rms->audiobuf);

}


void qmp_dump_guest_memory(bool paging, const char *file, bool has_begin,

                           int64_t begin, bool has_length, int64_t length,

                           Error **errp)

{

    const char *p;

    int fd = -1;

    DumpState *s;

    int ret;

    if (has_begin && !has_length) {

        error_set(errp, QERR_MISSING_PARAMETER, "length");

        return;

    }

    if (!has_begin && has_length) {

        error_set(errp, QERR_MISSING_PARAMETER, "begin");

        return;

    }

#if !defined(WIN32)

    if (strstart(file, "fd:", &p)) {

        fd = monitor_get_fd(cur_mon, p, errp);

        if (fd == -1) {

            return;

        }

    }

#endif

    if  (strstart(file, "file:", &p)) {

        fd = qemu_open(p, O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, S_IRUSR);

        if (fd < 0) {

            error_setg_file_open(errp, errno, p);

            return;

        }

    }

    if (fd == -1) {

        error_set(errp, QERR_INVALID_PARAMETER, "protocol");

        return;

    }

    s = g_malloc0(sizeof(DumpState));

    ret = dump_init(s, fd, paging, has_begin, begin, length, errp);

    if (ret < 0) {

        g_free(s);

        return;

    }

    if (create_vmcore(s) < 0 && !error_is_set(s->errp)) {

        error_set(errp, QERR_IO_ERROR);

    }

    g_free(s);

}


static bool spapr_drc_needed(void *opaque)

{

    sPAPRDRConnector *drc = (sPAPRDRConnector *)opaque;

    sPAPRDRConnectorClass *drck = SPAPR_DR_CONNECTOR_GET_CLASS(drc);

    /* If no dev is plugged in there is no need to migrate the DRC state */

    if (!drc->dev) {

        return false;

    }

    /*

     * We need to migrate the state if it's not equal to the expected

     * long-term state, which is the same as the coldplugged initial

     * state */

    return (drc->state != drck->ready_state);

}


int qcow2_snapshot_delete(BlockDriverState *bs,

                          const char *snapshot_id,

                          const char *name,

                          Error **errp)

{

    BDRVQcowState *s = bs->opaque;

    QCowSnapshot sn;

    int snapshot_index, ret;

    /* Search the snapshot */

    snapshot_index = find_snapshot_by_id_and_name(bs, snapshot_id, name);

    if (snapshot_index < 0) {

        error_setg(errp, "Can't find the snapshot");

        return -ENOENT;

    }

    sn = s->snapshots[snapshot_index];

    /* Remove it from the snapshot list */

    memmove(s->snapshots + snapshot_index,

            s->snapshots + snapshot_index + 1,

            (s->nb_snapshots - snapshot_index - 1) * sizeof(sn));

    s->nb_snapshots--;

    ret = qcow2_write_snapshots(bs);

    if (ret < 0) {

        error_setg(errp, "Failed to remove snapshot from snapshot list");

        return ret;

    }

    /*

     * The snapshot is now unused, clean up. If we fail after this point, we

     * won't recover but just leak clusters.

     */

    g_free(sn.id_str);

    g_free(sn.name);

    /*

     * Now decrease the refcounts of clusters referenced by the snapshot and

     * free the L1 table.

     */

    ret = qcow2_update_snapshot_refcount(bs, sn.l1_table_offset,

                                         sn.l1_size, -1);

    if (ret < 0) {

        error_setg(errp, "Failed to free the cluster and L1 table");

        return ret;

    }

    qcow2_free_clusters(bs, sn.l1_table_offset, sn.l1_size * sizeof(uint64_t),

                        QCOW2_DISCARD_SNAPSHOT);

    /* must update the copied flag on the current cluster offsets */

    ret = qcow2_update_snapshot_refcount(bs, s->l1_table_offset, s->l1_size, 0);

    if (ret < 0) {

        error_setg(errp, "Failed to update snapshot status in disk");

        return ret;

    }

#ifdef DEBUG_ALLOC

    {

        BdrvCheckResult result = {0};

        qcow2_check_refcounts(bs, &result, 0);

    }

#endif

    return 0;

}


int ff_raw_read_header(AVFormatContext *s, AVFormatParameters *ap)

{

    AVStream *st;

    enum CodecID id;

    st = av_new_stream(s, 0);

    if (!st)

        return AVERROR(ENOMEM);

        id = s->iformat->value;

        if (id == CODEC_ID_RAWVIDEO) {

            st->codec->codec_type = AVMEDIA_TYPE_VIDEO;

        } else {

            st->codec->codec_type = AVMEDIA_TYPE_AUDIO;

        }

        st->codec->codec_id = id;

        switch(st->codec->codec_type) {

        case AVMEDIA_TYPE_AUDIO: {

            RawAudioDemuxerContext *s1 = s->priv_data;

#if FF_API_FORMAT_PARAMETERS

            if (ap->sample_rate)

                st->codec->sample_rate = ap->sample_rate;

            if (ap->channels)

                st->codec->channels    = ap->channels;

            else st->codec->channels   = 1;

#endif

            if (s1->sample_rate)

                st->codec->sample_rate = s1->sample_rate;

            if (s1->channels)

                st->codec->channels    = s1->channels;

            st->codec->bits_per_coded_sample = av_get_bits_per_sample(st->codec->codec_id);

            assert(st->codec->bits_per_coded_sample > 0);

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

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

            break;

            }

        case AVMEDIA_TYPE_VIDEO: {

            FFRawVideoDemuxerContext *s1 = s->priv_data;

            int width = 0, height = 0, ret;

            enum PixelFormat pix_fmt;

            if(ap->time_base.num)

                av_set_pts_info(st, 64, ap->time_base.num, ap->time_base.den);

            else

                av_set_pts_info(st, 64, 1, 25);

            if (s1->video_size && (ret = av_parse_video_size(&width, &height, s1->video_size)) < 0) {

                av_log(s, AV_LOG_ERROR, "Couldn't parse video size.\n");

                goto fail;

            }

            if ((pix_fmt = av_get_pix_fmt(s1->pixel_format)) == PIX_FMT_NONE) {

                av_log(s, AV_LOG_ERROR, "No such pixel format: %s.\n", s1->pixel_format);

                ret = AVERROR(EINVAL);

                goto fail;

            }

#if FF_API_FORMAT_PARAMETERS

            if (ap->width > 0)

                width = ap->width;

            if (ap->height > 0)

                height = ap->height;

            if (ap->pix_fmt)

                pix_fmt = ap->pix_fmt;

#endif

            st->codec->width  = width;

            st->codec->height = height;

            st->codec->pix_fmt = pix_fmt;

fail:

            av_freep(&s1->video_size);

            av_freep(&s1->pixel_format);

            return ret;

            }

        default:

            return -1;

        }

    return 0;

}


void mcf_uart_mm_init(MemoryRegion *sysmem,

                      target_phys_addr_t base,

                      qemu_irq irq,

                      CharDriverState *chr)

{

    mcf_uart_state *s;

    s = mcf_uart_init(irq, chr);

    memory_region_init_io(&s->iomem, &mcf_uart_ops, s, "uart", 0x40);

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

}


static void expr_error(Monitor *mon, const char *msg)

{

    monitor_printf(mon, "%s\n", msg);

    siglongjmp(expr_env, 1);

}


static void usb_msd_send_status(MSDState *s, USBPacket *p)

{

    struct usb_msd_csw csw;

    int len;

    csw.sig = cpu_to_le32(0x53425355);

    csw.tag = cpu_to_le32(s->tag);

    csw.residue = s->residue;

    csw.status = s->result;

    len = MIN(sizeof(csw), p->len);

    memcpy(p->data, &csw, len);

}


static int read_access_unit(AVCodecContext *avctx, void* data, int *data_size,

                            AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    MLPDecodeContext *m = avctx->priv_data;

    GetBitContext gb;

    unsigned int length, substr;

    unsigned int substream_start;

    unsigned int header_size = 4;

    unsigned int substr_header_size = 0;

    uint8_t substream_parity_present[MAX_SUBSTREAMS];

    uint16_t substream_data_len[MAX_SUBSTREAMS];

    uint8_t parity_bits;

    if (buf_size < 4)

        return 0;

    length = (AV_RB16(buf) & 0xfff) * 2;

    if (length > buf_size)

        return -1;

    init_get_bits(&gb, (buf + 4), (length - 4) * 8);

    m->is_major_sync_unit = 0;

    if (show_bits_long(&gb, 31) == (0xf8726fba >> 1)) {

        if (read_major_sync(m, &gb) < 0)

            goto error;

        m->is_major_sync_unit = 1;

        header_size += 28;

    }

    if (!m->params_valid) {

        av_log(m->avctx, AV_LOG_WARNING,

               "Stream parameters not seen; skipping frame.\n");

        *data_size = 0;

        return length;

    }

    substream_start = 0;

    for (substr = 0; substr < m->num_substreams; substr++) {

        int extraword_present, checkdata_present, end, nonrestart_substr;

        extraword_present = get_bits1(&gb);

        nonrestart_substr = get_bits1(&gb);

        checkdata_present = get_bits1(&gb);

        skip_bits1(&gb);

        end = get_bits(&gb, 12) * 2;

        substr_header_size += 2;

        if (extraword_present) {

            if (m->avctx->codec_id == CODEC_ID_MLP) {

                av_log(m->avctx, AV_LOG_ERROR, "There must be no extraword for MLP.\n");

                goto error;

            }

            skip_bits(&gb, 16);

            substr_header_size += 2;

        }

        if (!(nonrestart_substr ^ m->is_major_sync_unit)) {

            av_log(m->avctx, AV_LOG_ERROR, "Invalid nonrestart_substr.\n");

            goto error;

        }

        if (end + header_size + substr_header_size > length) {

            av_log(m->avctx, AV_LOG_ERROR,

                   "Indicated length of substream %d data goes off end of "

                   "packet.\n", substr);

            end = length - header_size - substr_header_size;

        }

        if (end < substream_start) {

            av_log(avctx, AV_LOG_ERROR,

                   "Indicated end offset of substream %d data "

                   "is smaller than calculated start offset.\n",

                   substr);

            goto error;

        }

        if (substr > m->max_decoded_substream)

            continue;

        substream_parity_present[substr] = checkdata_present;

        substream_data_len[substr] = end - substream_start;

        substream_start = end;

    }

    parity_bits  = ff_mlp_calculate_parity(buf, 4);

    parity_bits ^= ff_mlp_calculate_parity(buf + header_size, substr_header_size);

    if ((((parity_bits >> 4) ^ parity_bits) & 0xF) != 0xF) {

        av_log(avctx, AV_LOG_ERROR, "Parity check failed.\n");

        goto error;

    }

    buf += header_size + substr_header_size;

    for (substr = 0; substr <= m->max_decoded_substream; substr++) {

        SubStream *s = &m->substream[substr];

        init_get_bits(&gb, buf, substream_data_len[substr] * 8);

        m->matrix_changed = 0;

        memset(m->filter_changed, 0, sizeof(m->filter_changed));

        s->blockpos = 0;

        do {

            if (get_bits1(&gb)) {

                if (get_bits1(&gb)) {

                    /* A restart header should be present. */

                    if (read_restart_header(m, &gb, buf, substr) < 0)

                        goto next_substr;

                    s->restart_seen = 1;

                }

                if (!s->restart_seen)

                    goto next_substr;

                if (read_decoding_params(m, &gb, substr) < 0)

                    goto next_substr;

            }

            if (!s->restart_seen)

                goto next_substr;

            if (read_block_data(m, &gb, substr) < 0)

                return -1;

            if (get_bits_count(&gb) >= substream_data_len[substr] * 8)

                goto substream_length_mismatch;

        } while (!get_bits1(&gb));

        skip_bits(&gb, (-get_bits_count(&gb)) & 15);

        if (substream_data_len[substr] * 8 - get_bits_count(&gb) >= 32) {

            int shorten_by;

            if (get_bits(&gb, 16) != 0xD234)

                return -1;

            shorten_by = get_bits(&gb, 16);

            if      (m->avctx->codec_id == CODEC_ID_TRUEHD && shorten_by  & 0x2000)

                s->blockpos -= FFMIN(shorten_by & 0x1FFF, s->blockpos);

            else if (m->avctx->codec_id == CODEC_ID_MLP    && shorten_by != 0xD234)

                return -1;

            if (substr == m->max_decoded_substream)

                av_log(m->avctx, AV_LOG_INFO, "End of stream indicated.\n");

        }

        if (substream_parity_present[substr]) {

            uint8_t parity, checksum;

            if (substream_data_len[substr] * 8 - get_bits_count(&gb) != 16)

                goto substream_length_mismatch;

            parity   = ff_mlp_calculate_parity(buf, substream_data_len[substr] - 2);

            checksum = ff_mlp_checksum8       (buf, substream_data_len[substr] - 2);

            if ((get_bits(&gb, 8) ^ parity) != 0xa9    )

                av_log(m->avctx, AV_LOG_ERROR, "Substream %d parity check failed.\n", substr);

            if ( get_bits(&gb, 8)           != checksum)

                av_log(m->avctx, AV_LOG_ERROR, "Substream %d checksum failed.\n"    , substr);

        }

        if (substream_data_len[substr] * 8 != get_bits_count(&gb))

            goto substream_length_mismatch;

next_substr:

        if (!s->restart_seen)

            av_log(m->avctx, AV_LOG_ERROR,

                   "No restart header present in substream %d.\n", substr);

        buf += substream_data_len[substr];

    }

    rematrix_channels(m, m->max_decoded_substream);

    if (output_data(m, m->max_decoded_substream, data, data_size) < 0)

        return -1;

    return length;

substream_length_mismatch:

    av_log(m->avctx, AV_LOG_ERROR, "substream %d length mismatch\n", substr);

    return -1;

error:

    m->params_valid = 0;

    return -1;

}


static void sunrast_image_write_image(AVCodecContext *avctx,

                                      const uint8_t *pixels,

                                      const uint32_t *palette_data,

                                      int linesize)

{

    SUNRASTContext *s = avctx->priv_data;

    const uint8_t *ptr;

    int len, alen, x;

    if (s->maplength) {     // palettized

        PutByteContext pb_r, pb_g;

        int len = s->maplength / 3;

        pb_r = s->p;

        bytestream2_skip_p(&s->p, len);

        pb_g = s->p;

        bytestream2_skip_p(&s->p, len);

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

            uint32_t pixel = palette_data[x];

            bytestream2_put_byteu(&pb_r, (pixel >> 16) & 0xFF);

            bytestream2_put_byteu(&pb_g, (pixel >> 8)  & 0xFF);

            bytestream2_put_byteu(&s->p,  pixel        & 0xFF);

        }

    }

    len  = (s->depth * avctx->width + 7) >> 3;

    alen = len + (len & 1);

    ptr  = pixels;

     if (s->type == RT_BYTE_ENCODED) {

        uint8_t value, value2;

        int run;

        const uint8_t *end = pixels + avctx->height * linesize;

        ptr = pixels;

#define GET_VALUE ptr >= end ? 0 : x >= len ? ptr[len-1] : ptr[x]

        x = 0;

        value2 = GET_VALUE;

        while (ptr < end) {

            run = 1;

            value = value2;

            x++;

            if (x >= alen) {

                x = 0;

                ptr += linesize;

            }

            value2 = GET_VALUE;

            while (value2 == value && run < 256 && ptr < end) {

                x++;

                run++;

                if (x >= alen) {

                    x = 0;

                    ptr += linesize;

                }

                value2 = GET_VALUE;

            }

            if (run > 2 || value == RLE_TRIGGER) {

                bytestream2_put_byteu(&s->p, RLE_TRIGGER);

                bytestream2_put_byteu(&s->p, run - 1);

                if (run > 1)

                    bytestream2_put_byteu(&s->p, value);

            } else if (run == 1) {

                bytestream2_put_byteu(&s->p, value);

            } else

                bytestream2_put_be16u(&s->p, (value << 8) | value);

        }

        // update data length for header

        s->length = bytestream2_tell_p(&s->p) - 32 - s->maplength;

    } else {

        int y;

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

            bytestream2_put_buffer(&s->p, ptr, len);

            if (len < alen)

                bytestream2_put_byteu(&s->p, 0);

            ptr += linesize;

        }

    }

}


static NetSocketState *net_socket_fd_init(VLANState *vlan,

                                          const char *model, const char *name,

                                          int fd, int is_connected)

{

    int so_type=-1, optlen=sizeof(so_type);

    if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,

        (socklen_t *)&optlen)< 0) {

	fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);

	return NULL;

    }

    switch(so_type) {

    case SOCK_DGRAM:

        return net_socket_fd_init_dgram(vlan, model, name, fd, is_connected);

    case SOCK_STREAM:

        return net_socket_fd_init_stream(vlan, model, name, fd, is_connected);

    default:

        /* who knows ... this could be a eg. a pty, do warn and continue as stream */

        fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);

        return net_socket_fd_init_stream(vlan, model, name, fd, is_connected);

    }

    return NULL;

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);

    k->init = pci_ich9_ahci_init;

    k->exit = pci_ich9_uninit;

    k->config_write = pci_ich9_write_config;

    k->vendor_id = PCI_VENDOR_ID_INTEL;

    k->device_id = PCI_DEVICE_ID_INTEL_82801IR;

    k->revision = 0x02;

    k->class_id = PCI_CLASS_STORAGE_SATA;

    dc->alias = "ahci";

    dc->vmsd = &vmstate_ahci;

}


static int sol_probe(AVProbeData *p)

{

    /* check file header */

    uint16_t magic;

    if (p->buf_size <= 14)

        return 0;

    magic=le2me_16(*((uint16_t*)p->buf));

    if ((magic == 0x0B8D || magic == 0x0C0D || magic == 0x0C8D) &&

        p->buf[2] == 'S' && p->buf[3] == 'O' &&

        p->buf[4] == 'L' && p->buf[5] == 0)

        return AVPROBE_SCORE_MAX;

    else

        return 0;

}


static int daala_header(AVFormatContext *s, int idx)

{

    int i, err;

    uint8_t *cdp;

    GetByteContext gb;

    AVRational timebase;

    struct ogg *ogg        = s->priv_data;

    struct ogg_stream *os  = ogg->streams + idx;

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

    int cds                = st->codec->extradata_size + os->psize + 2;

    DaalaInfoHeader *hdr   = os->private;

    if (!(os->buf[os->pstart] & 0x80))

        return 0;

    if (!hdr) {

        hdr = av_mallocz(sizeof(*hdr));

        if (!hdr)

            return AVERROR(ENOMEM);

        os->private = hdr;

    switch (os->buf[os->pstart]) {

    case 0x80:

        bytestream2_init(&gb, os->buf + os->pstart, os->psize);

        bytestream2_skip(&gb, ff_daala_codec.magicsize);

        hdr->version_maj = bytestream2_get_byte(&gb);

        hdr->version_min = bytestream2_get_byte(&gb);

        hdr->version_sub = bytestream2_get_byte(&gb);

        st->codec->width  = bytestream2_get_ne32(&gb);

        st->codec->height = bytestream2_get_ne32(&gb);

        st->sample_aspect_ratio.num = bytestream2_get_ne32(&gb);

        st->sample_aspect_ratio.den = bytestream2_get_ne32(&gb);

        timebase.num = bytestream2_get_ne32(&gb);

        timebase.den = bytestream2_get_ne32(&gb);

        if (timebase.num < 0 && timebase.den < 0) {

            av_log(s, AV_LOG_WARNING, "Invalid timebase, assuming 30 FPS\n");

            timebase.num = 1;

            timebase.den = 30;

        avpriv_set_pts_info(st, 64, timebase.den, timebase.num);

        hdr->frame_duration = bytestream2_get_ne32(&gb);

        hdr->gpshift = bytestream2_get_byte(&gb);

        hdr->gpmask  = (1 << hdr->gpshift) - 1;

        hdr->format.depth  = 8 + 2*(bytestream2_get_byte(&gb)-1);

        hdr->fpr = bytestream2_get_byte(&gb);

        hdr->format.planes = bytestream2_get_byte(&gb);

        for (i = 0; i < hdr->format.planes; i++) {

            hdr->format.xdec[i] = bytestream2_get_byte(&gb);

            hdr->format.ydec[i] = bytestream2_get_byte(&gb);

        if ((st->codec->pix_fmt = daala_match_pix_fmt(&hdr->format)) < 0)

            av_log(s, AV_LOG_ERROR, "Unsupported pixel format - %i %i\n",

                   hdr->format.depth, hdr->format.planes);

        st->codec->codec_id   = AV_CODEC_ID_DAALA;

        st->codec->codec_type = AVMEDIA_TYPE_VIDEO;

        st->need_parsing      = AVSTREAM_PARSE_HEADERS;

        hdr->init_d = 1;

        break;

    case 0x81:

        if (!hdr->init_d)

        ff_vorbis_stream_comment(s, st,

                                 os->buf + os->pstart + ff_daala_codec.magicsize,

                                 os->psize - ff_daala_codec.magicsize);

        break;

    case 0x82:

        if (!hdr->init_d)

        break;

    default:

        av_log(s, AV_LOG_ERROR, "Unknown header type %X\n", os->buf[os->pstart]);

        break;

    if ((err = av_reallocp(&st->codec->extradata,

                           cds + AV_INPUT_BUFFER_PADDING_SIZE)) < 0) {

        st->codec->extradata_size = 0;

        return err;

    memset(st->codec->extradata + cds, 0, AV_INPUT_BUFFER_PADDING_SIZE);

    cdp    = st->codec->extradata + st->codec->extradata_size;

    *cdp++ = os->psize >> 8;

    *cdp++ = os->psize & 0xff;

    memcpy(cdp, os->buf + os->pstart, os->psize);

    st->codec->extradata_size = cds;

    return 1;


static int vorbis_parse_setup_hdr_mappings(vorbis_context *vc) {

    GetBitContext *gb=&vc->gb;

    uint_fast8_t i, j;

    vc->mapping_count=get_bits(gb, 6)+1;

    vc->mappings=av_mallocz(vc->mapping_count * sizeof(vorbis_mapping));

    AV_DEBUG(" There are %d mappings. \n", vc->mapping_count);

    for(i=0;i<vc->mapping_count;++i) {

        vorbis_mapping *mapping_setup=&vc->mappings[i];

        if (get_bits(gb, 16)) {

            av_log(vc->avccontext, AV_LOG_ERROR, "Other mappings than type 0 are not compliant with the Vorbis I specification. \n");

            return 1;

        }

        if (get_bits1(gb)) {

            mapping_setup->submaps=get_bits(gb, 4)+1;

        } else {

            mapping_setup->submaps=1;

        }

        if (get_bits1(gb)) {

            mapping_setup->coupling_steps=get_bits(gb, 8)+1;

            mapping_setup->magnitude=av_mallocz(mapping_setup->coupling_steps * sizeof(uint_fast8_t));

            mapping_setup->angle    =av_mallocz(mapping_setup->coupling_steps * sizeof(uint_fast8_t));

            for(j=0;j<mapping_setup->coupling_steps;++j) {

                mapping_setup->magnitude[j]=get_bits(gb, ilog(vc->audio_channels-1));

                mapping_setup->angle[j]=get_bits(gb, ilog(vc->audio_channels-1));

                // FIXME: sanity checks

            }

        } else {

            mapping_setup->coupling_steps=0;

        }

        AV_DEBUG("   %d mapping coupling steps: %d \n", i, mapping_setup->coupling_steps);

        if(get_bits(gb, 2)) {

            av_log(vc->avccontext, AV_LOG_ERROR, "%d. mapping setup data invalid. \n", i);

            return 1; // following spec.

        }

        if (mapping_setup->submaps>1) {

            mapping_setup->mux=av_mallocz(vc->audio_channels * sizeof(uint_fast8_t));

            for(j=0;j<vc->audio_channels;++j) {

                mapping_setup->mux[j]=get_bits(gb, 4);

            }

        }

        for(j=0;j<mapping_setup->submaps;++j) {

            skip_bits(gb, 8); // FIXME check?

            mapping_setup->submap_floor[j]=get_bits(gb, 8);

            mapping_setup->submap_residue[j]=get_bits(gb, 8);

            AV_DEBUG("   %d mapping %d submap : floor %d, residue %d \n", i, j, mapping_setup->submap_floor[j], mapping_setup->submap_residue[j]);

        }

    }

    return 0;

}


static target_long monitor_get_psr (const struct MonitorDef *md, int val)

{

    CPUState *env = mon_get_cpu();

    if (!env)

        return 0;

    return GET_PSR(env);

}


static int qemu_rdma_connect(RDMAContext *rdma, Error **errp)

{

    RDMACapabilities cap = {

                                .version = RDMA_CONTROL_VERSION_CURRENT,

                                .flags = 0,

                           };

    struct rdma_conn_param conn_param = { .initiator_depth = 2,

                                          .retry_count = 5,

                                          .private_data = &cap,

                                          .private_data_len = sizeof(cap),

                                        };

    struct rdma_cm_event *cm_event;

    int ret;

    /*

     * Only negotiate the capability with destination if the user

     * on the source first requested the capability.

     */

    if (rdma->pin_all) {

        trace_qemu_rdma_connect_pin_all_requested();

        cap.flags |= RDMA_CAPABILITY_PIN_ALL;

    }

    caps_to_network(&cap);

    ret = rdma_connect(rdma->cm_id, &conn_param);

    if (ret) {

        perror("rdma_connect");

        ERROR(errp, "connecting to destination!");

        goto err_rdma_source_connect;

    }

    ret = rdma_get_cm_event(rdma->channel, &cm_event);

    if (ret) {

        perror("rdma_get_cm_event after rdma_connect");

        ERROR(errp, "connecting to destination!");

        rdma_ack_cm_event(cm_event);

        goto err_rdma_source_connect;

    }

    if (cm_event->event != RDMA_CM_EVENT_ESTABLISHED) {

        perror("rdma_get_cm_event != EVENT_ESTABLISHED after rdma_connect");

        ERROR(errp, "connecting to destination!");

        rdma_ack_cm_event(cm_event);

        goto err_rdma_source_connect;

    }

    rdma->connected = true;

    memcpy(&cap, cm_event->param.conn.private_data, sizeof(cap));

    network_to_caps(&cap);

    /*

     * Verify that the *requested* capabilities are supported by the destination

     * and disable them otherwise.

     */

    if (rdma->pin_all && !(cap.flags & RDMA_CAPABILITY_PIN_ALL)) {

        ERROR(errp, "Server cannot support pinning all memory. "

                        "Will register memory dynamically.");

        rdma->pin_all = false;

    }

    trace_qemu_rdma_connect_pin_all_outcome(rdma->pin_all);

    rdma_ack_cm_event(cm_event);

    ret = qemu_rdma_post_recv_control(rdma, RDMA_WRID_READY);

    if (ret) {

        ERROR(errp, "posting second control recv!");

        goto err_rdma_source_connect;

    }

    rdma->control_ready_expected = 1;

    rdma->nb_sent = 0;

    return 0;

err_rdma_source_connect:

    qemu_rdma_cleanup(rdma);

    return -1;

}


opts_start_list(Visitor *v, const char *name, Error **errp)

{

    OptsVisitor *ov = to_ov(v);

    /* we can't traverse a list in a list */

    assert(ov->list_mode == LM_NONE);

    ov->repeated_opts = lookup_distinct(ov, name, errp);

    if (ov->repeated_opts != NULL) {

        ov->list_mode = LM_STARTED;

    }

}


void commit_start(const char *job_id, BlockDriverState *bs,

                  BlockDriverState *base, BlockDriverState *top, int64_t speed,

                  BlockdevOnError on_error, BlockCompletionFunc *cb,

                  void *opaque, const char *backing_file_str, Error **errp)

{

    CommitBlockJob *s;

    BlockReopenQueue *reopen_queue = NULL;

    int orig_overlay_flags;

    int orig_base_flags;

    BlockDriverState *overlay_bs;

    Error *local_err = NULL;

    assert(top != bs);

    if (top == base) {

        error_setg(errp, "Invalid files for merge: top and base are the same");

        return;

    }

    overlay_bs = bdrv_find_overlay(bs, top);

    if (overlay_bs == NULL) {

        error_setg(errp, "Could not find overlay image for %s:", top->filename);

        return;

    }

    s = block_job_create(job_id, &commit_job_driver, bs, speed,

                         cb, opaque, errp);

    if (!s) {

        return;

    }

    orig_base_flags    = bdrv_get_flags(base);

    orig_overlay_flags = bdrv_get_flags(overlay_bs);

    /* convert base & overlay_bs to r/w, if necessary */

    if (!(orig_overlay_flags & BDRV_O_RDWR)) {

        reopen_queue = bdrv_reopen_queue(reopen_queue, overlay_bs, NULL,

                                         orig_overlay_flags | BDRV_O_RDWR);

    }

    if (!(orig_base_flags & BDRV_O_RDWR)) {

        reopen_queue = bdrv_reopen_queue(reopen_queue, base, NULL,

                                         orig_base_flags | BDRV_O_RDWR);

    }

    if (reopen_queue) {

        bdrv_reopen_multiple(reopen_queue, &local_err);

        if (local_err != NULL) {

            error_propagate(errp, local_err);

            block_job_unref(&s->common);

            return;

        }

    }

    s->base = blk_new();

    blk_insert_bs(s->base, base);

    s->top = blk_new();

    blk_insert_bs(s->top, top);

    s->active = bs;

    s->base_flags          = orig_base_flags;

    s->orig_overlay_flags  = orig_overlay_flags;

    s->backing_file_str = g_strdup(backing_file_str);

    s->on_error = on_error;

    s->common.co = qemu_coroutine_create(commit_run, s);

    trace_commit_start(bs, base, top, s, s->common.co, opaque);

    qemu_coroutine_enter(s->common.co);

}


static bool bdrv_drain_recurse(BlockDriverState *bs)

{

    BdrvChild *child;

    bool waited;

    waited = bdrv_drain_poll(bs);

    if (bs->drv && bs->drv->bdrv_drain) {

        bs->drv->bdrv_drain(bs);

    }

    QLIST_FOREACH(child, &bs->children, next) {

        waited |= bdrv_drain_recurse(child->bs);

    }

    return waited;

}


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

{

    I2CSlaveClass *k = I2C_SLAVE_CLASS(klass);

    k->init = pxa2xx_i2c_slave_init;

    k->event = pxa2xx_i2c_event;

    k->recv = pxa2xx_i2c_rx;

    k->send = pxa2xx_i2c_tx;

}


static inline int32_t efsctsi(uint32_t val)

{

    CPU_FloatU u;

    u.l = val;

    /* NaN are not treated the same way IEEE 754 does */

    if (unlikely(float32_is_nan(u.f)))

        return 0;

    return float32_to_int32(u.f, &env->vec_status);

}


static inline int handle_cpu_signal(unsigned long pc,

                                    unsigned long address,

                                    int is_write,

                                    sigset_t *old_set)

{

#if defined(DEBUG_SIGNAL)

    printf("qemu: SIGSEGV pc=0x%08lx address=%08lx wr=%d oldset=0x%08lx\n",

           pc, address, is_write, *(unsigned long *)old_set);

#endif

    /* XXX: locking issue */

    if (is_write && page_unprotect(address)) {

        sigprocmask(SIG_SETMASK, old_set, NULL);

        return 1;

    }

    if (pc >= (unsigned long)code_gen_buffer &&

        pc < (unsigned long)code_gen_buffer + CODE_GEN_BUFFER_SIZE) {

        /* the PC is inside the translated code. It means that we have

           a virtual CPU fault */

        /* we restore the process signal mask as the sigreturn should

           do it */

        sigprocmask(SIG_SETMASK, old_set, NULL);

        /* XXX: need to compute virtual pc position by retranslating

           code. The rest of the CPU state should be correct. */

        env->cr2 = address;

        raise_exception_err(EXCP0E_PAGE, 4 | (is_write << 1));

        /* never comes here */

        return 1;

    } else {

        return 0;

    }

}


void DBDMA_schedule(void)

{

    CPUState *env = cpu_single_env;

    if (env)

        cpu_interrupt(env, CPU_INTERRUPT_EXIT);

}


void helper_fdmulq(CPUSPARCState *env, float64 src1, float64 src2)

{

    clear_float_exceptions(env);

    QT0 = float128_mul(float64_to_float128(src1, &env->fp_status),

                       float64_to_float128(src2, &env->fp_status),

                       &env->fp_status);

    check_ieee_exceptions(env);

}


void helper_iret_real(int shift)

{

    uint32_t sp, new_cs, new_eip, new_eflags, new_esp;

    uint8_t *ssp;

    int eflags_mask;

    sp = env->regs[R_ESP] & 0xffff;

    ssp = env->segs[R_SS].base + sp;

    if (shift == 1) {

        /* 32 bits */

        new_eflags = ldl(ssp + 8);

        new_cs = ldl(ssp + 4) & 0xffff;

        new_eip = ldl(ssp) & 0xffff;

    } else {

        /* 16 bits */

        new_eflags = lduw(ssp + 4);

        new_cs = lduw(ssp + 2);

        new_eip = lduw(ssp);

    }

    new_esp = sp + (6 << shift);

    env->regs[R_ESP] = (env->regs[R_ESP] & 0xffff0000) |

        (new_esp & 0xffff);

    load_seg_vm(R_CS, new_cs);

    env->eip = new_eip;

    eflags_mask = FL_UPDATE_CPL0_MASK;

    if (shift == 0)

        eflags_mask &= 0xffff;

    load_eflags(new_eflags, eflags_mask);

}


static void residue_encode(venc_context_t * venc, residue_t * rc, PutBitContext * pb, float * coeffs, int samples, int real_ch) {

    int pass, i, j, p, k;

    int psize = rc->partition_size;

    int partitions = (rc->end - rc->begin) / psize;

    int channels = (rc->type == 2) ? 1 : real_ch;

    int classes[channels][partitions];

    int classwords = venc->codebooks[rc->classbook].ndimentions;

    assert(rc->type == 2);

    assert(real_ch == 2);

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

        float max1 = 0., max2 = 0.;

        int s = rc->begin + p * psize;

        for (k = s; k < s + psize; k += 2) {

            max1 = FFMAX(max1, fabs(coeffs[          k / real_ch]));

            max2 = FFMAX(max2, fabs(coeffs[samples + k / real_ch]));

        }

        for (i = 0; i < rc->classifications - 1; i++) {

            if (max1 < rc->maxes[i][0] && max2 < rc->maxes[i][1]) break;

        }

        classes[0][p] = i;

    }

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

        p = 0;

        while (p < partitions) {

            if (pass == 0) for (j = 0; j < channels; j++) {

                codebook_t * book = &venc->codebooks[rc->classbook];

                int entry = 0;

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

                    entry *= rc->classifications;

                    entry += classes[j][p + i];

                }

                put_codeword(pb, book, entry);

            }

            for (i = 0; i < classwords && p < partitions; i++, p++) {

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

                    int nbook = rc->books[classes[j][p]][pass];

                    codebook_t * book = &venc->codebooks[nbook];

                    float * buf = coeffs + samples*j + rc->begin + p*psize;

                    if (nbook == -1) continue;

                    assert(rc->type == 0 || rc->type == 2);

                    assert(!(psize % book->ndimentions));

                    if (rc->type == 0) {

                        for (k = 0; k < psize; k += book->ndimentions) {

                            float * a = put_vector(book, pb, &buf[k]);

                            int l;

                            for (l = 0; l < book->ndimentions; l++) buf[k + l] -= a[l];

                        }

                    } else {

                        for (k = 0; k < psize; k += book->ndimentions) {

                            int dim = book->ndimentions, s = rc->begin + p * psize + k, l;

                            float vec[dim], * a = vec;

                            for (l = s; l < s + dim; l++)

                                *a++ = coeffs[(l % real_ch) * samples + l / real_ch];

                            a = put_vector(book, pb, vec);

                            for (l = s; l < s + dim; l++)

                                coeffs[(l % real_ch) * samples + l / real_ch] -= *a++;

                        }

                    }

                }

            }

        }

    }

}


static void process_ncq_command(AHCIState *s, int port, uint8_t *cmd_fis,

                                uint8_t slot)

{

    AHCIDevice *ad = &s->dev[port];

    IDEState *ide_state = &ad->port.ifs[0];

    NCQFrame *ncq_fis = (NCQFrame*)cmd_fis;

    uint8_t tag = ncq_fis->tag >> 3;

    NCQTransferState *ncq_tfs = &ad->ncq_tfs[tag];

    size_t size;

    g_assert(is_ncq(ncq_fis->command));

    if (ncq_tfs->used) {

        /* error - already in use */

        fprintf(stderr, "%s: tag %d already used\n", __FUNCTION__, tag);

        return;

    }

    ncq_tfs->used = 1;

    ncq_tfs->drive = ad;

    ncq_tfs->slot = slot;

    ncq_tfs->cmdh = &((AHCICmdHdr *)ad->lst)[slot];

    ncq_tfs->cmd = ncq_fis->command;

    ncq_tfs->lba = ((uint64_t)ncq_fis->lba5 << 40) |

                   ((uint64_t)ncq_fis->lba4 << 32) |

                   ((uint64_t)ncq_fis->lba3 << 24) |

                   ((uint64_t)ncq_fis->lba2 << 16) |

                   ((uint64_t)ncq_fis->lba1 << 8) |

                   (uint64_t)ncq_fis->lba0;

    ncq_tfs->tag = tag;

    /* Sanity-check the NCQ packet */

    if (tag != slot) {

        DPRINTF(port, "Warn: NCQ slot (%d) did not match the given tag (%d)\n",

                slot, tag);

    }

    if (ncq_fis->aux0 || ncq_fis->aux1 || ncq_fis->aux2 || ncq_fis->aux3) {

        DPRINTF(port, "Warn: Attempt to use NCQ auxiliary fields.\n");

    }

    if (ncq_fis->prio || ncq_fis->icc) {

        DPRINTF(port, "Warn: Unsupported attempt to use PRIO/ICC fields\n");

    }

    if (ncq_fis->fua & NCQ_FIS_FUA_MASK) {

        DPRINTF(port, "Warn: Unsupported attempt to use Force Unit Access\n");

    }

    if (ncq_fis->tag & NCQ_FIS_RARC_MASK) {

        DPRINTF(port, "Warn: Unsupported attempt to use Rebuild Assist\n");

    }

    ncq_tfs->sector_count = ((ncq_fis->sector_count_high << 8) |

                             ncq_fis->sector_count_low);

    if (!ncq_tfs->sector_count) {

        ncq_tfs->sector_count = 0x10000;

    }

    size = ncq_tfs->sector_count * 512;

    ahci_populate_sglist(ad, &ncq_tfs->sglist, ncq_tfs->cmdh, size, 0);

    if (ncq_tfs->sglist.size < size) {

        error_report("ahci: PRDT length for NCQ command (0x%zx) "

                     "is smaller than the requested size (0x%zx)",

                     ncq_tfs->sglist.size, size);

        qemu_sglist_destroy(&ncq_tfs->sglist);

        ncq_err(ncq_tfs);

        ahci_trigger_irq(ad->hba, ad, PORT_IRQ_OVERFLOW);

        return;

    } else if (ncq_tfs->sglist.size != size) {

        DPRINTF(port, "Warn: PRDTL (0x%zx)"

                " does not match requested size (0x%zx)",

                ncq_tfs->sglist.size, size);

    }

    DPRINTF(port, "NCQ transfer LBA from %"PRId64" to %"PRId64", "

            "drive max %"PRId64"\n",

            ncq_tfs->lba, ncq_tfs->lba + ncq_tfs->sector_count - 1,

            ide_state->nb_sectors - 1);

    execute_ncq_command(ncq_tfs);

}


USBDevice *usb_msd_init(const char *filename)

{

    static int nr=0;

    char id[8];

    QemuOpts *opts;

    DriveInfo *dinfo;

    USBDevice *dev;

    int fatal_error;

    const char *p1;

    char fmt[32];

    /* parse -usbdevice disk: syntax into drive opts */

    snprintf(id, sizeof(id), "usb%d", nr++);

    opts = qemu_opts_create(&qemu_drive_opts, id, 0);

    p1 = strchr(filename, ':');

    if (p1++) {

        const char *p2;

        if (strstart(filename, "format=", &p2)) {

            int len = MIN(p1 - p2, sizeof(fmt));

            pstrcpy(fmt, len, p2);

            qemu_opt_set(opts, "format", fmt);

        } else if (*filename != ':') {

            printf("unrecognized USB mass-storage option %s\n", filename);

            return NULL;

        }

        filename = p1;

    }

    if (!*filename) {

        printf("block device specification needed\n");

        return NULL;

    }

    qemu_opt_set(opts, "file", filename);

    qemu_opt_set(opts, "if", "none");

    /* create host drive */

    dinfo = drive_init(opts, NULL, &fatal_error);

    if (!dinfo) {

        qemu_opts_del(opts);

        return NULL;

    }

    /* create guest device */

    dev = usb_create(NULL /* FIXME */, "QEMU USB MSD");

    qdev_prop_set_drive(&dev->qdev, "drive", dinfo);

    qdev_init(&dev->qdev);

    return dev;

}


sowrite(so)

	struct socket *so;

{

	int  n,nn;

	struct sbuf *sb = &so->so_rcv;

	int len = sb->sb_cc;

	struct iovec iov[2];

	DEBUG_CALL("sowrite");

	DEBUG_ARG("so = %lx", (long)so);

	if (so->so_urgc) {

		sosendoob(so);

		if (sb->sb_cc == 0)

			return 0;

	}

	/*

	 * No need to check if there's something to write,

	 * sowrite wouldn't have been called otherwise

	 */

        len = sb->sb_cc;

	iov[0].iov_base = sb->sb_rptr;

	if (sb->sb_rptr < sb->sb_wptr) {

		iov[0].iov_len = sb->sb_wptr - sb->sb_rptr;

		/* Should never succeed, but... */

		if (iov[0].iov_len > len) iov[0].iov_len = len;

		n = 1;

	} else {

		iov[0].iov_len = (sb->sb_data + sb->sb_datalen) - sb->sb_rptr;

		if (iov[0].iov_len > len) iov[0].iov_len = len;

		len -= iov[0].iov_len;

		if (len) {

			iov[1].iov_base = sb->sb_data;

			iov[1].iov_len = sb->sb_wptr - sb->sb_data;

			if (iov[1].iov_len > len) iov[1].iov_len = len;

			n = 2;

		} else

			n = 1;

	}

	/* Check if there's urgent data to send, and if so, send it */

#ifdef HAVE_READV

	nn = writev(so->s, (const struct iovec *)iov, n);

	DEBUG_MISC((dfd, "  ... wrote nn = %d bytes\n", nn));

#else

	nn = send(so->s, iov[0].iov_base, iov[0].iov_len,0);

#endif

	/* This should never happen, but people tell me it does *shrug* */

	if (nn < 0 && (errno == EAGAIN || errno == EINTR))

		return 0;

	if (nn <= 0) {

		DEBUG_MISC((dfd, " --- sowrite disconnected, so->so_state = %x, errno = %d\n",

			so->so_state, errno));

		sofcantsendmore(so);

		tcp_sockclosed(sototcpcb(so));

		return -1;

	}

#ifndef HAVE_READV

	if (n == 2 && nn == iov[0].iov_len) {

            int ret;

            ret = send(so->s, iov[1].iov_base, iov[1].iov_len,0);

            if (ret > 0)

                nn += ret;

        }

        DEBUG_MISC((dfd, "  ... wrote nn = %d bytes\n", nn));

#endif

	/* Update sbuf */

	sb->sb_cc -= nn;

	sb->sb_rptr += nn;

	if (sb->sb_rptr >= (sb->sb_data + sb->sb_datalen))

		sb->sb_rptr -= sb->sb_datalen;

	/*

	 * If in DRAIN mode, and there's no more data, set

	 * it CANTSENDMORE

	 */

	if ((so->so_state & SS_FWDRAIN) && sb->sb_cc == 0)

		sofcantsendmore(so);

	return nn;

}


static void rtc_get_date(Object *obj, Visitor *v, void *opaque,

                         const char *name, Error **errp)

{

    Error *err = NULL;

    RTCState *s = MC146818_RTC(obj);

    struct tm current_tm;

    rtc_update_time(s);

    rtc_get_time(s, &current_tm);

    visit_start_struct(v, NULL, "struct tm", name, 0, &err);

    if (err) {

        goto out;

    }

    visit_type_int32(v, &current_tm.tm_year, "tm_year", &err);

    visit_type_int32(v, &current_tm.tm_mon, "tm_mon", &err);

    visit_type_int32(v, &current_tm.tm_mday, "tm_mday", &err);

    visit_type_int32(v, &current_tm.tm_hour, "tm_hour", &err);

    visit_type_int32(v, &current_tm.tm_min, "tm_min", &err);

    visit_type_int32(v, &current_tm.tm_sec, "tm_sec", &err);

    visit_end_struct(v, &err);

out:

    error_propagate(errp, err);

}


static void ff_compute_band_indexes(MPADecodeContext *s, GranuleDef *g)

{

    if (g->block_type == 2) {

        if (g->switch_point) {

            /* if switched mode, we handle the 36 first samples as

                long blocks.  For 8000Hz, we handle the 72 first

                exponents as long blocks */

            if (s->sample_rate_index <= 2)

                g->long_end = 8;

            else

                g->long_end = 6;

            g->short_start = 2 + (s->sample_rate_index != 8);

        } else {

            g->long_end    = 0;

            g->short_start = 0;

        }

    } else {

        g->short_start = 13;

        g->long_end    = 22;

    }

}


static uint16_t phys_section_add(MemoryRegionSection *section)

{

    /* The physical section number is ORed with a page-aligned

     * pointer to produce the iotlb entries.  Thus it should

     * never overflow into the page-aligned value.

     */

    assert(next_map.sections_nb < TARGET_PAGE_SIZE);

    if (next_map.sections_nb == next_map.sections_nb_alloc) {

        next_map.sections_nb_alloc = MAX(next_map.sections_nb_alloc * 2,

                                         16);

        next_map.sections = g_renew(MemoryRegionSection, next_map.sections,

                                    next_map.sections_nb_alloc);

    }

    next_map.sections[next_map.sections_nb] = *section;

    memory_region_ref(section->mr);

    return next_map.sections_nb++;

}


static uint32_t intel_hda_mmio_readb(void *opaque, target_phys_addr_t addr)

{

    IntelHDAState *d = opaque;

    const IntelHDAReg *reg = intel_hda_reg_find(d, addr);

    return intel_hda_reg_read(d, reg, 0xff);

}


static av_cold int vaapi_encode_h264_init_fixed_qp(AVCodecContext *avctx)

{

    VAAPIEncodeContext      *ctx = avctx->priv_data;

    VAAPIEncodeH264Context *priv = ctx->priv_data;

    VAAPIEncodeH264Options  *opt = ctx->codec_options;

    priv->fixed_qp_p = opt->qp;

    if (avctx->i_quant_factor > 0.0)

        priv->fixed_qp_idr = (int)((priv->fixed_qp_p * avctx->i_quant_factor +

                                    avctx->i_quant_offset) + 0.5);

    else

        priv->fixed_qp_idr = priv->fixed_qp_p;

    if (avctx->b_quant_factor > 0.0)

        priv->fixed_qp_b = (int)((priv->fixed_qp_p * avctx->b_quant_factor +

                                  avctx->b_quant_offset) + 0.5);

    else

        priv->fixed_qp_b = priv->fixed_qp_p;

    av_log(avctx, AV_LOG_DEBUG, "Using fixed QP = "

           "%d / %d / %d for IDR- / P- / B-frames.\n",

           priv->fixed_qp_idr, priv->fixed_qp_p, priv->fixed_qp_b);

    return 0;

}


static bool is_zero(BlockDriverState *bs, int64_t offset, int64_t bytes)

{

    int nr;

    int64_t res;

    int64_t start;

    /* TODO: Widening to sector boundaries should only be needed as

     * long as we can't query finer granularity. */

    start = QEMU_ALIGN_DOWN(offset, BDRV_SECTOR_SIZE);

    bytes = QEMU_ALIGN_UP(offset + bytes, BDRV_SECTOR_SIZE) - start;

    /* Clamp to image length, before checking status of underlying sectors */

    if (start + bytes > bs->total_sectors * BDRV_SECTOR_SIZE) {

        bytes = bs->total_sectors * BDRV_SECTOR_SIZE - start;

    }

    if (!bytes) {

        return true;

    }

    res = bdrv_get_block_status_above(bs, NULL, start >> BDRV_SECTOR_BITS,

                                      bytes >> BDRV_SECTOR_BITS, &nr, NULL);

    return res >= 0 && (res & BDRV_BLOCK_ZERO) &&

        nr * BDRV_SECTOR_SIZE == bytes;

}


int ff_bgmc_init(AVCodecContext *avctx, uint8_t **cf_lut, int **cf_lut_status)

{

    *cf_lut        = av_malloc(sizeof(**cf_lut)        * LUT_BUFF * 16 * LUT_SIZE);

    *cf_lut_status = av_malloc(sizeof(**cf_lut_status) * LUT_BUFF);

    if (!cf_lut || !cf_lut_status) {

        ff_bgmc_end(cf_lut, cf_lut_status);

        av_log(avctx, AV_LOG_ERROR, "Allocating buffer memory failed.\n");

        return AVERROR(ENOMEM);

    } else {

        // initialize lut_status buffer to a value never used to compare against

        memset(*cf_lut_status, -1, sizeof(**cf_lut_status) * LUT_BUFF);

    }

    return 0;

}


void ram_handle_compressed(void *host, uint8_t ch, uint64_t size)

{

    if (ch != 0 || !is_zero_range(host, size)) {

        memset(host, ch, size);

#ifndef _WIN32

        if (ch == 0 && (!kvm_enabled() || kvm_has_sync_mmu())) {

            size = size & ~(getpagesize() - 1);

            if (size > 0) {

                qemu_madvise(host, size, QEMU_MADV_DONTNEED);

            }

        }

#endif

    }

}


static QEMUMachine *machine_parse(const char *name)

{

    QEMUMachine *m, *machine = NULL;

    if (name) {

        machine = find_machine(name);

    }

    if (machine) {

        return machine;

    }

    printf("Supported machines are:\n");

    for (m = first_machine; m != NULL; m = m->next) {

        if (m->alias) {

            printf("%-20s %s (alias of %s)\n", m->alias, m->desc, m->name);

        }

        printf("%-20s %s%s\n", m->name, m->desc,

               m->is_default ? " (default)" : "");

    }

    exit(!name || *name != '?');

}


static int do_getfd(Monitor *mon, const QDict *qdict, QObject **ret_data)

{

    const char *fdname = qdict_get_str(qdict, "fdname");

    mon_fd_t *monfd;

    int fd;

    fd = qemu_chr_get_msgfd(mon->chr);

    if (fd == -1) {

        qerror_report(QERR_FD_NOT_SUPPLIED);

        return -1;

    }

    if (qemu_isdigit(fdname[0])) {

        qerror_report(QERR_INVALID_PARAMETER_VALUE, "fdname",

                      "a name not starting with a digit");

        return -1;

    }

    fd = dup(fd);

    if (fd == -1) {

        if (errno == EMFILE)

            qerror_report(QERR_TOO_MANY_FILES);

        else

            qerror_report(QERR_UNDEFINED_ERROR);

        return -1;

    }

    QLIST_FOREACH(monfd, &mon->fds, next) {

        if (strcmp(monfd->name, fdname) != 0) {

            continue;

        }

        close(monfd->fd);

        monfd->fd = fd;

        return 0;

    }

    monfd = qemu_mallocz(sizeof(mon_fd_t));

    monfd->name = qemu_strdup(fdname);

    monfd->fd = fd;

    QLIST_INSERT_HEAD(&mon->fds, monfd, next);

    return 0;

}


static int virtio_net_load(QEMUFile *f, void *opaque, int version_id)

{

    VirtIONet *n = opaque;

    if (version_id < 2 || version_id > VIRTIO_NET_VM_VERSION)

        return -EINVAL;

    virtio_load(&n->vdev, f);

    qemu_get_buffer(f, n->mac, ETH_ALEN);

    n->tx_timer_active = qemu_get_be32(f);

    n->mergeable_rx_bufs = qemu_get_be32(f);

    if (version_id >= 3)

        n->status = qemu_get_be16(f);

    if (version_id >= 4) {

        if (version_id < 8) {

            n->promisc = qemu_get_be32(f);

            n->allmulti = qemu_get_be32(f);

        } else {

            n->promisc = qemu_get_byte(f);

            n->allmulti = qemu_get_byte(f);

        }

    }

    if (version_id >= 5) {

        n->mac_table.in_use = qemu_get_be32(f);

        /* MAC_TABLE_ENTRIES may be different from the saved image */

        if (n->mac_table.in_use <= MAC_TABLE_ENTRIES) {

            qemu_get_buffer(f, n->mac_table.macs,

                            n->mac_table.in_use * ETH_ALEN);

        } else if (n->mac_table.in_use) {

            qemu_fseek(f, n->mac_table.in_use * ETH_ALEN, SEEK_CUR);

            n->promisc = 1;

            n->mac_table.in_use = 0;

        }

    }

    if (version_id >= 6)

        qemu_get_buffer(f, (uint8_t *)n->vlans, MAX_VLAN >> 3);

    if (version_id >= 7 && qemu_get_be32(f)) {

        fprintf(stderr,

                "virtio-net: saved image requires vnet header support\n");

        exit(1);

    }

    if (n->tx_timer_active) {

        qemu_mod_timer(n->tx_timer,

                       qemu_get_clock(vm_clock) + TX_TIMER_INTERVAL);

    }

    return 0;

}


uint32_t lm4549_write_samples(lm4549_state *s, uint32_t left, uint32_t right)

{

    /* The left and right samples are in 20-bit resolution.

       The LM4549 has 18-bit resolution and only uses the bits [19:2].

       This model supports 16-bit playback.

    */

    if (s->buffer_level >= LM4549_BUFFER_SIZE) {

        DPRINTF("write_sample Buffer full\n");

        return 0;

    }

    /* Store 16-bit samples in the buffer */

    s->buffer[s->buffer_level++] = (left >> 4);

    s->buffer[s->buffer_level++] = (right >> 4);

    if (s->buffer_level == LM4549_BUFFER_SIZE) {

        /* Trigger the transfer of the buffer to the audio host */

        lm4549_audio_transfer(s);

    }

    return 1;

}


static inline void code_gen_alloc(size_t tb_size)

{

    tcg_ctx.code_gen_buffer_size = size_code_gen_buffer(tb_size);

    tcg_ctx.code_gen_buffer = alloc_code_gen_buffer();

    if (tcg_ctx.code_gen_buffer == NULL) {

        fprintf(stderr, "Could not allocate dynamic translator buffer\n");

        exit(1);

    }

    qemu_madvise(tcg_ctx.code_gen_buffer, tcg_ctx.code_gen_buffer_size,

                 QEMU_MADV_HUGEPAGE);

    /* Estimate a good size for the number of TBs we can support.  We

       still haven't deducted the prologue from the buffer size here,

       but that's minimal and won't affect the estimate much.  */

    tcg_ctx.code_gen_max_blocks

        = tcg_ctx.code_gen_buffer_size / CODE_GEN_AVG_BLOCK_SIZE;

    tcg_ctx.tb_ctx.tbs = g_new(TranslationBlock, tcg_ctx.code_gen_max_blocks);

    qemu_mutex_init(&tcg_ctx.tb_ctx.tb_lock);

}


int net_init_socket(QemuOpts *opts,

                    Monitor *mon,

                    const char *name,

                    VLANState *vlan)

{

    if (qemu_opt_get(opts, "fd")) {

        int fd;

        if (qemu_opt_get(opts, "listen") ||

            qemu_opt_get(opts, "connect") ||

            qemu_opt_get(opts, "mcast") ||

            qemu_opt_get(opts, "localaddr")) {

            error_report("listen=, connect=, mcast= and localaddr= is invalid with fd=");

            return -1;

        }

        fd = net_handle_fd_param(mon, qemu_opt_get(opts, "fd"));

        if (fd == -1) {

            return -1;

        }

        if (!net_socket_fd_init(vlan, "socket", name, fd, 1)) {

            close(fd);

            return -1;

        }

    } else if (qemu_opt_get(opts, "listen")) {

        const char *listen;

        if (qemu_opt_get(opts, "fd") ||

            qemu_opt_get(opts, "connect") ||

            qemu_opt_get(opts, "mcast") ||

            qemu_opt_get(opts, "localaddr")) {

            error_report("fd=, connect=, mcast= and localaddr= is invalid with listen=");

            return -1;

        }

        listen = qemu_opt_get(opts, "listen");

        if (net_socket_listen_init(vlan, "socket", name, listen) == -1) {

            return -1;

        }

    } else if (qemu_opt_get(opts, "connect")) {

        const char *connect;

        if (qemu_opt_get(opts, "fd") ||

            qemu_opt_get(opts, "listen") ||

            qemu_opt_get(opts, "mcast") ||

            qemu_opt_get(opts, "localaddr")) {

            error_report("fd=, listen=, mcast= and localaddr= is invalid with connect=");

            return -1;

        }

        connect = qemu_opt_get(opts, "connect");

        if (net_socket_connect_init(vlan, "socket", name, connect) == -1) {

            return -1;

        }

    } else if (qemu_opt_get(opts, "mcast")) {

        const char *mcast, *localaddr;

        if (qemu_opt_get(opts, "fd") ||

            qemu_opt_get(opts, "connect") ||

            qemu_opt_get(opts, "listen")) {

            error_report("fd=, connect= and listen= is invalid with mcast=");

            return -1;

        }

        mcast = qemu_opt_get(opts, "mcast");

        localaddr = qemu_opt_get(opts, "localaddr");

        if (net_socket_mcast_init(vlan, "socket", name, mcast, localaddr) == -1) {

            return -1;

        }

    } else {

        error_report("-socket requires fd=, listen=, connect= or mcast=");

        return -1;

    }

    return 0;

}


QEMUTimerList *qemu_clock_get_main_loop_timerlist(QEMUClockType type)

{

    return main_loop_tlg.tl[type];

}


static void openpic_update_irq(openpic_t *opp, int n_IRQ)

{

    IRQ_src_t *src;

    int i;

    src = &opp->src[n_IRQ];

    if (!src->pending) {

        /* no irq pending */

        DPRINTF("%s: IRQ %d is not pending\n", __func__, n_IRQ);

        return;

    }

    if (test_bit(&src->ipvp, IPVP_MASK)) {

        /* Interrupt source is disabled */

        DPRINTF("%s: IRQ %d is disabled\n", __func__, n_IRQ);

        return;

    }

    if (IPVP_PRIORITY(src->ipvp) == 0) {

        /* Priority set to zero */

        DPRINTF("%s: IRQ %d has 0 priority\n", __func__, n_IRQ);

        return;

    }

    if (test_bit(&src->ipvp, IPVP_ACTIVITY)) {

        /* IRQ already active */

        DPRINTF("%s: IRQ %d is already active\n", __func__, n_IRQ);

        return;

    }

    if (src->ide == 0x00000000) {

        /* No target */

        DPRINTF("%s: IRQ %d has no target\n", __func__, n_IRQ);

        return;

    }

    if (src->ide == (1 << src->last_cpu)) {

        /* Only one CPU is allowed to receive this IRQ */

        IRQ_local_pipe(opp, src->last_cpu, n_IRQ);

    } else if (!test_bit(&src->ipvp, IPVP_MODE)) {

        /* Directed delivery mode */

        for (i = 0; i < opp->nb_cpus; i++) {

            if (test_bit(&src->ide, i))

                IRQ_local_pipe(opp, i, n_IRQ);

        }

    } else {

        /* Distributed delivery mode */

        for (i = src->last_cpu + 1; i != src->last_cpu; i++) {

            if (i == opp->nb_cpus)

                i = 0;

            if (test_bit(&src->ide, i)) {

                IRQ_local_pipe(opp, i, n_IRQ);

                src->last_cpu = i;

                break;

            }

        }

    }

}


static void kqemu_reset_modified_ram_pages(void)

{

    int i;

    unsigned long page_index;

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

        page_index = modified_ram_pages[i] >> TARGET_PAGE_BITS;

        modified_ram_pages_table[page_index] = 0;

    }

    nb_modified_ram_pages = 0;

}


static void cirrus_mmio_write(void *opaque, target_phys_addr_t addr,

                              uint64_t val, unsigned size)

{

    CirrusVGAState *s = opaque;

    if (addr >= 0x100) {

	cirrus_mmio_blt_write(s, addr - 0x100, val);

    } else {

        cirrus_vga_ioport_write(s, addr + 0x3c0, val);

    }

}