static int ffm_read_header(AVFormatContext *s)

{

    FFMContext *ffm = s->priv_data;

    AVStream *st;

    AVIOContext *pb = s->pb;

    AVCodecContext *codec;

    const AVCodecDescriptor *codec_desc;

    int i, nb_streams;

    uint32_t tag;

    /* header */

    tag = avio_rl32(pb);

    if (tag == MKTAG('F', 'F', 'M', '2'))

        return ffm2_read_header(s);

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

    ffm->packet_size = avio_rb32(pb);

    if (ffm->packet_size != FFM_PACKET_SIZE)

    ffm->write_index = avio_rb64(pb);

    /* get also filesize */

    if (pb->seekable) {

        ffm->file_size = avio_size(pb);

        if (ffm->write_index && 0)

            adjust_write_index(s);

    } else {

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

    nb_streams = avio_rb32(pb);

    avio_rb32(pb); /* total bitrate */

    /* read each stream */

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

        char rc_eq_buf[128];

        st = avformat_new_stream(s, NULL);

        if (!st)

        avpriv_set_pts_info(st, 64, 1, 1000000);

        codec = st->codec;

        /* generic info */

        codec->codec_id = avio_rb32(pb);

        codec_desc = avcodec_descriptor_get(codec->codec_id);

        if (!codec_desc) {

            av_log(s, AV_LOG_ERROR, "Invalid codec id: %d\n", codec->codec_id);

            codec->codec_id = AV_CODEC_ID_NONE;

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

        if (codec->codec_type != codec_desc->type) {

            av_log(s, AV_LOG_ERROR, "Codec type mismatch: expected %d, found %d\n",

                   codec_desc->type, codec->codec_type);

            codec->codec_id = AV_CODEC_ID_NONE;

            codec->codec_type = AVMEDIA_TYPE_UNKNOWN;

        codec->bit_rate = avio_rb32(pb);

        codec->flags = avio_rb32(pb);

        codec->flags2 = avio_rb32(pb);

        codec->debug = avio_rb32(pb);

        /* specific info */

        switch(codec->codec_type) {

        case AVMEDIA_TYPE_VIDEO:

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

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

            if (codec->time_base.num <= 0 || codec->time_base.den <= 0) {

                av_log(s, AV_LOG_ERROR, "Invalid time base %d/%d\n",

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

            codec->width = avio_rb16(pb);

            codec->height = avio_rb16(pb);

            codec->gop_size = avio_rb16(pb);

            codec->pix_fmt = avio_rb32(pb);

            codec->qmin = avio_r8(pb);

            codec->qmax = avio_r8(pb);

            codec->max_qdiff = avio_r8(pb);

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

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

            codec->bit_rate_tolerance = avio_rb32(pb);

            avio_get_str(pb, INT_MAX, rc_eq_buf, sizeof(rc_eq_buf));

            codec->rc_eq = av_strdup(rc_eq_buf);

            codec->rc_max_rate = avio_rb32(pb);

            codec->rc_min_rate = avio_rb32(pb);

            codec->rc_buffer_size = avio_rb32(pb);

            codec->i_quant_factor = av_int2double(avio_rb64(pb));

            codec->b_quant_factor = av_int2double(avio_rb64(pb));

            codec->i_quant_offset = av_int2double(avio_rb64(pb));

            codec->b_quant_offset = av_int2double(avio_rb64(pb));

            codec->dct_algo = avio_rb32(pb);

            codec->strict_std_compliance = avio_rb32(pb);

            codec->max_b_frames = avio_rb32(pb);

            codec->mpeg_quant = avio_rb32(pb);

            codec->intra_dc_precision = avio_rb32(pb);

            codec->me_method = avio_rb32(pb);

            codec->mb_decision = avio_rb32(pb);

            codec->nsse_weight = avio_rb32(pb);

            codec->frame_skip_cmp = avio_rb32(pb);

            codec->rc_buffer_aggressivity = av_int2double(avio_rb64(pb));

            codec->codec_tag = avio_rb32(pb);

            codec->thread_count = avio_r8(pb);

            codec->coder_type = avio_rb32(pb);

            codec->me_cmp = avio_rb32(pb);

            codec->me_subpel_quality = avio_rb32(pb);

            codec->me_range = avio_rb32(pb);

            codec->keyint_min = avio_rb32(pb);

            codec->scenechange_threshold = avio_rb32(pb);

            codec->b_frame_strategy = avio_rb32(pb);

            codec->qcompress = av_int2double(avio_rb64(pb));

            codec->qblur = av_int2double(avio_rb64(pb));

            codec->max_qdiff = avio_rb32(pb);

            codec->refs = avio_rb32(pb);

            break;

        case AVMEDIA_TYPE_AUDIO:

            codec->sample_rate = avio_rb32(pb);

            codec->channels = avio_rl16(pb);

            codec->frame_size = avio_rl16(pb);

            break;

        default:

        if (codec->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {

            int size = avio_rb32(pb);

            codec->extradata = av_mallocz(size + AV_INPUT_BUFFER_PADDING_SIZE);

            if (!codec->extradata)

                return AVERROR(ENOMEM);

            codec->extradata_size = size;

            avio_read(pb, codec->extradata, size);

        avcodec_parameters_from_context(st->codecpar, codec);

    /* get until end of block reached */

    while ((avio_tell(pb) % ffm->packet_size) != 0 && !pb->eof_reached)

        avio_r8(pb);

    /* init packet demux */

    ffm->packet_ptr = ffm->packet;

    ffm->packet_end = ffm->packet;

    ffm->frame_offset = 0;

    ffm->dts = 0;

    ffm->read_state = READ_HEADER;

    ffm->first_packet = 1;

    return 0;

 fail:

    ffm_close(s);

    return -1;


static void shpc_interrupt_update(PCIDevice *d)

{

    SHPCDevice *shpc = d->shpc;

    int slot;

    int level = 0;

    uint32_t serr_int;

    uint32_t int_locator = 0;

    /* Update interrupt locator register */

    for (slot = 0; slot < shpc->nslots; ++slot) {

        uint8_t event = shpc->config[SHPC_SLOT_EVENT_LATCH(slot)];

        uint8_t disable = shpc->config[SHPC_SLOT_EVENT_SERR_INT_DIS(d, slot)];

        uint32_t mask = 1 << SHPC_IDX_TO_LOGICAL(slot);

        if (event & ~disable) {

            int_locator |= mask;

        }

    }

    serr_int = pci_get_long(shpc->config + SHPC_SERR_INT);

    if ((serr_int & SHPC_CMD_DETECTED) && !(serr_int & SHPC_CMD_INT_DIS)) {

        int_locator |= SHPC_INT_COMMAND;

    }

    pci_set_long(shpc->config + SHPC_INT_LOCATOR, int_locator);

    level = (!(serr_int & SHPC_INT_DIS) && int_locator) ? 1 : 0;

    if (msi_enabled(d) && shpc->msi_requested != level)

        msi_notify(d, 0);

    else

        pci_set_irq(d, level);

    shpc->msi_requested = level;

}


static void usb_mtp_command(MTPState *s, MTPControl *c)

{

    MTPData *data_in = NULL;

    MTPObject *o;

    uint32_t nres = 0, res0 = 0;

    /* sanity checks */

    if (c->code >= CMD_CLOSE_SESSION && s->session == 0) {

        usb_mtp_queue_result(s, RES_SESSION_NOT_OPEN,

                             c->trans, 0, 0, 0);

        return;

    }

    /* process commands */

    switch (c->code) {

    case CMD_GET_DEVICE_INFO:

        data_in = usb_mtp_get_device_info(s, c);

        break;

    case CMD_OPEN_SESSION:

        if (s->session) {

            usb_mtp_queue_result(s, RES_SESSION_ALREADY_OPEN,

                                 c->trans, 1, s->session, 0);

            return;

        }

        if (c->argv[0] == 0) {

            usb_mtp_queue_result(s, RES_INVALID_PARAMETER,

                                 c->trans, 0, 0, 0);

            return;

        }

        trace_usb_mtp_op_open_session(s->dev.addr);

        s->session = c->argv[0];

        usb_mtp_object_alloc(s, s->next_handle++, NULL, s->root);

#ifdef __linux__

        if (usb_mtp_inotify_init(s)) {

            fprintf(stderr, "usb-mtp: file monitoring init failed\n");

        }

#endif

        break;

    case CMD_CLOSE_SESSION:

        trace_usb_mtp_op_close_session(s->dev.addr);

        s->session = 0;

        s->next_handle = 0;

#ifdef __linux__

        usb_mtp_inotify_cleanup(s);

#endif

        usb_mtp_object_free(s, QTAILQ_FIRST(&s->objects));

        assert(QTAILQ_EMPTY(&s->objects));

        break;

    case CMD_GET_STORAGE_IDS:

        data_in = usb_mtp_get_storage_ids(s, c);

        break;

    case CMD_GET_STORAGE_INFO:

        if (c->argv[0] != QEMU_STORAGE_ID &&

            c->argv[0] != 0xffffffff) {

            usb_mtp_queue_result(s, RES_INVALID_STORAGE_ID,

                                 c->trans, 0, 0, 0);

            return;

        }

        data_in = usb_mtp_get_storage_info(s, c);

        break;

    case CMD_GET_NUM_OBJECTS:

    case CMD_GET_OBJECT_HANDLES:

        if (c->argv[0] != QEMU_STORAGE_ID &&

            c->argv[0] != 0xffffffff) {

            usb_mtp_queue_result(s, RES_INVALID_STORAGE_ID,

                                 c->trans, 0, 0, 0);

            return;

        }

        if (c->argv[1] != 0x00000000) {

            usb_mtp_queue_result(s, RES_SPEC_BY_FORMAT_UNSUPPORTED,

                                 c->trans, 0, 0, 0);

            return;

        }

        if (c->argv[2] == 0x00000000 ||

            c->argv[2] == 0xffffffff) {

            o = QTAILQ_FIRST(&s->objects);

        } else {

            o = usb_mtp_object_lookup(s, c->argv[2]);

        }

        if (o == NULL) {

            usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,

                                 c->trans, 0, 0, 0);

            return;

        }

        if (o->format != FMT_ASSOCIATION) {

            usb_mtp_queue_result(s, RES_INVALID_PARENT_OBJECT,

                                 c->trans, 0, 0, 0);

            return;

        }

        usb_mtp_object_readdir(s, o);

        if (c->code == CMD_GET_NUM_OBJECTS) {

            trace_usb_mtp_op_get_num_objects(s->dev.addr, o->handle, o->path);

            nres = 1;

            res0 = o->nchildren;

        } else {

            data_in = usb_mtp_get_object_handles(s, c, o);

        }

        break;

    case CMD_GET_OBJECT_INFO:

        o = usb_mtp_object_lookup(s, c->argv[0]);

        if (o == NULL) {

            usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,

                                 c->trans, 0, 0, 0);

            return;

        }

        data_in = usb_mtp_get_object_info(s, c, o);

        break;

    case CMD_GET_OBJECT:

        o = usb_mtp_object_lookup(s, c->argv[0]);

        if (o == NULL) {

            usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,

                                 c->trans, 0, 0, 0);

            return;

        }

        if (o->format == FMT_ASSOCIATION) {

            usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,

                                 c->trans, 0, 0, 0);

            return;

        }

        data_in = usb_mtp_get_object(s, c, o);

        if (data_in == NULL) {

            usb_mtp_queue_result(s, RES_GENERAL_ERROR,

                                 c->trans, 0, 0, 0);

            return;

        }

        break;

    case CMD_GET_PARTIAL_OBJECT:

        o = usb_mtp_object_lookup(s, c->argv[0]);

        if (o == NULL) {

            usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,

                                 c->trans, 0, 0, 0);

            return;

        }

        if (o->format == FMT_ASSOCIATION) {

            usb_mtp_queue_result(s, RES_INVALID_OBJECT_HANDLE,

                                 c->trans, 0, 0, 0);

            return;

        }

        data_in = usb_mtp_get_partial_object(s, c, o);

        if (data_in == NULL) {

            usb_mtp_queue_result(s, RES_GENERAL_ERROR,

                                 c->trans, 0, 0, 0);

            return;

        }

        nres = 1;

        res0 = data_in->length;

        break;

    default:

        trace_usb_mtp_op_unknown(s->dev.addr, c->code);

        usb_mtp_queue_result(s, RES_OPERATION_NOT_SUPPORTED,

                             c->trans, 0, 0, 0);

        return;

    }

    /* return results on success */

    if (data_in) {

        assert(s->data_in == NULL);

        s->data_in = data_in;

    }

    usb_mtp_queue_result(s, RES_OK, c->trans, nres, res0, 0);

}


static int sdp_read_header(AVFormatContext *s)

{

    RTSPState *rt = s->priv_data;

    RTSPStream *rtsp_st;

    int size, i, err;

    char *content;

    char url[1024];

    if (!ff_network_init())

        return AVERROR(EIO);

    if (s->max_delay < 0) /* Not set by the caller */

        s->max_delay = DEFAULT_REORDERING_DELAY;

    if (rt->rtsp_flags & RTSP_FLAG_CUSTOM_IO)

        rt->lower_transport = RTSP_LOWER_TRANSPORT_CUSTOM;

    /* read the whole sdp file */

    /* XXX: better loading */

    content = av_malloc(SDP_MAX_SIZE);

    size = avio_read(s->pb, content, SDP_MAX_SIZE - 1);

    if (size <= 0) {

        av_free(content);

        return AVERROR_INVALIDDATA;

    }

    content[size] ='\0';

    err = ff_sdp_parse(s, content);

    av_freep(&content);

    if (err) goto fail;

    /* open each RTP stream */

    for (i = 0; i < rt->nb_rtsp_streams; i++) {

        char namebuf[50];

        rtsp_st = rt->rtsp_streams[i];

        if (!(rt->rtsp_flags & RTSP_FLAG_CUSTOM_IO)) {

            AVDictionary *opts = map_to_opts(rt);

            getnameinfo((struct sockaddr*) &rtsp_st->sdp_ip, sizeof(rtsp_st->sdp_ip),

                        namebuf, sizeof(namebuf), NULL, 0, NI_NUMERICHOST);

            ff_url_join(url, sizeof(url), "rtp", NULL,

                        namebuf, rtsp_st->sdp_port,

                        "?localport=%d&ttl=%d&connect=%d&write_to_source=%d",

                        rtsp_st->sdp_port, rtsp_st->sdp_ttl,

                        rt->rtsp_flags & RTSP_FLAG_FILTER_SRC ? 1 : 0,

                        rt->rtsp_flags & RTSP_FLAG_RTCP_TO_SOURCE ? 1 : 0);

            append_source_addrs(url, sizeof(url), "sources",

                                rtsp_st->nb_include_source_addrs,

                                rtsp_st->include_source_addrs);

            append_source_addrs(url, sizeof(url), "block",

                                rtsp_st->nb_exclude_source_addrs,

                                rtsp_st->exclude_source_addrs);

            err = ffurl_open(&rtsp_st->rtp_handle, url, AVIO_FLAG_READ_WRITE,

                           &s->interrupt_callback, &opts);

            av_dict_free(&opts);

            if (err < 0) {

                err = AVERROR_INVALIDDATA;

                goto fail;

            }

        }

        if ((err = ff_rtsp_open_transport_ctx(s, rtsp_st)))

            goto fail;

    }

    return 0;

fail:

    ff_rtsp_close_streams(s);

    ff_network_close();

    return err;

}


static inline void gen_op_mfspr(DisasContext *ctx)

{

    void (*read_cb)(void *opaque, int gprn, int sprn);

    uint32_t sprn = SPR(ctx->opcode);

#if !defined(CONFIG_USER_ONLY)

    if (ctx->mem_idx == 2)

        read_cb = ctx->spr_cb[sprn].hea_read;

    else if (ctx->mem_idx)

        read_cb = ctx->spr_cb[sprn].oea_read;

    else

#endif

        read_cb = ctx->spr_cb[sprn].uea_read;

    if (likely(read_cb != NULL)) {

        if (likely(read_cb != SPR_NOACCESS)) {

            (*read_cb)(ctx, rD(ctx->opcode), sprn);

        } else {

            /* Privilege exception */

            /* This is a hack to avoid warnings when running Linux:

             * this OS breaks the PowerPC virtualisation model,

             * allowing userland application to read the PVR

             */

            if (sprn != SPR_PVR) {

                qemu_log("Trying to read privileged spr %d %03x at "

                         TARGET_FMT_lx "\n", sprn, sprn, ctx->nip);

                printf("Trying to read privileged spr %d %03x at "

                       TARGET_FMT_lx "\n", sprn, sprn, ctx->nip);

            }

            gen_inval_exception(ctx, POWERPC_EXCP_PRIV_REG);

        }

    } else {

        /* Not defined */

        qemu_log("Trying to read invalid spr %d %03x at "

                    TARGET_FMT_lx "\n", sprn, sprn, ctx->nip);

        printf("Trying to read invalid spr %d %03x at " TARGET_FMT_lx "\n",

               sprn, sprn, ctx->nip);

        gen_inval_exception(ctx, POWERPC_EXCP_INVAL_SPR);

    }

}


static int mov_create_chapter_track(AVFormatContext *s, int tracknum)

{

    MOVMuxContext *mov = s->priv_data;

    MOVTrack *track = &mov->tracks[tracknum];

    AVPacket pkt = { .stream_index = tracknum, .flags = AV_PKT_FLAG_KEY };

    int i, len;

    // These properties are required to make QT recognize the chapter track

    uint8_t chapter_properties[43] = { 0, 0, 0, 0, 0, 0, 0, 1, };

    track->mode = mov->mode;

    track->tag = MKTAG('t','e','x','t');

    track->timescale = MOV_TIMESCALE;

    track->enc = avcodec_alloc_context3(NULL);

    if (!track->enc)

    track->enc->codec_type = AVMEDIA_TYPE_SUBTITLE;

    track->enc->extradata = av_malloc(sizeof(chapter_properties));

    if (track->enc->extradata == NULL)

    track->enc->extradata_size = sizeof(chapter_properties);

    memcpy(track->enc->extradata, chapter_properties, sizeof(chapter_properties));

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

        AVChapter *c = s->chapters[i];

        AVDictionaryEntry *t;

        int64_t end = av_rescale_q(c->end, c->time_base, (AVRational){1,MOV_TIMESCALE});

        pkt.pts = pkt.dts = av_rescale_q(c->start, c->time_base, (AVRational){1,MOV_TIMESCALE});

        pkt.duration = end - pkt.dts;

        if ((t = av_dict_get(c->metadata, "title", NULL, 0))) {

            len      = strlen(t->value);

            pkt.size = len + 2;

            pkt.data = av_malloc(pkt.size);

            AV_WB16(pkt.data, len);

            memcpy(pkt.data + 2, t->value, len);

            ff_mov_write_packet(s, &pkt);

            av_freep(&pkt.data);

        }

    }

    return 0;

}


static void xhci_check_iso_kick(XHCIState *xhci, XHCITransfer *xfer,

                                XHCIEPContext *epctx, uint64_t mfindex)

{

    if (xfer->mfindex_kick > mfindex) {

        timer_mod(epctx->kick_timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) +

                       (xfer->mfindex_kick - mfindex) * 125000);

        xfer->running_retry = 1;

    } else {

        epctx->mfindex_last = xfer->mfindex_kick;

        timer_del(epctx->kick_timer);

        xfer->running_retry = 0;

    }

}


static void watch_mem_write(void *opaque, hwaddr addr,

                            uint64_t val, unsigned size)

{

    check_watchpoint(addr & ~TARGET_PAGE_MASK, size, BP_MEM_WRITE);

    switch (size) {

    case 1:

        stb_phys(&address_space_memory, addr, val);

        break;

    case 2:

        stw_phys(&address_space_memory, addr, val);

        break;

    case 4:

        stl_phys(&address_space_memory, addr, val);

        break;

    default: abort();

    }

}


static void compute_rematrixing_strategy(AC3EncodeContext *s)

{

    int nb_coefs;

    int blk, bnd, i;

    AC3Block *block, *av_uninit(block0);

    if (s->channel_mode != AC3_CHMODE_STEREO)

        return;

    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++) {

        block = &s->blocks[blk];

        block->new_rematrixing_strategy = !blk;

        if (!s->rematrixing_enabled) {

            block0 = block;

            continue;

        }

        block->num_rematrixing_bands = 4;

        if (block->cpl_in_use) {

            block->num_rematrixing_bands -= (s->start_freq[CPL_CH] <= 61);

            block->num_rematrixing_bands -= (s->start_freq[CPL_CH] == 37);

            if (blk && block->num_rematrixing_bands != block0->num_rematrixing_bands)

                block->new_rematrixing_strategy = 1;

        }

        nb_coefs = FFMIN(block->end_freq[1], block->end_freq[2]);

        for (bnd = 0; bnd < block->num_rematrixing_bands; bnd++) {

            /* calculate calculate sum of squared coeffs for one band in one block */

            int start = ff_ac3_rematrix_band_tab[bnd];

            int end   = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);

            CoefSumType sum[4] = {0,};

            for (i = start; i < end; i++) {

                CoefType lt = block->mdct_coef[1][i];

                CoefType rt = block->mdct_coef[2][i];

                CoefType md = lt + rt;

                CoefType sd = lt - rt;

                MAC_COEF(sum[0], lt, lt);

                MAC_COEF(sum[1], rt, rt);

                MAC_COEF(sum[2], md, md);

                MAC_COEF(sum[3], sd, sd);

            }

            /* compare sums to determine if rematrixing will be used for this band */

            if (FFMIN(sum[2], sum[3]) < FFMIN(sum[0], sum[1]))

                block->rematrixing_flags[bnd] = 1;

            else

                block->rematrixing_flags[bnd] = 0;

            /* determine if new rematrixing flags will be sent */

            if (blk &&

                block->rematrixing_flags[bnd] != block0->rematrixing_flags[bnd]) {

                block->new_rematrixing_strategy = 1;

            }

        }

        block0 = block;

    }

}


