static void property_get_tm(Object *obj, Visitor *v, const char *name,

                            void *opaque, Error **errp)

{

    TMProperty *prop = opaque;

    Error *err = NULL;

    struct tm value;

    prop->get(obj, &value, &err);

    if (err) {

        goto out;

    }

    visit_start_struct(v, name, NULL, 0, &err);

    if (err) {

        goto out;

    }

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

    if (err) {

        goto out_end;

    }

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

    if (err) {

        goto out_end;

    }

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

    if (err) {

        goto out_end;

    }

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

    if (err) {

        goto out_end;

    }

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

    if (err) {

        goto out_end;

    }

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

    if (err) {

        goto out_end;

    }

out_end:

    error_propagate(errp, err);

    err = NULL;

    visit_end_struct(v, errp);

out:

    error_propagate(errp, err);

}


e1000e_write_lgcy_rx_descr(E1000ECore *core, uint8_t *desc,

                           struct NetRxPkt *pkt,

                           const E1000E_RSSInfo *rss_info,

                           uint16_t length)

{

    uint32_t status_flags, rss, mrq;

    uint16_t ip_id;

    struct e1000_rx_desc *d = (struct e1000_rx_desc *) desc;

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

    assert(!rss_info->enabled);

    d->length = cpu_to_le16(length);

    e1000e_build_rx_metadata(core, pkt, pkt != NULL,

                             rss_info,

                             &rss, &mrq,

                             &status_flags, &ip_id,

                             &d->special);

    d->errors = (uint8_t) (le32_to_cpu(status_flags) >> 24);

    d->status = (uint8_t) le32_to_cpu(status_flags);

}


void qemu_put_byte(QEMUFile *f, int v)

{

    if (f->last_error) {

        return;

    }

    f->buf[f->buf_index] = v;

    f->bytes_xfer++;

    if (f->ops->writev_buffer) {

        add_to_iovec(f, f->buf + f->buf_index, 1);

    }

    f->buf_index++;

    if (f->buf_index == IO_BUF_SIZE) {

        qemu_fflush(f);

    }

}


long do_rt_sigreturn(CPUX86State *env)

{

    abi_ulong frame_addr;

    struct rt_sigframe *frame;

    sigset_t set;

    frame_addr = env->regs[R_ESP] - 4;

    trace_user_do_rt_sigreturn(env, frame_addr);

    if (!lock_user_struct(VERIFY_READ, frame, frame_addr, 1))

        goto badframe;

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

    set_sigmask(&set);

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

        goto badframe;

    }

    if (do_sigaltstack(frame_addr + offsetof(struct rt_sigframe, uc.tuc_stack), 0,

                       get_sp_from_cpustate(env)) == -EFAULT) {

        goto badframe;

    }

    unlock_user_struct(frame, frame_addr, 0);

    return -TARGET_QEMU_ESIGRETURN;

badframe:

    unlock_user_struct(frame, frame_addr, 0);

    force_sig(TARGET_SIGSEGV);

    return 0;

}


unsigned ff_els_decode_unsigned(ElsDecCtx *ctx, ElsUnsignedRung *ur)

{

    int i, n, r, bit;

    ElsRungNode *rung_node;

    if (ctx->err)

        return 0;

    /* decode unary prefix */

    for (n = 0; n < ELS_EXPGOLOMB_LEN + 1; n++)

        if (ff_els_decode_bit(ctx, &ur->prefix_rung[n]))

            break;

    /* handle the error/overflow case */

    if (ctx->err || n >= ELS_EXPGOLOMB_LEN) {

        ctx->err = AVERROR(EOVERFLOW);

        return 0;

    }

    /* handle the zero case */

    if (!n)

        return 0;

    /* initialize probability tree */

    if (!ur->rem_rung_list) {

        ur->rem_rung_list = av_realloc(NULL, RUNG_SPACE);

        if (!ur->rem_rung_list) {

            ctx->err = AVERROR(ENOMEM);

            return 0;

        }

        memset(ur->rem_rung_list, 0, RUNG_SPACE);

        ur->rung_list_size = RUNG_SPACE;

        ur->avail_index    = ELS_EXPGOLOMB_LEN;

    }

    /* decode the remainder */

    for (i = 0, r = 0, bit = 0; i < n; i++) {

        if (!i)

            rung_node = &ur->rem_rung_list[n];

        else {

            if (!rung_node->next_index) {

                if (ur->rung_list_size <= (ur->avail_index + 2) * sizeof(ElsRungNode)) {

                    // remember rung_node position

                    ptrdiff_t pos     = rung_node - ur->rem_rung_list;

                    ur->rem_rung_list = av_realloc(ur->rem_rung_list,

                                                   ur->rung_list_size +

                                                   RUNG_SPACE);

                    if (!ur->rem_rung_list) {

                        av_free(ur->rem_rung_list);

                        ctx->err = AVERROR(ENOMEM);

                        return 0;

                    }

                    memset((uint8_t *) ur->rem_rung_list + ur->rung_list_size, 0,

                           RUNG_SPACE);

                    ur->rung_list_size += RUNG_SPACE;

                    // restore rung_node position in the new list

                    rung_node = &ur->rem_rung_list[pos];

                }

                rung_node->next_index = ur->avail_index;

                ur->avail_index      += 2;

            }

            rung_node = &ur->rem_rung_list[rung_node->next_index + bit];

        }

        bit = ff_els_decode_bit(ctx, &rung_node->rung);

        if (ctx->err)

            return bit;

        r = (r << 1) + bit;

    }

    return (1 << n) - 1 + r; /* make value from exp golomb code */

}


static int sse_mb(MpegEncContext *s){

    int w= 16;

    int h= 16;

    if(s->mb_x*16 + 16 > s->width ) w= s->width - s->mb_x*16;

    if(s->mb_y*16 + 16 > s->height) h= s->height- s->mb_y*16;

    if(w==16 && h==16)

      if(s->avctx->mb_cmp == FF_CMP_NSSE){

        return  s->dsp.nsse[0](s, s->new_picture.f.data[0] + s->mb_x*16 + s->mb_y*s->linesize*16, s->dest[0], s->linesize, 16)

               +s->dsp.nsse[1](s, s->new_picture.f.data[1] + s->mb_x*8  + s->mb_y*s->uvlinesize*8,s->dest[1], s->uvlinesize, 8)

               +s->dsp.nsse[1](s, s->new_picture.f.data[2] + s->mb_x*8  + s->mb_y*s->uvlinesize*8,s->dest[2], s->uvlinesize, 8);

      }else{

        return  s->dsp.sse[0](NULL, s->new_picture.f.data[0] + s->mb_x*16 + s->mb_y*s->linesize*16, s->dest[0], s->linesize, 16)

               +s->dsp.sse[1](NULL, s->new_picture.f.data[1] + s->mb_x*8  + s->mb_y*s->uvlinesize*8,s->dest[1], s->uvlinesize, 8)

               +s->dsp.sse[1](NULL, s->new_picture.f.data[2] + s->mb_x*8  + s->mb_y*s->uvlinesize*8,s->dest[2], s->uvlinesize, 8);

      }

    else

        return  sse(s, s->new_picture.f.data[0] + s->mb_x*16 + s->mb_y*s->linesize*16, s->dest[0], w, h, s->linesize)

               +sse(s, s->new_picture.f.data[1] + s->mb_x*8  + s->mb_y*s->uvlinesize*8,s->dest[1], w>>1, h>>1, s->uvlinesize)

               +sse(s, s->new_picture.f.data[2] + s->mb_x*8  + s->mb_y*s->uvlinesize*8,s->dest[2], w>>1, h>>1, s->uvlinesize);

}


static uint64_t alloc_cluster_offset(BlockDriverState *bs,

                                     uint64_t offset,

                                     int n_start, int n_end,

                                     int *num, QCowL2Meta *m)

{

    BDRVQcowState *s = bs->opaque;

    int l2_index, ret;

    uint64_t l2_offset, *l2_table, cluster_offset;

    int nb_clusters, i = 0;

    ret = get_cluster_table(bs, offset, &l2_table, &l2_offset, &l2_index);

    if (ret == 0)

        return 0;

    nb_clusters = size_to_clusters(s, n_end << 9);

    nb_clusters = MIN(nb_clusters, s->l2_size - l2_index);

    cluster_offset = be64_to_cpu(l2_table[l2_index]);

    /* We keep all QCOW_OFLAG_COPIED clusters */

    if (cluster_offset & QCOW_OFLAG_COPIED) {

        nb_clusters = count_contiguous_clusters(nb_clusters, s->cluster_size,

                &l2_table[l2_index], 0);

        cluster_offset &= ~QCOW_OFLAG_COPIED;

        m->nb_clusters = 0;

        goto out;

    }

    /* for the moment, multiple compressed clusters are not managed */

    if (cluster_offset & QCOW_OFLAG_COMPRESSED)

        nb_clusters = 1;

    /* how many available clusters ? */

    while (i < nb_clusters) {

        i += count_contiguous_clusters(nb_clusters - i, s->cluster_size,

                &l2_table[l2_index + i], 0);

        if(be64_to_cpu(l2_table[l2_index + i]))

            break;

        i += count_contiguous_free_clusters(nb_clusters - i,

                &l2_table[l2_index + i]);

        cluster_offset = be64_to_cpu(l2_table[l2_index + i]);

        if ((cluster_offset & QCOW_OFLAG_COPIED) ||

                (cluster_offset & QCOW_OFLAG_COMPRESSED))

            break;

    }

    nb_clusters = i;

    /* allocate a new cluster */

    cluster_offset = alloc_clusters(bs, nb_clusters * s->cluster_size);

    /* save info needed for meta data update */

    m->offset = offset;

    m->n_start = n_start;

    m->nb_clusters = nb_clusters;

out:

    m->nb_available = MIN(nb_clusters << (s->cluster_bits - 9), n_end);

    *num = m->nb_available - n_start;

    return cluster_offset;

}


static int dv_extract_audio(uint8_t* frame, uint8_t* ppcm[4],

                            const DVprofile *sys)

{

    int size, chan, i, j, d, of, smpls, freq, quant, half_ch;

    uint16_t lc, rc;

    const uint8_t* as_pack;

    uint8_t *pcm, ipcm;

    as_pack = dv_extract_pack(frame, dv_audio_source);

    if (!as_pack)    /* No audio ? */

        return 0;

    smpls =  as_pack[1] & 0x3f;       /* samples in this frame - min. samples */

    freq  = (as_pack[4] >> 3) & 0x07; /* 0 - 48kHz, 1 - 44,1kHz, 2 - 32kHz */

    quant =  as_pack[4] & 0x07;       /* 0 - 16bit linear, 1 - 12bit nonlinear */

    if (quant > 1)

        return -1; /* unsupported quantization */

    size = (sys->audio_min_samples[freq] + smpls) * 4; /* 2ch, 2bytes */

    half_ch = sys->difseg_size / 2;

    /* We work with 720p frames split in half, thus even frames have

     * channels 0,1 and odd 2,3. */

    ipcm = (sys->height == 720 && !(frame[1] & 0x0C)) ? 2 : 0;

    pcm  = ppcm[ipcm++];

    /* for each DIF channel */

    for (chan = 0; chan < sys->n_difchan; chan++) {

        /* for each DIF segment */

        for (i = 0; i < sys->difseg_size; i++) {

            frame += 6 * 80; /* skip DIF segment header */

            if (quant == 1 && i == half_ch) {

                /* next stereo channel (12bit mode only) */

                pcm = ppcm[ipcm++];

                if (!pcm)

                    break;

            }

            /* for each AV sequence */

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

                for (d = 8; d < 80; d += 2) {

                    if (quant == 0) {  /* 16bit quantization */

                        of = sys->audio_shuffle[i][j] + (d - 8) / 2 * sys->audio_stride;

                        if (of*2 >= size)

                            continue;

                        pcm[of*2]   = frame[d+1]; // FIXME: maybe we have to admit

                        pcm[of*2+1] = frame[d];   //        that DV is a big-endian PCM

                        if (pcm[of*2+1] == 0x80 && pcm[of*2] == 0x00)

                            pcm[of*2+1] = 0;

                    } else {           /* 12bit quantization */

                        lc = ((uint16_t)frame[d]   << 4) |

                             ((uint16_t)frame[d+2] >> 4);

                        rc = ((uint16_t)frame[d+1] << 4) |

                             ((uint16_t)frame[d+2] & 0x0f);

                        lc = (lc == 0x800 ? 0 : dv_audio_12to16(lc));

                        rc = (rc == 0x800 ? 0 : dv_audio_12to16(rc));

                        of = sys->audio_shuffle[i%half_ch][j] + (d - 8) / 3 * sys->audio_stride;

                        if (of*2 >= size)

                            continue;

                        pcm[of*2]   = lc & 0xff; // FIXME: maybe we have to admit

                        pcm[of*2+1] = lc >> 8;   //        that DV is a big-endian PCM

                        of = sys->audio_shuffle[i%half_ch+half_ch][j] +

                            (d - 8) / 3 * sys->audio_stride;

                        pcm[of*2]   = rc & 0xff; // FIXME: maybe we have to admit

                        pcm[of*2+1] = rc >> 8;   //        that DV is a big-endian PCM

                        ++d;

                    }

                }

                frame += 16 * 80; /* 15 Video DIFs + 1 Audio DIF */

            }

        }

        /* next stereo channel (50Mbps and 100Mbps only) */

        pcm = ppcm[ipcm++];

        if (!pcm)

            break;

    }

    return size;

}


