static void guess_mv(MpegEncContext *s){

    uint8_t fixed[s->mb_stride * s->mb_height];

#define MV_FROZEN    3

#define MV_CHANGED   2

#define MV_UNCHANGED 1

    const int mb_stride = s->mb_stride;

    const int mb_width = s->mb_width;

    const int mb_height= s->mb_height;

    int i, depth, num_avail;

    int mb_x, mb_y, mot_step, mot_stride;

    set_mv_strides(s, &mot_step, &mot_stride);

    num_avail=0;

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

        const int mb_xy= s->mb_index2xy[ i ];

        int f=0;

        int error= s->error_status_table[mb_xy];

        if(IS_INTRA(s->current_picture.mb_type[mb_xy])) f=MV_FROZEN; //intra //FIXME check

        if(!(error&MV_ERROR)) f=MV_FROZEN;           //inter with undamaged MV

        fixed[mb_xy]= f;

        if(f==MV_FROZEN)

            num_avail++;

    }

    if((!(s->avctx->error_concealment&FF_EC_GUESS_MVS)) || num_avail <= mb_width/2){

        for(mb_y=0; mb_y<s->mb_height; mb_y++){

            for(mb_x=0; mb_x<s->mb_width; mb_x++){

                const int mb_xy= mb_x + mb_y*s->mb_stride;

                if(IS_INTRA(s->current_picture.mb_type[mb_xy]))  continue;

                if(!(s->error_status_table[mb_xy]&MV_ERROR)) continue;

                s->mv_dir = s->last_picture.data[0] ? MV_DIR_FORWARD : MV_DIR_BACKWARD;

                s->mb_intra=0;

                s->mv_type = MV_TYPE_16X16;

                s->mb_skipped=0;

                s->dsp.clear_blocks(s->block[0]);

                s->mb_x= mb_x;

                s->mb_y= mb_y;

                s->mv[0][0][0]= 0;

                s->mv[0][0][1]= 0;

                decode_mb(s, 0);

            }

        }

        return;

    }

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

        int changed, pass, none_left;

        none_left=1;

        changed=1;

        for(pass=0; (changed || pass<2) && pass<10; pass++){

            int mb_x, mb_y;

int score_sum=0;

            changed=0;

            for(mb_y=0; mb_y<s->mb_height; mb_y++){

                for(mb_x=0; mb_x<s->mb_width; mb_x++){

                    const int mb_xy= mb_x + mb_y*s->mb_stride;

                    int mv_predictor[8][2]={{0}};

                    int ref[8]={0};

                    int pred_count=0;

                    int j;

                    int best_score=256*256*256*64;

                    int best_pred=0;

                    const int mot_index= (mb_x + mb_y*mot_stride) * mot_step;

                    int prev_x, prev_y, prev_ref;

                    if((mb_x^mb_y^pass)&1) continue;

                    if(fixed[mb_xy]==MV_FROZEN) continue;

                    assert(!IS_INTRA(s->current_picture.mb_type[mb_xy]));

                    assert(s->last_picture_ptr && s->last_picture_ptr->data[0]);

                    j=0;

                    if(mb_x>0           && fixed[mb_xy-1        ]==MV_FROZEN) j=1;

                    if(mb_x+1<mb_width  && fixed[mb_xy+1        ]==MV_FROZEN) j=1;

                    if(mb_y>0           && fixed[mb_xy-mb_stride]==MV_FROZEN) j=1;

                    if(mb_y+1<mb_height && fixed[mb_xy+mb_stride]==MV_FROZEN) j=1;

                    if(j==0) continue;

                    j=0;

                    if(mb_x>0           && fixed[mb_xy-1        ]==MV_CHANGED) j=1;

                    if(mb_x+1<mb_width  && fixed[mb_xy+1        ]==MV_CHANGED) j=1;

                    if(mb_y>0           && fixed[mb_xy-mb_stride]==MV_CHANGED) j=1;

                    if(mb_y+1<mb_height && fixed[mb_xy+mb_stride]==MV_CHANGED) j=1;

                    if(j==0 && pass>1) continue;

                    none_left=0;

                    if(mb_x>0 && fixed[mb_xy-1]){

                        mv_predictor[pred_count][0]= s->current_picture.motion_val[0][mot_index - mot_step][0];

                        mv_predictor[pred_count][1]= s->current_picture.motion_val[0][mot_index - mot_step][1];

                        ref         [pred_count]   = s->current_picture.ref_index[0][4*(mb_xy-1)];

                        pred_count++;

                    }

                    if(mb_x+1<mb_width && fixed[mb_xy+1]){

                        mv_predictor[pred_count][0]= s->current_picture.motion_val[0][mot_index + mot_step][0];

                        mv_predictor[pred_count][1]= s->current_picture.motion_val[0][mot_index + mot_step][1];

                        ref         [pred_count]   = s->current_picture.ref_index[0][4*(mb_xy+1)];

                        pred_count++;

                    }

                    if(mb_y>0 && fixed[mb_xy-mb_stride]){

                        mv_predictor[pred_count][0]= s->current_picture.motion_val[0][mot_index - mot_stride*mot_step][0];

                        mv_predictor[pred_count][1]= s->current_picture.motion_val[0][mot_index - mot_stride*mot_step][1];

                        ref         [pred_count]   = s->current_picture.ref_index[0][4*(mb_xy-s->mb_stride)];

                        pred_count++;

                    }

                    if(mb_y+1<mb_height && fixed[mb_xy+mb_stride]){

                        mv_predictor[pred_count][0]= s->current_picture.motion_val[0][mot_index + mot_stride*mot_step][0];

                        mv_predictor[pred_count][1]= s->current_picture.motion_val[0][mot_index + mot_stride*mot_step][1];

                        ref         [pred_count]   = s->current_picture.ref_index[0][4*(mb_xy+s->mb_stride)];

                        pred_count++;

                    }

                    if(pred_count==0) continue;

                    if(pred_count>1){

                        int sum_x=0, sum_y=0, sum_r=0;

                        int max_x, max_y, min_x, min_y, max_r, min_r;

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

                            sum_x+= mv_predictor[j][0];

                            sum_y+= mv_predictor[j][1];

                            sum_r+= ref[j];

                            if(j && ref[j] != ref[j-1])

                                goto skip_mean_and_median;

                        }

                        /* mean */

                        mv_predictor[pred_count][0] = sum_x/j;

                        mv_predictor[pred_count][1] = sum_y/j;

                        ref         [pred_count]    = sum_r/j;

                        /* median */

                        if(pred_count>=3){

                            min_y= min_x= min_r= 99999;

                            max_y= max_x= max_r=-99999;

                        }else{

                            min_x=min_y=max_x=max_y=min_r=max_r=0;

                        }

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

                            max_x= FFMAX(max_x, mv_predictor[j][0]);

                            max_y= FFMAX(max_y, mv_predictor[j][1]);

                            max_r= FFMAX(max_r, ref[j]);

                            min_x= FFMIN(min_x, mv_predictor[j][0]);

                            min_y= FFMIN(min_y, mv_predictor[j][1]);

                            min_r= FFMIN(min_r, ref[j]);

                        }

                        mv_predictor[pred_count+1][0] = sum_x - max_x - min_x;

                        mv_predictor[pred_count+1][1] = sum_y - max_y - min_y;

                        ref         [pred_count+1]    = sum_r - max_r - min_r;

                        if(pred_count==4){

                            mv_predictor[pred_count+1][0] /= 2;

                            mv_predictor[pred_count+1][1] /= 2;

                            ref         [pred_count+1]    /= 2;

                        }

                        pred_count+=2;

                    }

skip_mean_and_median:

                    /* zero MV */

                    pred_count++;

                    if (!fixed[mb_xy]) {

                        if (s->avctx->codec_id == CODEC_ID_H264) {

                            // FIXME

                        } else {

                            ff_thread_await_progress((AVFrame *) s->last_picture_ptr,

                                                     mb_y, 0);

                        }

                        if (!s->last_picture.motion_val[0] ||

                            !s->last_picture.ref_index[0])

                            goto skip_last_mv;

                        prev_x = s->last_picture.motion_val[0][mot_index][0];

                        prev_y = s->last_picture.motion_val[0][mot_index][1];

                        prev_ref = s->last_picture.ref_index[0][4*mb_xy];

                    } else {

                        prev_x = s->current_picture.motion_val[0][mot_index][0];

                        prev_y = s->current_picture.motion_val[0][mot_index][1];

                        prev_ref = s->current_picture.ref_index[0][4*mb_xy];

                    }

                    /* last MV */

                    mv_predictor[pred_count][0]= prev_x;

                    mv_predictor[pred_count][1]= prev_y;

                    ref         [pred_count]   = prev_ref;

                    pred_count++;

                    s->mv_dir = MV_DIR_FORWARD;

                    s->mb_intra=0;

                    s->mv_type = MV_TYPE_16X16;

                    s->mb_skipped=0;

                    s->dsp.clear_blocks(s->block[0]);

                    s->mb_x= mb_x;

                    s->mb_y= mb_y;

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

                        int score=0;

                        uint8_t *src= s->current_picture.data[0] + mb_x*16 + mb_y*16*s->linesize;

                        s->current_picture.motion_val[0][mot_index][0]= s->mv[0][0][0]= mv_predictor[j][0];

                        s->current_picture.motion_val[0][mot_index][1]= s->mv[0][0][1]= mv_predictor[j][1];

                        if(ref[j]<0) //predictor intra or otherwise not available

                            continue;

                        decode_mb(s, ref[j]);

                        if(mb_x>0 && fixed[mb_xy-1]){

                            int k;

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

                                score += FFABS(src[k*s->linesize-1 ]-src[k*s->linesize   ]);

                        }

                        if(mb_x+1<mb_width && fixed[mb_xy+1]){

                            int k;

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

                                score += FFABS(src[k*s->linesize+15]-src[k*s->linesize+16]);

                        }

                        if(mb_y>0 && fixed[mb_xy-mb_stride]){

                            int k;

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

                                score += FFABS(src[k-s->linesize   ]-src[k               ]);

                        }

                        if(mb_y+1<mb_height && fixed[mb_xy+mb_stride]){

                            int k;

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

                                score += FFABS(src[k+s->linesize*15]-src[k+s->linesize*16]);

                        }

                        if(score <= best_score){ // <= will favor the last MV

                            best_score= score;

                            best_pred= j;

                        }

                    }

score_sum+= best_score;

                    s->mv[0][0][0]= mv_predictor[best_pred][0];

                    s->mv[0][0][1]= mv_predictor[best_pred][1];

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

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

                            s->current_picture.motion_val[0][mot_index+i+j*mot_stride][0]= s->mv[0][0][0];

                            s->current_picture.motion_val[0][mot_index+i+j*mot_stride][1]= s->mv[0][0][1];

                        }

                    decode_mb(s, ref[best_pred]);

                    if(s->mv[0][0][0] != prev_x || s->mv[0][0][1] != prev_y){

                        fixed[mb_xy]=MV_CHANGED;

                        changed++;

                    }else

                        fixed[mb_xy]=MV_UNCHANGED;

                }

            }

//            printf(".%d/%d", changed, score_sum); fflush(stdout);

        }

        if(none_left)

            return;

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

            int mb_xy= s->mb_index2xy[i];

            if(fixed[mb_xy])

                fixed[mb_xy]=MV_FROZEN;

        }

//        printf(":"); fflush(stdout);

    }

}


void qemu_bh_delete(QEMUBH *bh)

{

    qemu_bh_cancel(bh);

    qemu_free(bh);

}


static int read_var_block_data(ALSDecContext *ctx, ALSBlockData *bd)