long vnc_client_read_ws(VncState *vs)

{

    int ret, err;

    uint8_t *payload;

    size_t payload_size, frame_size;

    VNC_DEBUG("Read websocket %p size %zd offset %zd\n", vs->ws_input.buffer,

            vs->ws_input.capacity, vs->ws_input.offset);

    buffer_reserve(&vs->ws_input, 4096);

    ret = vnc_client_read_buf(vs, buffer_end(&vs->ws_input), 4096);

    if (!ret) {

        return 0;

    }

    vs->ws_input.offset += ret;

    /* make sure that nothing is left in the ws_input buffer */

    do {

        err = vncws_decode_frame(&vs->ws_input, &payload,

                              &payload_size, &frame_size);

        if (err <= 0) {

            return err;

        }

        buffer_reserve(&vs->input, payload_size);

        buffer_append(&vs->input, payload, payload_size);

        buffer_advance(&vs->ws_input, frame_size);

    } while (vs->ws_input.offset > 0);

    return ret;

}


int ff_msmpeg4_pred_dc(MpegEncContext *s, int n,

                       int16_t **dc_val_ptr, int *dir_ptr)

{

    int a, b, c, wrap, pred, scale;

    int16_t *dc_val;

    /* find prediction */

    if (n < 4) {

        scale = s->y_dc_scale;

    } else {

        scale = s->c_dc_scale;

    }

    wrap = s->block_wrap[n];

    dc_val= s->dc_val[0] + s->block_index[n];

    /* B C

     * A X

     */

    a = dc_val[ - 1];

    b = dc_val[ - 1 - wrap];

    c = dc_val[ - wrap];

    if(s->first_slice_line && (n&2)==0 && s->msmpeg4_version<4){

        b=c=1024;

    }

    /* XXX: the following solution consumes divisions, but it does not

       necessitate to modify mpegvideo.c. The problem comes from the

       fact they decided to store the quantized DC (which would lead

       to problems if Q could vary !) */

#if ARCH_X86 && HAVE_7REGS && HAVE_EBX_AVAILABLE

    __asm__ volatile(

        "movl %3, %%eax         \n\t"

        "shrl $1, %%eax         \n\t"

        "addl %%eax, %2         \n\t"

        "addl %%eax, %1         \n\t"

        "addl %0, %%eax         \n\t"

        "mull %4                \n\t"

        "movl %%edx, %0         \n\t"

        "movl %1, %%eax         \n\t"

        "mull %4                \n\t"

        "movl %%edx, %1         \n\t"

        "movl %2, %%eax         \n\t"

        "mull %4                \n\t"

        "movl %%edx, %2         \n\t"

        : "+b" (a), "+c" (b), "+D" (c)

        : "g" (scale), "S" (ff_inverse[scale])

        : "%eax", "%edx"

    );

#else

    /* Divisions are costly everywhere; optimize the most common case. */

    if (scale == 8) {

        a = (a + (8 >> 1)) / 8;

        b = (b + (8 >> 1)) / 8;

        c = (c + (8 >> 1)) / 8;

    } else {

        a = FASTDIV((a + (scale >> 1)), scale);

        b = FASTDIV((b + (scale >> 1)), scale);

        c = FASTDIV((c + (scale >> 1)), scale);

    }

#endif

    /* XXX: WARNING: they did not choose the same test as MPEG4. This

       is very important ! */

    if(s->msmpeg4_version>3){

        if(s->inter_intra_pred){

            uint8_t *dest;

            int wrap;

            if(n==1){

                pred=a;

                *dir_ptr = 0;

            }else if(n==2){

                pred=c;

                *dir_ptr = 1;

            }else if(n==3){

                if (abs(a - b) < abs(b - c)) {

                    pred = c;

                    *dir_ptr = 1;

                } else {

                    pred = a;

                    *dir_ptr = 0;

                }

            }else{

                if(n<4){

                    wrap= s->linesize;

                    dest= s->current_picture.f.data[0] + (((n >> 1) + 2*s->mb_y) * 8*  wrap ) + ((n & 1) + 2*s->mb_x) * 8;

                }else{

                    wrap= s->uvlinesize;

                    dest= s->current_picture.f.data[n - 3] + (s->mb_y * 8 * wrap) + s->mb_x * 8;

                }

                if(s->mb_x==0) a= (1024 + (scale>>1))/scale;

                else           a= get_dc(dest-8, wrap, scale*8);

                if(s->mb_y==0) c= (1024 + (scale>>1))/scale;

                else           c= get_dc(dest-8*wrap, wrap, scale*8);

                if (s->h263_aic_dir==0) {

                    pred= a;

                    *dir_ptr = 0;

                }else if (s->h263_aic_dir==1) {

                    if(n==0){

                        pred= c;

                        *dir_ptr = 1;

                    }else{

                        pred= a;

                        *dir_ptr = 0;

                    }

                }else if (s->h263_aic_dir==2) {

                    if(n==0){

                        pred= a;

                        *dir_ptr = 0;

                    }else{

                        pred= c;

                        *dir_ptr = 1;

                    }

                } else {

                    pred= c;

                    *dir_ptr = 1;

                }

            }

        }else{

            if (abs(a - b) < abs(b - c)) {

                pred = c;

                *dir_ptr = 1;

            } else {

                pred = a;

                *dir_ptr = 0;

            }

        }

    }else{

        if (abs(a - b) <= abs(b - c)) {

            pred = c;

            *dir_ptr = 1;

        } else {

            pred = a;

            *dir_ptr = 0;

        }

    }

    /* update predictor */

    *dc_val_ptr = &dc_val[0];

    return pred;

}