static int transcode_init(void)

{

    int ret = 0, i, j, k;

    AVFormatContext *oc;

    AVCodecContext *codec, *icodec;

    OutputStream *ost;

    InputStream *ist;

    char error[1024];

    int want_sdp = 1;

    /* init framerate emulation */

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

        InputFile *ifile = input_files[i];

        if (ifile->rate_emu)

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

                input_streams[j + ifile->ist_index]->start = av_gettime();

    }

    /* output stream init */

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

        oc = output_files[i]->ctx;

        if (!oc->nb_streams && !(oc->oformat->flags & AVFMT_NOSTREAMS)) {

            av_dump_format(oc, i, oc->filename, 1);

            av_log(NULL, AV_LOG_ERROR, "Output file #%d does not contain any stream\n", i);

            return AVERROR(EINVAL);

        }

    }

    /* init complex filtergraphs */

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

        if ((ret = avfilter_graph_config(filtergraphs[i]->graph, NULL)) < 0)

            return ret;

    /* for each output stream, we compute the right encoding parameters */

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

        ost = output_streams[i];

        oc  = output_files[ost->file_index]->ctx;

        ist = get_input_stream(ost);

        if (ost->attachment_filename)

            continue;

        codec  = ost->st->codec;

        if (ist) {

            icodec = ist->st->codec;

            ost->st->disposition          = ist->st->disposition;

            codec->bits_per_raw_sample    = icodec->bits_per_raw_sample;

            codec->chroma_sample_location = icodec->chroma_sample_location;

        }

        if (ost->stream_copy) {

            uint64_t extra_size;

            av_assert0(ist && !ost->filter);

            extra_size = (uint64_t)icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE;

            if (extra_size > INT_MAX) {

                return AVERROR(EINVAL);

            }

            /* if stream_copy is selected, no need to decode or encode */

            codec->codec_id   = icodec->codec_id;

            codec->codec_type = icodec->codec_type;

            if (!codec->codec_tag) {

                if (!oc->oformat->codec_tag ||

                     av_codec_get_id (oc->oformat->codec_tag, icodec->codec_tag) == codec->codec_id ||

                     av_codec_get_tag(oc->oformat->codec_tag, icodec->codec_id) <= 0)

                    codec->codec_tag = icodec->codec_tag;

            }

            codec->bit_rate       = icodec->bit_rate;

            codec->rc_max_rate    = icodec->rc_max_rate;

            codec->rc_buffer_size = icodec->rc_buffer_size;

            codec->field_order    = icodec->field_order;

            codec->extradata      = av_mallocz(extra_size);

            if (!codec->extradata) {

                return AVERROR(ENOMEM);

            }

            memcpy(codec->extradata, icodec->extradata, icodec->extradata_size);

            codec->extradata_size = icodec->extradata_size;

            if (!copy_tb) {

                codec->time_base      = icodec->time_base;

                codec->time_base.num *= icodec->ticks_per_frame;

                av_reduce(&codec->time_base.num, &codec->time_base.den,

                          codec->time_base.num, codec->time_base.den, INT_MAX);

            } else

                codec->time_base = ist->st->time_base;

            switch (codec->codec_type) {

            case AVMEDIA_TYPE_AUDIO:

                if (audio_volume != 256) {

                    av_log(NULL, AV_LOG_FATAL, "-acodec copy and -vol are incompatible (frames are not decoded)\n");

                    exit_program(1);

                }

                codec->channel_layout     = icodec->channel_layout;

                codec->sample_rate        = icodec->sample_rate;

                codec->channels           = icodec->channels;

                codec->frame_size         = icodec->frame_size;

                codec->audio_service_type = icodec->audio_service_type;

                codec->block_align        = icodec->block_align;

                break;

            case AVMEDIA_TYPE_VIDEO:

                codec->pix_fmt            = icodec->pix_fmt;

                codec->width              = icodec->width;

                codec->height             = icodec->height;

                codec->has_b_frames       = icodec->has_b_frames;

                if (!codec->sample_aspect_ratio.num) {

                    codec->sample_aspect_ratio   =

                    ost->st->sample_aspect_ratio =

                        ist->st->sample_aspect_ratio.num ? ist->st->sample_aspect_ratio :

                        ist->st->codec->sample_aspect_ratio.num ?

                        ist->st->codec->sample_aspect_ratio : (AVRational){0, 1};

                }

                break;

            case AVMEDIA_TYPE_SUBTITLE:

                codec->width  = icodec->width;

                codec->height = icodec->height;

                break;

            case AVMEDIA_TYPE_DATA:

            case AVMEDIA_TYPE_ATTACHMENT:

                break;

            default:

                abort();

            }

        } else {

            if (!ost->enc) {

                /* should only happen when a default codec is not present. */

                snprintf(error, sizeof(error), "Automatic encoder selection "

                         "failed for output stream #%d:%d. Default encoder for "

                         "format %s is probably disabled. Please choose an "

                         "encoder manually.\n", ost->file_index, ost->index,

                         oc->oformat->name);

                ret = AVERROR(EINVAL);

                goto dump_format;

            }

            if (ist)

                ist->decoding_needed = 1;

            ost->encoding_needed = 1;

            switch (codec->codec_type) {

            case AVMEDIA_TYPE_AUDIO:

                ost->fifo = av_fifo_alloc(1024);

                if (!ost->fifo) {

                    return AVERROR(ENOMEM);

                }

                if (!codec->sample_rate)

                    codec->sample_rate = icodec->sample_rate;

                choose_sample_rate(ost->st, ost->enc);

                codec->time_base = (AVRational){ 1, codec->sample_rate };

                if (codec->sample_fmt == AV_SAMPLE_FMT_NONE)

                    codec->sample_fmt = icodec->sample_fmt;

                choose_sample_fmt(ost->st, ost->enc);

                if (!codec->channels)

                    codec->channels = icodec->channels;

                if (!codec->channel_layout)

                    codec->channel_layout = icodec->channel_layout;

                if (av_get_channel_layout_nb_channels(codec->channel_layout) != codec->channels)

                    codec->channel_layout = 0;

                icodec->request_channels  = codec-> channels;

                ost->resample_sample_fmt  = icodec->sample_fmt;

                ost->resample_sample_rate = icodec->sample_rate;

                ost->resample_channels    = icodec->channels;

                ost->resample_channel_layout = icodec->channel_layout;

                break;

            case AVMEDIA_TYPE_VIDEO:

                if (!ost->filter) {

                    FilterGraph *fg;

                    fg = init_simple_filtergraph(ist, ost);

                    if (configure_video_filters(fg)) {

                        av_log(NULL, AV_LOG_FATAL, "Error opening filters!\n");

                        exit(1);

                    }

                }

                /*

                 * We want CFR output if and only if one of those is true:

                 * 1) user specified output framerate with -r

                 * 2) user specified -vsync cfr

                 * 3) output format is CFR and the user didn't force vsync to

                 *    something else than CFR

                 *

                 * in such a case, set ost->frame_rate

                 */

                if (!ost->frame_rate.num && ist &&

                    (video_sync_method ==  VSYNC_CFR ||

                     (video_sync_method ==  VSYNC_AUTO &&

                      !(oc->oformat->flags & (AVFMT_NOTIMESTAMPS | AVFMT_VARIABLE_FPS))))) {

                    ost->frame_rate = ist->st->r_frame_rate.num ? ist->st->r_frame_rate : (AVRational){25, 1};

                    if (ost->enc && ost->enc->supported_framerates && !ost->force_fps) {

                        int idx = av_find_nearest_q_idx(ost->frame_rate, ost->enc->supported_framerates);

                        ost->frame_rate = ost->enc->supported_framerates[idx];

                    }

                }

                if (ost->frame_rate.num) {

                    codec->time_base = (AVRational){ost->frame_rate.den, ost->frame_rate.num};

                    video_sync_method = VSYNC_CFR;

                } else if (ist)

                    codec->time_base = ist->st->time_base;

                else

                    codec->time_base = ost->filter->filter->inputs[0]->time_base;

                codec->width  = ost->filter->filter->inputs[0]->w;

                codec->height = ost->filter->filter->inputs[0]->h;

                codec->sample_aspect_ratio = ost->st->sample_aspect_ratio =

                    ost->frame_aspect_ratio ? // overridden by the -aspect cli option

                    av_d2q(ost->frame_aspect_ratio * codec->height/codec->width, 255) :

                    ost->filter->filter->inputs[0]->sample_aspect_ratio;

                codec->pix_fmt = ost->filter->filter->inputs[0]->format;

                if (codec->width   != icodec->width  ||

                    codec->height  != icodec->height ||

                    codec->pix_fmt != icodec->pix_fmt) {

                    codec->bits_per_raw_sample = 0;

                }

                break;

            case AVMEDIA_TYPE_SUBTITLE:

                codec->time_base = (AVRational){1, 1000};

                break;

            default:

                abort();

                break;

            }

            /* two pass mode */

            if ((codec->flags & (CODEC_FLAG_PASS1 | CODEC_FLAG_PASS2))) {

                char logfilename[1024];

                FILE *f;

                snprintf(logfilename, sizeof(logfilename), "%s-%d.log",

                         pass_logfilename_prefix ? pass_logfilename_prefix : DEFAULT_PASS_LOGFILENAME_PREFIX,

                         i);

                if (!strcmp(ost->enc->name, "libx264")) {

                    av_dict_set(&ost->opts, "stats", logfilename, AV_DICT_DONT_OVERWRITE);

                } else {

                    if (codec->flags & CODEC_FLAG_PASS1) {

                        f = fopen(logfilename, "wb");

                        if (!f) {

                            av_log(NULL, AV_LOG_FATAL, "Cannot write log file '%s' for pass-1 encoding: %s\n",

                                   logfilename, strerror(errno));

                            exit_program(1);

                        }

                        ost->logfile = f;

                    } else {

                        char  *logbuffer;

                        size_t logbuffer_size;

                        if (cmdutils_read_file(logfilename, &logbuffer, &logbuffer_size) < 0) {

                            av_log(NULL, AV_LOG_FATAL, "Error reading log file '%s' for pass-2 encoding\n",

                                   logfilename);

                            exit_program(1);

                        }

                        codec->stats_in = logbuffer;

                    }

                }

            }

        }

    }

    /* open each encoder */

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

        ost = output_streams[i];

        if (ost->encoding_needed) {

            AVCodec      *codec = ost->enc;

            AVCodecContext *dec = NULL;

            if ((ist = get_input_stream(ost)))

                dec = ist->st->codec;

            if (dec && dec->subtitle_header) {

                ost->st->codec->subtitle_header = av_malloc(dec->subtitle_header_size);

                if (!ost->st->codec->subtitle_header) {

                    ret = AVERROR(ENOMEM);

                    goto dump_format;

                }

                memcpy(ost->st->codec->subtitle_header, dec->subtitle_header, dec->subtitle_header_size);

                ost->st->codec->subtitle_header_size = dec->subtitle_header_size;

            }

            if (!av_dict_get(ost->opts, "threads", NULL, 0))

                av_dict_set(&ost->opts, "threads", "auto", 0);

            if (avcodec_open2(ost->st->codec, codec, &ost->opts) < 0) {

                snprintf(error, sizeof(error), "Error while opening encoder for output stream #%d:%d - maybe incorrect parameters such as bit_rate, rate, width or height",

                        ost->file_index, ost->index);

                ret = AVERROR(EINVAL);

                goto dump_format;

            }

            assert_codec_experimental(ost->st->codec, 1);

            assert_avoptions(ost->opts);

            if (ost->st->codec->bit_rate && ost->st->codec->bit_rate < 1000)

                av_log(NULL, AV_LOG_WARNING, "The bitrate parameter is set too low."

                                             "It takes bits/s as argument, not kbits/s\n");

            extra_size += ost->st->codec->extradata_size;

            if (ost->st->codec->me_threshold)

                input_streams[ost->source_index]->st->codec->debug |= FF_DEBUG_MV;

        }

    }

    /* init input streams */

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

        if ((ret = init_input_stream(i, error, sizeof(error))) < 0)

            goto dump_format;

    /* discard unused programs */

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

        InputFile *ifile = input_files[i];

        for (j = 0; j < ifile->ctx->nb_programs; j++) {

            AVProgram *p = ifile->ctx->programs[j];

            int discard  = AVDISCARD_ALL;

            for (k = 0; k < p->nb_stream_indexes; k++)

                if (!input_streams[ifile->ist_index + p->stream_index[k]]->discard) {

                    discard = AVDISCARD_DEFAULT;

                    break;

                }

            p->discard = discard;

        }

    }

    /* open files and write file headers */

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

        oc = output_files[i]->ctx;

        oc->interrupt_callback = int_cb;

        if (avformat_write_header(oc, &output_files[i]->opts) < 0) {

            snprintf(error, sizeof(error), "Could not write header for output file #%d (incorrect codec parameters ?)", i);

            ret = AVERROR(EINVAL);

            goto dump_format;

        }

        assert_avoptions(output_files[i]->opts);

        if (strcmp(oc->oformat->name, "rtp")) {

            want_sdp = 0;

        }

    }

 dump_format:

    /* dump the file output parameters - cannot be done before in case

       of stream copy */

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

        av_dump_format(output_files[i]->ctx, i, output_files[i]->ctx->filename, 1);

    }

    /* dump the stream mapping */

    av_log(NULL, AV_LOG_INFO, "Stream mapping:\n");

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

        ist = input_streams[i];

        for (j = 0; j < ist->nb_filters; j++) {

            AVFilterLink *link = ist->filters[j]->filter->outputs[0];

            if (ist->filters[j]->graph->graph_desc) {

                av_log(NULL, AV_LOG_INFO, "  Stream #%d:%d (%s) -> %s",

                       ist->file_index, ist->st->index, ist->dec ? ist->dec->name : "?",

                       link->dst->filter->name);

                if (link->dst->input_count > 1)

                    av_log(NULL, AV_LOG_INFO, ":%s", link->dstpad->name);

                if (nb_filtergraphs > 1)

                    av_log(NULL, AV_LOG_INFO, " (graph %d)", ist->filters[j]->graph->index);

                av_log(NULL, AV_LOG_INFO, "\n");

            }

        }

    }

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

        ost = output_streams[i];

        if (ost->attachment_filename) {

            /* an attached file */

            av_log(NULL, AV_LOG_INFO, "  File %s -> Stream #%d:%d\n",

                   ost->attachment_filename, ost->file_index, ost->index);

            continue;

        }

        if (ost->filter && ost->filter->graph->graph_desc) {

            /* output from a complex graph */

            AVFilterLink *link = ost->filter->filter->inputs[0];

            av_log(NULL, AV_LOG_INFO, "  %s", link->src->filter->name);

            if (link->src->output_count > 1)

                av_log(NULL, AV_LOG_INFO, ":%s", link->srcpad->name);

            if (nb_filtergraphs > 1)

                av_log(NULL, AV_LOG_INFO, " (graph %d)", ost->filter->graph->index);

            av_log(NULL, AV_LOG_INFO, " -> Stream #%d:%d (%s)\n", ost->file_index,

                   ost->index, ost->enc ? ost->enc->name : "?");

            continue;

        }

        av_log(NULL, AV_LOG_INFO, "  Stream #%d:%d -> #%d:%d",

               input_streams[ost->source_index]->file_index,

               input_streams[ost->source_index]->st->index,

               ost->file_index,

               ost->index);

        if (ost->sync_ist != input_streams[ost->source_index])

            av_log(NULL, AV_LOG_INFO, " [sync #%d:%d]",

                   ost->sync_ist->file_index,

                   ost->sync_ist->st->index);

        if (ost->stream_copy)

            av_log(NULL, AV_LOG_INFO, " (copy)");

        else

            av_log(NULL, AV_LOG_INFO, " (%s -> %s)", input_streams[ost->source_index]->dec ?

                   input_streams[ost->source_index]->dec->name : "?",

                   ost->enc ? ost->enc->name : "?");

        av_log(NULL, AV_LOG_INFO, "\n");

    }

    if (ret) {

        av_log(NULL, AV_LOG_ERROR, "%s\n", error);

        return ret;

    }

    if (want_sdp) {

        print_sdp();

    }

    return 0;

}