{

    ALSSpecificConfig *sconf = &ctx->sconf;

    AVCodecContext *avctx    = ctx->avctx;

    GetBitContext *gb        = &ctx->gb;

    unsigned int k;

    unsigned int s[8];

    unsigned int sx[8];

    unsigned int sub_blocks, log2_sub_blocks, sb_length;

    unsigned int start      = 0;

    unsigned int opt_order;

    int          sb;

    int32_t      *quant_cof = bd->quant_cof;

    int32_t      *current_res;

    // ensure variable block decoding by reusing this field

    *bd->const_block = 0;

    *bd->opt_order  = 1;

    bd->js_blocks   = get_bits1(gb);

    opt_order       = *bd->opt_order;

    // determine the number of subblocks for entropy decoding

    if (!sconf->bgmc && !sconf->sb_part) {

        log2_sub_blocks = 0;

    } else {

        if (sconf->bgmc && sconf->sb_part)

            log2_sub_blocks = get_bits(gb, 2);

        else

            log2_sub_blocks = 2 * get_bits1(gb);

    sub_blocks = 1 << log2_sub_blocks;

    // do not continue in case of a damaged stream since

    // block_length must be evenly divisible by sub_blocks

    if (bd->block_length & (sub_blocks - 1)) {

        av_log(avctx, AV_LOG_WARNING,

               "Block length is not evenly divisible by the number of subblocks.\n");

    sb_length = bd->block_length >> log2_sub_blocks;

    if (sconf->bgmc) {

        s[0] = get_bits(gb, 8 + (sconf->resolution > 1));

            s[k] = s[k - 1] + decode_rice(gb, 2);

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

            sx[k]   = s[k] & 0x0F;

            s [k] >>= 4;

    } else {

        s[0] = get_bits(gb, 4 + (sconf->resolution > 1));

            s[k] = s[k - 1] + decode_rice(gb, 0);

    if (get_bits1(gb))

        *bd->shift_lsbs = get_bits(gb, 4) + 1;

    *bd->store_prev_samples = (bd->js_blocks && bd->raw_other) || *bd->shift_lsbs;

    if (!sconf->rlslms) {

        if (sconf->adapt_order) {

            int opt_order_length = av_ceil_log2(av_clip((bd->block_length >> 3) - 1,

                                                2, sconf->max_order + 1));

            *bd->opt_order       = get_bits(gb, opt_order_length);

            if (*bd->opt_order > sconf->max_order) {

                *bd->opt_order = sconf->max_order;

                av_log(avctx, AV_LOG_ERROR, "Predictor order too large!\n");

        } else {

            *bd->opt_order = sconf->max_order;

        opt_order = *bd->opt_order;

        if (opt_order) {

            int add_base;

            if (sconf->coef_table == 3) {

                add_base = 0x7F;

                // read coefficient 0

                quant_cof[0] = 32 * parcor_scaled_values[get_bits(gb, 7)];

                // read coefficient 1

                if (opt_order > 1)

                    quant_cof[1] = -32 * parcor_scaled_values[get_bits(gb, 7)];

                // read coefficients 2 to opt_order

                for (k = 2; k < opt_order; k++)

                    quant_cof[k] = get_bits(gb, 7);

            } else {

                int k_max;

                add_base = 1;

                // read coefficient 0 to 19

                k_max = FFMIN(opt_order, 20);

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

                    int rice_param = parcor_rice_table[sconf->coef_table][k][1];

                    int offset     = parcor_rice_table[sconf->coef_table][k][0];

                    quant_cof[k] = decode_rice(gb, rice_param) + offset;

                    if (quant_cof[k] < -64 || quant_cof[k] > 63) {

                        av_log(avctx, AV_LOG_ERROR, "Quantization coefficient %d is out of range!\n", quant_cof[k]);

                        return AVERROR_INVALIDDATA;

                // read coefficients 20 to 126

                k_max = FFMIN(opt_order, 127);

                for (; k < k_max; k++)

                    quant_cof[k] = decode_rice(gb, 2) + (k & 1);

                // read coefficients 127 to opt_order

                for (; k < opt_order; k++)

                    quant_cof[k] = decode_rice(gb, 1);

                quant_cof[0] = 32 * parcor_scaled_values[quant_cof[0] + 64];

                if (opt_order > 1)

                    quant_cof[1] = -32 * parcor_scaled_values[quant_cof[1] + 64];

            for (k = 2; k < opt_order; k++)

                quant_cof[k] = (quant_cof[k] << 14) + (add_base << 13);

    // read LTP gain and lag values

    if (sconf->long_term_prediction) {

        *bd->use_ltp = get_bits1(gb);

        if (*bd->use_ltp) {

            int r, c;

            bd->ltp_gain[0]   = decode_rice(gb, 1) << 3;

            bd->ltp_gain[1]   = decode_rice(gb, 2) << 3;

            r                 = get_unary(gb, 0, 3);

            c                 = get_bits(gb, 2);

            bd->ltp_gain[2]   = ltp_gain_values[r][c];

            bd->ltp_gain[3]   = decode_rice(gb, 2) << 3;

            bd->ltp_gain[4]   = decode_rice(gb, 1) << 3;

            *bd->ltp_lag      = get_bits(gb, ctx->ltp_lag_length);

            *bd->ltp_lag     += FFMAX(4, opt_order + 1);

    // read first value and residuals in case of a random access block

    if (bd->ra_block) {

        if (opt_order)

            bd->raw_samples[0] = decode_rice(gb, avctx->bits_per_raw_sample - 4);

        if (opt_order > 1)

            bd->raw_samples[1] = decode_rice(gb, FFMIN(s[0] + 3, ctx->s_max));

        if (opt_order > 2)

            bd->raw_samples[2] = decode_rice(gb, FFMIN(s[0] + 1, ctx->s_max));

        start = FFMIN(opt_order, 3);

    // read all residuals

    if (sconf->bgmc) {

        int          delta[8];

        unsigned int k    [8];

        unsigned int b = av_clip((av_ceil_log2(bd->block_length) - 3) >> 1, 0, 5);

        unsigned int i = start;

        // read most significant bits

        unsigned int high;

        unsigned int low;

        unsigned int value;

        ff_bgmc_decode_init(gb, &high, &low, &value);

        current_res = bd->raw_samples + start;

        for (sb = 0; sb < sub_blocks; sb++, i = 0) {

            k    [sb] = s[sb] > b ? s[sb] - b : 0;

            delta[sb] = 5 - s[sb] + k[sb];

            ff_bgmc_decode(gb, sb_length, current_res,

                        delta[sb], sx[sb], &high, &low, &value, ctx->bgmc_lut, ctx->bgmc_lut_status);

            current_res += sb_length;

        ff_bgmc_decode_end(gb);

        // read least significant bits and tails

        i = start;

        current_res = bd->raw_samples + start;

        for (sb = 0; sb < sub_blocks; sb++, i = 0) {

            unsigned int cur_tail_code = tail_code[sx[sb]][delta[sb]];

            unsigned int cur_k         = k[sb];

            unsigned int cur_s         = s[sb];

            for (; i < sb_length; i++) {

                int32_t res = *current_res;

                if (res == cur_tail_code) {

                    unsigned int max_msb =   (2 + (sx[sb] > 2) + (sx[sb] > 10))

                                          << (5 - delta[sb]);

                    res = decode_rice(gb, cur_s);

                    if (res >= 0) {

                        res += (max_msb    ) << cur_k;

                    } else {

                        res -= (max_msb - 1) << cur_k;

                } else {

                    if (res > cur_tail_code)

                        res--;

                    if (res & 1)

                        res = -res;

                    res >>= 1;

                    if (cur_k) {

                        res <<= cur_k;

                        res  |= get_bits_long(gb, cur_k);

                *current_res++ = res;

    } else {

        current_res = bd->raw_samples + start;

        for (sb = 0; sb < sub_blocks; sb++, start = 0)

            for (; start < sb_length; start++)

                *current_res++ = decode_rice(gb, s[sb]);

    if (!sconf->mc_coding || ctx->js_switch)

        align_get_bits(gb);

    return 0;


void select_soundhw(const char *optarg)

{

}


static void cpu_exec_nocache(CPUState *cpu, int max_cycles,

                             TranslationBlock *orig_tb)

{

    TranslationBlock *tb;

    /* Should never happen.

       We only end up here when an existing TB is too long.  */

    if (max_cycles > CF_COUNT_MASK)

        max_cycles = CF_COUNT_MASK;

    tb = tb_gen_code(cpu, orig_tb->pc, orig_tb->cs_base, orig_tb->flags,

                     max_cycles | CF_NOCACHE);

    tb->orig_tb = tcg_ctx.tb_ctx.tb_invalidated_flag ? NULL : orig_tb;

    cpu->current_tb = tb;

    /* execute the generated code */

    trace_exec_tb_nocache(tb, tb->pc);

    cpu_tb_exec(cpu, tb->tc_ptr);

    cpu->current_tb = NULL;

    tb_phys_invalidate(tb, -1);

    tb_free(tb);

}


static int xhci_submit(XHCIState *xhci, XHCITransfer *xfer, XHCIEPContext *epctx)

{

    uint64_t mfindex;

    DPRINTF("xhci_submit(slotid=%d,epid=%d)\n", xfer->slotid, xfer->epid);

    xfer->in_xfer = epctx->type>>2;

    switch(epctx->type) {

    case ET_INTR_OUT:

    case ET_INTR_IN:

        xfer->pkts = 0;

        xfer->iso_xfer = false;

        xfer->timed_xfer = true;

        mfindex = xhci_mfindex_get(xhci);

        xhci_calc_intr_kick(xhci, xfer, epctx, mfindex);

        xhci_check_intr_iso_kick(xhci, xfer, epctx, mfindex);

        if (xfer->running_retry) {

            return -1;

        }

        break;

    case ET_BULK_OUT:

    case ET_BULK_IN:

        xfer->pkts = 0;

        xfer->iso_xfer = false;

        xfer->timed_xfer = false;

        break;

    case ET_ISO_OUT:

    case ET_ISO_IN:

        xfer->pkts = 1;

        xfer->iso_xfer = true;

        xfer->timed_xfer = true;

        mfindex = xhci_mfindex_get(xhci);

        xhci_calc_iso_kick(xhci, xfer, epctx, mfindex);

        xhci_check_intr_iso_kick(xhci, xfer, epctx, mfindex);

        if (xfer->running_retry) {

            return -1;

        }

        break;

    default:

        trace_usb_xhci_unimplemented("endpoint type", epctx->type);

        return -1;

    }

    if (xhci_setup_packet(xfer) < 0) {

        return -1;

    }

    usb_handle_packet(xfer->packet.ep->dev, &xfer->packet);

    xhci_try_complete_packet(xfer);

    if (!xfer->running_async && !xfer->running_retry) {

        xhci_kick_epctx(xfer->epctx, xfer->streamid);

    }

    return 0;

}


static void nvram_writel (void *opaque, target_phys_addr_t addr, uint32_t value)

{

    M48t59State *NVRAM = opaque;

    m48t59_write(NVRAM, addr, (value >> 24) & 0xff);

    m48t59_write(NVRAM, addr + 1, (value >> 16) & 0xff);

    m48t59_write(NVRAM, addr + 2, (value >> 8) & 0xff);

    m48t59_write(NVRAM, addr + 3, value & 0xff);

}


static QIOChannelSocket *nbd_establish_connection(SocketAddress *saddr,

                                                  Error **errp)

{

    QIOChannelSocket *sioc;

    Error *local_err = NULL;

    sioc = qio_channel_socket_new();

    qio_channel_set_name(QIO_CHANNEL(sioc), "nbd-client");

    qio_channel_socket_connect_sync(sioc,

                                    saddr,

                                    &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        return NULL;

    }

    qio_channel_set_delay(QIO_CHANNEL(sioc), false);

    return sioc;

}


static int write_abst(AVFormatContext *s, OutputStream *os, int final)

{

    HDSContext *c = s->priv_data;

    AVIOContext *out;

    char filename[1024], temp_filename[1024];

    int i, ret;

    int64_t asrt_pos, afrt_pos;

    int start = 0, fragments;

    int index = s->streams[os->first_stream]->id;

    int64_t cur_media_time = 0;

    if (c->window_size)

        start = FFMAX(os->nb_fragments - c->window_size, 0);

    fragments = os->nb_fragments - start;

    if (final)

        cur_media_time = os->last_ts;

    else if (os->nb_fragments)

        cur_media_time = os->fragments[os->nb_fragments - 1]->start_time;

    snprintf(filename, sizeof(filename),

             "%s/stream%d.abst", s->filename, index);

    snprintf(temp_filename, sizeof(temp_filename),

             "%s/stream%d.abst.tmp", s->filename, index);

    ret = avio_open2(&out, temp_filename, AVIO_FLAG_WRITE,

                     &s->interrupt_callback, NULL);

    if (ret < 0) {

        av_log(s, AV_LOG_ERROR, "Unable to open %s for writing\n", temp_filename);

        return ret;

    }

    avio_wb32(out, 0); // abst size

    avio_wl32(out, MKTAG('a','b','s','t'));

    avio_wb32(out, 0); // version + flags

    avio_wb32(out, os->fragment_index - 1); // BootstrapinfoVersion

    avio_w8(out, final ? 0 : 0x20); // profile, live, update

    avio_wb32(out, 1000); // timescale

    avio_wb64(out, cur_media_time);

    avio_wb64(out, 0); // SmpteTimeCodeOffset

    avio_w8(out, 0); // MovieIdentifer (null string)

    avio_w8(out, 0); // ServerEntryCount

    avio_w8(out, 0); // QualityEntryCount

    avio_w8(out, 0); // DrmData (null string)

    avio_w8(out, 0); // MetaData (null string)

    avio_w8(out, 1); // SegmentRunTableCount

    asrt_pos = avio_tell(out);

    avio_wb32(out, 0); // asrt size

    avio_wl32(out, MKTAG('a','s','r','t'));

    avio_wb32(out, 0); // version + flags

    avio_w8(out, 0); // QualityEntryCount

    avio_wb32(out, 1); // SegmentRunEntryCount

    avio_wb32(out, 1); // FirstSegment

    avio_wb32(out, final ? (os->fragment_index - 1) : 0xffffffff); // FragmentsPerSegment

    update_size(out, asrt_pos);

    avio_w8(out, 1); // FragmentRunTableCount

    afrt_pos = avio_tell(out);

    avio_wb32(out, 0); // afrt size

    avio_wl32(out, MKTAG('a','f','r','t'));

    avio_wb32(out, 0); // version + flags

    avio_wb32(out, 1000); // timescale

    avio_w8(out, 0); // QualityEntryCount

    avio_wb32(out, fragments); // FragmentRunEntryCount

    for (i = start; i < os->nb_fragments; i++) {

        avio_wb32(out, os->fragments[i]->n);

        avio_wb64(out, os->fragments[i]->start_time);

        avio_wb32(out, os->fragments[i]->duration);

    }

    update_size(out, afrt_pos);

    update_size(out, 0);

    avio_close(out);

    return ff_rename(temp_filename, filename);

}


static int mptsas_process_scsi_io_request(MPTSASState *s,

                                          MPIMsgSCSIIORequest *scsi_io,

                                          hwaddr addr)

{

    MPTSASRequest *req;

    MPIMsgSCSIIOReply reply;

    SCSIDevice *sdev;

    int status;

    mptsas_fix_scsi_io_endianness(scsi_io);

    trace_mptsas_process_scsi_io_request(s, scsi_io->Bus, scsi_io->TargetID,

                                         scsi_io->LUN[1], scsi_io->DataLength);

    status = mptsas_scsi_device_find(s, scsi_io->Bus, scsi_io->TargetID,

                                     scsi_io->LUN, &sdev);

    if (status) {

        goto bad;

    }

    req = g_new(MPTSASRequest, 1);

    QTAILQ_INSERT_TAIL(&s->pending, req, next);

    req->scsi_io = *scsi_io;

    req->dev = s;

    status = mptsas_build_sgl(s, req, addr);

    if (status) {

        goto free_bad;

    }

    if (req->qsg.size < scsi_io->DataLength) {

        trace_mptsas_sgl_overflow(s, scsi_io->MsgContext, scsi_io->DataLength,

                                  req->qsg.size);

        status = MPI_IOCSTATUS_INVALID_SGL;

        goto free_bad;

    }

    req->sreq = scsi_req_new(sdev, scsi_io->MsgContext,

                            scsi_io->LUN[1], scsi_io->CDB, req);

    if (req->sreq->cmd.xfer > scsi_io->DataLength) {

        goto overrun;

    }

    switch (scsi_io->Control & MPI_SCSIIO_CONTROL_DATADIRECTION_MASK) {

    case MPI_SCSIIO_CONTROL_NODATATRANSFER:

        if (req->sreq->cmd.mode != SCSI_XFER_NONE) {

            goto overrun;

        }

        break;

    case MPI_SCSIIO_CONTROL_WRITE:

        if (req->sreq->cmd.mode != SCSI_XFER_TO_DEV) {

            goto overrun;

        }

        break;

    case MPI_SCSIIO_CONTROL_READ:

        if (req->sreq->cmd.mode != SCSI_XFER_FROM_DEV) {

            goto overrun;

        }

        break;

    }

    if (scsi_req_enqueue(req->sreq)) {

        scsi_req_continue(req->sreq);

    }

    return 0;

overrun:

    trace_mptsas_scsi_overflow(s, scsi_io->MsgContext, req->sreq->cmd.xfer,

                               scsi_io->DataLength);

    status = MPI_IOCSTATUS_SCSI_DATA_OVERRUN;

free_bad:

    mptsas_free_request(req);

bad:

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

    reply.TargetID          = scsi_io->TargetID;

    reply.Bus               = scsi_io->Bus;

    reply.MsgLength         = sizeof(reply) / 4;

    reply.Function          = scsi_io->Function;

    reply.CDBLength         = scsi_io->CDBLength;

    reply.SenseBufferLength = scsi_io->SenseBufferLength;

    reply.MsgContext        = scsi_io->MsgContext;

    reply.SCSIState         = MPI_SCSI_STATE_NO_SCSI_STATUS;

    reply.IOCStatus         = status;

    mptsas_fix_scsi_io_reply_endianness(&reply);

    mptsas_reply(s, (MPIDefaultReply *)&reply);

    return 0;

}


bool s390_cpu_exec_interrupt(CPUState *cs, int interrupt_request)

{

    if (interrupt_request & CPU_INTERRUPT_HARD) {

        S390CPU *cpu = S390_CPU(cs);

        CPUS390XState *env = &cpu->env;

        if (env->ex_value) {

            /* Execution of the target insn is indivisible from

               the parent EXECUTE insn.  */

            return false;

        }

        if (env->psw.mask & PSW_MASK_EXT) {

            s390_cpu_do_interrupt(cs);

            return true;

        }

    }

    return false;

}


ioapic_mem_read(void *opaque, target_phys_addr_t addr, unsigned int size)

{

    IOAPICCommonState *s = opaque;

    int index;

    uint32_t val = 0;

    switch (addr & 0xff) {

    case IOAPIC_IOREGSEL:

        val = s->ioregsel;

        break;

    case IOAPIC_IOWIN:

        if (size != 4) {

            break;

        }

        switch (s->ioregsel) {

        case IOAPIC_REG_ID:

            val = s->id << IOAPIC_ID_SHIFT;

            break;

        case IOAPIC_REG_VER:

            val = IOAPIC_VERSION |

                ((IOAPIC_NUM_PINS - 1) << IOAPIC_VER_ENTRIES_SHIFT);

            break;

        case IOAPIC_REG_ARB:

            val = 0;

            break;

        default:

            index = (s->ioregsel - IOAPIC_REG_REDTBL_BASE) >> 1;

            if (index >= 0 && index < IOAPIC_NUM_PINS) {

                if (s->ioregsel & 1) {

                    val = s->ioredtbl[index] >> 32;

                } else {

                    val = s->ioredtbl[index] & 0xffffffff;

                }

            }

        }

        DPRINTF("read: %08x = %08x\n", s->ioregsel, val);

        break;

    }

    return val;

}


static void piix4_pm_machine_ready(Notifier *n, void *opaque)

{

    PIIX4PMState *s = container_of(n, PIIX4PMState, machine_ready);

    PCIDevice *d = PCI_DEVICE(s);

    MemoryRegion *io_as = pci_address_space_io(d);

    uint8_t *pci_conf;

    pci_conf = d->config;

    pci_conf[0x5f] = 0x10 |

        (memory_region_present(io_as, 0x378) ? 0x80 : 0);

    pci_conf[0x63] = 0x60;

    pci_conf[0x67] = (memory_region_present(io_as, 0x3f8) ? 0x08 : 0) |

        (memory_region_present(io_as, 0x2f8) ? 0x90 : 0);

    if (s->use_acpi_pci_hotplug) {

        pci_for_each_bus(d->bus, piix4_update_bus_hotplug, s);

    } else {

        piix4_update_bus_hotplug(d->bus, s);

    }

}


static void vnc_dpy_resize(DisplayState *ds)

{

    int size_changed;

    VncDisplay *vd = ds->opaque;

    VncState *vs;

    /* server surface */

    if (!vd->server)

        vd->server = qemu_mallocz(sizeof(*vd->server));

    if (vd->server->data)

        qemu_free(vd->server->data);

    *(vd->server) = *(ds->surface);

    vd->server->data = qemu_mallocz(vd->server->linesize *

                                    vd->server->height);

    /* guest surface */

    if (!vd->guest.ds)

        vd->guest.ds = qemu_mallocz(sizeof(*vd->guest.ds));

    if (ds_get_bytes_per_pixel(ds) != vd->guest.ds->pf.bytes_per_pixel)

        console_color_init(ds);

    size_changed = ds_get_width(ds) != vd->guest.ds->width ||

                   ds_get_height(ds) != vd->guest.ds->height;

    *(vd->guest.ds) = *(ds->surface);

    memset(vd->guest.dirty, 0xFF, sizeof(vd->guest.dirty));

    QTAILQ_FOREACH(vs, &vd->clients, next) {

        vnc_colordepth(vs);

        if (size_changed) {

            vnc_desktop_resize(vs);

        }

        if (vs->vd->cursor) {

            vnc_cursor_define(vs);

        }

        memset(vs->dirty, 0xFF, sizeof(vs->dirty));

    }

}


bool hpet_find(void)

{

    return object_resolve_path_type("", TYPE_HPET, NULL);

}


static void gen_load_exclusive(DisasContext *s, int rt, int rt2,

                               TCGv_i32 addr, int size)

{

    TCGv_i32 tmp = tcg_temp_new_i32();

    s->is_ldex = true;

    switch (size) {

    case 0:

        gen_aa32_ld8u(tmp, addr, get_mem_index(s));

        break;

    case 1:

        gen_aa32_ld16u(tmp, addr, get_mem_index(s));

        break;

    case 2:

    case 3:

        gen_aa32_ld32u(tmp, addr, get_mem_index(s));

        break;

    default:

        abort();

    }

    if (size == 3) {

        TCGv_i32 tmp2 = tcg_temp_new_i32();

        TCGv_i32 tmp3 = tcg_temp_new_i32();

        tcg_gen_addi_i32(tmp2, addr, 4);

        gen_aa32_ld32u(tmp3, tmp2, get_mem_index(s));

        tcg_temp_free_i32(tmp2);

        tcg_gen_concat_i32_i64(cpu_exclusive_val, tmp, tmp3);

        store_reg(s, rt2, tmp3);

    } else {

        tcg_gen_extu_i32_i64(cpu_exclusive_val, tmp);

    }

    store_reg(s, rt, tmp);

    tcg_gen_extu_i32_i64(cpu_exclusive_addr, addr);

}


static inline void RENAME(bgr24ToUV)(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1, const uint8_t *src2, long width, uint32_t *unused)

{

#if COMPILE_TEMPLATE_MMX

    RENAME(bgr24ToUV_mmx)(dstU, dstV, src1, width, PIX_FMT_BGR24);

#else

    int i;

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

        int b= src1[3*i + 0];

        int g= src1[3*i + 1];

        int r= src1[3*i + 2];

        dstU[i]= (RU*r + GU*g + BU*b + (257<<(RGB2YUV_SHIFT-1)))>>RGB2YUV_SHIFT;

        dstV[i]= (RV*r + GV*g + BV*b + (257<<(RGB2YUV_SHIFT-1)))>>RGB2YUV_SHIFT;

    }

#endif /* COMPILE_TEMPLATE_MMX */

    assert(src1 == src2);

}


static void sigp_stop_and_store_status(CPUState *cs, run_on_cpu_data arg)

{

    S390CPU *cpu = S390_CPU(cs);

    SigpInfo *si = arg.host_ptr;

    struct kvm_s390_irq irq = {

        .type = KVM_S390_SIGP_STOP,

    };

    /* disabled wait - sleeping in user space */

    if (s390_cpu_get_state(cpu) == CPU_STATE_OPERATING && cs->halted) {

        s390_cpu_set_state(CPU_STATE_STOPPED, cpu);

    }

    switch (s390_cpu_get_state(cpu)) {

    case CPU_STATE_OPERATING:

        cpu->env.sigp_order = SIGP_STOP_STORE_STATUS;

        kvm_s390_vcpu_interrupt(cpu, &irq);

        /* store will be performed when handling the stop intercept */

        break;

    case CPU_STATE_STOPPED:

        /* already stopped, just store the status */

        cpu_synchronize_state(cs);

        kvm_s390_store_status(cpu, KVM_S390_STORE_STATUS_DEF_ADDR, true);

        break;

    }

    si->cc = SIGP_CC_ORDER_CODE_ACCEPTED;

}


static int xen_remove_from_physmap(XenIOState *state,

                                   hwaddr start_addr,

                                   ram_addr_t size)

{

    unsigned long i = 0;

    int rc = 0;

    XenPhysmap *physmap = NULL;

    hwaddr phys_offset = 0;

    physmap = get_physmapping(state, start_addr, size);

    if (physmap == NULL) {

        return -1;

    }

    phys_offset = physmap->phys_offset;

    size = physmap->size;

    DPRINTF("unmapping vram to %"HWADDR_PRIx" - %"HWADDR_PRIx", at "

            "%"HWADDR_PRIx"\n", start_addr, start_addr + size, phys_offset);

    size >>= TARGET_PAGE_BITS;

    start_addr >>= TARGET_PAGE_BITS;

    phys_offset >>= TARGET_PAGE_BITS;

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

        unsigned long idx = start_addr + i;

        xen_pfn_t gpfn = phys_offset + i;

        rc = xc_domain_add_to_physmap(xen_xc, xen_domid, XENMAPSPACE_gmfn, idx, gpfn);

        if (rc) {

            fprintf(stderr, "add_to_physmap MFN %"PRI_xen_pfn" to PFN %"

                    PRI_xen_pfn" failed: %d\n", idx, gpfn, rc);

            return -rc;

        }

    }

    QLIST_REMOVE(physmap, list);

    if (state->log_for_dirtybit == physmap) {

        state->log_for_dirtybit = NULL;

    }

    g_free(physmap);

    return 0;

}


int json_lexer_flush(JSONLexer *lexer)

{

    return lexer->state == IN_START ? 0 : json_lexer_feed_char(lexer, 0);

}


float64 helper_fxtod(CPUSPARCState *env, int64_t src)

{

    float64 ret;

    clear_float_exceptions(env);

    ret = int64_to_float64(src, &env->fp_status);

    check_ieee_exceptions(env);

    return ret;

}


static void test_visitor_out_list(TestOutputVisitorData *data,

                                  const void *unused)

{

    const char *value_str = "list value";

    TestStructList *p, *head = NULL;

    const int max_items = 10;

    bool value_bool = true;

    int value_int = 10;

    Error *err = NULL;

    QListEntry *entry;

    QObject *obj;

    QList *qlist;

    int i;

    /* Build the list in reverse order... */

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

        p = g_malloc0(sizeof(*p));

        p->value = g_malloc0(sizeof(*p->value));

        p->value->integer = value_int + (max_items - i - 1);

        p->value->boolean = value_bool;

        p->value->string = g_strdup(value_str);

        p->next = head;

        head = p;

    }

    visit_type_TestStructList(data->ov, &head, NULL, &err);

    g_assert(!err);

    obj = qmp_output_get_qobject(data->qov);

    g_assert(obj != NULL);

    g_assert(qobject_type(obj) == QTYPE_QLIST);

    qlist = qobject_to_qlist(obj);

    g_assert(!qlist_empty(qlist));

    /* ...and ensure that the visitor sees it in order */

    i = 0;

    QLIST_FOREACH_ENTRY(qlist, entry) {

        QDict *qdict;

        g_assert(qobject_type(entry->value) == QTYPE_QDICT);

        qdict = qobject_to_qdict(entry->value);

        g_assert_cmpint(qdict_size(qdict), ==, 3);

        g_assert_cmpint(qdict_get_int(qdict, "integer"), ==, value_int + i);

        g_assert_cmpint(qdict_get_bool(qdict, "boolean"), ==, value_bool);

        g_assert_cmpstr(qdict_get_str(qdict, "string"), ==, value_str);

        i++;

    }

    g_assert_cmpint(i, ==, max_items);

    QDECREF(qlist);

    qapi_free_TestStructList(head);

}


static uint64_t qemu_opt_get_size_helper(QemuOpts *opts, const char *name,

                                         uint64_t defval, bool del)

{

    QemuOpt *opt = qemu_opt_find(opts, name);

    uint64_t ret = defval;

    if (opt == NULL) {

        const QemuOptDesc *desc = find_desc_by_name(opts->list->desc, name);

        if (desc && desc->def_value_str) {

            parse_option_size(name, desc->def_value_str, &ret, &error_abort);

        }

        return ret;

    }

    assert(opt->desc && opt->desc->type == QEMU_OPT_SIZE);

    ret = opt->value.uint;

    if (del) {

        qemu_opt_del_all(opts, name);

    }

    return ret;

}


static int foreach_device_config(int type, int (*func)(const char *cmdline))

{

    struct device_config *conf;

    int rc;

    TAILQ_FOREACH(conf, &device_configs, next) {

        if (conf->type != type)

            continue;

        rc = func(conf->cmdline);

        if (0 != rc)

            return rc;

    }

    return 0;

}


static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,

                                                   int flags,

                                                   QDict *snapshot_options,

                                                   Error **errp)

{

    /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */

    char *tmp_filename = g_malloc0(PATH_MAX + 1);

    int64_t total_size;

    QemuOpts *opts = NULL;

    BlockDriverState *bs_snapshot;

    Error *local_err = NULL;

    int ret;

    /* if snapshot, we create a temporary backing file and open it

       instead of opening 'filename' directly */

    /* Get the required size from the image */

    total_size = bdrv_getlength(bs);

    if (total_size < 0) {

        error_setg_errno(errp, -total_size, "Could not get image size");

        goto out;

    }

    /* Create the temporary image */

    ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);

    if (ret < 0) {

        error_setg_errno(errp, -ret, "Could not get temporary filename");

        goto out;

    }

    opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,

                            &error_abort);

    qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);

    ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);

    qemu_opts_del(opts);

    if (ret < 0) {

        error_prepend(errp, "Could not create temporary overlay '%s': ",

                      tmp_filename);

        goto out;

    }

    /* Prepare options QDict for the temporary file */

    qdict_put_str(snapshot_options, "file.driver", "file");

    qdict_put_str(snapshot_options, "file.filename", tmp_filename);

    qdict_put_str(snapshot_options, "driver", "qcow2");

    bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);

    snapshot_options = NULL;

    if (!bs_snapshot) {

        ret = -EINVAL;

        goto out;

    }

    /* bdrv_append() consumes a strong reference to bs_snapshot (i.e. it will

     * call bdrv_unref() on it), so in order to be able to return one, we have

     * to increase bs_snapshot's refcount here */

    bdrv_ref(bs_snapshot);

    bdrv_append(bs_snapshot, bs, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        ret = -EINVAL;

        goto out;

    }

    g_free(tmp_filename);

    return bs_snapshot;

out:

    QDECREF(snapshot_options);

    g_free(tmp_filename);

    return NULL;

}


int qdev_prop_set_drive(DeviceState *dev, const char *name, BlockDriverState *value)

{

    int res;

    res = bdrv_attach(value, dev);

    if (res < 0) {

        error_report("Can't attach drive %s to %s.%s: %s",

                     bdrv_get_device_name(value),

                     dev->id ? dev->id : dev->info->name,

                     name, strerror(-res));

        return -1;

    }

    qdev_prop_set(dev, name, &value, PROP_TYPE_DRIVE);

    return 0;

}


static inline int cris_lz(int x)

{

	int r;

	asm ("lz\t%1, %0\n" : "=r" (r) : "r" (x));

	return r;

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    X86IOMMUClass *dc_class = X86_IOMMU_CLASS(klass);

    dc->reset = amdvi_reset;

    dc->vmsd = &vmstate_amdvi;

    dc->hotpluggable = false;

    dc_class->realize = amdvi_realize;

}


static void pci_ehci_config(void)

{

    /* hands over all ports from companion uhci to ehci */

    qpci_io_writew(ehci1.dev, ehci1.base + 0x60, 1);

}


static int v9fs_synth_renameat(FsContext *ctx, V9fsPath *olddir,

                               const char *old_name, V9fsPath *newdir,

                               const char *new_name)

{

    errno = EPERM;

    return -1;

}


static int vmdk_write_cid(BlockDriverState *bs, uint32_t cid)

{

    char desc[DESC_SIZE], tmp_desc[DESC_SIZE];

    char *p_name, *tmp_str;

    BDRVVmdkState *s = bs->opaque;

    memset(desc, 0, sizeof(desc));

    if (bdrv_pread(bs->file, s->desc_offset, desc, DESC_SIZE) != DESC_SIZE) {

        return -EIO;

    }

    tmp_str = strstr(desc,"parentCID");

    pstrcpy(tmp_desc, sizeof(tmp_desc), tmp_str);

    if ((p_name = strstr(desc,"CID")) != NULL) {

        p_name += sizeof("CID");

        snprintf(p_name, sizeof(desc) - (p_name - desc), "%x\n", cid);

        pstrcat(desc, sizeof(desc), tmp_desc);

    }

    if (bdrv_pwrite_sync(bs->file, s->desc_offset, desc, DESC_SIZE) < 0) {

        return -EIO;

    }

    return 0;

}


static void qemu_signal_lock(unsigned int msecs)

{

    qemu_mutex_lock(&qemu_fair_mutex);

    while (qemu_mutex_trylock(&qemu_global_mutex)) {

        qemu_thread_signal(tcg_cpu_thread, SIGUSR1);

        if (!qemu_mutex_timedlock(&qemu_global_mutex, msecs))

            break;

    }

    qemu_mutex_unlock(&qemu_fair_mutex);

}


static void gen_mttr(CPUMIPSState *env, DisasContext *ctx, int rd, int rt,

                     int u, int sel, int h)

{

    int other_tc = env->CP0_VPEControl & (0xff << CP0VPECo_TargTC);

    TCGv t0 = tcg_temp_local_new();

    gen_load_gpr(t0, rt);

    if ((env->CP0_VPEConf0 & (1 << CP0VPEC0_MVP)) == 0 &&

        ((env->tcs[other_tc].CP0_TCBind & (0xf << CP0TCBd_CurVPE)) !=

         (env->active_tc.CP0_TCBind & (0xf << CP0TCBd_CurVPE))))

        /* NOP */ ;

    else if ((env->CP0_VPEControl & (0xff << CP0VPECo_TargTC)) >

             (env->mvp->CP0_MVPConf0 & (0xff << CP0MVPC0_PTC)))

        /* NOP */ ;

    else if (u == 0) {

        switch (rd) {

        case 1:

            switch (sel) {

            case 1:

                gen_helper_mttc0_vpecontrol(cpu_env, t0);

                break;

            case 2:

                gen_helper_mttc0_vpeconf0(cpu_env, t0);

                break;

            default:

                goto die;

                break;

            }

            break;

        case 2:

            switch (sel) {

            case 1:

                gen_helper_mttc0_tcstatus(cpu_env, t0);

                break;

            case 2:

                gen_helper_mttc0_tcbind(cpu_env, t0);

                break;

            case 3:

                gen_helper_mttc0_tcrestart(cpu_env, t0);

                break;

            case 4:

                gen_helper_mttc0_tchalt(cpu_env, t0);

                break;

            case 5:

                gen_helper_mttc0_tccontext(cpu_env, t0);

                break;

            case 6:

                gen_helper_mttc0_tcschedule(cpu_env, t0);

                break;

            case 7:

                gen_helper_mttc0_tcschefback(cpu_env, t0);

                break;

            default:

                gen_mtc0(ctx, t0, rd, sel);

                break;

            }

            break;

        case 10:

            switch (sel) {

            case 0:

                gen_helper_mttc0_entryhi(cpu_env, t0);

                break;

            default:

                gen_mtc0(ctx, t0, rd, sel);

                break;

            }

        case 12:

            switch (sel) {

            case 0:

                gen_helper_mttc0_status(cpu_env, t0);

                break;

            default:

                gen_mtc0(ctx, t0, rd, sel);

                break;

            }

        case 13:

            switch (sel) {

            case 0:

                gen_helper_mttc0_cause(cpu_env, t0);

                break;

            default:

                goto die;

                break;

            }

            break;

        case 15:

            switch (sel) {

            case 1:

                gen_helper_mttc0_ebase(cpu_env, t0);

                break;

            default:

                goto die;

                break;

            }

            break;

        case 23:

            switch (sel) {

            case 0:

                gen_helper_mttc0_debug(cpu_env, t0);

                break;

            default:

                gen_mtc0(ctx, t0, rd, sel);

                break;

            }

            break;

        default:

            gen_mtc0(ctx, t0, rd, sel);

        }

    } else switch (sel) {

    /* GPR registers. */

    case 0:

        gen_helper_0e1i(mttgpr, t0, rd);

        break;

    /* Auxiliary CPU registers */

    case 1:

        switch (rd) {

        case 0:

            gen_helper_0e1i(mttlo, t0, 0);

            break;

        case 1:

            gen_helper_0e1i(mtthi, t0, 0);

            break;

        case 2:

            gen_helper_0e1i(mttacx, t0, 0);

            break;

        case 4:

            gen_helper_0e1i(mttlo, t0, 1);

            break;

        case 5:

            gen_helper_0e1i(mtthi, t0, 1);

            break;

        case 6:

            gen_helper_0e1i(mttacx, t0, 1);

            break;

        case 8:

            gen_helper_0e1i(mttlo, t0, 2);

            break;

        case 9:

            gen_helper_0e1i(mtthi, t0, 2);

            break;

        case 10:

            gen_helper_0e1i(mttacx, t0, 2);

            break;

        case 12:

            gen_helper_0e1i(mttlo, t0, 3);

            break;

        case 13:

            gen_helper_0e1i(mtthi, t0, 3);

            break;

        case 14:

            gen_helper_0e1i(mttacx, t0, 3);

            break;

        case 16:

            gen_helper_mttdsp(cpu_env, t0);

            break;

        default:

            goto die;

        }

        break;

    /* Floating point (COP1). */

    case 2:

        /* XXX: For now we support only a single FPU context. */

        if (h == 0) {

            TCGv_i32 fp0 = tcg_temp_new_i32();

            tcg_gen_trunc_tl_i32(fp0, t0);

            gen_store_fpr32(fp0, rd);

            tcg_temp_free_i32(fp0);

        } else {

            TCGv_i32 fp0 = tcg_temp_new_i32();

            tcg_gen_trunc_tl_i32(fp0, t0);

            gen_store_fpr32h(fp0, rd);

            tcg_temp_free_i32(fp0);

        }

        break;

    case 3:

        /* XXX: For now we support only a single FPU context. */

        {

            TCGv_i32 fs_tmp = tcg_const_i32(rd);

            gen_helper_0e2i(ctc1, t0, fs_tmp, rt);

            tcg_temp_free_i32(fs_tmp);

        }

        break;

    /* COP2: Not implemented. */

    case 4:

    case 5:

        /* fall through */

    default:

        goto die;

    }

    LOG_DISAS("mttr (reg %d u %d sel %d h %d)\n", rd, u, sel, h);

    tcg_temp_free(t0);

    return;

die:

    tcg_temp_free(t0);

    LOG_DISAS("mttr (reg %d u %d sel %d h %d)\n", rd, u, sel, h);

    generate_exception(ctx, EXCP_RI);

}


int net_init_slirp(const NetClientOptions *opts, const char *name,

                   NetClientState *peer, Error **errp)

{

    /* FIXME error_setg(errp, ...) on failure */

    struct slirp_config_str *config;

    char *vnet;

    int ret;

    const NetdevUserOptions *user;

    const char **dnssearch;

    assert(opts->kind == NET_CLIENT_OPTIONS_KIND_USER);

    user = opts->user;

    vnet = user->has_net ? g_strdup(user->net) :

           user->has_ip  ? g_strdup_printf("%s/24", user->ip) :

           NULL;

    dnssearch = slirp_dnssearch(user->dnssearch);

    /* all optional fields are initialized to "all bits zero" */

    net_init_slirp_configs(user->hostfwd, SLIRP_CFG_HOSTFWD);

    net_init_slirp_configs(user->guestfwd, 0);

    ret = net_slirp_init(peer, "user", name, user->q_restrict, vnet,

                         user->host, user->hostname, user->tftp,

                         user->bootfile, user->dhcpstart, user->dns, user->smb,

                         user->smbserver, dnssearch);

    while (slirp_configs) {

        config = slirp_configs;

        slirp_configs = config->next;

        g_free(config);

    }

    g_free(vnet);

    g_free(dnssearch);

    return ret;

}


void bdrv_detach(BlockDriverState *bs, DeviceState *qdev)

{

    assert(bs->peer == qdev);

    bs->peer = NULL;

    bs->change_cb = NULL;

    bs->change_opaque = NULL;

}


static void vmsa_ttbcr_reset(CPUARMState *env, const ARMCPRegInfo *ri)

{

    env->cp15.c2_base_mask = 0xffffc000u;

    env->cp15.c2_control = 0;

    env->cp15.c2_mask = 0;

}


static inline void helper_ret_protected(int shift, int is_iret, int addend)

{

    uint32_t sp, new_cs, new_eip, new_eflags, new_esp, new_ss;

    uint32_t new_es, new_ds, new_fs, new_gs;

    uint32_t e1, e2, ss_e1, ss_e2;

    int cpl, dpl, rpl, eflags_mask;

    uint8_t *ssp;

    sp = ESP;

    if (!(env->segs[R_SS].flags & DESC_B_MASK))

        sp &= 0xffff;

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

    if (shift == 1) {

        /* 32 bits */

        if (is_iret)

            new_eflags = ldl_kernel(ssp + 8);

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

        new_eip = ldl_kernel(ssp);

        if (is_iret && (new_eflags & VM_MASK))

            goto return_to_vm86;

    } else {

        /* 16 bits */

        if (is_iret)

            new_eflags = lduw_kernel(ssp + 4);

        new_cs = lduw_kernel(ssp + 2);

        new_eip = lduw_kernel(ssp);

    }

    if ((new_cs & 0xfffc) == 0)

        raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);

    if (load_segment(&e1, &e2, new_cs) != 0)

        raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);

    if (!(e2 & DESC_S_MASK) ||

        !(e2 & DESC_CS_MASK))

        raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);

    cpl = env->hflags & HF_CPL_MASK;

    rpl = new_cs & 3;

    if (rpl < cpl)

        raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);

    dpl = (e2 >> DESC_DPL_SHIFT) & 3;

    if (e2 & DESC_CS_MASK) {

        if (dpl > rpl)

            raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);

    } else {

        if (dpl != rpl)

            raise_exception_err(EXCP0D_GPF, new_cs & 0xfffc);

    }

    if (!(e2 & DESC_P_MASK))

        raise_exception_err(EXCP0B_NOSEG, new_cs & 0xfffc);

    if (rpl == cpl) {

        /* return to same priledge level */

        cpu_x86_load_seg_cache(env, R_CS, new_cs,

                       get_seg_base(e1, e2),

                       get_seg_limit(e1, e2),

                       e2);

        new_esp = sp + (4 << shift) + ((2 * is_iret) << shift) + addend;

    } else {

        /* return to different priviledge level */

        ssp += (4 << shift) + ((2 * is_iret) << shift) + addend;

        if (shift == 1) {

            /* 32 bits */

            new_esp = ldl_kernel(ssp);

            new_ss = ldl_kernel(ssp + 4) & 0xffff;

        } else {

            /* 16 bits */

            new_esp = lduw_kernel(ssp);

            new_ss = lduw_kernel(ssp + 2);

        }

        if ((new_ss & 3) != rpl)

            raise_exception_err(EXCP0D_GPF, new_ss & 0xfffc);

        if (load_segment(&ss_e1, &ss_e2, new_ss) != 0)

            raise_exception_err(EXCP0D_GPF, new_ss & 0xfffc);

        if (!(ss_e2 & DESC_S_MASK) ||

            (ss_e2 & DESC_CS_MASK) ||

            !(ss_e2 & DESC_W_MASK))

            raise_exception_err(EXCP0D_GPF, new_ss & 0xfffc);

        dpl = (ss_e2 >> DESC_DPL_SHIFT) & 3;

        if (dpl != rpl)

            raise_exception_err(EXCP0D_GPF, new_ss & 0xfffc);

        if (!(ss_e2 & DESC_P_MASK))

            raise_exception_err(EXCP0B_NOSEG, new_ss & 0xfffc);

        cpu_x86_load_seg_cache(env, R_CS, new_cs,

                       get_seg_base(e1, e2),

                       get_seg_limit(e1, e2),

                       e2);

        cpu_x86_load_seg_cache(env, R_SS, new_ss,

                       get_seg_base(ss_e1, ss_e2),

                       get_seg_limit(ss_e1, ss_e2),

                       ss_e2);

        cpu_x86_set_cpl(env, rpl);

    }

    if (env->segs[R_SS].flags & DESC_B_MASK)

        ESP = new_esp;

    else

        ESP = (ESP & 0xffff0000) |

            (new_esp & 0xffff);

    env->eip = new_eip;

    if (is_iret) {

        /* NOTE: 'cpl' can be different from the current CPL */

        if (cpl == 0)

            eflags_mask = FL_UPDATE_CPL0_MASK;

        else

            eflags_mask = FL_UPDATE_MASK32;

        if (shift == 0)

            eflags_mask &= 0xffff;

        load_eflags(new_eflags, eflags_mask);

    }

    return;

 return_to_vm86:

    new_esp = ldl_kernel(ssp + 12);

    new_ss = ldl_kernel(ssp + 16);

    new_es = ldl_kernel(ssp + 20);

    new_ds = ldl_kernel(ssp + 24);

    new_fs = ldl_kernel(ssp + 28);

    new_gs = ldl_kernel(ssp + 32);

    /* modify processor state */

    load_eflags(new_eflags, FL_UPDATE_CPL0_MASK | VM_MASK | VIF_MASK | VIP_MASK);

    load_seg_vm(R_CS, new_cs);

    cpu_x86_set_cpl(env, 3);

    load_seg_vm(R_SS, new_ss);

    load_seg_vm(R_ES, new_es);

    load_seg_vm(R_DS, new_ds);

    load_seg_vm(R_FS, new_fs);

    load_seg_vm(R_GS, new_gs);

    env->eip = new_eip;

    ESP = new_esp;

}


static int vnc_refresh_lossy_rect(VncDisplay *vd, int x, int y)

{

    VncState *vs;

    int sty = y / VNC_STAT_RECT;

    int stx = x / VNC_STAT_RECT;

    int has_dirty = 0;

    y = y / VNC_STAT_RECT * VNC_STAT_RECT;

    x = x / VNC_STAT_RECT * VNC_STAT_RECT;

    QTAILQ_FOREACH(vs, &vd->clients, next) {

        int j;

        /* kernel send buffers are full -> refresh later */

        if (vs->output.offset) {

            continue;

        }

        if (!vs->lossy_rect[sty][stx]) {

            continue;

        }

        vs->lossy_rect[sty][stx] = 0;

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

            vnc_set_bits(vs->dirty[y + j], x / 16, VNC_STAT_RECT / 16);

        }

        has_dirty++;

    }

    return has_dirty;

}


void cpu_exec_step_atomic(CPUState *cpu)

{

    start_exclusive();

    /* Since we got here, we know that parallel_cpus must be true.  */

    parallel_cpus = false;

    cpu_exec_step(cpu);

    parallel_cpus = true;

    end_exclusive();

}


void acpi_build(AcpiBuildTables *tables)

{

    PCMachineState *pcms = PC_MACHINE(qdev_get_machine());

    PCMachineClass *pcmc = PC_MACHINE_GET_CLASS(pcms);

    GArray *table_offsets;

    unsigned facs, dsdt, rsdt, fadt;

    AcpiCpuInfo cpu;

    AcpiPmInfo pm;

    AcpiMiscInfo misc;

    AcpiMcfgInfo mcfg;

    PcPciInfo pci;

    uint8_t *u;

    size_t aml_len = 0;

    GArray *tables_blob = tables->table_data;

    AcpiSlicOem slic_oem = { .id = NULL, .table_id = NULL };

    acpi_get_cpu_info(&cpu);

    acpi_get_pm_info(&pm);

    acpi_get_misc_info(&misc);

    acpi_get_pci_info(&pci);

    acpi_get_slic_oem(&slic_oem);

    table_offsets = g_array_new(false, true /* clear */,

                                        sizeof(uint32_t));

    ACPI_BUILD_DPRINTF("init ACPI tables\n");

    bios_linker_loader_alloc(tables->linker, ACPI_BUILD_TABLE_FILE,

                             64 /* Ensure FACS is aligned */,

                             false /* high memory */);

    /*

     * FACS is pointed to by FADT.

     * We place it first since it's the only table that has alignment

     * requirements.

     */

    facs = tables_blob->len;

    build_facs(tables_blob, tables->linker);

    /* DSDT is pointed to by FADT */

    dsdt = tables_blob->len;

    build_dsdt(tables_blob, tables->linker, &cpu, &pm, &misc, &pci);

    /* Count the size of the DSDT and SSDT, we will need it for legacy

     * sizing of ACPI tables.

     */

    aml_len += tables_blob->len - dsdt;

    /* ACPI tables pointed to by RSDT */

    fadt = tables_blob->len;

    acpi_add_table(table_offsets, tables_blob);

    build_fadt(tables_blob, tables->linker, &pm, facs, dsdt,

               slic_oem.id, slic_oem.table_id);

    aml_len += tables_blob->len - fadt;

    acpi_add_table(table_offsets, tables_blob);

    build_madt(tables_blob, tables->linker, &cpu);

    if (misc.has_hpet) {

        acpi_add_table(table_offsets, tables_blob);

        build_hpet(tables_blob, tables->linker);

    }

    if (misc.tpm_version != TPM_VERSION_UNSPEC) {

        acpi_add_table(table_offsets, tables_blob);

        build_tpm_tcpa(tables_blob, tables->linker, tables->tcpalog);

        if (misc.tpm_version == TPM_VERSION_2_0) {

            acpi_add_table(table_offsets, tables_blob);

            build_tpm2(tables_blob, tables->linker);

        }

    }

    if (pcms->numa_nodes) {

        acpi_add_table(table_offsets, tables_blob);

        build_srat(tables_blob, tables->linker);

    }

    if (acpi_get_mcfg(&mcfg)) {

        acpi_add_table(table_offsets, tables_blob);

        build_mcfg_q35(tables_blob, tables->linker, &mcfg);

    }

    if (acpi_has_iommu()) {

        acpi_add_table(table_offsets, tables_blob);

        build_dmar_q35(tables_blob, tables->linker);

    }

    if (acpi_has_nvdimm()) {

        nvdimm_build_acpi(table_offsets, tables_blob, tables->linker);

    }

    /* Add tables supplied by user (if any) */

    for (u = acpi_table_first(); u; u = acpi_table_next(u)) {

        unsigned len = acpi_table_len(u);

        acpi_add_table(table_offsets, tables_blob);

        g_array_append_vals(tables_blob, u, len);

    }

    /* RSDT is pointed to by RSDP */

    rsdt = tables_blob->len;

    build_rsdt(tables_blob, tables->linker, table_offsets,

               slic_oem.id, slic_oem.table_id);

    /* RSDP is in FSEG memory, so allocate it separately */

    build_rsdp(tables->rsdp, tables->linker, rsdt);

    /* We'll expose it all to Guest so we want to reduce

     * chance of size changes.

     *

     * We used to align the tables to 4k, but of course this would

     * too simple to be enough.  4k turned out to be too small an

     * alignment very soon, and in fact it is almost impossible to

     * keep the table size stable for all (max_cpus, max_memory_slots)

     * combinations.  So the table size is always 64k for pc-i440fx-2.1

     * and we give an error if the table grows beyond that limit.

     *

     * We still have the problem of migrating from "-M pc-i440fx-2.0".  For

     * that, we exploit the fact that QEMU 2.1 generates _smaller_ tables

     * than 2.0 and we can always pad the smaller tables with zeros.  We can

     * then use the exact size of the 2.0 tables.

     *

     * All this is for PIIX4, since QEMU 2.0 didn't support Q35 migration.

     */

    if (pcmc->legacy_acpi_table_size) {

        /* Subtracting aml_len gives the size of fixed tables.  Then add the

         * size of the PIIX4 DSDT/SSDT in QEMU 2.0.

         */

        int legacy_aml_len =

            pcmc->legacy_acpi_table_size +

            ACPI_BUILD_LEGACY_CPU_AML_SIZE * max_cpus;

        int legacy_table_size =

            ROUND_UP(tables_blob->len - aml_len + legacy_aml_len,

                     ACPI_BUILD_ALIGN_SIZE);

        if (tables_blob->len > legacy_table_size) {

            /* Should happen only with PCI bridges and -M pc-i440fx-2.0.  */

            error_report("Warning: migration may not work.");

        }

        g_array_set_size(tables_blob, legacy_table_size);

    } else {

        /* Make sure we have a buffer in case we need to resize the tables. */

        if (tables_blob->len > ACPI_BUILD_TABLE_SIZE / 2) {

            /* As of QEMU 2.1, this fires with 160 VCPUs and 255 memory slots.  */

            error_report("Warning: ACPI tables are larger than 64k.");

            error_report("Warning: migration may not work.");

            error_report("Warning: please remove CPUs, NUMA nodes, "

                         "memory slots or PCI bridges.");

        }

        acpi_align_size(tables_blob, ACPI_BUILD_TABLE_SIZE);

    }

    acpi_align_size(tables->linker, ACPI_BUILD_ALIGN_SIZE);

    /* Cleanup memory that's no longer used. */

    g_array_free(table_offsets, true);

}


static void qnull_destroy_obj(QObject *obj)

{

    assert(0);

}


void hmp_info_snapshots(Monitor *mon, const QDict *qdict)

{

    BlockDriverState *bs, *bs1;

    QEMUSnapshotInfo *sn_tab, *sn, s, *sn_info = &s;

    int nb_sns, i, ret, available;

    int total;

    int *available_snapshots;

    bs = find_vmstate_bs();

    if (!bs) {

        monitor_printf(mon, "No available block device supports snapshots\n");

        return;

    }

    nb_sns = bdrv_snapshot_list(bs, &sn_tab);

    if (nb_sns < 0) {

        monitor_printf(mon, "bdrv_snapshot_list: error %d\n", nb_sns);

        return;

    }

    if (nb_sns == 0) {

        monitor_printf(mon, "There is no snapshot available.\n");

        return;

    }

    available_snapshots = g_new0(int, nb_sns);

    total = 0;

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

        sn = &sn_tab[i];

        available = 1;

        bs1 = NULL;

        while ((bs1 = bdrv_next(bs1))) {

            if (bdrv_can_snapshot(bs1) && bs1 != bs) {

                ret = bdrv_snapshot_find(bs1, sn_info, sn->id_str);

                if (ret < 0) {

                    available = 0;

                    break;

                }

            }

        }

        if (available) {

            available_snapshots[total] = i;

            total++;

        }

    }

    if (total > 0) {

        bdrv_snapshot_dump((fprintf_function)monitor_printf, mon, NULL);

        monitor_printf(mon, "\n");

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

            sn = &sn_tab[available_snapshots[i]];

            bdrv_snapshot_dump((fprintf_function)monitor_printf, mon, sn);

            monitor_printf(mon, "\n");

        }

    } else {

        monitor_printf(mon, "There is no suitable snapshot available\n");

    }

    g_free(sn_tab);

    g_free(available_snapshots);

}


static void set_fifodepth(MSSSpiState *s)

{

    unsigned int size = s->regs[R_SPI_DFSIZE] & FRAMESZ_MASK;

    if (size <= 8) {

        s->fifo_depth = 32;

    } else if (size <= 16) {

        s->fifo_depth = 16;

    } else if (size <= 32) {

        s->fifo_depth = 8;

    } else {

        s->fifo_depth = 4;

    }

}


void qdev_unplug(DeviceState *dev, Error **errp)

{

    DeviceClass *dc = DEVICE_GET_CLASS(dev);

    if (!dev->parent_bus->allow_hotplug) {

        error_set(errp, QERR_BUS_NO_HOTPLUG, dev->parent_bus->name);

        return;

    }

    assert(dc->unplug != NULL);

    qdev_hot_removed = true;

    if (dc->unplug(dev) < 0) {

        error_set(errp, QERR_UNDEFINED_ERROR);

        return;

    }

}


int rom_add_file(const char *file, const char *fw_dir, const char *fw_file,

                 target_phys_addr_t addr)

{

    Rom *rom;

    int rc, fd = -1;

    rom = qemu_mallocz(sizeof(*rom));

    rom->name = qemu_strdup(file);

    rom->path = qemu_find_file(QEMU_FILE_TYPE_BIOS, rom->name);

    if (rom->path == NULL) {

        rom->path = qemu_strdup(file);

    }

    fd = open(rom->path, O_RDONLY | O_BINARY);

    if (fd == -1) {

        fprintf(stderr, "Could not open option rom '%s': %s\n",

                rom->path, strerror(errno));

        goto err;

    }

    rom->fw_dir  = fw_dir  ? qemu_strdup(fw_dir)  : NULL;

    rom->fw_file = fw_file ? qemu_strdup(fw_file) : NULL;

    rom->addr    = addr;

    rom->romsize = lseek(fd, 0, SEEK_END);

    rom->data    = qemu_mallocz(rom->romsize);

    lseek(fd, 0, SEEK_SET);

    rc = read(fd, rom->data, rom->romsize);

    if (rc != rom->romsize) {

        fprintf(stderr, "rom: file %-20s: read error: rc=%d (expected %zd)\n",

                rom->name, rc, rom->romsize);

        goto err;

    }

    close(fd);

    rom_insert(rom);

    return 0;

err:

    if (fd != -1)

        close(fd);

    qemu_free(rom->data);

    qemu_free(rom->path);

    qemu_free(rom->name);

    qemu_free(rom);

    return -1;

}


static void ide_ioport_write(void *opaque, uint32_t addr, uint32_t val)

{

    IDEState *ide_if = opaque;

    IDEState *s;

    int unit, n;

    int lba48 = 0;

#ifdef DEBUG_IDE

    printf("IDE: write addr=0x%x val=0x%02x\n", addr, val);

#endif

    addr &= 7;

    /* ignore writes to command block while busy with previous command */

    if (addr != 7 && (ide_if->cur_drive->status & (BUSY_STAT|DRQ_STAT)))

        return;

    switch(addr) {

    case 0:

        break;

    case 1:

	ide_clear_hob(ide_if);

        /* NOTE: data is written to the two drives */

	ide_if[0].hob_feature = ide_if[0].feature;

	ide_if[1].hob_feature = ide_if[1].feature;

        ide_if[0].feature = val;

        ide_if[1].feature = val;

        break;

    case 2:

	ide_clear_hob(ide_if);

	ide_if[0].hob_nsector = ide_if[0].nsector;

	ide_if[1].hob_nsector = ide_if[1].nsector;

        ide_if[0].nsector = val;

        ide_if[1].nsector = val;

        break;

    case 3:

	ide_clear_hob(ide_if);

	ide_if[0].hob_sector = ide_if[0].sector;

	ide_if[1].hob_sector = ide_if[1].sector;

        ide_if[0].sector = val;

        ide_if[1].sector = val;

        break;

    case 4:

	ide_clear_hob(ide_if);

	ide_if[0].hob_lcyl = ide_if[0].lcyl;

	ide_if[1].hob_lcyl = ide_if[1].lcyl;

        ide_if[0].lcyl = val;

        ide_if[1].lcyl = val;

        break;

    case 5:

	ide_clear_hob(ide_if);

	ide_if[0].hob_hcyl = ide_if[0].hcyl;

	ide_if[1].hob_hcyl = ide_if[1].hcyl;

        ide_if[0].hcyl = val;

        ide_if[1].hcyl = val;

        break;

    case 6:

	/* FIXME: HOB readback uses bit 7 */

        ide_if[0].select = (val & ~0x10) | 0xa0;

        ide_if[1].select = (val | 0x10) | 0xa0;

        /* select drive */

        unit = (val >> 4) & 1;

        s = ide_if + unit;

        ide_if->cur_drive = s;

        break;

    default:

    case 7:

        /* command */

#if defined(DEBUG_IDE)

        printf("ide: CMD=%02x\n", val);

#endif

        s = ide_if->cur_drive;

        /* ignore commands to non existant slave */

        if (s != ide_if && !s->bs)

            break;

        /* Only DEVICE RESET is allowed while BSY or/and DRQ are set */

        if ((s->status & (BUSY_STAT|DRQ_STAT)) && val != WIN_DEVICE_RESET)

            break;

        switch(val) {

        case WIN_IDENTIFY:

            if (s->bs && !s->is_cdrom) {

                if (!s->is_cf)

                    ide_identify(s);

                else

                    ide_cfata_identify(s);

                s->status = READY_STAT | SEEK_STAT;

                ide_transfer_start(s, s->io_buffer, 512, ide_transfer_stop);

            } else {

                if (s->is_cdrom) {

                    ide_set_signature(s);

                }

                ide_abort_command(s);

            }

            ide_set_irq(s);

            break;

        case WIN_SPECIFY:

        case WIN_RECAL:

            s->error = 0;

            s->status = READY_STAT | SEEK_STAT;

            ide_set_irq(s);

            break;

        case WIN_SETMULT:

            if (s->is_cf && s->nsector == 0) {

                /* Disable Read and Write Multiple */

                s->mult_sectors = 0;

                s->status = READY_STAT | SEEK_STAT;

            } else if ((s->nsector & 0xff) != 0 &&

                ((s->nsector & 0xff) > MAX_MULT_SECTORS ||

                 (s->nsector & (s->nsector - 1)) != 0)) {

                ide_abort_command(s);

            } else {

                s->mult_sectors = s->nsector & 0xff;

                s->status = READY_STAT | SEEK_STAT;

            }

            ide_set_irq(s);

            break;

        case WIN_VERIFY_EXT:

	    lba48 = 1;

        case WIN_VERIFY:

        case WIN_VERIFY_ONCE:

            /* do sector number check ? */

	    ide_cmd_lba48_transform(s, lba48);

            s->status = READY_STAT | SEEK_STAT;

            ide_set_irq(s);

            break;

	case WIN_READ_EXT:

	    lba48 = 1;

        case WIN_READ:

        case WIN_READ_ONCE:

            if (!s->bs)

                goto abort_cmd;

	    ide_cmd_lba48_transform(s, lba48);

            s->req_nb_sectors = 1;

            ide_sector_read(s);

            break;

	case WIN_WRITE_EXT:

	    lba48 = 1;

        case WIN_WRITE:

        case WIN_WRITE_ONCE:

        case CFA_WRITE_SECT_WO_ERASE:

        case WIN_WRITE_VERIFY:

	    ide_cmd_lba48_transform(s, lba48);

            s->error = 0;

            s->status = SEEK_STAT | READY_STAT;

            s->req_nb_sectors = 1;

            ide_transfer_start(s, s->io_buffer, 512, ide_sector_write);

            s->media_changed = 1;

            break;

	case WIN_MULTREAD_EXT:

	    lba48 = 1;

        case WIN_MULTREAD:

            if (!s->mult_sectors)

                goto abort_cmd;

	    ide_cmd_lba48_transform(s, lba48);

            s->req_nb_sectors = s->mult_sectors;

            ide_sector_read(s);

            break;

        case WIN_MULTWRITE_EXT:

	    lba48 = 1;

        case WIN_MULTWRITE:

        case CFA_WRITE_MULTI_WO_ERASE:

            if (!s->mult_sectors)

                goto abort_cmd;

	    ide_cmd_lba48_transform(s, lba48);

            s->error = 0;

            s->status = SEEK_STAT | READY_STAT;

            s->req_nb_sectors = s->mult_sectors;

            n = s->nsector;

            if (n > s->req_nb_sectors)

                n = s->req_nb_sectors;

            ide_transfer_start(s, s->io_buffer, 512 * n, ide_sector_write);

            s->media_changed = 1;

            break;

	case WIN_READDMA_EXT:

	    lba48 = 1;

        case WIN_READDMA:

        case WIN_READDMA_ONCE:

            if (!s->bs)

                goto abort_cmd;

	    ide_cmd_lba48_transform(s, lba48);

            ide_sector_read_dma(s);

            break;

	case WIN_WRITEDMA_EXT:

	    lba48 = 1;

        case WIN_WRITEDMA:

        case WIN_WRITEDMA_ONCE:

            if (!s->bs)

                goto abort_cmd;

	    ide_cmd_lba48_transform(s, lba48);

            ide_sector_write_dma(s);

            s->media_changed = 1;

            break;

        case WIN_READ_NATIVE_MAX_EXT:

	    lba48 = 1;

        case WIN_READ_NATIVE_MAX:

	    ide_cmd_lba48_transform(s, lba48);

            ide_set_sector(s, s->nb_sectors - 1);

            s->status = READY_STAT | SEEK_STAT;

            ide_set_irq(s);

            break;

        case WIN_CHECKPOWERMODE1:

        case WIN_CHECKPOWERMODE2:

            s->nsector = 0xff; /* device active or idle */

            s->status = READY_STAT | SEEK_STAT;

            ide_set_irq(s);

            break;

        case WIN_SETFEATURES:

            if (!s->bs)

                goto abort_cmd;

            /* XXX: valid for CDROM ? */

            switch(s->feature) {

            case 0xcc: /* reverting to power-on defaults enable */

            case 0x66: /* reverting to power-on defaults disable */

            case 0x02: /* write cache enable */

            case 0x82: /* write cache disable */

            case 0xaa: /* read look-ahead enable */

            case 0x55: /* read look-ahead disable */

            case 0x05: /* set advanced power management mode */

            case 0x85: /* disable advanced power management mode */

            case 0x69: /* NOP */

            case 0x67: /* NOP */

            case 0x96: /* NOP */

            case 0x9a: /* NOP */

            case 0x42: /* enable Automatic Acoustic Mode */

            case 0xc2: /* disable Automatic Acoustic Mode */

                s->status = READY_STAT | SEEK_STAT;

                ide_set_irq(s);

                break;

            case 0x03: { /* set transfer mode */

		uint8_t val = s->nsector & 0x07;

		switch (s->nsector >> 3) {

		    case 0x00: /* pio default */

		    case 0x01: /* pio mode */

			put_le16(s->identify_data + 62,0x07);

			put_le16(s->identify_data + 63,0x07);

			put_le16(s->identify_data + 88,0x3f);

			break;

                    case 0x02: /* sigle word dma mode*/

			put_le16(s->identify_data + 62,0x07 | (1 << (val + 8)));

			put_le16(s->identify_data + 63,0x07);

			put_le16(s->identify_data + 88,0x3f);

			break;

		    case 0x04: /* mdma mode */

			put_le16(s->identify_data + 62,0x07);

			put_le16(s->identify_data + 63,0x07 | (1 << (val + 8)));

			put_le16(s->identify_data + 88,0x3f);

			break;

		    case 0x08: /* udma mode */

			put_le16(s->identify_data + 62,0x07);

			put_le16(s->identify_data + 63,0x07);

			put_le16(s->identify_data + 88,0x3f | (1 << (val + 8)));

			break;

		    default:

			goto abort_cmd;

		}

                s->status = READY_STAT | SEEK_STAT;

                ide_set_irq(s);

                break;

	    }

            default:

                goto abort_cmd;

            }

            break;

        case WIN_FLUSH_CACHE:

        case WIN_FLUSH_CACHE_EXT:

            if (s->bs)

                bdrv_flush(s->bs);

	    s->status = READY_STAT | SEEK_STAT;

            ide_set_irq(s);

            break;

        case WIN_STANDBY:

        case WIN_STANDBY2:

        case WIN_STANDBYNOW1:

        case WIN_STANDBYNOW2:

        case WIN_IDLEIMMEDIATE:

        case CFA_IDLEIMMEDIATE:

        case WIN_SETIDLE1:

        case WIN_SETIDLE2:

        case WIN_SLEEPNOW1:

        case WIN_SLEEPNOW2:

            s->status = READY_STAT;

            ide_set_irq(s);

            break;

            /* ATAPI commands */

        case WIN_PIDENTIFY:

            if (s->is_cdrom) {

                ide_atapi_identify(s);

                s->status = READY_STAT | SEEK_STAT;

                ide_transfer_start(s, s->io_buffer, 512, ide_transfer_stop);

            } else {

                ide_abort_command(s);

            }

            ide_set_irq(s);

            break;

        case WIN_DIAGNOSE:

            ide_set_signature(s);

            s->status = READY_STAT | SEEK_STAT;

            s->error = 0x01;

            ide_set_irq(s);

            break;

        case WIN_SRST:

            if (!s->is_cdrom)

                goto abort_cmd;

            ide_set_signature(s);

            s->status = 0x00; /* NOTE: READY is _not_ set */

            s->error = 0x01;

            break;

        case WIN_PACKETCMD:

            if (!s->is_cdrom)

                goto abort_cmd;

            /* overlapping commands not supported */

            if (s->feature & 0x02)

                goto abort_cmd;

            s->status = READY_STAT | SEEK_STAT;

            s->atapi_dma = s->feature & 1;

            s->nsector = 1;

            ide_transfer_start(s, s->io_buffer, ATAPI_PACKET_SIZE,

                               ide_atapi_cmd);

            break;

        /* CF-ATA commands */

        case CFA_REQ_EXT_ERROR_CODE:

            if (!s->is_cf)

                goto abort_cmd;

            s->error = 0x09;    /* miscellaneous error */

            s->status = READY_STAT | SEEK_STAT;

            ide_set_irq(s);

            break;

        case CFA_ERASE_SECTORS:

        case CFA_WEAR_LEVEL:

            if (!s->is_cf)

                goto abort_cmd;

            if (val == CFA_WEAR_LEVEL)

                s->nsector = 0;

            if (val == CFA_ERASE_SECTORS)

                s->media_changed = 1;

            s->error = 0x00;

            s->status = READY_STAT | SEEK_STAT;

            ide_set_irq(s);

            break;

        case CFA_TRANSLATE_SECTOR:

            if (!s->is_cf)

                goto abort_cmd;

            s->error = 0x00;

            s->status = READY_STAT | SEEK_STAT;

            memset(s->io_buffer, 0, 0x200);

            s->io_buffer[0x00] = s->hcyl;			/* Cyl MSB */

            s->io_buffer[0x01] = s->lcyl;			/* Cyl LSB */

            s->io_buffer[0x02] = s->select;			/* Head */

            s->io_buffer[0x03] = s->sector;			/* Sector */

            s->io_buffer[0x04] = ide_get_sector(s) >> 16;	/* LBA MSB */

            s->io_buffer[0x05] = ide_get_sector(s) >> 8;	/* LBA */

            s->io_buffer[0x06] = ide_get_sector(s) >> 0;	/* LBA LSB */

            s->io_buffer[0x13] = 0x00;				/* Erase flag */

            s->io_buffer[0x18] = 0x00;				/* Hot count */

            s->io_buffer[0x19] = 0x00;				/* Hot count */

            s->io_buffer[0x1a] = 0x01;				/* Hot count */

            ide_transfer_start(s, s->io_buffer, 0x200, ide_transfer_stop);

            ide_set_irq(s);

            break;

        case CFA_ACCESS_METADATA_STORAGE:

            if (!s->is_cf)

                goto abort_cmd;

            switch (s->feature) {

            case 0x02:	/* Inquiry Metadata Storage */

                ide_cfata_metadata_inquiry(s);

                break;

            case 0x03:	/* Read Metadata Storage */

                ide_cfata_metadata_read(s);

                break;

            case 0x04:	/* Write Metadata Storage */

                ide_cfata_metadata_write(s);

                break;

            default:

                goto abort_cmd;

            }

            ide_transfer_start(s, s->io_buffer, 0x200, ide_transfer_stop);

            s->status = 0x00; /* NOTE: READY is _not_ set */

            ide_set_irq(s);

            break;

        case IBM_SENSE_CONDITION:

            if (!s->is_cf)

                goto abort_cmd;

            switch (s->feature) {

            case 0x01:  /* sense temperature in device */

                s->nsector = 0x50;      /* +20 C */

                break;

            default:

                goto abort_cmd;

            }

            s->status = READY_STAT | SEEK_STAT;

            ide_set_irq(s);

            break;

        default:

        abort_cmd:

            ide_abort_command(s);

            ide_set_irq(s);

            break;

        }

    }

}


_syscall3(int,sys_faccessat,int,dirfd,const char *,pathname,int,mode)

#endif

#if defined(TARGET_NR_fchmodat) && defined(__NR_fchmodat)

_syscall3(int,sys_fchmodat,int,dirfd,const char *,pathname, mode_t,mode)

#endif

#if defined(TARGET_NR_fchownat) && defined(__NR_fchownat) && defined(USE_UID16)

_syscall5(int,sys_fchownat,int,dirfd,const char *,pathname,

          uid_t,owner,gid_t,group,int,flags)

#endif

#if (defined(TARGET_NR_fstatat64) || defined(TARGET_NR_newfstatat)) && \

        defined(__NR_fstatat64)

_syscall4(int,sys_fstatat64,int,dirfd,const char *,pathname,

          struct stat *,buf,int,flags)

#endif

#if defined(TARGET_NR_futimesat) && defined(__NR_futimesat)

_syscall3(int,sys_futimesat,int,dirfd,const char *,pathname,

         const struct timeval *,times)

#endif

#if (defined(TARGET_NR_newfstatat) || defined(TARGET_NR_fstatat64) ) && \

        defined(__NR_newfstatat)

_syscall4(int,sys_newfstatat,int,dirfd,const char *,pathname,

          struct stat *,buf,int,flags)

#endif

#if defined(TARGET_NR_linkat) && defined(__NR_linkat)

_syscall5(int,sys_linkat,int,olddirfd,const char *,oldpath,

      int,newdirfd,const char *,newpath,int,flags)

#endif

#if defined(TARGET_NR_mkdirat) && defined(__NR_mkdirat)

_syscall3(int,sys_mkdirat,int,dirfd,const char *,pathname,mode_t,mode)

#endif

#if defined(TARGET_NR_mknodat) && defined(__NR_mknodat)

_syscall4(int,sys_mknodat,int,dirfd,const char *,pathname,

          mode_t,mode,dev_t,dev)

#endif

#if defined(TARGET_NR_openat) && defined(__NR_openat)

_syscall4(int,sys_openat,int,dirfd,const char *,pathname,int,flags,mode_t,mode)

#endif

#if defined(TARGET_NR_readlinkat) && defined(__NR_readlinkat)

_syscall4(int,sys_readlinkat,int,dirfd,const char *,pathname,

          char *,buf,size_t,bufsize)

#endif

#if defined(TARGET_NR_renameat) && defined(__NR_renameat)

_syscall4(int,sys_renameat,int,olddirfd,const char *,oldpath,

          int,newdirfd,const char *,newpath)

#endif

#if defined(TARGET_NR_symlinkat) && defined(__NR_symlinkat)

_syscall3(int,sys_symlinkat,const char *,oldpath,

          int,newdirfd,const char *,newpath)

#endif

#if defined(TARGET_NR_unlinkat) && defined(__NR_unlinkat)

_syscall3(int,sys_unlinkat,int,dirfd,const char *,pathname,int,flags)

#endif

#if defined(TARGET_NR_utimensat) && defined(__NR_utimensat)

_syscall4(int,sys_utimensat,int,dirfd,const char *,pathname,

          const struct timespec *,tsp,int,flags)

#endif

#endif /* CONFIG_ATFILE */

#ifdef CONFIG_INOTIFY

#include <sys/inotify.h>

#if defined(TARGET_NR_inotify_init) && defined(__NR_inotify_init)

static int sys_inotify_init(void)

{

  return (inotify_init());

}


static SocketAddress *sd_socket_address(const char *path,

                                        const char *host, const char *port)

{

    SocketAddress *addr = g_new0(SocketAddress, 1);

    if (path) {

        addr->type = SOCKET_ADDRESS_KIND_UNIX;

        addr->u.q_unix.data = g_new0(UnixSocketAddress, 1);

        addr->u.q_unix.data->path = g_strdup(path);

    } else {

        addr->type = SOCKET_ADDRESS_KIND_INET;

        addr->u.inet.data = g_new0(InetSocketAddress, 1);

        addr->u.inet.data->host = g_strdup(host ?: SD_DEFAULT_ADDR);

        addr->u.inet.data->port = g_strdup(port ?: stringify(SD_DEFAULT_PORT));

    }

    return addr;

}


static void configure_alarms(char const *opt)

{

    int i;

    int cur = 0;

    int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;

    char *arg;

    char *name;

    if (!strcmp(opt, "help")) {

        show_available_alarms();

        exit(0);

    }

    arg = strdup(opt);

    /* Reorder the array */

    name = strtok(arg, ",");

    while (name) {

        struct qemu_alarm_timer tmp;

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

            if (!strcmp(alarm_timers[i].name, name))

                break;

        }

        if (i == count) {

            fprintf(stderr, "Unknown clock %s\n", name);

            goto next;

        }

        if (i < cur)

            /* Ignore */

            goto next;

	/* Swap */

        tmp = alarm_timers[i];

        alarm_timers[i] = alarm_timers[cur];

        alarm_timers[cur] = tmp;

        cur++;

next:

        name = strtok(NULL, ",");

    }

    free(arg);

    if (cur) {

	/* Disable remaining timers */

        for (i = cur; i < count; i++)

            alarm_timers[i].name = NULL;

    }

    /* debug */

    show_available_alarms();

}


static void rtas_ibm_get_system_parameter(PowerPCCPU *cpu,

                                          sPAPRMachineState *spapr,

                                          uint32_t token, uint32_t nargs,

                                          target_ulong args,

                                          uint32_t nret, target_ulong rets)

{

    target_ulong parameter = rtas_ld(args, 0);

    target_ulong buffer = rtas_ld(args, 1);

    target_ulong length = rtas_ld(args, 2);

    target_ulong ret;

    switch (parameter) {

    case RTAS_SYSPARM_SPLPAR_CHARACTERISTICS: {

        char *param_val = g_strdup_printf("MaxEntCap=%d,"

                                          "DesMem=%llu,"

                                          "DesProcs=%d,"

                                          "MaxPlatProcs=%d",

                                          max_cpus,

                                          current_machine->ram_size / M_BYTE,

                                          smp_cpus,

                                          max_cpus);

        ret = sysparm_st(buffer, length, param_val, strlen(param_val) + 1);

        g_free(param_val);

        break;

    }

    case RTAS_SYSPARM_DIAGNOSTICS_RUN_MODE: {

        uint8_t param_val = DIAGNOSTICS_RUN_MODE_DISABLED;

        ret = sysparm_st(buffer, length, &param_val, sizeof(param_val));

        break;

    }

    case RTAS_SYSPARM_UUID:

        ret = sysparm_st(buffer, length, qemu_uuid, (qemu_uuid_set ? 16 : 0));

        break;

    default:

        ret = RTAS_OUT_NOT_SUPPORTED;

    }

    rtas_st(rets, 0, ret);

}


static void test_qemu_strtoull_trailing(void)

{

    const char *str = "123xxx";

    char f = 'X';

    const char *endptr = &f;

    uint64_t res = 999;

    int err;

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

    g_assert_cmpint(err, ==, 0);

    g_assert_cmpint(res, ==, 123);

    g_assert(endptr == str + 3);

}


void bdrv_set_dirty_bitmap(BdrvDirtyBitmap *bitmap,

                           int64_t cur_sector, int64_t nr_sectors)

{

    assert(bdrv_dirty_bitmap_enabled(bitmap));

    hbitmap_set(bitmap->bitmap, cur_sector, nr_sectors);

}


int kvm_has_xsave(void)

{

    return kvm_state->xsave;

}


static BlockDriverAIOCB *curl_aio_readv(BlockDriverState *bs,

        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,

        BlockDriverCompletionFunc *cb, void *opaque)

{

    CURLAIOCB *acb;

    acb = qemu_aio_get(&curl_aiocb_info, bs, cb, opaque);

    acb->qiov = qiov;

    acb->sector_num = sector_num;

    acb->nb_sectors = nb_sectors;

    acb->bh = qemu_bh_new(curl_readv_bh_cb, acb);

    qemu_bh_schedule(acb->bh);

    return &acb->common;

}


static int translate_pages(S390CPU *cpu, vaddr addr, int nr_pages,

                           target_ulong *pages, bool is_write)

{

    bool lowprot = is_write && lowprot_enabled(&cpu->env);

    uint64_t asc = cpu->env.psw.mask & PSW_MASK_ASC;

    CPUS390XState *env = &cpu->env;

    int ret, i, pflags;

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

        /* Low-address protection? */

        if (lowprot && (addr < 512 || (addr >= 4096 && addr < 4096 + 512))) {

            trigger_access_exception(env, PGM_PROTECTION, ILEN_AUTO, 0);

            return -EACCES;

        }

        ret = mmu_translate(env, addr, is_write, asc, &pages[i], &pflags, true);

        if (ret) {

            return ret;

        }

        if (!address_space_access_valid(&address_space_memory, pages[i],

                                        TARGET_PAGE_SIZE, is_write)) {

            program_interrupt(env, PGM_ADDRESSING, ILEN_AUTO);

            return -EFAULT;

        }

        addr += TARGET_PAGE_SIZE;

    }

    return 0;

}


static unsigned int dec_move_sr(DisasContext *dc)

{

	DIS(fprintf (logfile, "move $s%u, $r%u\n", dc->op2, dc->op1));

	cris_cc_mask(dc, 0);

	tcg_gen_helper_0_2(helper_movl_reg_sreg,

			   tcg_const_tl(dc->op1), tcg_const_tl(dc->op2));

	return 2;

}


static int xen_pt_msixctrl_reg_init(XenPCIPassthroughState *s,

                                    XenPTRegInfo *reg, uint32_t real_offset,

                                    uint32_t *data)

{

    PCIDevice *d = &s->dev;

    uint16_t reg_field = 0;

    /* use I/O device register's value as initial value */

    reg_field = pci_get_word(d->config + real_offset);

    if (reg_field & PCI_MSIX_FLAGS_ENABLE) {

        XEN_PT_LOG(d, "MSIX already enabled, disabling it first\n");

        xen_host_pci_set_word(&s->real_device, real_offset,

                              reg_field & ~PCI_MSIX_FLAGS_ENABLE);

    }

    s->msix->ctrl_offset = real_offset;

    *data = reg->init_val;

    return 0;

}


static ssize_t v9fs_synth_readlink(FsContext *fs_ctx, V9fsPath *path,

                                   char *buf, size_t bufsz)

{

    errno = ENOSYS;

    return -1;

}


static bool cmd_read_dma(IDEState *s, uint8_t cmd)

{

    bool lba48 = (cmd == WIN_READDMA_EXT);

    if (!s->bs) {

        ide_abort_command(s);

        return true;

    }

    ide_cmd_lba48_transform(s, lba48);

    ide_sector_start_dma(s, IDE_DMA_READ);

    return false;

}


static void timer_start(SpiceTimer *timer, uint32_t ms)

{

    qemu_mod_timer(timer->timer, qemu_get_clock(rt_clock) + ms);

}


static int pci_pbm_init_device(SysBusDevice *dev)

{

    APBState *s;

    int pci_mem_config, pci_mem_data, apb_config, pci_ioport;

    s = FROM_SYSBUS(APBState, dev);

    /* apb_config */

    apb_config = cpu_register_io_memory(apb_config_read,

                                        apb_config_write, s);

    sysbus_init_mmio(dev, 0x40ULL, apb_config);

    /* pci_ioport */

    pci_ioport = cpu_register_io_memory(pci_apb_ioread,

                                          pci_apb_iowrite, s);

    sysbus_init_mmio(dev, 0x10000ULL, pci_ioport);

    /* mem_config  */

    pci_mem_config = cpu_register_io_memory(pci_apb_config_read,

                                            pci_apb_config_write, s);

    sysbus_init_mmio(dev, 0x10ULL, pci_mem_config);

    /* mem_data */

    pci_mem_data = cpu_register_io_memory(pci_apb_read,

                                          pci_apb_write, &s->host_state);

    sysbus_init_mmio(dev, 0x10000000ULL, pci_mem_data);

    return 0;

}


void cpu_reset (CPUMIPSState *env)

{

    memset(env, 0, offsetof(CPUMIPSState, breakpoints));

    tlb_flush(env, 1);

    /* Minimal init */

#if !defined(CONFIG_USER_ONLY)

    if (env->hflags & MIPS_HFLAG_BMASK) {

        /* If the exception was raised from a delay slot,

         * come back to the jump.  */

        env->CP0_ErrorEPC = env->PC - 4;

        env->hflags &= ~MIPS_HFLAG_BMASK;

    } else {

        env->CP0_ErrorEPC = env->PC;

    }

    env->PC = (int32_t)0xBFC00000;

#if defined (MIPS_USES_R4K_TLB)

    env->CP0_Random = MIPS_TLB_NB - 1;

    env->tlb_in_use = MIPS_TLB_NB;

#endif

    env->CP0_Wired = 0;

    /* SMP not implemented */

    env->CP0_EBase = (int32_t)0x80000000;

    env->CP0_Config0 = MIPS_CONFIG0;

    env->CP0_Config1 = MIPS_CONFIG1;

    env->CP0_Config2 = MIPS_CONFIG2;

    env->CP0_Config3 = MIPS_CONFIG3;

    env->CP0_Status = (1 << CP0St_BEV) | (1 << CP0St_ERL);

    env->CP0_WatchLo = 0;

    env->hflags = MIPS_HFLAG_ERL;

    /* Count register increments in debug mode, EJTAG version 1 */

    env->CP0_Debug = (1 << CP0DB_CNT) | (0x1 << CP0DB_VER);

    env->CP0_PRid = MIPS_CPU;

#endif

    env->exception_index = EXCP_NONE;

#if defined(CONFIG_USER_ONLY)

    env->hflags |= MIPS_HFLAG_UM;

    env->user_mode_only = 1;

#endif

#ifdef MIPS_USES_FPU

    env->fcr0 = MIPS_FCR0;

#endif

    /* XXX some guesswork here, values are CPU specific */

    env->SYNCI_Step = 16;

    env->CCRes = 2;

}


static void gen_neon_unzip_u8(TCGv t0, TCGv t1)

{

    TCGv rd, rm, tmp;

    rd = new_tmp();

    rm = new_tmp();

    tmp = new_tmp();

    tcg_gen_andi_i32(rd, t0, 0xff);

    tcg_gen_shri_i32(tmp, t0, 8);

    tcg_gen_andi_i32(tmp, tmp, 0xff00);

    tcg_gen_or_i32(rd, rd, tmp);

    tcg_gen_shli_i32(tmp, t1, 16);

    tcg_gen_andi_i32(tmp, tmp, 0xff0000);

    tcg_gen_or_i32(rd, rd, tmp);

    tcg_gen_shli_i32(tmp, t1, 8);

    tcg_gen_andi_i32(tmp, tmp, 0xff000000);

    tcg_gen_or_i32(rd, rd, tmp);

    tcg_gen_shri_i32(rm, t0, 8);

    tcg_gen_andi_i32(rm, rm, 0xff);

    tcg_gen_shri_i32(tmp, t0, 16);

    tcg_gen_andi_i32(tmp, tmp, 0xff00);

    tcg_gen_or_i32(rm, rm, tmp);

    tcg_gen_shli_i32(tmp, t1, 8);

    tcg_gen_andi_i32(tmp, tmp, 0xff0000);

    tcg_gen_or_i32(rm, rm, tmp);

    tcg_gen_andi_i32(tmp, t1, 0xff000000);

    tcg_gen_or_i32(t1, rm, tmp);

    tcg_gen_mov_i32(t0, rd);

    dead_tmp(tmp);

    dead_tmp(rm);

    dead_tmp(rd);

}


static int nic_can_receive(NetClientState *nc)

{

    EEPRO100State *s = qemu_get_nic_opaque(nc);

    TRACE(RXTX, logout("%p\n", s));

    return get_ru_state(s) == ru_ready;

#if 0

    return !eepro100_buffer_full(s);

#endif

}


int omap_validate_emiff_addr(struct omap_mpu_state_s *s,

                target_phys_addr_t addr)

{

    return addr >= OMAP_EMIFF_BASE && addr < OMAP_EMIFF_BASE + s->sdram_size;

}


PCIDevice *pci_nic_init(NICInfo *nd, const char *default_model,

                        const char *default_devaddr)

{

    const char *devaddr = nd->devaddr ? nd->devaddr : default_devaddr;

    PCIBus *bus;

    int devfn;

    PCIDevice *pci_dev;

    DeviceState *dev;

    int i;

    i = qemu_find_nic_model(nd, pci_nic_models, default_model);

    if (i < 0)

        return NULL;

    bus = pci_get_bus_devfn(&devfn, devaddr);

    if (!bus) {

        error_report("Invalid PCI device address %s for device %s",

                     devaddr, pci_nic_names[i]);

        return NULL;

    }

    pci_dev = pci_create(bus, devfn, pci_nic_names[i]);

    dev = &pci_dev->qdev;

    if (nd->name)

        dev->id = qemu_strdup(nd->name);

    qdev_set_nic_properties(dev, nd);

    if (qdev_init(dev) < 0)

        return NULL;

    return pci_dev;

}


static const char *local_mapped_attr_path(FsContext *ctx,

                                          const char *path, char *buffer)

{

    char *dir_name;

    char *tmp_path = g_strdup(path);

    char *base_name = basename(tmp_path);

    /* NULL terminate the directory */

    dir_name = tmp_path;

    *(base_name - 1) = '\0';

    snprintf(buffer, PATH_MAX, "%s/%s/%s/%s",

             ctx->fs_root, dir_name, VIRTFS_META_DIR, base_name);

    g_free(tmp_path);

    return buffer;

}


RxFilterInfoList *qmp_query_rx_filter(bool has_name, const char *name,

                                      Error **errp)

{

    NetClientState *nc;

    RxFilterInfoList *filter_list = NULL, *last_entry = NULL;

    QTAILQ_FOREACH(nc, &net_clients, next) {

        RxFilterInfoList *entry;

        RxFilterInfo *info;

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

            continue;

        }

        /* only query rx-filter information of NIC */

        if (nc->info->type != NET_CLIENT_OPTIONS_KIND_NIC) {

            if (has_name) {

                error_setg(errp, "net client(%s) isn't a NIC", name);

                break;

            }

            continue;

        }

        if (nc->info->query_rx_filter) {

            info = nc->info->query_rx_filter(nc);

            entry = g_malloc0(sizeof(*entry));

            entry->value = info;

            if (!filter_list) {

                filter_list = entry;

            } else {

                last_entry->next = entry;

            }

            last_entry = entry;

        } else if (has_name) {

            error_setg(errp, "net client(%s) doesn't support"

                       " rx-filter querying", name);

            break;

        }

        if (has_name) {

            break;

        }

    }

    if (filter_list == NULL && !error_is_set(errp) && has_name) {

        error_setg(errp, "invalid net client name: %s", name);

    }

    return filter_list;

}