int url_open(URLContext **puc, const char *filename, int flags)

{

    URLProtocol *up;

    const char *p;

    char proto_str[128], *q;

    p = filename;

    q = proto_str;

    while (*p != '\0' && *p != ':') {

        /* protocols can only contain alphabetic chars */

        if (!isalpha(*p))

            goto file_proto;

        if ((q - proto_str) < sizeof(proto_str) - 1)

            *q++ = *p;

        p++;

    }

    /* if the protocol has length 1, we consider it is a dos drive */

    if (*p == '\0' || (q - proto_str) <= 1) {

    file_proto:

        strcpy(proto_str, "file");

    } else {

        *q = '\0';

    }

    up = first_protocol;

    while (up != NULL) {

        if (!strcmp(proto_str, up->name))

            return url_open_protocol (puc, up, filename, flags);

        up = up->next;

    }

    *puc = NULL;

    return AVERROR(ENOENT);

}


static void gen_mfsrin_64b(DisasContext *ctx)

{

#if defined(CONFIG_USER_ONLY)

    gen_inval_exception(ctx, POWERPC_EXCP_PRIV_REG);

#else

    TCGv t0;

    if (unlikely(ctx->pr)) {

        gen_inval_exception(ctx, POWERPC_EXCP_PRIV_REG);

        return;

    }

    t0 = tcg_temp_new();

    tcg_gen_shri_tl(t0, cpu_gpr[rB(ctx->opcode)], 28);

    tcg_gen_andi_tl(t0, t0, 0xF);

    gen_helper_load_sr(cpu_gpr[rD(ctx->opcode)], cpu_env, t0);

    tcg_temp_free(t0);

#endif

}


struct SwsContext *sws_getContext(int srcW, int srcH, int srcFormat,

                                  int dstW, int dstH, int dstFormat,

                                  int flags, SwsFilter *srcFilter,

                                  SwsFilter *dstFilter, double *param)

{

    struct SwsContext *ctx;

    ctx = av_malloc(sizeof(struct SwsContext));

    if (ctx)

        ctx->av_class = av_mallocz(sizeof(AVClass));

    if (!ctx || !ctx->av_class) {

        av_log(NULL, AV_LOG_ERROR, "Cannot allocate a resampling context!\n");

        return NULL;

    }

    if ((srcH != dstH) || (srcW != dstW)) {

        if ((srcFormat != PIX_FMT_YUV420P) || (dstFormat != PIX_FMT_YUV420P)) {

            av_log(NULL, AV_LOG_INFO, "PIX_FMT_YUV420P will be used as an intermediate format for rescaling\n");

        }

        ctx->resampling_ctx = img_resample_init(dstW, dstH, srcW, srcH);

    } else {

        ctx->resampling_ctx = av_malloc(sizeof(ImgReSampleContext));

        ctx->resampling_ctx->iheight = srcH;

        ctx->resampling_ctx->iwidth = srcW;

        ctx->resampling_ctx->oheight = dstH;

        ctx->resampling_ctx->owidth = dstW;

    }

    ctx->src_pix_fmt = srcFormat;

    ctx->dst_pix_fmt = dstFormat;

    return ctx;

}


static int vp8_encode(AVCodecContext *avctx, AVPacket *pkt,

                      const AVFrame *frame, int *got_packet)

{

    VP8Context *ctx = avctx->priv_data;

    struct vpx_image *rawimg = NULL;

    struct vpx_image *rawimg_alpha = NULL;

    int64_t timestamp = 0;

    int res, coded_size;

    vpx_enc_frame_flags_t flags = 0;

    if (frame) {

        rawimg                      = &ctx->rawimg;

        rawimg->planes[VPX_PLANE_Y] = frame->data[0];

        rawimg->planes[VPX_PLANE_U] = frame->data[1];

        rawimg->planes[VPX_PLANE_V] = frame->data[2];

        rawimg->stride[VPX_PLANE_Y] = frame->linesize[0];

        rawimg->stride[VPX_PLANE_U] = frame->linesize[1];

        rawimg->stride[VPX_PLANE_V] = frame->linesize[2];

        if (ctx->is_alpha) {

            uint8_t *u_plane, *v_plane;

            rawimg_alpha = &ctx->rawimg_alpha;

            rawimg_alpha->planes[VPX_PLANE_Y] = frame->data[3];

            u_plane = av_malloc(frame->linesize[1] * frame->height);

            memset(u_plane, 0x80, frame->linesize[1] * frame->height);

            rawimg_alpha->planes[VPX_PLANE_U] = u_plane;

            v_plane = av_malloc(frame->linesize[2] * frame->height);

            memset(v_plane, 0x80, frame->linesize[2] * frame->height);

            rawimg_alpha->planes[VPX_PLANE_V] = v_plane;

            rawimg_alpha->stride[VPX_PLANE_Y] = frame->linesize[0];

            rawimg_alpha->stride[VPX_PLANE_U] = frame->linesize[1];

            rawimg_alpha->stride[VPX_PLANE_V] = frame->linesize[2];

        }

        timestamp                   = frame->pts;

        if (frame->pict_type == AV_PICTURE_TYPE_I)

            flags |= VPX_EFLAG_FORCE_KF;

    }

    res = vpx_codec_encode(&ctx->encoder, rawimg, timestamp,

                           avctx->ticks_per_frame, flags, ctx->deadline);

    if (res != VPX_CODEC_OK) {

        log_encoder_error(avctx, "Error encoding frame");

        return AVERROR_INVALIDDATA;

    }

    if (ctx->is_alpha) {

        res = vpx_codec_encode(&ctx->encoder_alpha, rawimg_alpha, timestamp,

                               avctx->ticks_per_frame, flags, ctx->deadline);

        if (res != VPX_CODEC_OK) {

            log_encoder_error(avctx, "Error encoding alpha frame");

            return AVERROR_INVALIDDATA;

        }

    }

    coded_size = queue_frames(avctx, pkt, avctx->coded_frame);

    if (!frame && avctx->flags & CODEC_FLAG_PASS1) {

        unsigned int b64_size = AV_BASE64_SIZE(ctx->twopass_stats.sz);

        avctx->stats_out = av_malloc(b64_size);

        if (!avctx->stats_out) {

            av_log(avctx, AV_LOG_ERROR, "Stat buffer alloc (%d bytes) failed\n",

                   b64_size);

            return AVERROR(ENOMEM);

        }

        av_base64_encode(avctx->stats_out, b64_size, ctx->twopass_stats.buf,

                         ctx->twopass_stats.sz);

    }

    if (rawimg_alpha) {

        av_freep(&rawimg_alpha->planes[VPX_PLANE_U]);

        av_freep(&rawimg_alpha->planes[VPX_PLANE_V]);

    }

    *got_packet = !!coded_size;

    return 0;

}


void av_opt_freep_ranges(AVOptionRanges **rangesp)

{

    int i;

    AVOptionRanges *ranges = *rangesp;

    if (!ranges)

        return;

    for (i = 0; i < ranges->nb_ranges * ranges->nb_components; i++) {

        AVOptionRange *range = ranges->range[i];

        av_freep(&range->str);

        av_freep(&ranges->range[i]);

    }

    av_freep(&ranges->range);

    av_freep(rangesp);

}


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

                                  const AVFrame *frame, int *got_packet_ptr)

{

    OggVorbisEncContext *s = avctx->priv_data;

    ogg_packet op;

    int ret, duration;

    /* send samples to libvorbis */

    if (frame) {

        const int samples = frame->nb_samples;

        float **buffer;

        int c, channels = s->vi.channels;

        buffer = vorbis_analysis_buffer(&s->vd, samples);

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

            int co = (channels > 8) ? c :

                     ff_vorbis_encoding_channel_layout_offsets[channels - 1][c];

            memcpy(buffer[c], frame->extended_data[co],

                   samples * sizeof(*buffer[c]));

        }

        if ((ret = vorbis_analysis_wrote(&s->vd, samples)) < 0) {

            av_log(avctx, AV_LOG_ERROR, "error in vorbis_analysis_wrote()\n");

            return vorbis_error_to_averror(ret);

        }

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

            return ret;

    } else {

        if (!s->eof)

            if ((ret = vorbis_analysis_wrote(&s->vd, 0)) < 0) {

                av_log(avctx, AV_LOG_ERROR, "error in vorbis_analysis_wrote()\n");

                return vorbis_error_to_averror(ret);

            }

        s->eof = 1;

    }

    /* retrieve available packets from libvorbis */

    while ((ret = vorbis_analysis_blockout(&s->vd, &s->vb)) == 1) {

        if ((ret = vorbis_analysis(&s->vb, NULL)) < 0)

            break;

        if ((ret = vorbis_bitrate_addblock(&s->vb)) < 0)

            break;

        /* add any available packets to the output packet buffer */

        while ((ret = vorbis_bitrate_flushpacket(&s->vd, &op)) == 1) {

            if (av_fifo_space(s->pkt_fifo) < sizeof(ogg_packet) + op.bytes) {

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

                return AVERROR_BUG;

            }

            av_fifo_generic_write(s->pkt_fifo, &op, sizeof(ogg_packet), NULL);

            av_fifo_generic_write(s->pkt_fifo, op.packet, op.bytes, NULL);

        }

        if (ret < 0) {

            av_log(avctx, AV_LOG_ERROR, "error getting available packets\n");

            break;

        }

    }

    if (ret < 0) {

        av_log(avctx, AV_LOG_ERROR, "error getting available packets\n");

        return vorbis_error_to_averror(ret);

    }

    /* check for available packets */

    if (av_fifo_size(s->pkt_fifo) < sizeof(ogg_packet))

        return 0;

    av_fifo_generic_read(s->pkt_fifo, &op, sizeof(ogg_packet), NULL);

    if ((ret = ff_alloc_packet2(avctx, avpkt, op.bytes)))

        return ret;

    av_fifo_generic_read(s->pkt_fifo, avpkt->data, op.bytes, NULL);

    avpkt->pts = ff_samples_to_time_base(avctx, op.granulepos);

    duration = avpriv_vorbis_parse_frame(&s->vp, avpkt->data, avpkt->size);

    if (duration > 0) {

        /* we do not know encoder delay until we get the first packet from

         * libvorbis, so we have to update the AudioFrameQueue counts */

        if (!avctx->delay && s->afq.frames) {

            avctx->delay              = duration;

            av_assert0(!s->afq.remaining_delay);

            s->afq.frames->duration  += duration;

            s->afq.frames->pts       -= duration;

            s->afq.remaining_samples += duration;

        }

        ff_af_queue_remove(&s->afq, duration, &avpkt->pts, &avpkt->duration);

    }

    *got_packet_ptr = 1;

    return 0;

}


static void scsi_req_dequeue(SCSIRequest *req)

{

    trace_scsi_req_dequeue(req->dev->id, req->lun, req->tag);

    if (req->enqueued) {

        QTAILQ_REMOVE(&req->dev->requests, req, next);

        req->enqueued = false;

    }

}


void check_aligned_anonymous_unfixed_colliding_mmaps(void)

{

	char *p1;

	char *p2;

	char *p3;

	uintptr_t p;

	int i;

	fprintf (stderr, "%s", __func__);

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

	{

		int nlen;

		p1 = mmap(NULL, pagesize, PROT_READ,

			  MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);

		fail_unless (p1 != MAP_FAILED);

		p = (uintptr_t) p1;

		fail_unless ((p & pagemask) == 0);

		memcpy (dummybuf, p1, pagesize);

		p2 = mmap(NULL, pagesize, PROT_READ,

			  MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);

		fail_unless (p2 != MAP_FAILED);

		p = (uintptr_t) p2;

		fail_unless ((p & pagemask) == 0);

		memcpy (dummybuf, p2, pagesize);

		munmap (p1, pagesize);

		nlen = pagesize * 8;

		p3 = mmap(NULL, nlen, PROT_READ,

			  MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);

		/* Check if the mmaped areas collide.  */

		if (p3 < p2

		    && (p3 + nlen) > p2)

			fail_unless (0);

		memcpy (dummybuf, p3, pagesize);

		/* Make sure we get pages aligned with the pagesize. The

		   target expects this.  */

		fail_unless (p3 != MAP_FAILED);

		p = (uintptr_t) p3;

		fail_unless ((p & pagemask) == 0);

		munmap (p2, pagesize);

		munmap (p3, nlen);

	}

	fprintf (stderr, " passed\n");

}