static int get_aiff_header(AVFormatContext *s, int size,

                                    unsigned version)

{

    AVIOContext *pb        = s->pb;

    AVCodecParameters *par = s->streams[0]->codecpar;

    AIFFInputContext *aiff = s->priv_data;

    int exp;

    uint64_t val;

    int sample_rate;

    unsigned int num_frames;

    if (size & 1)

        size++;

    par->codec_type = AVMEDIA_TYPE_AUDIO;

    par->channels = avio_rb16(pb);

    num_frames = avio_rb32(pb);

    par->bits_per_coded_sample = avio_rb16(pb);

    exp = avio_rb16(pb) - 16383 - 63;

    val = avio_rb64(pb);

    if (exp <-63 || exp >63) {

        av_log(s, AV_LOG_ERROR, "exp %d is out of range\n", exp);

        return AVERROR_INVALIDDATA;

    }

    if (exp >= 0)

        sample_rate = val << exp;

    else

        sample_rate = (val + (1ULL<<(-exp-1))) >> -exp;

    par->sample_rate = sample_rate;

    size -= 18;

    /* get codec id for AIFF-C */

    if (size < 4) {

        version = AIFF;

    } else if (version == AIFF_C_VERSION1) {

        par->codec_tag = avio_rl32(pb);

        par->codec_id  = ff_codec_get_id(ff_codec_aiff_tags, par->codec_tag);

        if (par->codec_id == AV_CODEC_ID_NONE) {

            char tag[32];

            av_get_codec_tag_string(tag, sizeof(tag), par->codec_tag);

            avpriv_request_sample(s, "unknown or unsupported codec tag: %s", tag);

        }

        size -= 4;

    }

    if (version != AIFF_C_VERSION1 || par->codec_id == AV_CODEC_ID_PCM_S16BE) {

        par->codec_id = aiff_codec_get_id(par->bits_per_coded_sample);

        par->bits_per_coded_sample = av_get_bits_per_sample(par->codec_id);

        aiff->block_duration = 1;

    } else {

        switch (par->codec_id) {

        case AV_CODEC_ID_PCM_F32BE:

        case AV_CODEC_ID_PCM_F64BE:

        case AV_CODEC_ID_PCM_S16LE:

        case AV_CODEC_ID_PCM_ALAW:

        case AV_CODEC_ID_PCM_MULAW:

            aiff->block_duration = 1;

            break;

        case AV_CODEC_ID_ADPCM_IMA_QT:

            par->block_align = 34 * par->channels;

            break;

        case AV_CODEC_ID_MACE3:

            par->block_align = 2 * par->channels;

            break;

        case AV_CODEC_ID_ADPCM_G726LE:

            par->bits_per_coded_sample = 5;

        case AV_CODEC_ID_ADPCM_IMA_WS:

        case AV_CODEC_ID_ADPCM_G722:

        case AV_CODEC_ID_MACE6:

        case AV_CODEC_ID_SDX2_DPCM:

            par->block_align = 1 * par->channels;

            break;

        case AV_CODEC_ID_GSM:

            par->block_align = 33;

            break;

        default:

            aiff->block_duration = 1;

            break;

        }

        if (par->block_align > 0)

            aiff->block_duration = av_get_audio_frame_duration2(par,

                                                                par->block_align);

    }

    /* Block align needs to be computed in all cases, as the definition

     * is specific to applications -> here we use the WAVE format definition */

    if (!par->block_align)

        par->block_align = (av_get_bits_per_sample(par->codec_id) * par->channels) >> 3;

    if (aiff->block_duration) {

        par->bit_rate = par->sample_rate * (par->block_align << 3) /

                        aiff->block_duration;

    }

    /* Chunk is over */

    if (size)

        avio_skip(pb, size);

    return num_frames;

}


static void xen_init_pv(QEMUMachineInitArgs *args)

{

    const char *cpu_model = args->cpu_model;

    const char *kernel_filename = args->kernel_filename;

    const char *kernel_cmdline = args->kernel_cmdline;

    const char *initrd_filename = args->initrd_filename;

    X86CPU *cpu;

    CPUState *cs;

    DriveInfo *dinfo;

    int i;

    /* Initialize a dummy CPU */

    if (cpu_model == NULL) {

#ifdef TARGET_X86_64

        cpu_model = "qemu64";

#else

        cpu_model = "qemu32";

#endif

    }

    cpu = cpu_x86_init(cpu_model);

    cs = CPU(cpu);

    cs->halted = 1;

    /* Initialize backend core & drivers */

    if (xen_be_init() != 0) {

        fprintf(stderr, "%s: xen backend core setup failed\n", __FUNCTION__);

        exit(1);

    }

    switch (xen_mode) {

    case XEN_ATTACH:

        /* nothing to do, xend handles everything */

        break;

    case XEN_CREATE:

        if (xen_domain_build_pv(kernel_filename, initrd_filename,

                                kernel_cmdline) < 0) {

            fprintf(stderr, "xen pv domain creation failed\n");

            exit(1);

        }

        break;

    case XEN_EMULATE:

        fprintf(stderr, "xen emulation not implemented (yet)\n");

        exit(1);

        break;

    }

    xen_be_register("console", &xen_console_ops);

    xen_be_register("vkbd", &xen_kbdmouse_ops);

    xen_be_register("vfb", &xen_framebuffer_ops);

    xen_be_register("qdisk", &xen_blkdev_ops);

    xen_be_register("qnic", &xen_netdev_ops);

    /* configure framebuffer */

    if (xenfb_enabled) {

        xen_config_dev_vfb(0, "vnc");

        xen_config_dev_vkbd(0);

    }

    /* configure disks */

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

        dinfo = drive_get(IF_XEN, 0, i);

        if (!dinfo)

            continue;

        xen_config_dev_blk(dinfo);

    }

    /* configure nics */

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

        if (!nd_table[i].model || 0 != strcmp(nd_table[i].model, "xen"))

            continue;

        xen_config_dev_nic(nd_table + i);

    }

    /* config cleanup hook */

    atexit(xen_config_cleanup);

    /* setup framebuffer */

    xen_init_display(xen_domid);

}


void signal_init(void)

{

    struct sigaction act;

    int i;

    /* set all host signal handlers. ALL signals are blocked during

       the handlers to serialize them. */

    sigfillset(&act.sa_mask);

    act.sa_flags = SA_SIGINFO;

    act.sa_sigaction = host_signal_handler;

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

	sigaction(i, &act, NULL);

    }

    memset(sigact_table, 0, sizeof(sigact_table));

    first_free = &sigqueue_table[0];

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

        sigqueue_table[i].next = &sigqueue_table[i + 1];

    sigqueue_table[MAX_SIGQUEUE_SIZE - 1].next = NULL;

}


static inline void gen_bx(DisasContext *s, TCGv_i32 var)

{

    s->is_jmp = DISAS_UPDATE;

    tcg_gen_andi_i32(cpu_R[15], var, ~1);

    tcg_gen_andi_i32(var, var, 1);

    store_cpu_field(var, thumb);

}


static int get_nb_samples(AVCodecContext *avctx, GetByteContext *gb,

                          int buf_size, int *coded_samples, int *approx_nb_samples)