write_f(int argc, char **argv)

{

	struct timeval t1, t2;

	int Cflag = 0, pflag = 0, qflag = 0, bflag = 0;

	int c, cnt;

	char *buf;

	int64_t offset;

	int count;

        /* Some compilers get confused and warn if this is not initialized.  */

        int total = 0;

	int pattern = 0xcd;

	while ((c = getopt(argc, argv, "bCpP:q")) != EOF) {

		switch (c) {

		case 'b':

			bflag = 1;

			break;

		case 'C':

			Cflag = 1;

			break;

		case 'p':

			pflag = 1;

			break;

		case 'P':

			pattern = atoi(optarg);

			break;

		case 'q':

			qflag = 1;

			break;

		default:

			return command_usage(&write_cmd);

		}

	}

	if (optind != argc - 2)

		return command_usage(&write_cmd);

	if (bflag && pflag) {

		printf("-b and -p cannot be specified at the same time\n");

		return 0;

	}

	offset = cvtnum(argv[optind]);

	if (offset < 0) {

		printf("non-numeric length argument -- %s\n", argv[optind]);

		return 0;

	}

	optind++;

	count = cvtnum(argv[optind]);

	if (count < 0) {

		printf("non-numeric length argument -- %s\n", argv[optind]);

		return 0;

	}

	if (!pflag) {

		if (offset & 0x1ff) {

			printf("offset %lld is not sector aligned\n",

				(long long)offset);

			return 0;

		}

		if (count & 0x1ff) {

			printf("count %d is not sector aligned\n",

				count);

			return 0;

		}

	}

	buf = qemu_io_alloc(count, pattern);

	gettimeofday(&t1, NULL);

	if (pflag)

		cnt = do_pwrite(buf, offset, count, &total);

	else if (bflag)

		cnt = do_save_vmstate(buf, offset, count, &total);

	else

		cnt = do_write(buf, offset, count, &total);

	gettimeofday(&t2, NULL);

	if (cnt < 0) {

		printf("write failed: %s\n", strerror(-cnt));

		goto out;

	}

	if (qflag)

		goto out;

	/* Finally, report back -- -C gives a parsable format */

	t2 = tsub(t2, t1);

	print_report("wrote", &t2, offset, count, total, cnt, Cflag);

out:

	qemu_io_free(buf);

	return 0;

}