void ff_er_add_slice(ERContext *s, int startx, int starty,

                     int endx, int endy, int status)

{

    const int start_i  = av_clip(startx + starty * s->mb_width, 0, s->mb_num - 1);

    const int end_i    = av_clip(endx   + endy   * s->mb_width, 0, s->mb_num);

    const int start_xy = s->mb_index2xy[start_i];

    const int end_xy   = s->mb_index2xy[end_i];

    int mask           = -1;

    if (s->avctx->hwaccel)

        return;

    if (start_i > end_i || start_xy > end_xy) {

        av_log(s->avctx, AV_LOG_ERROR,

               "internal error, slice end before start\n");

        return;

    }

    if (!s->avctx->err_recognition)

        return;

    mask &= ~VP_START;

    if (status & (ER_AC_ERROR | ER_AC_END)) {

        mask           &= ~(ER_AC_ERROR | ER_AC_END);

        s->error_count -= end_i - start_i + 1;

    }

    if (status & (ER_DC_ERROR | ER_DC_END)) {

        mask           &= ~(ER_DC_ERROR | ER_DC_END);

        s->error_count -= end_i - start_i + 1;

    }

    if (status & (ER_MV_ERROR | ER_MV_END)) {

        mask           &= ~(ER_MV_ERROR | ER_MV_END);

        s->error_count -= end_i - start_i + 1;

    }

    if (status & ER_MB_ERROR) {

        s->error_occurred = 1;

        s->error_count    = INT_MAX;

    }

    if (mask == ~0x7F) {

        memset(&s->error_status_table[start_xy], 0,

               (end_xy - start_xy) * sizeof(uint8_t));

    } else {

        int i;

        for (i = start_xy; i < end_xy; i++)

            s->error_status_table[i] &= mask;

    }

    if (end_i == s->mb_num)

        s->error_count = INT_MAX;

    else {

        s->error_status_table[end_xy] &= mask;

        s->error_status_table[end_xy] |= status;

    }

    s->error_status_table[start_xy] |= VP_START;

    if (start_xy > 0 && !(s->avctx->active_thread_type & FF_THREAD_SLICE) &&

        s->avctx->skip_top * s->mb_width < start_i) {

        int prev_status = s->error_status_table[s->mb_index2xy[start_i - 1]];

        prev_status &= ~ VP_START;

        if (prev_status != (ER_MV_END | ER_DC_END | ER_AC_END)) {

            s->error_occurred = 1;

            s->error_count = INT_MAX;

        }

    }

}


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

                                   int32_t src_stride, uint8_t *dst,

                                   int32_t dst_stride, int32_t height)

{

    uint32_t loop_cnt;

    v16i8 src_hz0, src_hz1, src_hz2, src_hz3;

    v16i8 src_vt0, src_vt1, src_vt2, src_vt3, src_vt4;

    v16i8 src_vt5, src_vt6, src_vt7, src_vt8;

    v16i8 mask0, mask1, mask2;

    v8i16 hz_out0, hz_out1, vert_out0, vert_out1;

    v8i16 out0, out1;

    v16u8 out;

    LD_SB3(&luma_mask_arr[48], 16, mask0, mask1, mask2);

    LD_SB5(src_y, src_stride, src_vt0, src_vt1, src_vt2, src_vt3, src_vt4);

    src_y += (5 * src_stride);

    src_vt0 = (v16i8) __msa_insve_w((v4i32) src_vt0, 1, (v4i32) src_vt1);

    src_vt1 = (v16i8) __msa_insve_w((v4i32) src_vt1, 1, (v4i32) src_vt2);

    src_vt2 = (v16i8) __msa_insve_w((v4i32) src_vt2, 1, (v4i32) src_vt3);

    src_vt3 = (v16i8) __msa_insve_w((v4i32) src_vt3, 1, (v4i32) src_vt4);

    XORI_B4_128_SB(src_vt0, src_vt1, src_vt2, src_vt3);

    for (loop_cnt = (height >> 2); loop_cnt--;) {

        LD_SB4(src_x, src_stride, src_hz0, src_hz1, src_hz2, src_hz3);

        src_x += (4 * src_stride);

        XORI_B4_128_SB(src_hz0, src_hz1, src_hz2, src_hz3);

        hz_out0 = AVC_XOR_VSHF_B_AND_APPLY_6TAP_HORIZ_FILT_SH(src_hz0,

                                                              src_hz1, mask0,

                                                              mask1, mask2);

        hz_out1 = AVC_XOR_VSHF_B_AND_APPLY_6TAP_HORIZ_FILT_SH(src_hz2,

                                                              src_hz3, mask0,

                                                              mask1, mask2);

        SRARI_H2_SH(hz_out0, hz_out1, 5);

        SAT_SH2_SH(hz_out0, hz_out1, 7);

        LD_SB4(src_y, src_stride, src_vt5, src_vt6, src_vt7, src_vt8);

        src_y += (4 * src_stride);

        src_vt4 = (v16i8) __msa_insve_w((v4i32) src_vt4, 1, (v4i32) src_vt5);

        src_vt5 = (v16i8) __msa_insve_w((v4i32) src_vt5, 1, (v4i32) src_vt6);

        src_vt6 = (v16i8) __msa_insve_w((v4i32) src_vt6, 1, (v4i32) src_vt7);

        src_vt7 = (v16i8) __msa_insve_w((v4i32) src_vt7, 1, (v4i32) src_vt8);

        XORI_B4_128_SB(src_vt4, src_vt5, src_vt6, src_vt7);

        /* filter calc */

        vert_out0 = AVC_CALC_DPADD_B_6PIX_2COEFF_R_SH(src_vt0, src_vt1,

                                                      src_vt2, src_vt3,

                                                      src_vt4, src_vt5);

        vert_out1 = AVC_CALC_DPADD_B_6PIX_2COEFF_R_SH(src_vt2, src_vt3,

                                                      src_vt4, src_vt5,

                                                      src_vt6, src_vt7);

        SRARI_H2_SH(vert_out0, vert_out1, 5);

        SAT_SH2_SH(vert_out0, vert_out1, 7);

        out0 = __msa_srari_h((hz_out0 + vert_out0), 1);

        out1 = __msa_srari_h((hz_out1 + vert_out1), 1);

        SAT_SH2_SH(out0, out1, 7);

        out = PCKEV_XORI128_UB(out0, out1);

        ST4x4_UB(out, out, 0, 1, 2, 3, dst, dst_stride);

        dst += (4 * dst_stride);

        src_vt3 = src_vt7;

        src_vt1 = src_vt5;

        src_vt0 = src_vt4;

        src_vt4 = src_vt8;

        src_vt2 = src_vt6;

    }

}


void qmp_migrate_set_downtime(double value, Error **errp)

{

    value *= 1e9;

    value = MAX(0, MIN(UINT64_MAX, value));

    max_downtime = (uint64_t)value;

}


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

                         void *opaque, Error **errp)

{

    sPAPRDRConnector *drc = SPAPR_DR_CONNECTOR(obj);

    Error *err = NULL;

    int fdt_offset_next, fdt_offset, fdt_depth;

    void *fdt;

    if (!drc->fdt) {

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

        if (!err) {

            visit_end_struct(v, &err);

        }

        error_propagate(errp, err);

        return;

    }

    fdt = drc->fdt;

    fdt_offset = drc->fdt_start_offset;

    fdt_depth = 0;

    do {

        const char *name = NULL;

        const struct fdt_property *prop = NULL;

        int prop_len = 0, name_len = 0;

        uint32_t tag;

        tag = fdt_next_tag(fdt, fdt_offset, &fdt_offset_next);

        switch (tag) {

        case FDT_BEGIN_NODE:

            fdt_depth++;

            name = fdt_get_name(fdt, fdt_offset, &name_len);

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

            if (err) {

                error_propagate(errp, err);

                return;

            }

            break;

        case FDT_END_NODE:

            /* shouldn't ever see an FDT_END_NODE before FDT_BEGIN_NODE */

            g_assert(fdt_depth > 0);

            visit_end_struct(v, &err);

            if (err) {

                error_propagate(errp, err);

                return;

            }

            fdt_depth--;

            break;

        case FDT_PROP: {

            int i;

            prop = fdt_get_property_by_offset(fdt, fdt_offset, &prop_len);

            name = fdt_string(fdt, fdt32_to_cpu(prop->nameoff));

            visit_start_list(v, name, &err);

            if (err) {

                error_propagate(errp, err);

                return;

            }

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

                visit_type_uint8(v, NULL, (uint8_t *)&prop->data[i], &err);

                if (err) {

                    error_propagate(errp, err);

                    return;

                }

            }

            visit_end_list(v);

            break;

        }

        default:

            error_setg(&error_abort, "device FDT in unexpected state: %d", tag);

        }

        fdt_offset = fdt_offset_next;

    } while (fdt_depth != 0);

}


static void qtrle_decode_24bpp(QtrleContext *s)

{

    int stream_ptr;

    int header;

    int start_line;

    int lines_to_change;

    signed char rle_code;

    int row_ptr, pixel_ptr;

    int row_inc = s->frame.linesize[0];

    unsigned char r, g, b;

    unsigned char *rgb = s->frame.data[0];

    int pixel_limit = s->frame.linesize[0] * s->avctx->height;

    /* check if this frame is even supposed to change */

    if (s->size < 8)

        return;

    /* start after the chunk size */

    stream_ptr = 4;

    /* fetch the header */

    CHECK_STREAM_PTR(2);

    header = BE_16(&s->buf[stream_ptr]);

    stream_ptr += 2;

    /* if a header is present, fetch additional decoding parameters */

    if (header & 0x0008) {

        CHECK_STREAM_PTR(8);

        start_line = BE_16(&s->buf[stream_ptr]);

        stream_ptr += 4;

        lines_to_change = BE_16(&s->buf[stream_ptr]);

        stream_ptr += 4;

    } else {

        start_line = 0;

        lines_to_change = s->avctx->height;

    }

    row_ptr = row_inc * start_line;

    while (lines_to_change--) {

        CHECK_STREAM_PTR(2);

        pixel_ptr = row_ptr + (s->buf[stream_ptr++] - 1) * 3;

        while ((rle_code = (signed char)s->buf[stream_ptr++]) != -1) {

            if (rle_code == 0) {

                /* there's another skip code in the stream */

                CHECK_STREAM_PTR(1);

                pixel_ptr += (s->buf[stream_ptr++] - 1) * 3;

                CHECK_PIXEL_PTR(0);  /* make sure pixel_ptr is positive */

            } else if (rle_code < 0) {

                /* decode the run length code */

                rle_code = -rle_code;

                CHECK_STREAM_PTR(3);

                r = s->buf[stream_ptr++];

                g = s->buf[stream_ptr++];

                b = s->buf[stream_ptr++];

                CHECK_PIXEL_PTR(rle_code * 3);

                while (rle_code--) {

                    rgb[pixel_ptr++] = r;

                    rgb[pixel_ptr++] = g;

                    rgb[pixel_ptr++] = b;

                }

            } else {

                CHECK_STREAM_PTR(rle_code * 3);

                CHECK_PIXEL_PTR(rle_code * 3);

                /* copy pixels directly to output */

                while (rle_code--) {

                    rgb[pixel_ptr++] = s->buf[stream_ptr++];

                    rgb[pixel_ptr++] = s->buf[stream_ptr++];

                    rgb[pixel_ptr++] = s->buf[stream_ptr++];

                }

            }

        }

        row_ptr += row_inc;

    }

}


static void rtcp_send_sr(AVFormatContext *s1, int64_t ntp_time)

{

    RTPDemuxContext *s = s1->priv_data;

    uint32_t rtp_ts;

#if defined(DEBUG)

    printf("RTCP: %02x %"PRIx64" %x\n", s->payload_type, ntp_time, s->timestamp);

#endif

    if (s->first_rtcp_ntp_time == AV_NOPTS_VALUE) s->first_rtcp_ntp_time = ntp_time;

    s->last_rtcp_ntp_time = ntp_time;

    rtp_ts = av_rescale_q(ntp_time - s->first_rtcp_ntp_time, AV_TIME_BASE_Q,

                          s1->streams[0]->time_base) + s->base_timestamp;

    put_byte(s1->pb, (RTP_VERSION << 6));

    put_byte(s1->pb, 200);

    put_be16(s1->pb, 6); /* length in words - 1 */

    put_be32(s1->pb, s->ssrc);

    put_be32(s1->pb, ntp_time / 1000000);

    put_be32(s1->pb, ((ntp_time % 1000000) << 32) / 1000000);

    put_be32(s1->pb, rtp_ts);

    put_be32(s1->pb, s->packet_count);

    put_be32(s1->pb, s->octet_count);

    put_flush_packet(s1->pb);

}


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

                                  void *opaque, Error **errp)

{

    Error *err = NULL;

    VirtIOBalloon *s = opaque;

    int i;

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

    if (err) {

        goto out;

    }

    visit_type_int(v, "last-update", &s->stats_last_update, &err);

    if (err) {

        goto out_end;

    }

    visit_start_struct(v, "stats", NULL, 0, &err);

    if (err) {

        goto out_end;

    }

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

        visit_type_uint64(v, balloon_stat_names[i], &s->stats[i], &err);

        if (err) {

            break;

        }

    }

    error_propagate(errp, err);

    err = NULL;

    visit_end_struct(v, &err);