{

    ADPCMDecodeContext *s = avctx->priv_data;

    int nb_samples        = 0;

    int ch                = avctx->channels;

    int has_coded_samples = 0;

    int header_size;

    *coded_samples = 0;

    *approx_nb_samples = 0;

    if(ch <= 0)

        return 0;

    switch (avctx->codec->id) {

    /* constant, only check buf_size */

    case AV_CODEC_ID_ADPCM_EA_XAS:

        if (buf_size < 76 * ch)

            return 0;

        nb_samples = 128;

        break;

    case AV_CODEC_ID_ADPCM_IMA_QT:

        if (buf_size < 34 * ch)

            return 0;

        nb_samples = 64;

        break;

    /* simple 4-bit adpcm */

    case AV_CODEC_ID_ADPCM_CT:

    case AV_CODEC_ID_ADPCM_IMA_APC:

    case AV_CODEC_ID_ADPCM_IMA_EA_SEAD:

    case AV_CODEC_ID_ADPCM_IMA_OKI:

    case AV_CODEC_ID_ADPCM_IMA_WS:

    case AV_CODEC_ID_ADPCM_YAMAHA:

        nb_samples = buf_size * 2 / ch;

        break;

    }

    if (nb_samples)

        return nb_samples;

    /* simple 4-bit adpcm, with header */

    header_size = 0;

    switch (avctx->codec->id) {

        case AV_CODEC_ID_ADPCM_4XM:

        case AV_CODEC_ID_ADPCM_IMA_ISS:     header_size = 4 * ch;      break;

        case AV_CODEC_ID_ADPCM_IMA_AMV:     header_size = 8;           break;

        case AV_CODEC_ID_ADPCM_IMA_SMJPEG:  header_size = 4 * ch;      break;

    }

    if (header_size > 0)

        return (buf_size - header_size) * 2 / ch;

    /* more complex formats */

    switch (avctx->codec->id) {

    case AV_CODEC_ID_ADPCM_EA:

        has_coded_samples = 1;

        *coded_samples  = bytestream2_get_le32(gb);

        *coded_samples -= *coded_samples % 28;

        nb_samples      = (buf_size - 12) / 30 * 28;

        break;

    case AV_CODEC_ID_ADPCM_IMA_EA_EACS:

        has_coded_samples = 1;

        *coded_samples = bytestream2_get_le32(gb);

        nb_samples     = (buf_size - (4 + 8 * ch)) * 2 / ch;

        break;

    case AV_CODEC_ID_ADPCM_EA_MAXIS_XA:

        nb_samples = (buf_size - ch) / ch * 2;

        break;

    case AV_CODEC_ID_ADPCM_EA_R1:

    case AV_CODEC_ID_ADPCM_EA_R2:

    case AV_CODEC_ID_ADPCM_EA_R3:

        /* maximum number of samples */

        /* has internal offsets and a per-frame switch to signal raw 16-bit */

        has_coded_samples = 1;

        switch (avctx->codec->id) {

        case AV_CODEC_ID_ADPCM_EA_R1:

            header_size    = 4 + 9 * ch;

            *coded_samples = bytestream2_get_le32(gb);

            break;

        case AV_CODEC_ID_ADPCM_EA_R2:

            header_size    = 4 + 5 * ch;

            *coded_samples = bytestream2_get_le32(gb);

            break;

        case AV_CODEC_ID_ADPCM_EA_R3:

            header_size    = 4 + 5 * ch;

            *coded_samples = bytestream2_get_be32(gb);

            break;

        }

        *coded_samples -= *coded_samples % 28;

        nb_samples      = (buf_size - header_size) * 2 / ch;

        nb_samples     -= nb_samples % 28;

        *approx_nb_samples = 1;

        break;

    case AV_CODEC_ID_ADPCM_IMA_DK3:

        if (avctx->block_align > 0)

            buf_size = FFMIN(buf_size, avctx->block_align);

        nb_samples = ((buf_size - 16) * 2 / 3 * 4) / ch;

        break;

    case AV_CODEC_ID_ADPCM_IMA_DK4:

        if (avctx->block_align > 0)

            buf_size = FFMIN(buf_size, avctx->block_align);

        nb_samples = 1 + (buf_size - 4 * ch) * 2 / ch;

        break;

    case AV_CODEC_ID_ADPCM_IMA_RAD:

        if (avctx->block_align > 0)

            buf_size = FFMIN(buf_size, avctx->block_align);

        nb_samples = (buf_size - 4 * ch) * 2 / ch;

        break;

    case AV_CODEC_ID_ADPCM_IMA_WAV:

    {

        int bsize = ff_adpcm_ima_block_sizes[avctx->bits_per_coded_sample - 2];

        int bsamples = ff_adpcm_ima_block_samples[avctx->bits_per_coded_sample - 2];

        if (avctx->block_align > 0)

            buf_size = FFMIN(buf_size, avctx->block_align);

        nb_samples = 1 + (buf_size - 4 * ch) / (bsize * ch) * bsamples;

        break;

    }

    case AV_CODEC_ID_ADPCM_MS:

        if (avctx->block_align > 0)

            buf_size = FFMIN(buf_size, avctx->block_align);

        nb_samples = 2 + (buf_size - 7 * ch) * 2 / ch;

        break;

    case AV_CODEC_ID_ADPCM_SBPRO_2:

    case AV_CODEC_ID_ADPCM_SBPRO_3:

    case AV_CODEC_ID_ADPCM_SBPRO_4:

    {

        int samples_per_byte;

        switch (avctx->codec->id) {

        case AV_CODEC_ID_ADPCM_SBPRO_2: samples_per_byte = 4; break;

        case AV_CODEC_ID_ADPCM_SBPRO_3: samples_per_byte = 3; break;

        case AV_CODEC_ID_ADPCM_SBPRO_4: samples_per_byte = 2; break;

        }

        if (!s->status[0].step_index) {

            nb_samples++;

            buf_size -= ch;

        }

        nb_samples += buf_size * samples_per_byte / ch;

        break;

    }

    case AV_CODEC_ID_ADPCM_SWF:

    {

        int buf_bits       = buf_size * 8 - 2;

        int nbits          = (bytestream2_get_byte(gb) >> 6) + 2;

        int block_hdr_size = 22 * ch;

        int block_size     = block_hdr_size + nbits * ch * 4095;

        int nblocks        = buf_bits / block_size;

        int bits_left      = buf_bits - nblocks * block_size;

        nb_samples         = nblocks * 4096;

        if (bits_left >= block_hdr_size)

            nb_samples += 1 + (bits_left - block_hdr_size) / (nbits * ch);

        break;

    }

    case AV_CODEC_ID_ADPCM_THP:

        if (avctx->extradata) {

            nb_samples = buf_size / (8 * ch) * 14;

            break;

        }

        has_coded_samples = 1;

        bytestream2_skip(gb, 4); // channel size

        *coded_samples  = bytestream2_get_be32(gb);

        *coded_samples -= *coded_samples % 14;

        nb_samples      = (buf_size - (8 + 36 * ch)) / (8 * ch) * 14;

        break;

    case AV_CODEC_ID_ADPCM_AFC:

        nb_samples = buf_size / (9 * ch) * 16;

        break;

    case AV_CODEC_ID_ADPCM_XA:

        nb_samples = (buf_size / 128) * 224 / ch;

        break;

    case AV_CODEC_ID_ADPCM_DTK:

        nb_samples = buf_size / (16 * ch) * 28;

        break;

    }

    /* validate coded sample count */

    if (has_coded_samples && (*coded_samples <= 0 || *coded_samples > nb_samples))

        return AVERROR_INVALIDDATA;

    return nb_samples;

}


static void serial_receive1(void *opaque, const uint8_t *buf, int size)

{

    SerialState *s = opaque;

    serial_receive_byte(s, buf[0]);

}


static TCGv_i32 gen_get_asi(DisasContext *dc, int insn)

{

    int asi;

    if (IS_IMM) {

#ifdef TARGET_SPARC64

        asi = dc->asi;

#else

        gen_exception(dc, TT_ILL_INSN);

        asi = 0;

#endif

    } else {

        asi = GET_FIELD(insn, 19, 26);

    }

    return tcg_const_i32(asi);

}


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

                           target_siginfo_t *info,

                           target_sigset_t *set, CPUSH4State *regs)

{

    struct target_rt_sigframe *frame;

    abi_ulong frame_addr;

    int i;

    int err = 0;

    int signal;

    frame_addr = get_sigframe(ka, regs->gregs[15], sizeof(*frame));

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

	goto give_sigsegv;

    signal = current_exec_domain_sig(sig);

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

    /* Create the ucontext.  */

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

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

    __put_user((unsigned long)target_sigaltstack_used.ss_sp,

               &frame->uc.tuc_stack.ss_sp);

    __put_user(sas_ss_flags(regs->gregs[15]),

               &frame->uc.tuc_stack.ss_flags);

    __put_user(target_sigaltstack_used.ss_size,

               &frame->uc.tuc_stack.ss_size);

    setup_sigcontext(&frame->uc.tuc_mcontext,

			    regs, set->sig[0]);

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

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

    }

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

       already in userspace.  */

    if (ka->sa_flags & TARGET_SA_RESTORER) {

        regs->pr = (unsigned long) ka->sa_restorer;

    } else {

        /* Generate return code (system call to sigreturn) */

        __put_user(MOVW(2), &frame->retcode[0]);

        __put_user(TRAP_NOARG, &frame->retcode[1]);

        __put_user((TARGET_NR_rt_sigreturn), &frame->retcode[2]);

        regs->pr = (unsigned long) frame->retcode;

    }

    if (err)

        goto give_sigsegv;

    /* Set up registers for signal handler */

    regs->gregs[15] = frame_addr;

    regs->gregs[4] = signal; /* Arg for signal handler */

    regs->gregs[5] = frame_addr + offsetof(typeof(*frame), info);

    regs->gregs[6] = frame_addr + offsetof(typeof(*frame), uc);

    regs->pc = (unsigned long) ka->_sa_handler;

    unlock_user_struct(frame, frame_addr, 1);

    return;

give_sigsegv:

    unlock_user_struct(frame, frame_addr, 1);

    force_sig(TARGET_SIGSEGV);

}


static void display_mouse_set(DisplayChangeListener *dcl,

                              int x, int y, int on)

{

    SimpleSpiceDisplay *ssd = container_of(dcl, SimpleSpiceDisplay, dcl);

    qemu_mutex_lock(&ssd->lock);

    ssd->ptr_x = x;

    ssd->ptr_y = y;

    if (ssd->ptr_move) {

        g_free(ssd->ptr_move);

    }

    ssd->ptr_move = qemu_spice_create_cursor_update(ssd, NULL, on);

    qemu_mutex_unlock(&ssd->lock);

}


static void cpu_request_exit(void *opaque, int irq, int level)

{

    CPUState *cpu = current_cpu;

    if (cpu && level) {

        cpu_exit(cpu);

    }

}


int qemu_get_thread_id(void)

{

#if defined (__linux__)

    return syscall(SYS_gettid);

#else

    return getpid();

#endif

}


static void listflags(char *buf, int bufsize, uint32_t fbits,

    const char **featureset, uint32_t flags)

{

    const char **p = &featureset[31];

    char *q, *b, bit;

    int nc;

    b = 4 <= bufsize ? buf + (bufsize -= 3) - 1 : NULL;

    *buf = '\0';

    for (q = buf, bit = 31; fbits && bufsize; --p, fbits &= ~(1 << bit), --bit)

        if (fbits & 1 << bit && (*p || !flags)) {

            if (*p)

                nc = snprintf(q, bufsize, "%s%s", q == buf ? "" : " ", *p);

            else

                nc = snprintf(q, bufsize, "%s[%d]", q == buf ? "" : " ", bit);

            if (bufsize <= nc) {

                if (b)

                    sprintf(b, "...");

                return;

            }

            q += nc;

            bufsize -= nc;

        }

}


void watchdog_add_model(WatchdogTimerModel *model)

{

    LIST_INSERT_HEAD(&watchdog_list, model, entry);

}


static void encode_plane(FFV1Context *s, uint8_t *src, int w, int h,

                         int stride, int plane_index)

{

    int x, y, i;

    const int ring_size = s->avctx->context_model ? 3 : 2;

    int16_t *sample[3];

    s->run_index = 0;

    memset(s->sample_buffer, 0, ring_size * (w + 6) * sizeof(*s->sample_buffer));

    for (y = 0; y < h; y++) {

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

            sample[i] = s->sample_buffer + (w + 6) * ((h + i - y) % ring_size) + 3;

        sample[0][-1]= sample[1][0  ];

        sample[1][ w]= sample[1][w-1];

// { START_TIMER

        if (s->bits_per_raw_sample <= 8) {

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

                sample[0][x] = src[x + stride * y];

            encode_line(s, w, sample, plane_index, 8);

        } else {

            if (s->packed_at_lsb) {

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

                    sample[0][x] = ((uint16_t*)(src + stride*y))[x];

                }

            } else {

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

                    sample[0][x] = ((uint16_t*)(src + stride*y))[x] >> (16 - s->bits_per_raw_sample);

                }

            }

            encode_line(s, w, sample, plane_index, s->bits_per_raw_sample);

        }

// STOP_TIMER("encode line") }

    }

}


static int decode_plane(Indeo3DecodeContext *ctx, AVCodecContext *avctx,

                        Plane *plane, const uint8_t *data, int32_t data_size,

                        int32_t strip_width)

{

    Cell            curr_cell;

    int             num_vectors;

    /* each plane data starts with mc_vector_count field, */

    /* an optional array of motion vectors followed by the vq data */

    num_vectors = bytestream_get_le32(&data);

    ctx->mc_vectors  = num_vectors ? data : 0;

    /* init the bitreader */

    init_get_bits(&ctx->gb, &data[num_vectors * 2], data_size << 3);

    ctx->skip_bits   = 0;

    ctx->need_resync = 0;

    ctx->last_byte = data + data_size - 1;

    /* initialize the 1st cell and set its dimensions to whole plane */

    curr_cell.xpos   = curr_cell.ypos = 0;

    curr_cell.width  = plane->width  >> 2;

    curr_cell.height = plane->height >> 2;

    curr_cell.tree   = 0; // we are in the MC tree now

    curr_cell.mv_ptr = 0; // no motion vector = INTRA cell

    return parse_bintree(ctx, avctx, plane, INTRA_NULL, &curr_cell, CELL_STACK_MAX, strip_width);

}


int qemu_savevm_state_iterate(QEMUFile *f)

{

    SaveStateEntry *se;

    int ret = 1;

    TAILQ_FOREACH(se, &savevm_handlers, entry) {

        if (se->save_live_state == NULL)

            continue;

        /* Section type */

        qemu_put_byte(f, QEMU_VM_SECTION_PART);

        qemu_put_be32(f, se->section_id);

        ret &= !!se->save_live_state(f, QEMU_VM_SECTION_PART, se->opaque);

    }

    if (ret)

        return 1;

    if (qemu_file_has_error(f))

        return -EIO;

    return 0;

}


static void qmp_cleanup(void *datap)

{

    QmpSerializeData *d = datap;

    visit_free(qmp_output_get_visitor(d->qov));

    visit_free(d->qiv);

    g_free(d);

}


void parse_numa_opts(MachineClass *mc)

{

    int i;

    if (qemu_opts_foreach(qemu_find_opts("numa"), parse_numa, NULL, NULL)) {

        exit(1);

    }

    assert(max_numa_nodeid <= MAX_NODES);

    /* No support for sparse NUMA node IDs yet: */

    for (i = max_numa_nodeid - 1; i >= 0; i--) {

        /* Report large node IDs first, to make mistakes easier to spot */

        if (!numa_info[i].present) {

            error_report("numa: Node ID missing: %d", i);

            exit(1);

        }

    }

    /* This must be always true if all nodes are present: */

    assert(nb_numa_nodes == max_numa_nodeid);

    if (nb_numa_nodes > 0) {

        uint64_t numa_total;

        if (nb_numa_nodes > MAX_NODES) {

            nb_numa_nodes = MAX_NODES;

        }

        /* If no memory size is given for any node, assume the default case

         * and distribute the available memory equally across all nodes

         */

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

            if (numa_info[i].node_mem != 0) {

                break;

            }

        }

        if (i == nb_numa_nodes) {

            uint64_t usedmem = 0;

            /* On Linux, each node's border has to be 8MB aligned,

             * the final node gets the rest.

             */

            for (i = 0; i < nb_numa_nodes - 1; i++) {

                numa_info[i].node_mem = (ram_size / nb_numa_nodes) &

                                        ~((1 << 23UL) - 1);

                usedmem += numa_info[i].node_mem;

            }

            numa_info[i].node_mem = ram_size - usedmem;

        }

        numa_total = 0;

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

            numa_total += numa_info[i].node_mem;

        }

        if (numa_total != ram_size) {

            error_report("total memory for NUMA nodes (0x%" PRIx64 ")"

                         " should equal RAM size (0x" RAM_ADDR_FMT ")",

                         numa_total, ram_size);

            exit(1);

        }

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

            QLIST_INIT(&numa_info[i].addr);

        }

        numa_set_mem_ranges();

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

            if (!bitmap_empty(numa_info[i].node_cpu, MAX_CPUMASK_BITS)) {

                break;

            }

        }

        /* Historically VCPUs were assigned in round-robin order to NUMA

         * nodes. However it causes issues with guest not handling it nice

         * in case where cores/threads from a multicore CPU appear on

         * different nodes. So allow boards to override default distribution

         * rule grouping VCPUs by socket so that VCPUs from the same socket

         * would be on the same node.

         */

        if (i == nb_numa_nodes) {

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

                unsigned node_id = i % nb_numa_nodes;

                if (mc->cpu_index_to_socket_id) {

                    node_id = mc->cpu_index_to_socket_id(i) % nb_numa_nodes;

                }

                set_bit(i, numa_info[node_id].node_cpu);

            }

        }

        validate_numa_cpus();

    } else {

        numa_set_mem_node_id(0, ram_size, 0);

    }

}


static inline uint8_t *bt_hci_event_start(struct bt_hci_s *hci,

                int evt, int len)

{

    uint8_t *packet, mask;

    int mask_byte;

    if (len > 255) {

        fprintf(stderr, "%s: HCI event params too long (%ib)\n",

                        __FUNCTION__, len);

        exit(-1);

    }

    mask_byte = (evt - 1) >> 3;

    mask = 1 << ((evt - 1) & 3);

    if (mask & bt_event_reserved_mask[mask_byte] & ~hci->event_mask[mask_byte])

        return NULL;

    packet = hci->evt_packet(hci->opaque);

    packet[0] = evt;

    packet[1] = len;

    return &packet[2];

}


uint64_t helper_efdctsidz (uint64_t val)

{

    CPU_DoubleU u;

    u.ll = val;

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

    if (unlikely(float64_is_nan(u.d)))

        return 0;

    return float64_to_int64_round_to_zero(u.d, &env->vec_status);

}


static int kvm_has_msr_star(CPUState *env)

{

    kvm_supported_msrs(env);

    return has_msr_star;

}


int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)

{

    if (whence == SEEK_SET) {

        /* nothing to do */

    } else if (whence == SEEK_CUR) {

        pos += qemu_ftell(f);

    } else {

        /* SEEK_END not supported */

        return -1;

    }

    if (f->is_writable) {

        qemu_fflush(f);

        f->buf_offset = pos;

    } else {

        f->buf_offset = pos;

        f->buf_index = 0;

        f->buf_size = 0;

    }

    return pos;

}


static void qbus_list_dev(BusState *bus, char *dest, int len)

{

    DeviceState *dev;

    const char *sep = " ";

    int pos = 0;

    pos += snprintf(dest+pos, len-pos, "devices at \"%s\":",

                    bus->name);

    LIST_FOREACH(dev, &bus->children, sibling) {

        pos += snprintf(dest+pos, len-pos, "%s\"%s\"",

                        sep, dev->info->name);

        if (dev->id)

            pos += snprintf(dest+pos, len-pos, "/\"%s\"", dev->id);

        sep = ", ";

    }

}


void vnc_zlib_zfree(void *x, void *addr)

{

    qemu_free(addr);

}


static target_ulong h_put_term_char(CPUState *env, sPAPREnvironment *spapr,

                                    target_ulong opcode, target_ulong *args)

{

    target_ulong reg = args[0];

    target_ulong len = args[1];

    target_ulong char0_7 = args[2];

    target_ulong char8_15 = args[3];

    VIOsPAPRDevice *sdev = spapr_vio_find_by_reg(spapr->vio_bus, reg);

    uint8_t buf[16];

    if (!sdev) {

        return H_PARAMETER;

    }

    if (len > 16) {

        return H_PARAMETER;

    }

    *((uint64_t *)buf) = cpu_to_be64(char0_7);

    *((uint64_t *)buf + 1) = cpu_to_be64(char8_15);

    vty_putchars(sdev, buf, len);

    return H_SUCCESS;

}


static void thread_pool_co_cb(void *opaque, int ret)

{

    ThreadPoolCo *co = opaque;

    co->ret = ret;

    qemu_coroutine_enter(co->co);

}


static int qemu_balloon(ram_addr_t target)

{

    if (!balloon_event_fn) {

        return 0;

    }

    trace_balloon_event(balloon_opaque, target);

    balloon_event_fn(balloon_opaque, target);

    return 1;

}


static bool cmd_write_dma(IDEState *s, uint8_t cmd)

{

    bool lba48 = (cmd == WIN_WRITEDMA_EXT);

    if (!s->bs) {

        ide_abort_command(s);

        return true;

    }

    ide_cmd_lba48_transform(s, lba48);

    ide_sector_start_dma(s, IDE_DMA_WRITE);

    s->media_changed = 1;

    return false;

}


static uint64_t pxa2xx_pm_read(void *opaque, hwaddr addr,

                               unsigned size)

{

    PXA2xxState *s = (PXA2xxState *) opaque;

    switch (addr) {

    case PMCR ... PCMD31:

        if (addr & 3)

            goto fail;

        return s->pm_regs[addr >> 2];

    default:

    fail:

        printf("%s: Bad register " REG_FMT "\n", __FUNCTION__, addr);

        break;

    }

    return 0;

}


static void ics_base_realize(DeviceState *dev, Error **errp)

{

    ICSStateClass *icsc = ICS_BASE_GET_CLASS(dev);

    ICSState *ics = ICS_BASE(dev);

    Object *obj;

    Error *err = NULL;

    obj = object_property_get_link(OBJECT(dev), ICS_PROP_XICS, &err);

    if (!obj) {

        error_setg(errp, "%s: required link '" ICS_PROP_XICS "' not found: %s",

                   __func__, error_get_pretty(err));

        return;

    }

    ics->xics = XICS_FABRIC(obj);

    if (icsc->realize) {

        icsc->realize(dev, errp);

    }

}


bool postcopy_ram_supported_by_host(void)

{

    error_report("%s: No OS support", __func__);

    return false;

}


int64_t qemu_file_get_rate_limit(QEMUFile *f)

{

    return f->xfer_limit;

}


static inline void put_codeword(PutBitContext *pb, vorbis_enc_codebook *cb,

                                int entry)

{

    assert(entry >= 0);

    assert(entry < cb->nentries);

    assert(cb->lens[entry]);

    put_bits(pb, cb->lens[entry], cb->codewords[entry]);

}


static inline int qemu_rdma_buffer_mergable(RDMAContext *rdma,

                    uint64_t offset, uint64_t len)

{

    RDMALocalBlock *block;

    uint8_t *host_addr;

    uint8_t *chunk_end;

    if (rdma->current_index < 0) {

        return 0;

    }

    if (rdma->current_chunk < 0) {

        return 0;

    }

    block = &(rdma->local_ram_blocks.block[rdma->current_index]);

    host_addr = block->local_host_addr + (offset - block->offset);

    chunk_end = ram_chunk_end(block, rdma->current_chunk);

    if (rdma->current_length == 0) {

        return 0;

    }

    /*

     * Only merge into chunk sequentially.

     */

    if (offset != (rdma->current_addr + rdma->current_length)) {

        return 0;

    }

    if (offset < block->offset) {

        return 0;

    }

    if ((offset + len) > (block->offset + block->length)) {

        return 0;

    }

    if ((host_addr + len) > chunk_end) {

        return 0;

    }

    return 1;

}


static int vmdk_open_desc_file(BlockDriverState *bs, int flags,

                               int64_t desc_offset)

{

    int ret;

    char buf[2048];

    char ct[128];

    BDRVVmdkState *s = bs->opaque;

    ret = bdrv_pread(bs->file, desc_offset, buf, sizeof(buf));

    if (ret < 0) {

        return ret;

    }

    buf[2047] = '\0';

    if (vmdk_parse_description(buf, "createType", ct, sizeof(ct))) {

        return -EINVAL;

    }

    if (strcmp(ct, "monolithicFlat") &&

        strcmp(ct, "twoGbMaxExtentSparse") &&

        strcmp(ct, "twoGbMaxExtentFlat")) {

        fprintf(stderr,

                "VMDK: Not supported image type \"%s\""".\n", ct);

        return -ENOTSUP;

    }

    s->desc_offset = 0;

    ret = vmdk_parse_extents(buf, bs, bs->file->filename);

    if (ret) {

        return ret;

    }

    /* try to open parent images, if exist */

    if (vmdk_parent_open(bs)) {

        g_free(s->extents);

        return -EINVAL;

    }

    s->parent_cid = vmdk_read_cid(bs, 1);

    return 0;

}