out_end:

    error_propagate(errp, err);

    err = NULL;

    visit_end_struct(v, &err);

out:

    error_propagate(errp, err);

}


envlist_setenv(envlist_t *envlist, const char *env)

{

	struct envlist_entry *entry = NULL;

	const char *eq_sign;

	size_t envname_len;

	if ((envlist == NULL) || (env == NULL))

		return (EINVAL);

	/* find out first equals sign in given env */

	if ((eq_sign = strchr(env, '=')) == NULL)

		return (EINVAL);

	envname_len = eq_sign - env + 1;

	/*

	 * If there already exists variable with given name

	 * we remove and release it before allocating a whole

	 * new entry.

	 */

	for (entry = envlist->el_entries.lh_first; entry != NULL;

	    entry = entry->ev_link.le_next) {

		if (strncmp(entry->ev_var, env, envname_len) == 0)

			break;

	}

	if (entry != NULL) {

		QLIST_REMOVE(entry, ev_link);

		free((char *)entry->ev_var);

		free(entry);

	} else {

		envlist->el_count++;

	}

	if ((entry = malloc(sizeof (*entry))) == NULL)

		return (errno);

	if ((entry->ev_var = strdup(env)) == NULL) {

		free(entry);

		return (errno);

	}

	QLIST_INSERT_HEAD(&envlist->el_entries, entry, ev_link);

	return (0);

}


static inline int check_ap(CPUARMState *env, int ap, int domain_prot,

                           int access_type, int is_user)

{

  int prot_ro;

  if (domain_prot == 3) {

    return PAGE_READ | PAGE_WRITE;

  }

  if (access_type == 1)

      prot_ro = 0;

  else

      prot_ro = PAGE_READ;

  switch (ap) {

  case 0:

      if (access_type == 1)

          return 0;

      switch ((env->cp15.c1_sys >> 8) & 3) {

      case 1:

          return is_user ? 0 : PAGE_READ;

      case 2:

          return PAGE_READ;

      default:

          return 0;

      }

  case 1:

      return is_user ? 0 : PAGE_READ | PAGE_WRITE;

  case 2:

      if (is_user)

          return prot_ro;

      else

          return PAGE_READ | PAGE_WRITE;

  case 3:

      return PAGE_READ | PAGE_WRITE;

  case 4: /* Reserved.  */

      return 0;

  case 5:

      return is_user ? 0 : prot_ro;

  case 6:

      return prot_ro;

  case 7:

      if (!arm_feature (env, ARM_FEATURE_V6K))

          return 0;

      return prot_ro;

  default:

      abort();

  }

}


static void test_mirror(void)

{

    int send_sock[2], recv_sock;

    char *cmdline;

    uint32_t ret = 0, len = 0;

    char send_buf[] = "Hello! filter-mirror~";

    char sock_path[] = "filter-mirror.XXXXXX";

    char *recv_buf;

    uint32_t size = sizeof(send_buf);

    size = htonl(size);

    ret = socketpair(PF_UNIX, SOCK_STREAM, 0, send_sock);

    g_assert_cmpint(ret, !=, -1);

    ret = mkstemp(sock_path);

    g_assert_cmpint(ret, !=, -1);

    cmdline = g_strdup_printf("-netdev socket,id=qtest-bn0,fd=%d "

                 "-device e1000,netdev=qtest-bn0,id=qtest-e0 "

                 "-chardev socket,id=mirror0,path=%s,server,nowait "

                 "-object filter-mirror,id=qtest-f0,netdev=qtest-bn0,queue=tx,outdev=mirror0 "

                 , send_sock[1], sock_path);

    qtest_start(cmdline);

    g_free(cmdline);

    recv_sock = unix_connect(sock_path, NULL);

    g_assert_cmpint(recv_sock, !=, -1);

    struct iovec iov[] = {

        {

            .iov_base = &size,

            .iov_len = sizeof(size),

        }, {

            .iov_base = send_buf,

            .iov_len = sizeof(send_buf),

        },

    };

    /* send a qmp command to guarantee that 'connected' is setting to true. */

    qmp_discard_response("{ 'execute' : 'query-status'}");

    ret = iov_send(send_sock[0], iov, 2, 0, sizeof(size) + sizeof(send_buf));

    g_assert_cmpint(ret, ==, sizeof(send_buf) + sizeof(size));

    close(send_sock[0]);

    ret = qemu_recv(recv_sock, &len, sizeof(len), 0);

    g_assert_cmpint(ret, ==, sizeof(len));

    len = ntohl(len);

    g_assert_cmpint(len, ==, sizeof(send_buf));

    recv_buf = g_malloc(len);

    ret = qemu_recv(recv_sock, recv_buf, len, 0);

    g_assert_cmpstr(recv_buf, ==, send_buf);

    g_free(recv_buf);

    close(recv_sock);

    unlink(sock_path);

}


S390PCIBusDevice *s390_pci_find_dev_by_fh(uint32_t fh)

{

    S390PCIBusDevice *pbdev;

    int i;

    S390pciState *s = S390_PCI_HOST_BRIDGE(

        object_resolve_path(TYPE_S390_PCI_HOST_BRIDGE, NULL));

    if (!s || !fh) {

        return NULL;

    }

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

        pbdev = &s->pbdev[i];

        if (pbdev->fh == fh) {

            return pbdev;

        }

    }

    return NULL;

}


static void serial_ioport_write(void *opaque, hwaddr addr, uint64_t val,

                                unsigned size)

{

    SerialState *s = opaque;

    addr &= 7;

    DPRINTF("write addr=0x%" HWADDR_PRIx " val=0x%" PRIx64 "\n", addr, val);

    switch(addr) {

    default:

    case 0:

        if (s->lcr & UART_LCR_DLAB) {

            s->divider = (s->divider & 0xff00) | val;

            serial_update_parameters(s);

        } else {

            s->thr = (uint8_t) val;

            if(s->fcr & UART_FCR_FE) {

                /* xmit overruns overwrite data, so make space if needed */

                if (fifo8_is_full(&s->xmit_fifo)) {

                    fifo8_pop(&s->xmit_fifo);

                }

                fifo8_push(&s->xmit_fifo, s->thr);

            }

            s->thr_ipending = 0;

            s->lsr &= ~UART_LSR_THRE;

            s->lsr &= ~UART_LSR_TEMT;

            serial_update_irq(s);

            if (s->tsr_retry <= 0) {

                serial_xmit(NULL, G_IO_OUT, s);

            }

        }

        break;

    case 1:

        if (s->lcr & UART_LCR_DLAB) {

            s->divider = (s->divider & 0x00ff) | (val << 8);

            serial_update_parameters(s);

        } else {

            uint8_t changed = (s->ier ^ val) & 0x0f;

            s->ier = val & 0x0f;

            /* If the backend device is a real serial port, turn polling of the modem

             * status lines on physical port on or off depending on UART_IER_MSI state.

             */

            if ((changed & UART_IER_MSI) && s->poll_msl >= 0) {

                if (s->ier & UART_IER_MSI) {

                     s->poll_msl = 1;

                     serial_update_msl(s);

                } else {

                     timer_del(s->modem_status_poll);

                     s->poll_msl = 0;

                }

            }

            /* Turning on the THRE interrupt on IER can trigger the interrupt

             * if LSR.THRE=1, even if it had been masked before by reading IIR.

             * This is not in the datasheet, but Windows relies on it.  It is

             * unclear if THRE has to be resampled every time THRI becomes

             * 1, or only on the rising edge.  Bochs does the latter, and Windows

             * always toggles IER to all zeroes and back to all ones, so do the

             * same.

             *

             * If IER.THRI is zero, thr_ipending is not used.  Set it to zero

             * so that the thr_ipending subsection is not migrated.

             */

            if (changed & UART_IER_THRI) {

                if ((s->ier & UART_IER_THRI) && (s->lsr & UART_LSR_THRE)) {

                    s->thr_ipending = 1;

                } else {

                    s->thr_ipending = 0;

                }

            }

            if (changed) {

                serial_update_irq(s);

            }

        }

        break;

    case 2:

        /* Did the enable/disable flag change? If so, make sure FIFOs get flushed */

        if ((val ^ s->fcr) & UART_FCR_FE) {

            val |= UART_FCR_XFR | UART_FCR_RFR;

        }

        /* FIFO clear */

        if (val & UART_FCR_RFR) {

            s->lsr &= ~(UART_LSR_DR | UART_LSR_BI);

            timer_del(s->fifo_timeout_timer);

            s->timeout_ipending = 0;

            fifo8_reset(&s->recv_fifo);

        }

        if (val & UART_FCR_XFR) {

            s->lsr |= UART_LSR_THRE;

            s->thr_ipending = 1;

            fifo8_reset(&s->xmit_fifo);

        }

        serial_write_fcr(s, val & 0xC9);

        serial_update_irq(s);

        break;

    case 3:

        {

            int break_enable;

            s->lcr = val;

            serial_update_parameters(s);

            break_enable = (val >> 6) & 1;

            if (break_enable != s->last_break_enable) {

                s->last_break_enable = break_enable;

                qemu_chr_fe_ioctl(s->chr, CHR_IOCTL_SERIAL_SET_BREAK,

                               &break_enable);

            }

        }

        break;

    case 4:

        {

            int flags;

            int old_mcr = s->mcr;

            s->mcr = val & 0x1f;

            if (val & UART_MCR_LOOP)

                break;

            if (s->poll_msl >= 0 && old_mcr != s->mcr) {

                qemu_chr_fe_ioctl(s->chr,CHR_IOCTL_SERIAL_GET_TIOCM, &flags);

                flags &= ~(CHR_TIOCM_RTS | CHR_TIOCM_DTR);

                if (val & UART_MCR_RTS)

                    flags |= CHR_TIOCM_RTS;

                if (val & UART_MCR_DTR)

                    flags |= CHR_TIOCM_DTR;

                qemu_chr_fe_ioctl(s->chr,CHR_IOCTL_SERIAL_SET_TIOCM, &flags);

                /* Update the modem status after a one-character-send wait-time, since there may be a response

                   from the device/computer at the other end of the serial line */

                timer_mod(s->modem_status_poll, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + s->char_transmit_time);

            }

        }

        break;

    case 5:

        break;

    case 6:

        break;

    case 7:

        s->scr = val;

        break;

    }

}


void bdrv_drain(BlockDriverState *bs)

{

    while (bdrv_drain_one(bs)) {

        /* Keep iterating */

    }

}


static void nvdimm_dsm_set_label_data(NVDIMMDevice *nvdimm, NvdimmDsmIn *in,

                                      hwaddr dsm_mem_addr)

{

    NVDIMMClass *nvc = NVDIMM_GET_CLASS(nvdimm);

    NvdimmFuncSetLabelDataIn *set_label_data;

    uint32_t status;

    set_label_data = (NvdimmFuncSetLabelDataIn *)in->arg3;

    le32_to_cpus(&set_label_data->offset);

    le32_to_cpus(&set_label_data->length);

    nvdimm_debug("Write Label Data: offset %#x length %#x.\n",

                 set_label_data->offset, set_label_data->length);

    status = nvdimm_rw_label_data_check(nvdimm, set_label_data->offset,

                                        set_label_data->length);

    if (status != 0 /* Success */) {

        nvdimm_dsm_no_payload(status, dsm_mem_addr);

        return;

    }

    assert(offsetof(NvdimmDsmIn, arg3) +

           sizeof(*set_label_data) + set_label_data->length <= 4096);

    nvc->write_label_data(nvdimm, set_label_data->in_buf,

                          set_label_data->length, set_label_data->offset);

    nvdimm_dsm_no_payload(0 /* Success */, dsm_mem_addr);

}


static void slirp_receive(void *opaque, const uint8_t *buf, size_t size)

{

#ifdef DEBUG_SLIRP

    printf("slirp input:\n");

    hex_dump(stdout, buf, size);

#endif

    slirp_input(buf, size);

}


void op_dmfc0_ebase (void)

{

    T0 = env->CP0_EBase;

    RETURN();

}


void sparc_cpu_list(FILE *f, int (*cpu_fprintf)(FILE *f, const char *fmt, ...))

{

    unsigned int i;

    for (i = 0; i < ARRAY_SIZE(sparc_defs); i++) {

        (*cpu_fprintf)(f, "Sparc %16s IU " TARGET_FMT_lx " FPU %08x MMU %08x NWINS %d ",

                       sparc_defs[i].name,

                       sparc_defs[i].iu_version,

                       sparc_defs[i].fpu_version,

                       sparc_defs[i].mmu_version,

                       sparc_defs[i].nwindows);

        print_features(f, cpu_fprintf, CPU_DEFAULT_FEATURES &

                       ~sparc_defs[i].features, "-");

        print_features(f, cpu_fprintf, ~CPU_DEFAULT_FEATURES &

                       sparc_defs[i].features, "+");

        (*cpu_fprintf)(f, "\n");

    }

    (*cpu_fprintf)(f, "Default CPU feature flags (use '-' to remove): ");

    print_features(f, cpu_fprintf, CPU_DEFAULT_FEATURES, NULL);

    (*cpu_fprintf)(f, "\n");

    (*cpu_fprintf)(f, "Available CPU feature flags (use '+' to add): ");

    print_features(f, cpu_fprintf, ~CPU_DEFAULT_FEATURES, NULL);

    (*cpu_fprintf)(f, "\n");

    (*cpu_fprintf)(f, "Numerical features (use '=' to set): iu_version "

                   "fpu_version mmu_version nwindows\n");

}