static void vc1_mc_4mv_chroma(VC1Context *v, int dir)

{

    MpegEncContext *s = &v->s;

    H264ChromaContext *h264chroma = &v->h264chroma;

    uint8_t *srcU, *srcV;

    int uvmx, uvmy, uvsrc_x, uvsrc_y;

    int k, tx = 0, ty = 0;

    int mvx[4], mvy[4], intra[4], mv_f[4];

    int valid_count;

    int chroma_ref_type = v->cur_field_type;

    int v_edge_pos = s->v_edge_pos >> v->field_mode;

    uint8_t (*lutuv)[256];

    int use_ic;

    if (!v->field_mode && !v->s.last_picture.f.data[0])

        return;

    if (s->flags & CODEC_FLAG_GRAY)

        return;

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

        mvx[k] = s->mv[dir][k][0];

        mvy[k] = s->mv[dir][k][1];

        intra[k] = v->mb_type[0][s->block_index[k]];

        if (v->field_mode)

            mv_f[k] = v->mv_f[dir][s->block_index[k] + v->blocks_off];

    }

    /* calculate chroma MV vector from four luma MVs */

    if (!v->field_mode || (v->field_mode && !v->numref)) {

        valid_count = get_chroma_mv(mvx, mvy, intra, 0, &tx, &ty);

        chroma_ref_type = v->reffield;

        if (!valid_count) {

            s->current_picture.motion_val[1][s->block_index[0] + v->blocks_off][0] = 0;

            s->current_picture.motion_val[1][s->block_index[0] + v->blocks_off][1] = 0;

            v->luma_mv[s->mb_x][0] = v->luma_mv[s->mb_x][1] = 0;

            return; //no need to do MC for intra blocks

        }

    } else {

        int dominant = 0;

        if (mv_f[0] + mv_f[1] + mv_f[2] + mv_f[3] > 2)

            dominant = 1;

        valid_count = get_chroma_mv(mvx, mvy, mv_f, dominant, &tx, &ty);

        if (dominant)

            chroma_ref_type = !v->cur_field_type;

    }

    if (v->field_mode && chroma_ref_type == 1 && v->cur_field_type == 1 && !v->s.last_picture.f.data[0])

        return;

    s->current_picture.motion_val[1][s->block_index[0] + v->blocks_off][0] = tx;

    s->current_picture.motion_val[1][s->block_index[0] + v->blocks_off][1] = ty;

    uvmx = (tx + ((tx & 3) == 3)) >> 1;

    uvmy = (ty + ((ty & 3) == 3)) >> 1;

    v->luma_mv[s->mb_x][0] = uvmx;

    v->luma_mv[s->mb_x][1] = uvmy;

    if (v->fastuvmc) {

        uvmx = uvmx + ((uvmx < 0) ? (uvmx & 1) : -(uvmx & 1));

        uvmy = uvmy + ((uvmy < 0) ? (uvmy & 1) : -(uvmy & 1));

    }

    // Field conversion bias

    if (v->cur_field_type != chroma_ref_type)

        uvmy += 2 - 4 * chroma_ref_type;

    uvsrc_x = s->mb_x * 8 + (uvmx >> 2);

    uvsrc_y = s->mb_y * 8 + (uvmy >> 2);

    if (v->profile != PROFILE_ADVANCED) {

        uvsrc_x = av_clip(uvsrc_x, -8, s->mb_width  * 8);

        uvsrc_y = av_clip(uvsrc_y, -8, s->mb_height * 8);

    } else {

        uvsrc_x = av_clip(uvsrc_x, -8, s->avctx->coded_width  >> 1);

        uvsrc_y = av_clip(uvsrc_y, -8, s->avctx->coded_height >> 1);

    }

    if (!dir) {

        if (v->field_mode && (v->cur_field_type != chroma_ref_type) && v->second_field) {

            srcU = s->current_picture.f.data[1];

            srcV = s->current_picture.f.data[2];

            lutuv = v->curr_lutuv;

            use_ic = v->curr_use_ic;

        } else {

            srcU = s->last_picture.f.data[1];

            srcV = s->last_picture.f.data[2];

            lutuv = v->last_lutuv;

            use_ic = v->last_use_ic;

        }

    } else {

        srcU = s->next_picture.f.data[1];

        srcV = s->next_picture.f.data[2];

        lutuv = v->next_lutuv;

        use_ic = v->next_use_ic;

    }

    if (!srcU) {

        av_log(v->s.avctx, AV_LOG_ERROR, "Referenced frame missing.\n");

        return;

    }

    srcU += uvsrc_y * s->uvlinesize + uvsrc_x;

    srcV += uvsrc_y * s->uvlinesize + uvsrc_x;

    if (v->field_mode) {

        if (chroma_ref_type) {

            srcU += s->current_picture_ptr->f.linesize[1];

            srcV += s->current_picture_ptr->f.linesize[2];

        }

    }

    if (v->rangeredfrm || use_ic

        || s->h_edge_pos < 18 || v_edge_pos < 18

        || (unsigned)uvsrc_x > (s->h_edge_pos >> 1) - 9

        || (unsigned)uvsrc_y > (v_edge_pos    >> 1) - 9) {

        s->vdsp.emulated_edge_mc(s->edge_emu_buffer, srcU,

                                 s->uvlinesize, s->uvlinesize,

                                 8 + 1, 8 + 1, uvsrc_x, uvsrc_y,

                                 s->h_edge_pos >> 1, v_edge_pos >> 1);

        s->vdsp.emulated_edge_mc(s->edge_emu_buffer + 16, srcV,

                                 s->uvlinesize, s->uvlinesize,

                                 8 + 1, 8 + 1, uvsrc_x, uvsrc_y,

                                 s->h_edge_pos >> 1, v_edge_pos >> 1);

        srcU = s->edge_emu_buffer;

        srcV = s->edge_emu_buffer + 16;

        /* if we deal with range reduction we need to scale source blocks */

        if (v->rangeredfrm) {

            int i, j;

            uint8_t *src, *src2;

            src  = srcU;

            src2 = srcV;

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

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

                    src[i]  = ((src[i]  - 128) >> 1) + 128;

                    src2[i] = ((src2[i] - 128) >> 1) + 128;

                }

                src  += s->uvlinesize;

                src2 += s->uvlinesize;

            }

        }

        /* if we deal with intensity compensation we need to scale source blocks */

        if (use_ic) {

            int i, j;

            uint8_t *src, *src2;

            src  = srcU;

            src2 = srcV;

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

                int f = v->field_mode ? chroma_ref_type : ((j + uvsrc_y) & 1);

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

                    src[i]  = lutuv[f][src[i]];

                    src2[i] = lutuv[f][src2[i]];

                }

                src  += s->uvlinesize;

                src2 += s->uvlinesize;

            }

        }

    }

    /* Chroma MC always uses qpel bilinear */

    uvmx = (uvmx & 3) << 1;

    uvmy = (uvmy & 3) << 1;

    if (!v->rnd) {

        h264chroma->put_h264_chroma_pixels_tab[0](s->dest[1], srcU, s->uvlinesize, 8, uvmx, uvmy);

        h264chroma->put_h264_chroma_pixels_tab[0](s->dest[2], srcV, s->uvlinesize, 8, uvmx, uvmy);

    } else {

        v->vc1dsp.put_no_rnd_vc1_chroma_pixels_tab[0](s->dest[1], srcU, s->uvlinesize, 8, uvmx, uvmy);

        v->vc1dsp.put_no_rnd_vc1_chroma_pixels_tab[0](s->dest[2], srcV, s->uvlinesize, 8, uvmx, uvmy);

    }

}


void palette8torgb24(const uint8_t *src, uint8_t *dst, unsigned num_pixels, const uint8_t *palette)

{

	unsigned i;

/*

	writes 1 byte o much and might cause alignment issues on some architectures?

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

		((unsigned *)(&dst[i*3])) = ((unsigned *)palette)[ src[i] ];

*/

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

	{

		//FIXME slow?

		dst[0]= palette[ src[i]*4+2 ];

		dst[1]= palette[ src[i]*4+1 ];

		dst[2]= palette[ src[i]*4+0 ];

		dst+= 3;

	}

}


static int ogg_restore(AVFormatContext *s, int discard)

{

    struct ogg *ogg = s->priv_data;

    AVIOContext *bc = s->pb;

    struct ogg_state *ost = ogg->state;

    int i;

    if (!ost)

        return 0;

    ogg->state = ost->next;

    if (!discard){

        for (i = 0; i < ogg->nstreams; i++)

            av_free (ogg->streams[i].buf);

        avio_seek (bc, ost->pos, SEEK_SET);

        ogg->curidx = ost->curidx;

        ogg->nstreams = ost->nstreams;

        memcpy(ogg->streams, ost->streams,

               ost->nstreams * sizeof(*ogg->streams));

    }

    av_free (ost);

    return 0;

}


rdt_free_context (PayloadContext *rdt)

{

    int i;

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

        if (rdt->rmst[i]) {

            ff_rm_free_rmstream(rdt->rmst[i]);

            av_freep(&rdt->rmst[i]);

        }

    if (rdt->rmctx)

        av_close_input_stream(rdt->rmctx);

    av_freep(&rdt->mlti_data);

    av_free(rdt);

}


static inline void RENAME(yuvPlanartoyuy2)(const uint8_t *ysrc, const uint8_t *usrc, const uint8_t *vsrc, uint8_t *dst,

	long width, long height,

	long lumStride, long chromStride, long dstStride, long vertLumPerChroma)

{

	long y;

	const long chromWidth= width>>1;

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

	{

#ifdef HAVE_MMX

//FIXME handle 2 lines a once (fewer prefetch, reuse some chrom, but very likely limited by mem anyway)

		asm volatile(

			"xor %%"REG_a", %%"REG_a"	\n\t"

			ASMALIGN(4)

			"1:				\n\t"

			PREFETCH" 32(%1, %%"REG_a", 2)	\n\t"

			PREFETCH" 32(%2, %%"REG_a")	\n\t"

			PREFETCH" 32(%3, %%"REG_a")	\n\t"

			"movq (%2, %%"REG_a"), %%mm0	\n\t" // U(0)

			"movq %%mm0, %%mm2		\n\t" // U(0)

			"movq (%3, %%"REG_a"), %%mm1	\n\t" // V(0)

			"punpcklbw %%mm1, %%mm0		\n\t" // UVUV UVUV(0)

			"punpckhbw %%mm1, %%mm2		\n\t" // UVUV UVUV(8)

			"movq (%1, %%"REG_a",2), %%mm3	\n\t" // Y(0)

			"movq 8(%1, %%"REG_a",2), %%mm5	\n\t" // Y(8)

			"movq %%mm3, %%mm4		\n\t" // Y(0)

			"movq %%mm5, %%mm6		\n\t" // Y(8)

			"punpcklbw %%mm0, %%mm3		\n\t" // YUYV YUYV(0)

			"punpckhbw %%mm0, %%mm4		\n\t" // YUYV YUYV(4)

			"punpcklbw %%mm2, %%mm5		\n\t" // YUYV YUYV(8)

			"punpckhbw %%mm2, %%mm6		\n\t" // YUYV YUYV(12)

			MOVNTQ" %%mm3, (%0, %%"REG_a", 4)\n\t"

			MOVNTQ" %%mm4, 8(%0, %%"REG_a", 4)\n\t"

			MOVNTQ" %%mm5, 16(%0, %%"REG_a", 4)\n\t"

			MOVNTQ" %%mm6, 24(%0, %%"REG_a", 4)\n\t"

			"add $8, %%"REG_a"		\n\t"

			"cmp %4, %%"REG_a"		\n\t"

			" jb 1b				\n\t"

			::"r"(dst), "r"(ysrc), "r"(usrc), "r"(vsrc), "g" (chromWidth)

			: "%"REG_a

		);

#else

#if defined ARCH_ALPHA && defined HAVE_MVI

#define pl2yuy2(n)					\

	y1 = yc[n];					\

	y2 = yc2[n];					\

	u = uc[n];					\

	v = vc[n];					\

	asm("unpkbw %1, %0" : "=r"(y1) : "r"(y1));	\

	asm("unpkbw %1, %0" : "=r"(y2) : "r"(y2));	\

	asm("unpkbl %1, %0" : "=r"(u) : "r"(u));	\

	asm("unpkbl %1, %0" : "=r"(v) : "r"(v));	\

	yuv1 = (u << 8) + (v << 24);			\

	yuv2 = yuv1 + y2;				\

	yuv1 += y1;					\

	qdst[n] = yuv1;					\

	qdst2[n] = yuv2;

		int i;

		uint64_t *qdst = (uint64_t *) dst;

		uint64_t *qdst2 = (uint64_t *) (dst + dstStride);

		const uint32_t *yc = (uint32_t *) ysrc;

		const uint32_t *yc2 = (uint32_t *) (ysrc + lumStride);

		const uint16_t *uc = (uint16_t*) usrc, *vc = (uint16_t*) vsrc;

		for(i = 0; i < chromWidth; i += 8){

			uint64_t y1, y2, yuv1, yuv2;

			uint64_t u, v;

			/* Prefetch */

			asm("ldq $31,64(%0)" :: "r"(yc));

			asm("ldq $31,64(%0)" :: "r"(yc2));

			asm("ldq $31,64(%0)" :: "r"(uc));

			asm("ldq $31,64(%0)" :: "r"(vc));

			pl2yuy2(0);

			pl2yuy2(1);

			pl2yuy2(2);

			pl2yuy2(3);

			yc += 4;

			yc2 += 4;

			uc += 4;

			vc += 4;

			qdst += 4;

			qdst2 += 4;

		}

		y++;

		ysrc += lumStride;

		dst += dstStride;

#elif __WORDSIZE >= 64

		int i;

		uint64_t *ldst = (uint64_t *) dst;

		const uint8_t *yc = ysrc, *uc = usrc, *vc = vsrc;

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

			uint64_t k, l;

			k = yc[0] + (uc[0] << 8) +

			    (yc[1] << 16) + (vc[0] << 24);

			l = yc[2] + (uc[1] << 8) +

			    (yc[3] << 16) + (vc[1] << 24);

			*ldst++ = k + (l << 32);

			yc += 4;

			uc += 2;

			vc += 2;

		}

#else

		int i, *idst = (int32_t *) dst;

		const uint8_t *yc = ysrc, *uc = usrc, *vc = vsrc;

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

#ifdef WORDS_BIGENDIAN

			*idst++ = (yc[0] << 24)+ (uc[0] << 16) +

			    (yc[1] << 8) + (vc[0] << 0);

#else

			*idst++ = yc[0] + (uc[0] << 8) +

			    (yc[1] << 16) + (vc[0] << 24);

#endif

			yc += 2;

			uc++;

			vc++;

		}

#endif

#endif

		if((y&(vertLumPerChroma-1))==(vertLumPerChroma-1) )

		{

			usrc += chromStride;

			vsrc += chromStride;

		}

		ysrc += lumStride;

		dst += dstStride;

	}

#ifdef HAVE_MMX

asm(    EMMS" \n\t"

        SFENCE" \n\t"

        :::"memory");

#endif

}


void visit_start_struct(Visitor *v, void **obj, const char *kind,

                        const char *name, size_t size, Error **errp)

{

    if (!error_is_set(errp)) {

        v->start_struct(v, obj, kind, name, size, errp);

    }

}


static int encode_nals(AVCodecContext *ctx, uint8_t *buf, int size,

                       x264_nal_t *nals, int nnal, int skip_sei)

{

    X264Context *x4 = ctx->priv_data;

    uint8_t *p = buf;

    int i;

    /* Write the SEI as part of the first frame. */

    if (x4->sei_size > 0 && nnal > 0) {

        if (x4->sei_size > size) {

            return -1;

        memcpy(p, x4->sei, x4->sei_size);

        p += x4->sei_size;

        x4->sei_size = 0;

        // why is x4->sei not freed?

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

        /* Don't put the SEI in extradata. */

        if (skip_sei && nals[i].i_type == NAL_SEI) {

            x4->sei_size = nals[i].i_payload;

            x4->sei      = av_malloc(x4->sei_size);

            memcpy(x4->sei, nals[i].p_payload, nals[i].i_payload);

            continue;

        memcpy(p, nals[i].p_payload, nals[i].i_payload);

        p += nals[i].i_payload;

    return p - buf;


static int copy_stream_props(AVStream *st, AVStream *source_st)

{

    int ret;

    if (st->codecpar->codec_id || !source_st->codecpar->codec_id) {

        if (st->codecpar->extradata_size < source_st->codecpar->extradata_size) {

            if (st->codecpar->extradata) {

                av_freep(&st->codecpar->extradata);

                st->codecpar->extradata_size = 0;

            }

            ret = ff_alloc_extradata(st->codecpar,

                                     source_st->codecpar->extradata_size);

            if (ret < 0)

                return ret;

        }

        memcpy(st->codecpar->extradata, source_st->codecpar->extradata,

               source_st->codecpar->extradata_size);

        return 0;

    }

    if ((ret = avcodec_parameters_copy(st->codecpar, source_st->codecpar)) < 0)

        return ret;

    st->r_frame_rate        = source_st->r_frame_rate;

    st->avg_frame_rate      = source_st->avg_frame_rate;

    st->time_base           = source_st->time_base;

    st->sample_aspect_ratio = source_st->sample_aspect_ratio;

    av_dict_copy(&st->metadata, source_st->metadata, 0);

    return 0;

}


aio_ctx_finalize(GSource     *source)
{
    AioContext *ctx = (AioContext *) source;
    thread_pool_free(ctx->thread_pool);
    aio_set_event_notifier(ctx, &ctx->notifier, NULL);
    event_notifier_cleanup(&ctx->notifier);
    rfifolock_destroy(&ctx->lock);
    qemu_mutex_destroy(&ctx->bh_lock);
    timerlistgroup_deinit(&ctx->tlg);


void gen_intermediate_code_internal(LM32CPU *cpu,

                                    TranslationBlock *tb, bool search_pc)

{

    CPUState *cs = CPU(cpu);

    CPULM32State *env = &cpu->env;

    struct DisasContext ctx, *dc = &ctx;

    uint16_t *gen_opc_end;

    uint32_t pc_start;

    int j, lj;

    uint32_t next_page_start;

    int num_insns;

    int max_insns;

    pc_start = tb->pc;

    dc->env = env;

    dc->tb = tb;

    gen_opc_end = tcg_ctx.gen_opc_buf + OPC_MAX_SIZE;

    dc->is_jmp = DISAS_NEXT;

    dc->pc = pc_start;

    dc->singlestep_enabled = cs->singlestep_enabled;

    dc->nr_nops = 0;

    if (pc_start & 3) {

        cpu_abort(env, "LM32: unaligned PC=%x\n", pc_start);

    }

    next_page_start = (pc_start & TARGET_PAGE_MASK) + TARGET_PAGE_SIZE;

    lj = -1;

    num_insns = 0;

    max_insns = tb->cflags & CF_COUNT_MASK;

    if (max_insns == 0) {

        max_insns = CF_COUNT_MASK;

    }

    gen_tb_start();

    do {

        check_breakpoint(env, dc);

        if (search_pc) {

            j = tcg_ctx.gen_opc_ptr - tcg_ctx.gen_opc_buf;

            if (lj < j) {

                lj++;

                while (lj < j) {

                    tcg_ctx.gen_opc_instr_start[lj++] = 0;

                }

            }

            tcg_ctx.gen_opc_pc[lj] = dc->pc;

            tcg_ctx.gen_opc_instr_start[lj] = 1;

            tcg_ctx.gen_opc_icount[lj] = num_insns;

        }

        /* Pretty disas.  */

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

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

            gen_io_start();

        }

        decode(dc, cpu_ldl_code(env, dc->pc));

        dc->pc += 4;

        num_insns++;

    } while (!dc->is_jmp

         && tcg_ctx.gen_opc_ptr < gen_opc_end

         && !cs->singlestep_enabled

         && !singlestep

         && (dc->pc < next_page_start)

         && num_insns < max_insns);

    if (tb->cflags & CF_LAST_IO) {

        gen_io_end();

    }

    if (unlikely(cs->singlestep_enabled)) {

        if (dc->is_jmp == DISAS_NEXT) {

            tcg_gen_movi_tl(cpu_pc, dc->pc);

        }

        t_gen_raise_exception(dc, EXCP_DEBUG);

    } else {

        switch (dc->is_jmp) {

        case DISAS_NEXT:

            gen_goto_tb(dc, 1, dc->pc);

            break;

        default:

        case DISAS_JUMP:

        case DISAS_UPDATE:

            /* indicate that the hash table must be used

               to find the next TB */

            tcg_gen_exit_tb(0);

            break;

        case DISAS_TB_JUMP:

            /* nothing more to generate */

            break;

        }

    }

    gen_tb_end(tb, num_insns);

    *tcg_ctx.gen_opc_ptr = INDEX_op_end;

    if (search_pc) {

        j = tcg_ctx.gen_opc_ptr - tcg_ctx.gen_opc_buf;

        lj++;

        while (lj <= j) {

            tcg_ctx.gen_opc_instr_start[lj++] = 0;

        }

    } else {

        tb->size = dc->pc - pc_start;

        tb->icount = num_insns;

    }

#ifdef DEBUG_DISAS

    if (qemu_loglevel_mask(CPU_LOG_TB_IN_ASM)) {

        qemu_log("\n");

        log_target_disas(env, pc_start, dc->pc - pc_start, 0);

        qemu_log("\nisize=%d osize=%td\n",

            dc->pc - pc_start, tcg_ctx.gen_opc_ptr -

            tcg_ctx.gen_opc_buf);

    }

#endif

}


static int parse_keyframes_index(AVFormatContext *s, AVIOContext *ioc, AVStream *vstream, int64_t max_pos) {

    unsigned int arraylen = 0, timeslen = 0, fileposlen = 0, i;

    double num_val;

    char str_val[256];

    int64_t *times = NULL;

    int64_t *filepositions = NULL;

    int ret = AVERROR(ENOSYS);

    int64_t initial_pos = avio_tell(ioc);

    AVDictionaryEntry *creator = av_dict_get(s->metadata, "metadatacreator",

                                             NULL, 0);

    if (creator && !strcmp(creator->value, "MEGA")) {

        /* Files with this metadatacreator tag seem to have filepositions

         * pointing at the 4 trailer bytes of the previous packet,

         * which isn't the norm (nor what we expect here, nor what

         * jwplayer + lighttpd expect, nor what flvtool2 produces).

         * Just ignore the index in this case, instead of risking trying

         * to adjust it to something that might or might not work. */

        return 0;

    }

    while (avio_tell(ioc) < max_pos - 2 && amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {

        int64_t* current_array;

        // Expect array object in context

        if (avio_r8(ioc) != AMF_DATA_TYPE_ARRAY)

            break;

        arraylen = avio_rb32(ioc);

        /*

         * Expect only 'times' or 'filepositions' sub-arrays in other case refuse to use such metadata

         * for indexing

         */

        if (!strcmp(KEYFRAMES_TIMESTAMP_TAG, str_val) && !times) {

            if (!(times = av_mallocz(sizeof(*times) * arraylen))) {

                ret = AVERROR(ENOMEM);

                goto finish;

            }

            timeslen = arraylen;

            current_array = times;

        } else if (!strcmp(KEYFRAMES_BYTEOFFSET_TAG, str_val) && !filepositions) {

            if (!(filepositions = av_mallocz(sizeof(*filepositions) * arraylen))) {

                ret = AVERROR(ENOMEM);

                goto finish;

            }

            fileposlen = arraylen;

            current_array = filepositions;

        } else // unexpected metatag inside keyframes, will not use such metadata for indexing

            break;

        for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++) {

            if (avio_r8(ioc) != AMF_DATA_TYPE_NUMBER)

                goto finish;

            num_val = av_int2dbl(avio_rb64(ioc));

            current_array[i] = num_val;

        }

        if (times && filepositions) {

            // All done, exiting at a position allowing amf_parse_object

            // to finish parsing the object

            ret = 0;

            break;

        }

    }

    if (timeslen == fileposlen)

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

             av_add_index_entry(vstream, filepositions[i], times[i]*1000, 0, 0, AVINDEX_KEYFRAME);

    else

        av_log(s, AV_LOG_WARNING, "Invalid keyframes object, skipping.\n");

finish:

    av_freep(&times);

    av_freep(&filepositions);

    // If we got unexpected data, but successfully reset back to

    // the start pos, the caller can continue parsing

    if (ret < 0 && avio_seek(ioc, initial_pos, SEEK_SET) > 0)

        return 0;

    return ret;

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);

    k->init = vt82c686b_ide_initfn;

    k->exit = vt82c686b_ide_exitfn;

    k->vendor_id = PCI_VENDOR_ID_VIA;

    k->device_id = PCI_DEVICE_ID_VIA_IDE;

    k->revision = 0x06;

    k->class_id = PCI_CLASS_STORAGE_IDE;

    set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);

    dc->no_user = 1;

}


static void vc1_extract_headers(AVCodecParserContext *s, AVCodecContext *avctx,

                                const uint8_t *buf, int buf_size)

{

    VC1ParseContext *vpc = s->priv_data;

    GetBitContext gb;

    const uint8_t *start, *end, *next;

    uint8_t *buf2 = av_mallocz(buf_size + FF_INPUT_BUFFER_PADDING_SIZE);

    vpc->v.s.avctx = avctx;

    vpc->v.parse_only = 1;

    vpc->v.first_pic_header_flag = 1;

    next = buf;

    s->repeat_pict = 0;

    for(start = buf, end = buf + buf_size; next < end; start = next){

        int buf2_size, size;

        next = find_next_marker(start + 4, end);

        size = next - start - 4;

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

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

        if(size <= 0) continue;

        switch(AV_RB32(start)){

        case VC1_CODE_SEQHDR:

            ff_vc1_decode_sequence_header(avctx, &vpc->v, &gb);

            break;

        case VC1_CODE_ENTRYPOINT:

            ff_vc1_decode_entry_point(avctx, &vpc->v, &gb);

            break;

        case VC1_CODE_FRAME:

            if(vpc->v.profile < PROFILE_ADVANCED)

                ff_vc1_parse_frame_header    (&vpc->v, &gb);

            else

                ff_vc1_parse_frame_header_adv(&vpc->v, &gb);

            /* keep AV_PICTURE_TYPE_BI internal to VC1 */

            if (vpc->v.s.pict_type == AV_PICTURE_TYPE_BI)

                s->pict_type = AV_PICTURE_TYPE_B;

            else

                s->pict_type = vpc->v.s.pict_type;

            if (avctx->ticks_per_frame > 1){

                // process pulldown flags

                s->repeat_pict = 1;

                // Pulldown flags are only valid when 'broadcast' has been set.

                // So ticks_per_frame will be 2

                if (vpc->v.rff){

                    // repeat field

                    s->repeat_pict = 2;

                }else if (vpc->v.rptfrm){

                    // repeat frames

                    s->repeat_pict = vpc->v.rptfrm * 2 + 1;

                }

            }

            if (vpc->v.broadcast && vpc->v.interlace && !vpc->v.psf)

                s->field_order = vpc->v.tff ? AV_FIELD_TT : AV_FIELD_BB;

            else

                s->field_order = AV_FIELD_PROGRESSIVE;

            break;

        }

    }

    av_free(buf2);

}


int ff_jpeg2000_init_component(Jpeg2000Component *comp,
                               Jpeg2000CodingStyle *codsty,
                               Jpeg2000QuantStyle *qntsty,
                               int cbps, int dx, int dy,
                               AVCodecContext *avctx)
{
    int reslevelno, bandno, gbandno = 0, ret, i, j;
    uint32_t csize;
    if (codsty->nreslevels2decode <= 0) {
        av_log(avctx, AV_LOG_ERROR, "nreslevels2decode %d invalid or uninitialized\n", codsty->nreslevels2decode);
        return AVERROR_INVALIDDATA;
    }
    if (ret = ff_jpeg2000_dwt_init(&comp->dwt, comp->coord,
                                   codsty->nreslevels2decode - 1,
                                   codsty->transform))
        return ret;
    if (av_image_check_size(comp->coord[0][1] - comp->coord[0][0],
                            comp->coord[1][1] - comp->coord[1][0], 0, avctx))
        return AVERROR_INVALIDDATA;
    csize = (comp->coord[0][1] - comp->coord[0][0]) *
            (comp->coord[1][1] - comp->coord[1][0]);
    if (comp->coord[0][1] - comp->coord[0][0] > 32768 ||
        comp->coord[1][1] - comp->coord[1][0] > 32768) {
        av_log(avctx, AV_LOG_ERROR, "component size too large\n");
        return AVERROR_PATCHWELCOME;
    }
    if (codsty->transform == FF_DWT97) {
        csize += AV_INPUT_BUFFER_PADDING_SIZE / sizeof(*comp->f_data);
        comp->i_data = NULL;
        comp->f_data = av_mallocz_array(csize, sizeof(*comp->f_data));
        if (!comp->f_data)
    } else {
        csize += AV_INPUT_BUFFER_PADDING_SIZE / sizeof(*comp->i_data);
        comp->f_data = NULL;
        comp->i_data = av_mallocz_array(csize, sizeof(*comp->i_data));
        if (!comp->i_data)
    }
    comp->reslevel = av_mallocz_array(codsty->nreslevels, sizeof(*comp->reslevel));
    if (!comp->reslevel)
    /* LOOP on resolution levels */
    for (reslevelno = 0; reslevelno < codsty->nreslevels; reslevelno++) {
        int declvl = codsty->nreslevels - reslevelno;    // N_L -r see  ISO/IEC 15444-1:2002 B.5
        Jpeg2000ResLevel *reslevel = comp->reslevel + reslevelno;
        /* Compute borders for each resolution level.
         * Computation of trx_0, trx_1, try_0 and try_1.
         * see ISO/IEC 15444-1:2002 eq. B.5 and B-14 */
        for (i = 0; i < 2; i++)
            for (j = 0; j < 2; j++)
                reslevel->coord[i][j] =
                    ff_jpeg2000_ceildivpow2(comp->coord_o[i][j], declvl - 1);
        // update precincts size: 2^n value
        reslevel->log2_prec_width  = codsty->log2_prec_widths[reslevelno];
        reslevel->log2_prec_height = codsty->log2_prec_heights[reslevelno];
        if (!reslevel->log2_prec_width || !reslevel->log2_prec_height) {
            return AVERROR_INVALIDDATA;
        }
        /* Number of bands for each resolution level */
        if (reslevelno == 0)
            reslevel->nbands = 1;
        else
            reslevel->nbands = 3;
        /* Number of precincts which span the tile for resolution level reslevelno
         * see B.6 in ISO/IEC 15444-1:2002 eq. B-16
         * num_precincts_x = |- trx_1 / 2 ^ log2_prec_width) -| - (trx_0 / 2 ^ log2_prec_width)
         * num_precincts_y = |- try_1 / 2 ^ log2_prec_width) -| - (try_0 / 2 ^ log2_prec_width)
         * for Dcinema profiles in JPEG 2000
         * num_precincts_x = |- trx_1 / 2 ^ log2_prec_width) -|
         * num_precincts_y = |- try_1 / 2 ^ log2_prec_width) -| */
        if (reslevel->coord[0][1] == reslevel->coord[0][0])
            reslevel->num_precincts_x = 0;
        else
            reslevel->num_precincts_x =
                ff_jpeg2000_ceildivpow2(reslevel->coord[0][1],
                                        reslevel->log2_prec_width) -
                (reslevel->coord[0][0] >> reslevel->log2_prec_width);
        if (reslevel->coord[1][1] == reslevel->coord[1][0])
            reslevel->num_precincts_y = 0;
        else
            reslevel->num_precincts_y =
                ff_jpeg2000_ceildivpow2(reslevel->coord[1][1],
                                        reslevel->log2_prec_height) -
                (reslevel->coord[1][0] >> reslevel->log2_prec_height);
        reslevel->band = av_mallocz_array(reslevel->nbands, sizeof(*reslevel->band));
        if (!reslevel->band)
        for (bandno = 0; bandno < reslevel->nbands; bandno++, gbandno++) {
            ret = init_band(avctx, reslevel,
                            comp, codsty, qntsty,
                            bandno, gbandno, reslevelno,
                            cbps, dx, dy);
            if (ret < 0)
                return ret;
        }
    }
    return 0;
}


void vhost_dev_cleanup(struct vhost_dev *hdev)

{

    int i;

    for (i = 0; i < hdev->nvqs; ++i) {

        vhost_virtqueue_cleanup(hdev->vqs + i);

    }

    memory_listener_unregister(&hdev->memory_listener);

    if (hdev->migration_blocker) {

        migrate_del_blocker(hdev->migration_blocker);

        error_free(hdev->migration_blocker);

    }

    g_free(hdev->mem);

    g_free(hdev->mem_sections);

    hdev->vhost_ops->vhost_backend_cleanup(hdev);

}


static void test_validate_fail_union_flat_no_discrim(TestInputVisitorData *data,

                                                     const void *unused)

{

    UserDefFlatUnion2 *tmp = NULL;

    Error *err = NULL;

    Visitor *v;

    /* test situation where discriminator field ('enum1' here) is missing */

    v = validate_test_init(data, "{ 'integer': 42, 'string': 'c', 'string1': 'd', 'string2': 'e' }");

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

    g_assert(err);

    error_free(err);

    qapi_free_UserDefFlatUnion2(tmp);

}


static void thread_pool_co_cb(void *opaque, int ret)

{

    ThreadPoolCo *co = opaque;

    co->ret = ret;

    qemu_coroutine_enter(co->co, NULL);

}


static void pc_dimm_plug(HotplugHandler *hotplug_dev,
                         DeviceState *dev, Error **errp)
{
    int slot;
    HotplugHandlerClass *hhc;
    Error *local_err = NULL;
    PCMachineState *pcms = PC_MACHINE(hotplug_dev);
    MachineState *machine = MACHINE(hotplug_dev);
    PCDIMMDevice *dimm = PC_DIMM(dev);
    PCDIMMDeviceClass *ddc = PC_DIMM_GET_CLASS(dimm);
    MemoryRegion *mr = ddc->get_memory_region(dimm);
    uint64_t addr = object_property_get_int(OBJECT(dimm), PC_DIMM_ADDR_PROP,
                                            &local_err);
    if (local_err) {
    addr = pc_dimm_get_free_addr(pcms->hotplug_memory_base,
                                 memory_region_size(&pcms->hotplug_memory),
                                 !addr ? NULL : &addr,
                                 memory_region_size(mr), &local_err);
    if (local_err) {
    object_property_set_int(OBJECT(dev), addr, PC_DIMM_ADDR_PROP, &local_err);
    if (local_err) {
    trace_mhp_pc_dimm_assigned_address(addr);
    slot = object_property_get_int(OBJECT(dev), PC_DIMM_SLOT_PROP, &local_err);
    if (local_err) {
    slot = pc_dimm_get_free_slot(slot == PC_DIMM_UNASSIGNED_SLOT ? NULL : &slot,
                                 machine->ram_slots, &local_err);
    if (local_err) {
    object_property_set_int(OBJECT(dev), slot, PC_DIMM_SLOT_PROP, &local_err);
    if (local_err) {
    trace_mhp_pc_dimm_assigned_slot(slot);
    if (!pcms->acpi_dev) {
        error_setg(&local_err,
                   "memory hotplug is not enabled: missing acpi device");
    memory_region_add_subregion(&pcms->hotplug_memory,
                                addr - pcms->hotplug_memory_base, mr);
    vmstate_register_ram(mr, dev);
    hhc = HOTPLUG_HANDLER_GET_CLASS(pcms->acpi_dev);
    hhc->plug(HOTPLUG_HANDLER(pcms->acpi_dev), dev, &local_err);
out:
    error_propagate(errp, local_err);


int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)

{

    BlockDriverAIOCB *acb;

    MultiwriteCB *mcb;

    int i;

    if (num_reqs == 0) {

        return 0;

    }

    // Create MultiwriteCB structure

    mcb = qemu_mallocz(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));

    mcb->num_requests = 0;

    mcb->num_callbacks = num_reqs;

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

        mcb->callbacks[i].cb = reqs[i].cb;

        mcb->callbacks[i].opaque = reqs[i].opaque;

    }

    // Check for mergable requests

    num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);

    // Run the aio requests

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

        acb = bdrv_aio_writev(bs, reqs[i].sector, reqs[i].qiov,

            reqs[i].nb_sectors, multiwrite_cb, mcb);

        if (acb == NULL) {

            // We can only fail the whole thing if no request has been

            // submitted yet. Otherwise we'll wait for the submitted AIOs to

            // complete and report the error in the callback.

            if (mcb->num_requests == 0) {

                reqs[i].error = -EIO;

                goto fail;

            } else {

                mcb->error = -EIO;

                break;

            }

        } else {

            mcb->num_requests++;

        }

    }

    return 0;

fail:

    free(mcb);

    return -1;

}