static uint32_t dma_rinvalid (void *opaque, target_phys_addr_t addr)

{

        hw_error("Unsupported short raccess. reg=" TARGET_FMT_plx "\n", addr);

        return 0;

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    SCSIDeviceClass *sc = SCSI_DEVICE_CLASS(klass);

    sc->init         = scsi_hd_initfn;

    sc->destroy      = scsi_destroy;

    sc->alloc_req    = scsi_new_request;

    sc->unit_attention_reported = scsi_disk_unit_attention_reported;

    dc->fw_name = "disk";

    dc->desc = "virtual SCSI disk";

    dc->reset = scsi_disk_reset;

    dc->props = scsi_hd_properties;

    dc->vmsd  = &vmstate_scsi_disk_state;

}


static int qxl_init_secondary(PCIDevice *dev)

{

    static int device_id = 1;

    PCIQXLDevice *qxl = DO_UPCAST(PCIQXLDevice, pci, dev);

    ram_addr_t ram_size = msb_mask(qxl->vga.vram_size * 2 - 1);

    qxl->id = device_id++;

    if (ram_size < 16 * 1024 * 1024) {

        ram_size = 16 * 1024 * 1024;

    }

    qxl->vga.vram_size = ram_size;

    qxl->vga.vram_offset = qemu_ram_alloc(&qxl->pci.qdev, "qxl.vgavram",

                                          qxl->vga.vram_size);

    qxl->vga.vram_ptr = qemu_get_ram_ptr(qxl->vga.vram_offset);

    pci_config_set_class(dev->config, PCI_CLASS_DISPLAY_OTHER);

    return qxl_init_common(qxl);

}


static inline void downmix_2f_2r_to_dolby(float *samples)

{

    int i;

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

        samples[i] -= samples[i + 512];

        samples[i + 256] += samples[i + 768];

        samples[i + 512] = samples[i + 768] = 0;

    }

}


static void disas_simd_3same_logic(DisasContext *s, uint32_t insn)

{

    int rd = extract32(insn, 0, 5);

    int rn = extract32(insn, 5, 5);

    int rm = extract32(insn, 16, 5);

    int size = extract32(insn, 22, 2);

    bool is_u = extract32(insn, 29, 1);

    bool is_q = extract32(insn, 30, 1);

    TCGv_i64 tcg_op1 = tcg_temp_new_i64();

    TCGv_i64 tcg_op2 = tcg_temp_new_i64();

    TCGv_i64 tcg_res[2];

    int pass;

    tcg_res[0] = tcg_temp_new_i64();

    tcg_res[1] = tcg_temp_new_i64();

    for (pass = 0; pass < (is_q ? 2 : 1); pass++) {

        read_vec_element(s, tcg_op1, rn, pass, MO_64);

        read_vec_element(s, tcg_op2, rm, pass, MO_64);

        if (!is_u) {

            switch (size) {

            case 0: /* AND */

                tcg_gen_and_i64(tcg_res[pass], tcg_op1, tcg_op2);

                break;

            case 1: /* BIC */

                tcg_gen_andc_i64(tcg_res[pass], tcg_op1, tcg_op2);

                break;

            case 2: /* ORR */

                tcg_gen_or_i64(tcg_res[pass], tcg_op1, tcg_op2);

                break;

            case 3: /* ORN */

                tcg_gen_orc_i64(tcg_res[pass], tcg_op1, tcg_op2);

                break;

            }

        } else {

            if (size != 0) {

                /* B* ops need res loaded to operate on */

                read_vec_element(s, tcg_res[pass], rd, pass, MO_64);

            }

            switch (size) {

            case 0: /* EOR */

                tcg_gen_xor_i64(tcg_res[pass], tcg_op1, tcg_op2);

                break;

            case 1: /* BSL bitwise select */

                tcg_gen_xor_i64(tcg_op1, tcg_op1, tcg_op2);

                tcg_gen_and_i64(tcg_op1, tcg_op1, tcg_res[pass]);

                tcg_gen_xor_i64(tcg_res[pass], tcg_op2, tcg_op1);

                break;

            case 2: /* BIT, bitwise insert if true */

                tcg_gen_xor_i64(tcg_op1, tcg_op1, tcg_res[pass]);

                tcg_gen_and_i64(tcg_op1, tcg_op1, tcg_op2);

                tcg_gen_xor_i64(tcg_res[pass], tcg_res[pass], tcg_op1);

                break;

            case 3: /* BIF, bitwise insert if false */

                tcg_gen_xor_i64(tcg_op1, tcg_op1, tcg_res[pass]);

                tcg_gen_andc_i64(tcg_op1, tcg_op1, tcg_op2);

                tcg_gen_xor_i64(tcg_res[pass], tcg_res[pass], tcg_op1);

                break;

            }

        }

    }

    write_vec_element(s, tcg_res[0], rd, 0, MO_64);

    if (!is_q) {

        tcg_gen_movi_i64(tcg_res[1], 0);

    }

    write_vec_element(s, tcg_res[1], rd, 1, MO_64);

    tcg_temp_free_i64(tcg_op1);

    tcg_temp_free_i64(tcg_op2);

    tcg_temp_free_i64(tcg_res[0]);

    tcg_temp_free_i64(tcg_res[1]);

}


void net_check_clients(void)

{

    VLANState *vlan;

    VLANClientState *vc;

    int i;

    /* Don't warn about the default network setup that you get if

     * no command line -net or -netdev options are specified. There

     * are two cases that we would otherwise complain about:

     * (1) board doesn't support a NIC but the implicit "-net nic"

     * requested one

     * (2) CONFIG_SLIRP not set, in which case the implicit "-net nic"

     * sets up a nic that isn't connected to anything.

     */

    if (default_net) {

        return;

    }

    QTAILQ_FOREACH(vlan, &vlans, next) {

        int has_nic = 0, has_host_dev = 0;

        QTAILQ_FOREACH(vc, &vlan->clients, next) {

            switch (vc->info->type) {

            case NET_CLIENT_OPTIONS_KIND_NIC:

                has_nic = 1;

                break;

            case NET_CLIENT_OPTIONS_KIND_USER:

            case NET_CLIENT_OPTIONS_KIND_TAP:

            case NET_CLIENT_OPTIONS_KIND_SOCKET:

            case NET_CLIENT_OPTIONS_KIND_VDE:

                has_host_dev = 1;

                break;

            default: ;

            }

        }

        if (has_host_dev && !has_nic)

            fprintf(stderr, "Warning: vlan %d with no nics\n", vlan->id);

        if (has_nic && !has_host_dev)

            fprintf(stderr,

                    "Warning: vlan %d is not connected to host network\n",

                    vlan->id);

    }

    QTAILQ_FOREACH(vc, &non_vlan_clients, next) {

        if (!vc->peer) {

            fprintf(stderr, "Warning: %s %s has no peer\n",

                    vc->info->type == NET_CLIENT_OPTIONS_KIND_NIC ? "nic" : "netdev",

                    vc->name);

        }

    }

    /* Check that all NICs requested via -net nic actually got created.

     * NICs created via -device don't need to be checked here because

     * they are always instantiated.

     */

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

        NICInfo *nd = &nd_table[i];

        if (nd->used && !nd->instantiated) {

            fprintf(stderr, "Warning: requested NIC (%s, model %s) "

                    "was not created (not supported by this machine?)\n",

                    nd->name ? nd->name : "anonymous",

                    nd->model ? nd->model : "unspecified");

        }

    }

}


static uint16_t read_u16(uint8_t *data, size_t offset)

{

    return ((data[offset] & 0xFF) << 8) | (data[offset + 1] & 0xFF);

}


av_cold void ff_psy_end(FFPsyContext *ctx)

{

    if (ctx->model->end)

        ctx->model->end(ctx);

    av_freep(&ctx->bands);

    av_freep(&ctx->num_bands);

    av_freep(&ctx->group);

    av_freep(&ctx->ch);

}


static void parse_str(StringInputVisitor *siv, Error **errp)

{

    char *str = (char *) siv->string;

    long long start, end;

    Range *cur;

    char *endptr;

    if (siv->ranges) {

        return;

    }

    do {

        errno = 0;

        start = strtoll(str, &endptr, 0);

        if (errno == 0 && endptr > str) {

            if (*endptr == '\0') {

                cur = g_malloc0(sizeof(*cur));

                cur->begin = start;

                cur->end = start + 1;

                siv->ranges = g_list_insert_sorted_merged(siv->ranges, cur,

                                                          range_compare);

                cur = NULL;

                str = NULL;

            } else if (*endptr == '-') {

                str = endptr + 1;

                errno = 0;

                end = strtoll(str, &endptr, 0);

                if (errno == 0 && endptr > str && start <= end &&

                    (start > INT64_MAX - 65536 ||

                     end < start + 65536)) {

                    if (*endptr == '\0') {

                        cur = g_malloc0(sizeof(*cur));

                        cur->begin = start;

                        cur->end = end + 1;

                        siv->ranges =

                            g_list_insert_sorted_merged(siv->ranges,

                                                        cur,

                                                        range_compare);

                        cur = NULL;

                        str = NULL;

                    } else if (*endptr == ',') {

                        str = endptr + 1;

                        cur = g_malloc0(sizeof(*cur));

                        cur->begin = start;

                        cur->end = end + 1;

                        siv->ranges =

                            g_list_insert_sorted_merged(siv->ranges,

                                                        cur,

                                                        range_compare);

                        cur = NULL;

                    } else {

                        goto error;

                    }

                } else {

                    goto error;

                }

            } else if (*endptr == ',') {

                str = endptr + 1;

                cur = g_malloc0(sizeof(*cur));

                cur->begin = start;

                cur->end = start + 1;

                siv->ranges = g_list_insert_sorted_merged(siv->ranges,

                                                          cur,

                                                          range_compare);

                cur = NULL;

            } else {

                goto error;

            }

        } else {

            goto error;

        }

    } while (str);

    return;

error:

    g_list_foreach(siv->ranges, free_range, NULL);

    g_list_free(siv->ranges);

    siv->ranges = NULL;

}


int inet_nonblocking_connect(const char *str, bool *in_progress,

                             Error **errp)

{

    QemuOpts *opts;

    int sock = -1;

    opts = qemu_opts_create(&dummy_opts, NULL, 0, NULL);

    if (inet_parse(opts, str) == 0) {

        sock = inet_connect_opts(opts, false, in_progress, errp);

    } else {

        error_set(errp, QERR_SOCKET_CREATE_FAILED);

    }

    qemu_opts_del(opts);

    return sock;

}


 roundAndPackFloatx80(

     int8 roundingPrecision, flag zSign, int32 zExp, uint64_t zSig0, uint64_t zSig1

 STATUS_PARAM)

{

    int8 roundingMode;

    flag roundNearestEven, increment, isTiny;

    int64 roundIncrement, roundMask, roundBits;

    roundingMode = STATUS(float_rounding_mode);

    roundNearestEven = ( roundingMode == float_round_nearest_even );

    if ( roundingPrecision == 80 ) goto precision80;

    if ( roundingPrecision == 64 ) {

        roundIncrement = LIT64( 0x0000000000000400 );

        roundMask = LIT64( 0x00000000000007FF );

    }

    else if ( roundingPrecision == 32 ) {

        roundIncrement = LIT64( 0x0000008000000000 );

        roundMask = LIT64( 0x000000FFFFFFFFFF );

    }

    else {

        goto precision80;

    }

    zSig0 |= ( zSig1 != 0 );

    if ( ! roundNearestEven ) {

        if ( roundingMode == float_round_to_zero ) {

            roundIncrement = 0;

        }

        else {

            roundIncrement = roundMask;

            if ( zSign ) {

                if ( roundingMode == float_round_up ) roundIncrement = 0;

            }

            else {

                if ( roundingMode == float_round_down ) roundIncrement = 0;

            }

        }

    }

    roundBits = zSig0 & roundMask;

    if ( 0x7FFD <= (uint32_t) ( zExp - 1 ) ) {

        if (    ( 0x7FFE < zExp )

             || ( ( zExp == 0x7FFE ) && ( zSig0 + roundIncrement < zSig0 ) )

           ) {

            goto overflow;

        }

        if ( zExp <= 0 ) {

            if ( STATUS(flush_to_zero) ) return packFloatx80( zSign, 0, 0 );

            isTiny =

                   ( STATUS(float_detect_tininess) == float_tininess_before_rounding )

                || ( zExp < 0 )

                || ( zSig0 <= zSig0 + roundIncrement );

            shift64RightJamming( zSig0, 1 - zExp, &zSig0 );

            zExp = 0;

            roundBits = zSig0 & roundMask;

            if ( isTiny && roundBits ) float_raise( float_flag_underflow STATUS_VAR);

            if ( roundBits ) STATUS(float_exception_flags) |= float_flag_inexact;

            zSig0 += roundIncrement;

            if ( (int64_t) zSig0 < 0 ) zExp = 1;

            roundIncrement = roundMask + 1;

            if ( roundNearestEven && ( roundBits<<1 == roundIncrement ) ) {

                roundMask |= roundIncrement;

            }

            zSig0 &= ~ roundMask;

            return packFloatx80( zSign, zExp, zSig0 );

        }

    }

    if ( roundBits ) STATUS(float_exception_flags) |= float_flag_inexact;

    zSig0 += roundIncrement;

    if ( zSig0 < roundIncrement ) {

        ++zExp;

        zSig0 = LIT64( 0x8000000000000000 );

    }

    roundIncrement = roundMask + 1;

    if ( roundNearestEven && ( roundBits<<1 == roundIncrement ) ) {

        roundMask |= roundIncrement;

    }

    zSig0 &= ~ roundMask;

    if ( zSig0 == 0 ) zExp = 0;

    return packFloatx80( zSign, zExp, zSig0 );

 precision80:

    increment = ( (int64_t) zSig1 < 0 );

    if ( ! roundNearestEven ) {

        if ( roundingMode == float_round_to_zero ) {

            increment = 0;

        }

        else {

            if ( zSign ) {

                increment = ( roundingMode == float_round_down ) && zSig1;

            }

            else {

                increment = ( roundingMode == float_round_up ) && zSig1;

            }

        }

    }

    if ( 0x7FFD <= (uint32_t) ( zExp - 1 ) ) {

        if (    ( 0x7FFE < zExp )

             || (    ( zExp == 0x7FFE )

                  && ( zSig0 == LIT64( 0xFFFFFFFFFFFFFFFF ) )

                  && increment

                )

           ) {

            roundMask = 0;

 overflow:

            float_raise( float_flag_overflow | float_flag_inexact STATUS_VAR);

            if (    ( roundingMode == float_round_to_zero )

                 || ( zSign && ( roundingMode == float_round_up ) )

                 || ( ! zSign && ( roundingMode == float_round_down ) )

               ) {

                return packFloatx80( zSign, 0x7FFE, ~ roundMask );

            }

            return packFloatx80( zSign, 0x7FFF, LIT64( 0x8000000000000000 ) );

        }

        if ( zExp <= 0 ) {

            isTiny =

                   ( STATUS(float_detect_tininess) == float_tininess_before_rounding )

                || ( zExp < 0 )

                || ! increment

                || ( zSig0 < LIT64( 0xFFFFFFFFFFFFFFFF ) );

            shift64ExtraRightJamming( zSig0, zSig1, 1 - zExp, &zSig0, &zSig1 );

            zExp = 0;

            if ( isTiny && zSig1 ) float_raise( float_flag_underflow STATUS_VAR);

            if ( zSig1 ) STATUS(float_exception_flags) |= float_flag_inexact;

            if ( roundNearestEven ) {

                increment = ( (int64_t) zSig1 < 0 );

            }

            else {

                if ( zSign ) {

                    increment = ( roundingMode == float_round_down ) && zSig1;

                }

                else {

                    increment = ( roundingMode == float_round_up ) && zSig1;

                }

            }

            if ( increment ) {

                ++zSig0;

                zSig0 &=

                    ~ ( ( (uint64_t) ( zSig1<<1 ) == 0 ) & roundNearestEven );

                if ( (int64_t) zSig0 < 0 ) zExp = 1;

            }

            return packFloatx80( zSign, zExp, zSig0 );

        }

    }

    if ( zSig1 ) STATUS(float_exception_flags) |= float_flag_inexact;

    if ( increment ) {

        ++zSig0;

        if ( zSig0 == 0 ) {

            ++zExp;

            zSig0 = LIT64( 0x8000000000000000 );

        }

        else {

            zSig0 &= ~ ( ( (uint64_t) ( zSig1<<1 ) == 0 ) & roundNearestEven );

        }

    }

    else {

        if ( zSig0 == 0 ) zExp = 0;

    }

    return packFloatx80( zSign, zExp, zSig0 );

}


static void win_stdio_close(CharDriverState *chr)

{

    WinStdioCharState *stdio = chr->opaque;

    if (stdio->hInputReadyEvent != INVALID_HANDLE_VALUE) {

        CloseHandle(stdio->hInputReadyEvent);

    }

    if (stdio->hInputDoneEvent != INVALID_HANDLE_VALUE) {

        CloseHandle(stdio->hInputDoneEvent);

    }

    if (stdio->hInputThread != INVALID_HANDLE_VALUE) {

        TerminateThread(stdio->hInputThread, 0);

    }

    g_free(chr->opaque);

    g_free(chr);

}


static int i2c_slave_post_load(void *opaque, int version_id)

{

    I2CSlave *dev = opaque;

    I2CBus *bus;

    I2CNode *node;

    bus = I2C_BUS(qdev_get_parent_bus(DEVICE(dev)));

    if ((bus->saved_address == dev->address) || (bus->broadcast)) {

        node = g_malloc(sizeof(struct I2CNode));

        node->elt = dev;

        QLIST_INSERT_HEAD(&bus->current_devs, node, next);

    }

    return 0;

}


int qemu_poll_ns(GPollFD *fds, guint nfds, int64_t timeout)

{

#ifdef CONFIG_PPOLL

    if (timeout < 0) {

        return ppoll((struct pollfd *)fds, nfds, NULL, NULL);

    } else {

        struct timespec ts;

        ts.tv_sec = timeout / 1000000000LL;

        ts.tv_nsec = timeout % 1000000000LL;

        return ppoll((struct pollfd *)fds, nfds, &ts, NULL);

    }

#else

    return g_poll(fds, nfds, qemu_timeout_ns_to_ms(timeout));

#endif

}


const char *error_get_pretty(Error *err)

{

    return err->msg;

}


static int qemu_rdma_put_buffer(void *opaque, const uint8_t *buf,

                                int64_t pos, int size)

{

    QEMUFileRDMA *r = opaque;

    QEMUFile *f = r->file;

    RDMAContext *rdma = r->rdma;

    size_t remaining = size;

    uint8_t * data = (void *) buf;

    int ret;

    CHECK_ERROR_STATE();

    /*

     * Push out any writes that

     * we're queued up for VM's ram.

     */

    ret = qemu_rdma_write_flush(f, rdma);

    if (ret < 0) {

        rdma->error_state = ret;

        return ret;

    }

    while (remaining) {

        RDMAControlHeader head;

        r->len = MIN(remaining, RDMA_SEND_INCREMENT);

        remaining -= r->len;

        head.len = r->len;

        head.type = RDMA_CONTROL_QEMU_FILE;

        ret = qemu_rdma_exchange_send(rdma, &head, data, NULL, NULL, NULL);

        if (ret < 0) {

            rdma->error_state = ret;

            return ret;

        }

        data += r->len;

    }

    return size;

}


static int peer_has_ufo(VirtIONet *n)

{

    if (!peer_has_vnet_hdr(n))

        return 0;

    n->has_ufo = qemu_peer_has_ufo(qemu_get_queue(n->nic));

    return n->has_ufo;

}


static uint64_t apb_pci_config_read(void *opaque, target_phys_addr_t addr,

                                    unsigned size)

{

    uint32_t ret;

    APBState *s = opaque;

    ret = pci_data_read(s->bus, addr, size);

    ret = qemu_bswap_len(ret, size);

    APB_DPRINTF("%s: addr " TARGET_FMT_lx " -> %x\n", __func__, addr, ret);

    return ret;

}


void s390_pci_sclp_deconfigure(SCCB *sccb)

{

    PciCfgSccb *psccb = (PciCfgSccb *)sccb;

    S390PCIBusDevice *pbdev = s390_pci_find_dev_by_fid(s390_get_phb(),

                                                       be32_to_cpu(psccb->aid));

    uint16_t rc;

    if (be16_to_cpu(sccb->h.length) < 16) {

        rc = SCLP_RC_INSUFFICIENT_SCCB_LENGTH;

        goto out;

    }

    if (!pbdev) {

        DPRINTF("sclp deconfig no dev found\n");

        rc = SCLP_RC_ADAPTER_ID_NOT_RECOGNIZED;

        goto out;

    }

    switch (pbdev->state) {

    case ZPCI_FS_RESERVED:

        rc = SCLP_RC_ADAPTER_IN_RESERVED_STATE;

        break;

    case ZPCI_FS_STANDBY:

        rc = SCLP_RC_NO_ACTION_REQUIRED;

        break;

    default:

        if (pbdev->summary_ind) {

            pci_dereg_irqs(pbdev);

        }

        if (pbdev->iommu->enabled) {

            pci_dereg_ioat(pbdev->iommu);

        }

        pbdev->state = ZPCI_FS_STANDBY;

        rc = SCLP_RC_NORMAL_COMPLETION;

        if (pbdev->release_timer) {

            qdev_unplug(DEVICE(pbdev->pdev), NULL);

        }

    }

out:

    psccb->header.response_code = cpu_to_be16(rc);

}


void cpu_register_physical_memory_offset(target_phys_addr_t start_addr,

                                         ram_addr_t size,

                                         ram_addr_t phys_offset,

                                         ram_addr_t region_offset)

{

    target_phys_addr_t addr, end_addr;

    PhysPageDesc *p;

    CPUState *env;

    ram_addr_t orig_size = size;

    void *subpage;

#ifdef CONFIG_KQEMU

    /* XXX: should not depend on cpu context */

    env = first_cpu;

    if (env->kqemu_enabled) {

        kqemu_set_phys_mem(start_addr, size, phys_offset);

    }

#endif

    if (kvm_enabled())

        kvm_set_phys_mem(start_addr, size, phys_offset);

    if (phys_offset == IO_MEM_UNASSIGNED) {

        region_offset = start_addr;

    }

    region_offset &= TARGET_PAGE_MASK;

    size = (size + TARGET_PAGE_SIZE - 1) & TARGET_PAGE_MASK;

    end_addr = start_addr + (target_phys_addr_t)size;

    for(addr = start_addr; addr != end_addr; addr += TARGET_PAGE_SIZE) {

        p = phys_page_find(addr >> TARGET_PAGE_BITS);

        if (p && p->phys_offset != IO_MEM_UNASSIGNED) {

            ram_addr_t orig_memory = p->phys_offset;

            target_phys_addr_t start_addr2, end_addr2;

            int need_subpage = 0;

            CHECK_SUBPAGE(addr, start_addr, start_addr2, end_addr, end_addr2,

                          need_subpage);

            if (need_subpage || phys_offset & IO_MEM_SUBWIDTH) {

                if (!(orig_memory & IO_MEM_SUBPAGE)) {

                    subpage = subpage_init((addr & TARGET_PAGE_MASK),

                                           &p->phys_offset, orig_memory,

                                           p->region_offset);

                } else {

                    subpage = io_mem_opaque[(orig_memory & ~TARGET_PAGE_MASK)

                                            >> IO_MEM_SHIFT];

                }

                subpage_register(subpage, start_addr2, end_addr2, phys_offset,

                                 region_offset);

                p->region_offset = 0;

            } else {

                p->phys_offset = phys_offset;

                if ((phys_offset & ~TARGET_PAGE_MASK) <= IO_MEM_ROM ||

                    (phys_offset & IO_MEM_ROMD))

                    phys_offset += TARGET_PAGE_SIZE;

            }

        } else {

            p = phys_page_find_alloc(addr >> TARGET_PAGE_BITS, 1);

            p->phys_offset = phys_offset;

            p->region_offset = region_offset;

            if ((phys_offset & ~TARGET_PAGE_MASK) <= IO_MEM_ROM ||

                (phys_offset & IO_MEM_ROMD)) {

                phys_offset += TARGET_PAGE_SIZE;

            } else {

                target_phys_addr_t start_addr2, end_addr2;

                int need_subpage = 0;

                CHECK_SUBPAGE(addr, start_addr, start_addr2, end_addr,

                              end_addr2, need_subpage);

                if (need_subpage || phys_offset & IO_MEM_SUBWIDTH) {

                    subpage = subpage_init((addr & TARGET_PAGE_MASK),

                                           &p->phys_offset, IO_MEM_UNASSIGNED,

                                           addr & TARGET_PAGE_MASK);

                    subpage_register(subpage, start_addr2, end_addr2,

                                     phys_offset, region_offset);

                    p->region_offset = 0;

                }

            }

        }

        region_offset += TARGET_PAGE_SIZE;

    }

    /* since each CPU stores ram addresses in its TLB cache, we must

       reset the modified entries */

    /* XXX: slow ! */

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

        tlb_flush(env, 1);

    }

}


static void help(int exitcode)

{

    const char *options_help =

#define QEMU_OPTIONS_GENERATE_HELP

#include "qemu-options-wrapper.h"

        ;

    version();

    printf("usage: %s [options] [disk_image]\n"

           "\n"

           "'disk_image' is a raw hard disk image for IDE hard disk 0\n"

           "\n"

           "%s\n"

           "During emulation, the following keys are useful:\n"

           "ctrl-alt-f      toggle full screen\n"

           "ctrl-alt-n      switch to virtual console 'n'\n"

           "ctrl-alt        toggle mouse and keyboard grab\n"

           "\n"

           "When using -nographic, press 'ctrl-a h' to get some help.\n",

           error_get_progname(),

           options_help);

    exit(exitcode);

}


static TileExcp gen_rr_opcode(DisasContext *dc, unsigned opext,

                              unsigned dest, unsigned srca)

{

    TCGv tdest, tsrca;

    const char *mnemonic;

    TCGMemOp memop;

    TileExcp ret = TILEGX_EXCP_NONE;

    /* Eliminate instructions with no output before doing anything else.  */

    switch (opext) {

    case OE_RR_Y0(NOP):

    case OE_RR_Y1(NOP):

    case OE_RR_X0(NOP):

    case OE_RR_X1(NOP):

        mnemonic = "nop";

        goto done0;

    case OE_RR_Y0(FNOP):

    case OE_RR_Y1(FNOP):

    case OE_RR_X0(FNOP):

    case OE_RR_X1(FNOP):

        mnemonic = "fnop";

        goto done0;

    case OE_RR_X1(DRAIN):

        mnemonic = "drain";

        goto done0;

    case OE_RR_X1(FLUSHWB):

        mnemonic = "flushwb";

        goto done0;

    case OE_RR_X1(ILL):

        if (dest == 0x1c && srca == 0x25) {

            mnemonic = "bpt";

            goto done2;

        }

        /* Fall through */

    case OE_RR_Y1(ILL):

        mnemonic = "ill";

    done2:

        qemu_log_mask(CPU_LOG_TB_IN_ASM, "%s", mnemonic);

        return TILEGX_EXCP_OPCODE_UNKNOWN;

    case OE_RR_X1(MF):

        mnemonic = "mf";

        goto done0;

    case OE_RR_X1(NAP):

        /* ??? This should yield, especially in system mode.  */

        mnemonic = "nap";

        goto done0;

    case OE_RR_X1(SWINT0):

    case OE_RR_X1(SWINT2):

    case OE_RR_X1(SWINT3):

        return TILEGX_EXCP_OPCODE_UNIMPLEMENTED;

    case OE_RR_X1(SWINT1):

        ret = TILEGX_EXCP_SYSCALL;

        mnemonic = "swint1";

    done0:

        if (srca || dest) {

            return TILEGX_EXCP_OPCODE_UNIMPLEMENTED;

        }

        qemu_log_mask(CPU_LOG_TB_IN_ASM, "%s", mnemonic);

        return ret;

    case OE_RR_X1(DTLBPR):

        return TILEGX_EXCP_OPCODE_UNIMPLEMENTED;

    case OE_RR_X1(FINV):

        mnemonic = "finv";

        goto done1;

    case OE_RR_X1(FLUSH):

        mnemonic = "flush";

        goto done1;

    case OE_RR_X1(ICOH):

        mnemonic = "icoh";

        goto done1;

    case OE_RR_X1(INV):

        mnemonic = "inv";

        goto done1;

    case OE_RR_X1(WH64):

        mnemonic = "wh64";

        goto done1;

    case OE_RR_X1(JRP):

    case OE_RR_Y1(JRP):

        mnemonic = "jrp";

        goto do_jr;

    case OE_RR_X1(JR):

    case OE_RR_Y1(JR):

        mnemonic = "jr";

        goto do_jr;

    case OE_RR_X1(JALRP):

    case OE_RR_Y1(JALRP):

        mnemonic = "jalrp";

        goto do_jalr;

    case OE_RR_X1(JALR):

    case OE_RR_Y1(JALR):

        mnemonic = "jalr";

    do_jalr:

        tcg_gen_movi_tl(dest_gr(dc, TILEGX_R_LR),

                        dc->pc + TILEGX_BUNDLE_SIZE_IN_BYTES);

    do_jr:

        dc->jmp.cond = TCG_COND_ALWAYS;

        dc->jmp.dest = tcg_temp_new();

        tcg_gen_andi_tl(dc->jmp.dest, load_gr(dc, srca), ~7);

    done1:

        if (dest) {

            return TILEGX_EXCP_OPCODE_UNIMPLEMENTED;

        }

        qemu_log_mask(CPU_LOG_TB_IN_ASM, "%s %s", mnemonic, reg_names[srca]);

        return ret;

    }

    tdest = dest_gr(dc, dest);

    tsrca = load_gr(dc, srca);

    switch (opext) {

    case OE_RR_X0(CNTLZ):

    case OE_RR_Y0(CNTLZ):

        gen_helper_cntlz(tdest, tsrca);

        mnemonic = "cntlz";

        break;

    case OE_RR_X0(CNTTZ):

    case OE_RR_Y0(CNTTZ):

        gen_helper_cnttz(tdest, tsrca);

        mnemonic = "cnttz";

        break;

    case OE_RR_X0(FSINGLE_PACK1):

    case OE_RR_Y0(FSINGLE_PACK1):

    case OE_RR_X1(IRET):

        return TILEGX_EXCP_OPCODE_UNIMPLEMENTED;

    case OE_RR_X1(LD1S):

        memop = MO_SB;

        mnemonic = "ld1s";

        goto do_load;

    case OE_RR_X1(LD1U):

        memop = MO_UB;

        mnemonic = "ld1u";

        goto do_load;

    case OE_RR_X1(LD2S):

        memop = MO_TESW;

        mnemonic = "ld2s";

        goto do_load;

    case OE_RR_X1(LD2U):

        memop = MO_TEUW;

        mnemonic = "ld2u";

        goto do_load;

    case OE_RR_X1(LD4S):

        memop = MO_TESL;

        mnemonic = "ld4s";

        goto do_load;

    case OE_RR_X1(LD4U):

        memop = MO_TEUL;

        mnemonic = "ld4u";

        goto do_load;

    case OE_RR_X1(LDNT1S):

        memop = MO_SB;

        mnemonic = "ldnt1s";

        goto do_load;

    case OE_RR_X1(LDNT1U):

        memop = MO_UB;

        mnemonic = "ldnt1u";

        goto do_load;

    case OE_RR_X1(LDNT2S):

        memop = MO_TESW;

        mnemonic = "ldnt2s";

        goto do_load;

    case OE_RR_X1(LDNT2U):

        memop = MO_TEUW;

        mnemonic = "ldnt2u";

        goto do_load;

    case OE_RR_X1(LDNT4S):

        memop = MO_TESL;

        mnemonic = "ldnt4s";

        goto do_load;

    case OE_RR_X1(LDNT4U):

        memop = MO_TEUL;

        mnemonic = "ldnt4u";

        goto do_load;

    case OE_RR_X1(LDNT):

        memop = MO_TEQ;

        mnemonic = "ldnt";

        goto do_load;

    case OE_RR_X1(LD):

        memop = MO_TEQ;

        mnemonic = "ld";

    do_load:

        tcg_gen_qemu_ld_tl(tdest, tsrca, dc->mmuidx, memop);

        break;

    case OE_RR_X1(LDNA):

        tcg_gen_andi_tl(tdest, tsrca, ~7);

        tcg_gen_qemu_ld_tl(tdest, tdest, dc->mmuidx, MO_TEQ);

        mnemonic = "ldna";

        break;

    case OE_RR_X1(LNK):

    case OE_RR_Y1(LNK):

        if (srca) {

            return TILEGX_EXCP_OPCODE_UNIMPLEMENTED;

        }

        tcg_gen_movi_tl(tdest, dc->pc + TILEGX_BUNDLE_SIZE_IN_BYTES);

        mnemonic = "lnk";

        break;

    case OE_RR_X0(PCNT):

    case OE_RR_Y0(PCNT):

        gen_helper_pcnt(tdest, tsrca);

        mnemonic = "pcnt";

        break;

    case OE_RR_X0(REVBITS):

    case OE_RR_Y0(REVBITS):

        gen_helper_revbits(tdest, tsrca);

        mnemonic = "revbits";

        break;

    case OE_RR_X0(REVBYTES):

    case OE_RR_Y0(REVBYTES):

        tcg_gen_bswap64_tl(tdest, tsrca);

        mnemonic = "revbytes";

        break;

    case OE_RR_X0(TBLIDXB0):

    case OE_RR_Y0(TBLIDXB0):

        tcg_gen_deposit_tl(tdest, load_gr(dc, dest), tsrca, 2, 8);

        mnemonic = "tblidxb0";

        break;

    case OE_RR_X0(TBLIDXB1):

    case OE_RR_Y0(TBLIDXB1):

        tcg_gen_shri_tl(tdest, tsrca, 8);

        tcg_gen_deposit_tl(tdest, load_gr(dc, dest), tdest, 2, 8);

        mnemonic = "tblidxb1";

        break;

    case OE_RR_X0(TBLIDXB2):

    case OE_RR_Y0(TBLIDXB2):

        tcg_gen_shri_tl(tdest, tsrca, 16);

        tcg_gen_deposit_tl(tdest, load_gr(dc, dest), tdest, 2, 8);

        mnemonic = "tblidxb2";

        break;

    case OE_RR_X0(TBLIDXB3):

    case OE_RR_Y0(TBLIDXB3):

        tcg_gen_shri_tl(tdest, tsrca, 24);

        tcg_gen_deposit_tl(tdest, load_gr(dc, dest), tdest, 2, 8);

        mnemonic = "tblidxb3";

        break;

    default:

        return TILEGX_EXCP_OPCODE_UNIMPLEMENTED;

    }

    qemu_log_mask(CPU_LOG_TB_IN_ASM, "%s %s, %s", mnemonic,

                  reg_names[dest], reg_names[srca]);

    return ret;

}


static void etsec_cleanup(NetClientState *nc)

{

    /* qemu_log("eTSEC cleanup\n"); */

}


static void qmp_input_push(QmpInputVisitor *qiv, const QObject *obj, Error **errp)

{

    qiv->stack[qiv->nb_stack].obj = obj;

    if (qobject_type(obj) == QTYPE_QLIST) {

        qiv->stack[qiv->nb_stack].entry = qlist_first(qobject_to_qlist(obj));

    }

    qiv->nb_stack++;

    if (qiv->nb_stack >= QIV_STACK_SIZE) {

        error_set(errp, QERR_BUFFER_OVERRUN);

        return;

    }

}


static const IntelHDAReg *intel_hda_reg_find(IntelHDAState *d, target_phys_addr_t addr)

{

    const IntelHDAReg *reg;

    if (addr >= sizeof(regtab)/sizeof(regtab[0])) {

        goto noreg;

    }

    reg = regtab+addr;

    if (reg->name == NULL) {

        goto noreg;

    }

    return reg;

noreg:

    dprint(d, 1, "unknown register, addr 0x%x\n", (int) addr);

    return NULL;

}


build_srat(GArray *table_data, BIOSLinker *linker, VirtMachineState *vms)

{

    AcpiSystemResourceAffinityTable *srat;

    AcpiSratProcessorGiccAffinity *core;

    AcpiSratMemoryAffinity *numamem;

    int i, srat_start;

    uint64_t mem_base;

    MachineClass *mc = MACHINE_GET_CLASS(vms);

    const CPUArchIdList *cpu_list = mc->possible_cpu_arch_ids(MACHINE(vms));

    srat_start = table_data->len;

    srat = acpi_data_push(table_data, sizeof(*srat));

    srat->reserved1 = cpu_to_le32(1);

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

        int node_id = cpu_list->cpus[i].props.has_node_id ?

            cpu_list->cpus[i].props.node_id : 0;

        core = acpi_data_push(table_data, sizeof(*core));

        core->type = ACPI_SRAT_PROCESSOR_GICC;

        core->length = sizeof(*core);

        core->proximity = cpu_to_le32(node_id);

        core->acpi_processor_uid = cpu_to_le32(i);

        core->flags = cpu_to_le32(1);

    }

    mem_base = vms->memmap[VIRT_MEM].base;

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

        numamem = acpi_data_push(table_data, sizeof(*numamem));

        build_srat_memory(numamem, mem_base, numa_info[i].node_mem, i,

                          MEM_AFFINITY_ENABLED);

        mem_base += numa_info[i].node_mem;

    }

    build_header(linker, table_data, (void *)srat, "SRAT",

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

}


void acpi_pcihp_init(AcpiPciHpState *s, PCIBus *root_bus,

                     MemoryRegion *address_space_io, bool bridges_enabled)

{

    uint16_t io_size = ACPI_PCIHP_SIZE;

    s->root= root_bus;

    s->legacy_piix = !bridges_enabled;

    if (s->legacy_piix) {

        unsigned *bus_bsel = g_malloc(sizeof *bus_bsel);

        io_size = ACPI_PCIHP_LEGACY_SIZE;

        *bus_bsel = ACPI_PCIHP_BSEL_DEFAULT;

        object_property_add_uint32_ptr(OBJECT(root_bus), ACPI_PCIHP_PROP_BSEL,

                                       bus_bsel, NULL);

    }

    memory_region_init_io(&s->io, NULL, &acpi_pcihp_io_ops, s,

                          "acpi-pci-hotplug", io_size);

    memory_region_add_subregion(address_space_io, ACPI_PCIHP_ADDR, &s->io);

}


static unsigned tget_short(GetByteContext *gb, int le)

{

    unsigned v = le ? bytestream2_get_le16u(gb) : bytestream2_get_be16u(gb);

    return v;

}


static void omap_lpg_tick(void *opaque)

{

    struct omap_lpg_s *s = opaque;

    if (s->cycle)

        timer_mod(s->tm, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + s->period - s->on);

    else

        timer_mod(s->tm, qemu_clock_get_ms(QEMU_CLOCK_VIRTUAL) + s->on);

    s->cycle = !s->cycle;

    printf("%s: LED is %s\n", __FUNCTION__, s->cycle ? "on" : "off");

}