static int rndis_query_response(USBNetState *s,

                rndis_query_msg_type *buf, unsigned int length)

{

    rndis_query_cmplt_type *resp;

    /* oid_supported_list is the largest data reply */

    uint8_t infobuf[sizeof(oid_supported_list)];

    uint32_t bufoffs, buflen;

    int infobuflen;

    unsigned int resplen;

    bufoffs = le32_to_cpu(buf->InformationBufferOffset) + 8;

    buflen = le32_to_cpu(buf->InformationBufferLength);

    if (bufoffs + buflen > length)

        return USB_RET_STALL;

    infobuflen = ndis_query(s, le32_to_cpu(buf->OID),

                            bufoffs + (uint8_t *) buf, buflen, infobuf,

                            sizeof(infobuf));

    resplen = sizeof(rndis_query_cmplt_type) +

            ((infobuflen < 0) ? 0 : infobuflen);

    resp = rndis_queue_response(s, resplen);

    if (!resp)

        return USB_RET_STALL;

    resp->MessageType = cpu_to_le32(RNDIS_QUERY_CMPLT);

    resp->RequestID = buf->RequestID; /* Still LE in msg buffer */

    resp->MessageLength = cpu_to_le32(resplen);

    if (infobuflen < 0) {

        /* OID not supported */

        resp->Status = cpu_to_le32(RNDIS_STATUS_NOT_SUPPORTED);

        resp->InformationBufferLength = cpu_to_le32(0);

        resp->InformationBufferOffset = cpu_to_le32(0);

        return 0;

    }

    resp->Status = cpu_to_le32(RNDIS_STATUS_SUCCESS);

    resp->InformationBufferOffset =

            cpu_to_le32(infobuflen ? sizeof(rndis_query_cmplt_type) - 8 : 0);

    resp->InformationBufferLength = cpu_to_le32(infobuflen);

    memcpy(resp + 1, infobuf, infobuflen);

    return 0;

}


static int pollfds_fill(GArray *pollfds, fd_set *rfds, fd_set *wfds,

                        fd_set *xfds)

{

    int nfds = -1;

    int i;

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

        GPollFD *pfd = &g_array_index(pollfds, GPollFD, i);

        int fd = pfd->fd;

        int events = pfd->events;

        if (events & (G_IO_IN | G_IO_HUP | G_IO_ERR)) {

            FD_SET(fd, rfds);

            nfds = MAX(nfds, fd);

        }

        if (events & (G_IO_OUT | G_IO_ERR)) {

            FD_SET(fd, wfds);

            nfds = MAX(nfds, fd);

        }

        if (events & G_IO_PRI) {

            FD_SET(fd, xfds);

            nfds = MAX(nfds, fd);

        }

    }

    return nfds;

}


static int matroska_parse_rm_audio(MatroskaDemuxContext *matroska,

                                   MatroskaTrack *track,

                                   AVStream *st,

                                   uint8_t *data, int size,

                                   uint64_t timecode,

                                   int64_t pos)

{

    int a = st->codec->block_align;

    int sps = track->audio.sub_packet_size;

    int cfs = track->audio.coded_framesize;

    int h = track->audio.sub_packet_h;

    int y = track->audio.sub_packet_cnt;

    int w = track->audio.frame_size;

    int x;

    if (!track->audio.pkt_cnt) {

        if (track->audio.sub_packet_cnt == 0)

            track->audio.buf_timecode = timecode;

        if (st->codec->codec_id == AV_CODEC_ID_RA_288) {

            if (size < cfs * h / 2) {

                av_log(matroska->ctx, AV_LOG_ERROR,

                       "Corrupt int4 RM-style audio packet size\n");

                return AVERROR_INVALIDDATA;

            }

            for (x=0; x<h/2; x++)

                memcpy(track->audio.buf+x*2*w+y*cfs,

                       data+x*cfs, cfs);

        } else if (st->codec->codec_id == AV_CODEC_ID_SIPR) {

            if (size < w) {

                av_log(matroska->ctx, AV_LOG_ERROR,

                       "Corrupt sipr RM-style audio packet size\n");

                return AVERROR_INVALIDDATA;

            }

            memcpy(track->audio.buf + y*w, data, w);

        } else {

            if (size < sps * w / sps) {

                av_log(matroska->ctx, AV_LOG_ERROR,

                       "Corrupt generic RM-style audio packet size\n");

                return AVERROR_INVALIDDATA;

            }

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

                memcpy(track->audio.buf+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), data+x*sps, sps);

        }

        if (++track->audio.sub_packet_cnt >= h) {

            if (st->codec->codec_id == AV_CODEC_ID_SIPR)

                ff_rm_reorder_sipr_data(track->audio.buf, h, w);

            track->audio.sub_packet_cnt = 0;

            track->audio.pkt_cnt = h*w / a;

        }

    }

    while (track->audio.pkt_cnt) {

        AVPacket *pkt = NULL;

        if (!(pkt = av_mallocz(sizeof(AVPacket))) || av_new_packet(pkt, a) < 0){

            av_free(pkt);

            return AVERROR(ENOMEM);

        }

        memcpy(pkt->data, track->audio.buf

               + a * (h*w / a - track->audio.pkt_cnt--), a);

        pkt->pts = track->audio.buf_timecode;

        track->audio.buf_timecode = AV_NOPTS_VALUE;

        pkt->pos = pos;

        pkt->stream_index = st->index;

        dynarray_add(&matroska->packets,&matroska->num_packets,pkt);

    }

    return 0;

}


void exit_program(int ret)

{

    int i, j;

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

        avfilter_graph_free(&filtergraphs[i]->graph);

        for (j = 0; j < filtergraphs[i]->nb_inputs; j++)

            av_freep(&filtergraphs[i]->inputs[j]);

        av_freep(&filtergraphs[i]->inputs);

        for (j = 0; j < filtergraphs[i]->nb_outputs; j++)

            av_freep(&filtergraphs[i]->outputs[j]);

        av_freep(&filtergraphs[i]->outputs);

        av_freep(&filtergraphs[i]);

    }

    av_freep(&filtergraphs);

    /* close files */

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

        AVFormatContext *s = output_files[i]->ctx;

        if (!(s->oformat->flags & AVFMT_NOFILE) && s->pb)

            avio_close(s->pb);

        avformat_free_context(s);

        av_dict_free(&output_files[i]->opts);

        av_freep(&output_files[i]);

    }

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

        AVBitStreamFilterContext *bsfc = output_streams[i]->bitstream_filters;

        while (bsfc) {

            AVBitStreamFilterContext *next = bsfc->next;

            av_bitstream_filter_close(bsfc);

            bsfc = next;

        }

        output_streams[i]->bitstream_filters = NULL;

        if (output_streams[i]->output_frame) {

            AVFrame *frame = output_streams[i]->output_frame;

            if (frame->extended_data != frame->data)

                av_freep(&frame->extended_data);

            av_freep(&frame);

        }

        av_freep(&output_streams[i]->avfilter);

        av_freep(&output_streams[i]->filtered_frame);

        av_freep(&output_streams[i]);

    }

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

        avformat_close_input(&input_files[i]->ctx);

        av_freep(&input_files[i]);

    }

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

        av_freep(&input_streams[i]->decoded_frame);

        av_dict_free(&input_streams[i]->opts);

        free_buffer_pool(input_streams[i]);

        av_freep(&input_streams[i]->filters);

        av_freep(&input_streams[i]);

    }

    if (vstats_file)

        fclose(vstats_file);

    av_free(vstats_filename);

    av_freep(&input_streams);

    av_freep(&input_files);

    av_freep(&output_streams);

    av_freep(&output_files);

    uninit_opts();

    av_free(audio_buf);

    allocated_audio_buf_size = 0;

    av_free(async_buf);

    allocated_async_buf_size = 0;

    avfilter_uninit();

    avformat_network_deinit();

    if (received_sigterm) {

        av_log(NULL, AV_LOG_INFO, "Received signal %d: terminating.\n",

               (int) received_sigterm);

        exit (255);

    }

    exit(ret);

}


static int parse_playlist(HLSContext *c, const char *url,

                          struct playlist *pls, AVIOContext *in)

{

    int ret = 0, is_segment = 0, is_variant = 0;

    int64_t duration = 0;

    enum KeyType key_type = KEY_NONE;

    uint8_t iv[16] = "";

    int has_iv = 0;

    char key[MAX_URL_SIZE] = "";

    char line[MAX_URL_SIZE];

    const char *ptr;

    int close_in = 0;

    int64_t seg_offset = 0;

    int64_t seg_size = -1;

    uint8_t *new_url = NULL;

    struct variant_info variant_info;

    char tmp_str[MAX_URL_SIZE];

    struct segment *cur_init_section = NULL;

    if (!in && c->http_persistent && c->playlist_pb) {

        in = c->playlist_pb;

        ret = open_url_keepalive(c->ctx, &c->playlist_pb, url);

        if (ret == AVERROR_EXIT) {

            return ret;

        } else if (ret < 0) {

            av_log(c->ctx, AV_LOG_WARNING,

                "keepalive request failed for '%s', retrying with new connection: %s\n",

                url, av_err2str(ret));

            in = NULL;

        }

    }

    if (!in) {

#if 1

        AVDictionary *opts = NULL;

        /* Some HLS servers don't like being sent the range header */

        av_dict_set(&opts, "seekable", "0", 0);

        // broker prior HTTP options that should be consistent across requests

        av_dict_set(&opts, "user_agent", c->user_agent, 0);

        av_dict_set(&opts, "cookies", c->cookies, 0);

        av_dict_set(&opts, "headers", c->headers, 0);

        av_dict_set(&opts, "http_proxy", c->http_proxy, 0);

        if (c->http_persistent)

            av_dict_set(&opts, "multiple_requests", "1", 0);

        ret = c->ctx->io_open(c->ctx, &in, url, AVIO_FLAG_READ, &opts);

        av_dict_free(&opts);

        if (ret < 0)

            return ret;

        if (c->http_persistent)

            c->playlist_pb = in;

        else

            close_in = 1;

#else

        ret = open_in(c, &in, url);

        if (ret < 0)

            return ret;

        close_in = 1;

#endif

    }

    if (av_opt_get(in, "location", AV_OPT_SEARCH_CHILDREN, &new_url) >= 0)

        url = new_url;

    read_chomp_line(in, line, sizeof(line));

    if (strcmp(line, "#EXTM3U")) {

        ret = AVERROR_INVALIDDATA;

        goto fail;

    }

    if (pls) {

        free_segment_list(pls);

        pls->finished = 0;

        pls->type = PLS_TYPE_UNSPECIFIED;

    }

    while (!avio_feof(in)) {

        read_chomp_line(in, line, sizeof(line));

        if (av_strstart(line, "#EXT-X-STREAM-INF:", &ptr)) {

            is_variant = 1;

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

            ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_variant_args,

                               &variant_info);

        } else if (av_strstart(line, "#EXT-X-KEY:", &ptr)) {

            struct key_info info = {{0}};

            ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_key_args,

                               &info);

            key_type = KEY_NONE;

            has_iv = 0;

            if (!strcmp(info.method, "AES-128"))

                key_type = KEY_AES_128;

            if (!strcmp(info.method, "SAMPLE-AES"))

                key_type = KEY_SAMPLE_AES;

            if (!strncmp(info.iv, "0x", 2) || !strncmp(info.iv, "0X", 2)) {

                ff_hex_to_data(iv, info.iv + 2);

                has_iv = 1;

            }

            av_strlcpy(key, info.uri, sizeof(key));

        } else if (av_strstart(line, "#EXT-X-MEDIA:", &ptr)) {

            struct rendition_info info = {{0}};

            ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_rendition_args,

                               &info);

            new_rendition(c, &info, url);

        } else if (av_strstart(line, "#EXT-X-TARGETDURATION:", &ptr)) {

            ret = ensure_playlist(c, &pls, url);

            if (ret < 0)

                goto fail;

            pls->target_duration = strtoll(ptr, NULL, 10) * AV_TIME_BASE;

        } else if (av_strstart(line, "#EXT-X-MEDIA-SEQUENCE:", &ptr)) {

            ret = ensure_playlist(c, &pls, url);

            if (ret < 0)

                goto fail;

            pls->start_seq_no = atoi(ptr);

        } else if (av_strstart(line, "#EXT-X-PLAYLIST-TYPE:", &ptr)) {

            ret = ensure_playlist(c, &pls, url);

            if (ret < 0)

                goto fail;

            if (!strcmp(ptr, "EVENT"))

                pls->type = PLS_TYPE_EVENT;

            else if (!strcmp(ptr, "VOD"))

                pls->type = PLS_TYPE_VOD;

        } else if (av_strstart(line, "#EXT-X-MAP:", &ptr)) {

            struct init_section_info info = {{0}};

            ret = ensure_playlist(c, &pls, url);

            if (ret < 0)

                goto fail;

            ff_parse_key_value(ptr, (ff_parse_key_val_cb) handle_init_section_args,

                               &info);

            cur_init_section = new_init_section(pls, &info, url);

        } else if (av_strstart(line, "#EXT-X-ENDLIST", &ptr)) {

            if (pls)

                pls->finished = 1;

        } else if (av_strstart(line, "#EXTINF:", &ptr)) {

            is_segment = 1;

            duration   = atof(ptr) * AV_TIME_BASE;

        } else if (av_strstart(line, "#EXT-X-BYTERANGE:", &ptr)) {

            seg_size = strtoll(ptr, NULL, 10);

            ptr = strchr(ptr, '@');

            if (ptr)

                seg_offset = strtoll(ptr+1, NULL, 10);

        } else if (av_strstart(line, "#", NULL)) {

            continue;

        } else if (line[0]) {

            if (is_variant) {

                if (!new_variant(c, &variant_info, line, url)) {

                    ret = AVERROR(ENOMEM);

                    goto fail;

                }

                is_variant = 0;

            }

            if (is_segment) {

                struct segment *seg;

                if (!pls) {

                    if (!new_variant(c, 0, url, NULL)) {

                        ret = AVERROR(ENOMEM);

                        goto fail;

                    }

                    pls = c->playlists[c->n_playlists - 1];

                }

                seg = av_malloc(sizeof(struct segment));

                if (!seg) {

                    ret = AVERROR(ENOMEM);

                    goto fail;

                }

                seg->duration = duration;

                seg->key_type = key_type;

                if (has_iv) {

                    memcpy(seg->iv, iv, sizeof(iv));

                } else {

                    int seq = pls->start_seq_no + pls->n_segments;

                    memset(seg->iv, 0, sizeof(seg->iv));

                    AV_WB32(seg->iv + 12, seq);

                }

                if (key_type != KEY_NONE) {

                    ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, key);

                    seg->key = av_strdup(tmp_str);

                    if (!seg->key) {

                        av_free(seg);

                        ret = AVERROR(ENOMEM);

                        goto fail;

                    }

                } else {

                    seg->key = NULL;

                }

                ff_make_absolute_url(tmp_str, sizeof(tmp_str), url, line);

                seg->url = av_strdup(tmp_str);

                if (!seg->url) {

                    av_free(seg->key);

                    av_free(seg);

                    ret = AVERROR(ENOMEM);

                    goto fail;

                }

                dynarray_add(&pls->segments, &pls->n_segments, seg);

                is_segment = 0;

                seg->size = seg_size;

                if (seg_size >= 0) {

                    seg->url_offset = seg_offset;

                    seg_offset += seg_size;

                    seg_size = -1;

                } else {

                    seg->url_offset = 0;

                    seg_offset = 0;

                }

                seg->init_section = cur_init_section;

            }

        }

    }

    if (pls)

        pls->last_load_time = av_gettime_relative();

fail:

    av_free(new_url);

    if (close_in)

        ff_format_io_close(c->ctx, &in);

    return ret;

}


static void RENAME(yuv2rgb555_1)(SwsContext *c, const uint16_t *buf0,

                                 const uint16_t *ubuf0, const uint16_t *ubuf1,

                                 const uint16_t *vbuf0, const uint16_t *vbuf1,

                                 const uint16_t *abuf0, uint8_t *dest,

                                 int dstW, int uvalpha, enum PixelFormat dstFormat,

                                 int flags, int y)

{

    const uint16_t *buf1= buf0; //FIXME needed for RGB1/BGR1

    if (uvalpha < 2048) { // note this is not correct (shifts chrominance by 0.5 pixels) but it is a bit faster

        __asm__ volatile(

            "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"

            "mov        %4, %%"REG_b"               \n\t"

            "push %%"REG_BP"                        \n\t"

            YSCALEYUV2RGB1(%%REGBP, %5)

            "pxor    %%mm7, %%mm7                   \n\t"

            /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */

#ifdef DITHER1XBPP

            "paddusb "BLUE_DITHER"(%5), %%mm2      \n\t"

            "paddusb "GREEN_DITHER"(%5), %%mm4      \n\t"

            "paddusb "RED_DITHER"(%5), %%mm5      \n\t"

#endif

            WRITERGB15(%%REGb, 8280(%5), %%REGBP)

            "pop %%"REG_BP"                         \n\t"

            "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"

            :: "c" (buf0), "d" (buf1), "S" (ubuf0), "D" (ubuf1), "m" (dest),

               "a" (&c->redDither)

        );

    } else {

        __asm__ volatile(

            "mov %%"REG_b", "ESP_OFFSET"(%5)        \n\t"

            "mov        %4, %%"REG_b"               \n\t"

            "push %%"REG_BP"                        \n\t"

            YSCALEYUV2RGB1b(%%REGBP, %5)

            "pxor    %%mm7, %%mm7                   \n\t"

            /* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */

#ifdef DITHER1XBPP

            "paddusb "BLUE_DITHER"(%5), %%mm2      \n\t"

            "paddusb "GREEN_DITHER"(%5), %%mm4      \n\t"

            "paddusb "RED_DITHER"(%5), %%mm5      \n\t"

#endif

            WRITERGB15(%%REGb, 8280(%5), %%REGBP)

            "pop %%"REG_BP"                         \n\t"

            "mov "ESP_OFFSET"(%5), %%"REG_b"        \n\t"

            :: "c" (buf0), "d" (buf1), "S" (ubuf0), "D" (ubuf1), "m" (dest),

               "a" (&c->redDither)

        );

    }

}


static int decode_slice(AVCodecContext *avctx, ProresThreadData *td)

{

    ProresContext *ctx = avctx->priv_data;

    int mb_x_pos  = td->x_pos;

    int mb_y_pos  = td->y_pos;

    int pic_num   = ctx->pic_num;

    int slice_num = td->slice_num;

    int mbs_per_slice = td->slice_width;

    const uint8_t *buf;

    uint8_t *y_data, *u_data, *v_data;

    AVFrame *pic = avctx->coded_frame;

    int i, sf, slice_width_factor;

    int slice_data_size, hdr_size, y_data_size, u_data_size, v_data_size;

    int y_linesize, u_linesize, v_linesize;

    buf             = ctx->slice_data[slice_num].index;

    slice_data_size = ctx->slice_data[slice_num + 1].index - buf;

    slice_width_factor = av_log2(mbs_per_slice);

    y_data     = pic->data[0];

    u_data     = pic->data[1];

    v_data     = pic->data[2];

    y_linesize = pic->linesize[0];

    u_linesize = pic->linesize[1];

    v_linesize = pic->linesize[2];

    if (pic->interlaced_frame) {

        if (!(pic_num ^ pic->top_field_first)) {

            y_data += y_linesize;

            u_data += u_linesize;

            v_data += v_linesize;

        }

        y_linesize <<= 1;

        u_linesize <<= 1;

        v_linesize <<= 1;

    }

    if (slice_data_size < 6) {

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

        return AVERROR_INVALIDDATA;

    }

    /* parse slice header */

    hdr_size    = buf[0] >> 3;

    y_data_size = AV_RB16(buf + 2);

    u_data_size = AV_RB16(buf + 4);

    v_data_size = slice_data_size - y_data_size - u_data_size - hdr_size;

    if (v_data_size < 0 || hdr_size < 6) {

        av_log(avctx, AV_LOG_ERROR, "invalid data size\n");

        return AVERROR_INVALIDDATA;

    }

    sf = av_clip(buf[1], 1, 224);

    sf = sf > 128 ? (sf - 96) << 2 : sf;

    /* scale quantization matrixes according with slice's scale factor */

    /* TODO: this can be SIMD-optimized alot */

    if (ctx->qmat_changed || sf != ctx->prev_slice_sf) {

        ctx->prev_slice_sf = sf;

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

            ctx->qmat_luma_scaled[ctx->dsp.idct_permutation[i]]   = ctx->qmat_luma[i]   * sf;

            ctx->qmat_chroma_scaled[ctx->dsp.idct_permutation[i]] = ctx->qmat_chroma[i] * sf;

        }

    }

    /* decode luma plane */

    decode_slice_plane(ctx, td, buf + hdr_size, y_data_size,

                       (uint16_t*) (y_data + (mb_y_pos << 4) * y_linesize +

                                    (mb_x_pos << 5)), y_linesize,

                       mbs_per_slice, 4, slice_width_factor + 2,

                       ctx->qmat_luma_scaled);

    /* decode U chroma plane */

    decode_slice_plane(ctx, td, buf + hdr_size + y_data_size, u_data_size,

                       (uint16_t*) (u_data + (mb_y_pos << 4) * u_linesize +

                                    (mb_x_pos << ctx->mb_chroma_factor)),

                       u_linesize, mbs_per_slice, ctx->num_chroma_blocks,

                       slice_width_factor + ctx->chroma_factor - 1,

                       ctx->qmat_chroma_scaled);

    /* decode V chroma plane */

    decode_slice_plane(ctx, td, buf + hdr_size + y_data_size + u_data_size,

                       v_data_size,

                       (uint16_t*) (v_data + (mb_y_pos << 4) * v_linesize +

                                    (mb_x_pos << ctx->mb_chroma_factor)),

                       v_linesize, mbs_per_slice, ctx->num_chroma_blocks,

                       slice_width_factor + ctx->chroma_factor - 1,

                       ctx->qmat_chroma_scaled);

    return 0;

}


static av_cold int eightsvx_decode_close(AVCodecContext *avctx)

{

    EightSvxContext *esc = avctx->priv_data;

    av_freep(&esc->samples);

    esc->samples_size = 0;

    esc->samples_idx = 0;

    return 0;

}


static int scale_vaapi_query_formats(AVFilterContext *avctx)

{

    enum AVPixelFormat pix_fmts[] = {

        AV_PIX_FMT_VAAPI, AV_PIX_FMT_NONE,

    };

    ff_formats_ref(ff_make_format_list(pix_fmts),

                   &avctx->inputs[0]->out_formats);

    ff_formats_ref(ff_make_format_list(pix_fmts),

                   &avctx->outputs[0]->in_formats);

    return 0;

}


static int decode_frame(FLACContext *s, int alloc_data_size)

{

    int bs_code, sr_code, bps_code, i;

    int ch_mode, bps, blocksize, samplerate;

    GetBitContext *gb = &s->gb;

    /* frame sync code */

    skip_bits(&s->gb, 16);

    /* block size and sample rate codes */

    bs_code = get_bits(gb, 4);

    sr_code = get_bits(gb, 4);

    /* channels and decorrelation */

    ch_mode = get_bits(gb, 4);

    if (ch_mode < FLAC_MAX_CHANNELS && s->channels == ch_mode+1) {

        ch_mode = FLAC_CHMODE_INDEPENDENT;

    } else if (ch_mode > FLAC_CHMODE_MID_SIDE || s->channels != 2) {

        av_log(s->avctx, AV_LOG_ERROR, "unsupported channel assignment %d (channels=%d)\n",

               ch_mode, s->channels);

        return -1;

    }

    /* bits per sample */

    bps_code = get_bits(gb, 3);

    if (bps_code == 0)

        bps= s->bps;

    else if ((bps_code != 3) && (bps_code != 7))

        bps = sample_size_table[bps_code];

    else {

        av_log(s->avctx, AV_LOG_ERROR, "invalid sample size code (%d)\n",

               bps_code);

        return -1;

    }

    if (bps > 16) {

        s->avctx->sample_fmt = SAMPLE_FMT_S32;

        s->sample_shift = 32 - bps;

        s->is32 = 1;

    } else {

        s->avctx->sample_fmt = SAMPLE_FMT_S16;

        s->sample_shift = 16 - bps;

        s->is32 = 0;

    }

    s->bps = s->avctx->bits_per_raw_sample = bps;

    /* reserved bit */

    if (get_bits1(gb)) {

        av_log(s->avctx, AV_LOG_ERROR, "broken stream, invalid padding\n");

        return -1;

    }

    /* sample or frame count */

    if (get_utf8(gb) < 0) {

        av_log(s->avctx, AV_LOG_ERROR, "utf8 fscked\n");

        return -1;

    }

    /* blocksize */

    if (bs_code == 0) {

        av_log(s->avctx, AV_LOG_ERROR, "reserved blocksize code: 0\n");

        return -1;

    } else if (bs_code == 6)

        blocksize = get_bits(gb, 8)+1;

    else if (bs_code == 7)

        blocksize = get_bits(gb, 16)+1;

    else

        blocksize = ff_flac_blocksize_table[bs_code];

    if (blocksize > s->max_blocksize) {

        av_log(s->avctx, AV_LOG_ERROR, "blocksize %d > %d\n", blocksize,

               s->max_blocksize);

        return -1;

    }

    if (blocksize * s->channels * (s->is32 ? 4 : 2) > alloc_data_size)

        return -1;

    /* sample rate */

    if (sr_code == 0)

        samplerate= s->samplerate;

    else if (sr_code < 12)

        samplerate = ff_flac_sample_rate_table[sr_code];

    else if (sr_code == 12)

        samplerate = get_bits(gb, 8) * 1000;

    else if (sr_code == 13)

        samplerate = get_bits(gb, 16);

    else if (sr_code == 14)

        samplerate = get_bits(gb, 16) * 10;

    else {

        av_log(s->avctx, AV_LOG_ERROR, "illegal sample rate code %d\n",

               sr_code);

        return -1;

    }

    /* header CRC-8 check */

    skip_bits(gb, 8);

    if (av_crc(av_crc_get_table(AV_CRC_8_ATM), 0, gb->buffer,

               get_bits_count(gb)/8)) {

        av_log(s->avctx, AV_LOG_ERROR, "header crc mismatch\n");

        return -1;

    }

    s->blocksize    = blocksize;

    s->samplerate   = samplerate;

    s->bps          = bps;

    s->ch_mode      = ch_mode;

//    dump_headers(s->avctx, (FLACStreaminfo *)s);

    /* subframes */

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

        if (decode_subframe(s, i) < 0)

            return -1;

    }

    align_get_bits(gb);

    /* frame footer */

    skip_bits(gb, 16); /* data crc */

    return 0;

}


static int ftp_getc(FTPContext *s)

{

    int len;

    if (s->control_buf_ptr >= s->control_buf_end) {

        if (s->conn_control_block_flag)

            return AVERROR_EXIT;

        len = ffurl_read(s->conn_control, s->control_buffer, CONTROL_BUFFER_SIZE);

        if (len < 0) {

            return len;

        } else if (!len) {

            return -1;

        } else {

            s->control_buf_ptr = s->control_buffer;

            s->control_buf_end = s->control_buffer + len;

        }

    }

    return *s->control_buf_ptr++;

}


static int filter_frame(AVFilterLink *inlink, AVFrame *in)

{

    AVFilterContext *ctx = inlink->dst;

    HDCDContext *s = ctx->priv;

    AVFilterLink *outlink = ctx->outputs[0];

    AVFrame *out;

    const int16_t *in_data;

    int32_t *out_data;

    int n, c;

    int detect, packets, pe_packets;

    out = ff_get_audio_buffer(outlink, in->nb_samples);

    if (!out) {

        av_frame_free(&in);

        return AVERROR(ENOMEM);

    }

    av_frame_copy_props(out, in);

    out->format = outlink->format;

    in_data  = (int16_t*)in->data[0];

    out_data = (int32_t*)out->data[0];

    for (n = 0; n < in->nb_samples * in->channels; n++) {

        out_data[n] = in_data[n];

    }

    detect = 0;

    packets = 0;

    pe_packets = 0;

    s->det_errors = 0;

    for (c = 0; c < inlink->channels; c++) {

        hdcd_state_t *state = &s->state[c];

        hdcd_process(s, state, out_data + c, in->nb_samples, out->channels);

        if (state->sustain) detect++;

        packets += state->code_counterA + state->code_counterB;

        pe_packets += state->count_peak_extend;

        s->uses_transient_filter |= !!state->count_transient_filter;

        s->max_gain_adjustment = FFMIN(s->max_gain_adjustment, GAINTOFLOAT(state->max_gain));

        s->det_errors += state->code_counterA_almost

            + state->code_counterB_checkfails

            + state->code_counterC_unmatched;

    }

    if (pe_packets) {

        /* if every valid packet has used PE, call it permanent */

        if (packets == pe_packets)

            s->peak_extend = HDCD_PE_PERMANENT;

        else

            s->peak_extend = HDCD_PE_INTERMITTENT;

    } else {

        s->peak_extend = HDCD_PE_NEVER;

    }

    /* HDCD is detected if a valid packet is active in all (both)

     * channels at the same time. */

    if (detect == inlink->channels) s->hdcd_detected = 1;

    s->sample_count += in->nb_samples * in->channels;

    av_frame_free(&in);

    return ff_filter_frame(outlink, out);

}


static TPMVersion tpm_passthrough_get_tpm_version(TPMBackend *tb)

{

    return TPM_VERSION_1_2;

}


static int pci_ich9_ahci_init(PCIDevice *dev)

{

    struct AHCIPCIState *d;

    d = DO_UPCAST(struct AHCIPCIState, card, dev);

    pci_config_set_vendor_id(d->card.config, PCI_VENDOR_ID_INTEL);

    pci_config_set_device_id(d->card.config, PCI_DEVICE_ID_INTEL_82801IR);

    pci_config_set_class(d->card.config, PCI_CLASS_STORAGE_SATA);

    pci_config_set_revision(d->card.config, 0x02);

    pci_config_set_prog_interface(d->card.config, AHCI_PROGMODE_MAJOR_REV_1);

    d->card.config[PCI_CACHE_LINE_SIZE] = 0x08;  /* Cache line size */

    d->card.config[PCI_LATENCY_TIMER]   = 0x00;  /* Latency timer */

    pci_config_set_interrupt_pin(d->card.config, 1);

    /* XXX Software should program this register */

    d->card.config[0x90]   = 1 << 6; /* Address Map Register - AHCI mode */

    qemu_register_reset(ahci_reset, d);

    /* XXX BAR size should be 1k, but that breaks, so bump it to 4k for now */

    pci_register_bar_simple(&d->card, 5, 0x1000, 0, d->ahci.mem);

    msi_init(dev, 0x50, 1, true, false);

    ahci_init(&d->ahci, &dev->qdev, 6);

    d->ahci.irq = d->card.irq[0];

    return 0;

}


static void ppc_core99_init(QEMUMachineInitArgs *args)

{

    ram_addr_t ram_size = args->ram_size;

    const char *cpu_model = args->cpu_model;

    const char *kernel_filename = args->kernel_filename;

    const char *kernel_cmdline = args->kernel_cmdline;

    const char *initrd_filename = args->initrd_filename;

    const char *boot_device = args->boot_device;

    PowerPCCPU *cpu = NULL;

    CPUPPCState *env = NULL;

    char *filename;

    qemu_irq *pic, **openpic_irqs;

    MemoryRegion *unin_memory = g_new(MemoryRegion, 1);

    int linux_boot, i;

    MemoryRegion *ram = g_new(MemoryRegion, 1), *bios = g_new(MemoryRegion, 1);

    hwaddr kernel_base, initrd_base, cmdline_base = 0;

    long kernel_size, initrd_size;

    PCIBus *pci_bus;

    MacIONVRAMState *nvr;

    int bios_size;

    MemoryRegion *pic_mem, *dbdma_mem, *cuda_mem, *escc_mem;

    MemoryRegion *escc_bar = g_new(MemoryRegion, 1);

    MemoryRegion *ide_mem[3];

    int ppc_boot_device;

    DriveInfo *hd[MAX_IDE_BUS * MAX_IDE_DEVS];

    void *fw_cfg;

    void *dbdma;

    int machine_arch;

    linux_boot = (kernel_filename != NULL);

    /* init CPUs */

    if (cpu_model == NULL)

#ifdef TARGET_PPC64

        cpu_model = "970fx";

#else

        cpu_model = "G4";

#endif

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

        cpu = cpu_ppc_init(cpu_model);

        if (cpu == NULL) {

            fprintf(stderr, "Unable to find PowerPC CPU definition\n");

            exit(1);

        }

        env = &cpu->env;

        /* Set time-base frequency to 100 Mhz */

        cpu_ppc_tb_init(env, 100UL * 1000UL * 1000UL);

        qemu_register_reset(ppc_core99_reset, cpu);

    }

    /* allocate RAM */

    memory_region_init_ram(ram, "ppc_core99.ram", ram_size);

    vmstate_register_ram_global(ram);

    memory_region_add_subregion(get_system_memory(), 0, ram);

    /* allocate and load BIOS */

    memory_region_init_ram(bios, "ppc_core99.bios", BIOS_SIZE);

    vmstate_register_ram_global(bios);

    if (bios_name == NULL)

        bios_name = PROM_FILENAME;

    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);

    memory_region_set_readonly(bios, true);

    memory_region_add_subregion(get_system_memory(), PROM_ADDR, bios);

    /* Load OpenBIOS (ELF) */

    if (filename) {

        bios_size = load_elf(filename, NULL, NULL, NULL,

                             NULL, NULL, 1, ELF_MACHINE, 0);

        g_free(filename);

    } else {

        bios_size = -1;

    }

    if (bios_size < 0 || bios_size > BIOS_SIZE) {

        hw_error("qemu: could not load PowerPC bios '%s'\n", bios_name);

        exit(1);

    }

    if (linux_boot) {

        uint64_t lowaddr = 0;

        int bswap_needed;

#ifdef BSWAP_NEEDED

        bswap_needed = 1;

#else

        bswap_needed = 0;

#endif

        kernel_base = KERNEL_LOAD_ADDR;

        kernel_size = load_elf(kernel_filename, translate_kernel_address, NULL,

                               NULL, &lowaddr, NULL, 1, ELF_MACHINE, 0);

        if (kernel_size < 0)

            kernel_size = load_aout(kernel_filename, kernel_base,

                                    ram_size - kernel_base, bswap_needed,

                                    TARGET_PAGE_SIZE);

        if (kernel_size < 0)

            kernel_size = load_image_targphys(kernel_filename,

                                              kernel_base,

                                              ram_size - kernel_base);

        if (kernel_size < 0) {

            hw_error("qemu: could not load kernel '%s'\n", kernel_filename);

            exit(1);

        }

        /* load initrd */

        if (initrd_filename) {

            initrd_base = round_page(kernel_base + kernel_size + KERNEL_GAP);

            initrd_size = load_image_targphys(initrd_filename, initrd_base,

                                              ram_size - initrd_base);

            if (initrd_size < 0) {

                hw_error("qemu: could not load initial ram disk '%s'\n",

                         initrd_filename);

                exit(1);

            }

            cmdline_base = round_page(initrd_base + initrd_size);

        } else {

            initrd_base = 0;

            initrd_size = 0;

            cmdline_base = round_page(kernel_base + kernel_size + KERNEL_GAP);

        }

        ppc_boot_device = 'm';

    } else {

        kernel_base = 0;

        kernel_size = 0;

        initrd_base = 0;

        initrd_size = 0;

        ppc_boot_device = '\0';

        /* We consider that NewWorld PowerMac never have any floppy drive

         * For now, OHW cannot boot from the network.

         */

        for (i = 0; boot_device[i] != '\0'; i++) {

            if (boot_device[i] >= 'c' && boot_device[i] <= 'f') {

                ppc_boot_device = boot_device[i];

                break;

            }

        }

        if (ppc_boot_device == '\0') {

            fprintf(stderr, "No valid boot device for Mac99 machine\n");

            exit(1);

        }

    }

    /* Register 8 MB of ISA IO space */

    isa_mmio_init(0xf2000000, 0x00800000);

    /* UniN init */

    memory_region_init_io(unin_memory, &unin_ops, NULL, "unin", 0x1000);

    memory_region_add_subregion(get_system_memory(), 0xf8000000, unin_memory);

    openpic_irqs = g_malloc0(smp_cpus * sizeof(qemu_irq *));

    openpic_irqs[0] =

        g_malloc0(smp_cpus * sizeof(qemu_irq) * OPENPIC_OUTPUT_NB);

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

        /* Mac99 IRQ connection between OpenPIC outputs pins

         * and PowerPC input pins

         */

        switch (PPC_INPUT(env)) {

        case PPC_FLAGS_INPUT_6xx:

            openpic_irqs[i] = openpic_irqs[0] + (i * OPENPIC_OUTPUT_NB);

            openpic_irqs[i][OPENPIC_OUTPUT_INT] =

                ((qemu_irq *)env->irq_inputs)[PPC6xx_INPUT_INT];

            openpic_irqs[i][OPENPIC_OUTPUT_CINT] =

                ((qemu_irq *)env->irq_inputs)[PPC6xx_INPUT_INT];

            openpic_irqs[i][OPENPIC_OUTPUT_MCK] =

                ((qemu_irq *)env->irq_inputs)[PPC6xx_INPUT_MCP];

            /* Not connected ? */

            openpic_irqs[i][OPENPIC_OUTPUT_DEBUG] = NULL;

            /* Check this */

            openpic_irqs[i][OPENPIC_OUTPUT_RESET] =

                ((qemu_irq *)env->irq_inputs)[PPC6xx_INPUT_HRESET];

            break;

#if defined(TARGET_PPC64)

        case PPC_FLAGS_INPUT_970:

            openpic_irqs[i] = openpic_irqs[0] + (i * OPENPIC_OUTPUT_NB);

            openpic_irqs[i][OPENPIC_OUTPUT_INT] =

                ((qemu_irq *)env->irq_inputs)[PPC970_INPUT_INT];

            openpic_irqs[i][OPENPIC_OUTPUT_CINT] =

                ((qemu_irq *)env->irq_inputs)[PPC970_INPUT_INT];

            openpic_irqs[i][OPENPIC_OUTPUT_MCK] =

                ((qemu_irq *)env->irq_inputs)[PPC970_INPUT_MCP];

            /* Not connected ? */

            openpic_irqs[i][OPENPIC_OUTPUT_DEBUG] = NULL;

            /* Check this */

            openpic_irqs[i][OPENPIC_OUTPUT_RESET] =

                ((qemu_irq *)env->irq_inputs)[PPC970_INPUT_HRESET];

            break;

#endif /* defined(TARGET_PPC64) */

        default:

            hw_error("Bus model not supported on mac99 machine\n");

            exit(1);

        }

    }

    pic = openpic_init(&pic_mem, smp_cpus, openpic_irqs, NULL);

    if (PPC_INPUT(env) == PPC_FLAGS_INPUT_970) {

        /* 970 gets a U3 bus */

        pci_bus = pci_pmac_u3_init(pic, get_system_memory(), get_system_io());

        machine_arch = ARCH_MAC99_U3;

    } else {

        pci_bus = pci_pmac_init(pic, get_system_memory(), get_system_io());

        machine_arch = ARCH_MAC99;

    }

    /* init basic PC hardware */

    pci_vga_init(pci_bus);

    escc_mem = escc_init(0, pic[0x25], pic[0x24],

                         serial_hds[0], serial_hds[1], ESCC_CLOCK, 4);

    memory_region_init_alias(escc_bar, "escc-bar",

                             escc_mem, 0, memory_region_size(escc_mem));

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

        pci_nic_init_nofail(&nd_table[i], "ne2k_pci", NULL);

    ide_drive_get(hd, MAX_IDE_BUS);

    dbdma = DBDMA_init(&dbdma_mem);

    /* We only emulate 2 out of 3 IDE controllers for now */

    ide_mem[0] = NULL;

    ide_mem[1] = pmac_ide_init(hd, pic[0x0d], dbdma, 0x16, pic[0x02]);

    ide_mem[2] = pmac_ide_init(&hd[MAX_IDE_DEVS], pic[0x0e], dbdma, 0x1a, pic[0x02]);

    cuda_init(&cuda_mem, pic[0x19]);

    adb_kbd_init(&adb_bus);

    adb_mouse_init(&adb_bus);

    macio_init(pci_bus, PCI_DEVICE_ID_APPLE_UNI_N_KEYL, 0, pic_mem,

               dbdma_mem, cuda_mem, NULL, 3, ide_mem, escc_bar);

    if (usb_enabled(machine_arch == ARCH_MAC99_U3)) {

        pci_create_simple(pci_bus, -1, "pci-ohci");

        /* U3 needs to use USB for input because Linux doesn't support via-cuda

        on PPC64 */

        if (machine_arch == ARCH_MAC99_U3) {

            usbdevice_create("keyboard");

            usbdevice_create("mouse");

        }

    }

    if (graphic_depth != 15 && graphic_depth != 32 && graphic_depth != 8)

        graphic_depth = 15;

    /* The NewWorld NVRAM is not located in the MacIO device */

    nvr = macio_nvram_init(0x2000, 1);

    pmac_format_nvram_partition(nvr, 0x2000);

    macio_nvram_setup_bar(nvr, get_system_memory(), 0xFFF04000);

    /* No PCI init: the BIOS will do it */

    fw_cfg = fw_cfg_init(0, 0, CFG_ADDR, CFG_ADDR + 2);

    fw_cfg_add_i32(fw_cfg, FW_CFG_ID, 1);

    fw_cfg_add_i64(fw_cfg, FW_CFG_RAM_SIZE, (uint64_t)ram_size);

    fw_cfg_add_i16(fw_cfg, FW_CFG_MACHINE_ID, machine_arch);

    fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_ADDR, kernel_base);

    fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_SIZE, kernel_size);

    if (kernel_cmdline) {

        fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_CMDLINE, cmdline_base);

        pstrcpy_targphys("cmdline", cmdline_base, TARGET_PAGE_SIZE, kernel_cmdline);

    } else {

        fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_CMDLINE, 0);

    }

    fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_ADDR, initrd_base);

    fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_SIZE, initrd_size);

    fw_cfg_add_i16(fw_cfg, FW_CFG_BOOT_DEVICE, ppc_boot_device);

    fw_cfg_add_i16(fw_cfg, FW_CFG_PPC_WIDTH, graphic_width);

    fw_cfg_add_i16(fw_cfg, FW_CFG_PPC_HEIGHT, graphic_height);

    fw_cfg_add_i16(fw_cfg, FW_CFG_PPC_DEPTH, graphic_depth);

    fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_IS_KVM, kvm_enabled());

    if (kvm_enabled()) {

#ifdef CONFIG_KVM

        uint8_t *hypercall;

        fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_TBFREQ, kvmppc_get_tbfreq());

        hypercall = g_malloc(16);

        kvmppc_get_hypercall(env, hypercall, 16);

        fw_cfg_add_bytes(fw_cfg, FW_CFG_PPC_KVM_HC, hypercall, 16);

        fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_KVM_PID, getpid());

#endif

    } else {

        fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_TBFREQ, get_ticks_per_sec());

    }

    qemu_register_boot_set(fw_cfg_boot_set, fw_cfg);

}


static void test_visitor_out_enum(TestOutputVisitorData *data,

                                  const void *unused)

{

    QObject *obj;

    EnumOne i;

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

        visit_type_EnumOne(data->ov, "unused", &i, &error_abort);

        obj = visitor_get(data);

        g_assert(qobject_type(obj) == QTYPE_QSTRING);

        g_assert_cmpstr(qstring_get_str(qobject_to_qstring(obj)), ==,

                        EnumOne_lookup[i]);

        visitor_reset(data);

    }

}


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

{

    PCIAC97LinkState *d = opaque;

    AC97LinkState *s = &d->ac97;

    AC97BusMasterRegs *r = NULL;

    uint32_t index = addr - s->base[1];

    switch (index) {

    case PI_BDBAR:

    case PO_BDBAR:

    case MC_BDBAR:

        r = &s->bm_regs[GET_BM (index)];

        r->bdbar = val & ~3;

        dolog ("BDBAR[%d] <- %#x (bdbar %#x)\n",

               GET_BM (index), val, r->bdbar);

        break;

    case GLOB_CNT:

        if (val & GC_WR)

            warm_reset (s);

        if (val & GC_CR)

            cold_reset (s);

        if (!(val & (GC_WR | GC_CR)))

            s->glob_cnt = val & GC_VALID_MASK;

        dolog ("glob_cnt <- %#x (glob_cnt %#x)\n", val, s->glob_cnt);

        break;

    case GLOB_STA:

        s->glob_sta &= ~(val & GS_WCLEAR_MASK);

        s->glob_sta |= (val & ~(GS_WCLEAR_MASK | GS_RO_MASK)) & GS_VALID_MASK;

        dolog ("glob_sta <- %#x (glob_sta %#x)\n", val, s->glob_sta);

        break;

    default:

        dolog ("U nabm writel %#x <- %#x\n", addr, val);

        break;

    }

}


PCIDevice *pci_get_function_0(PCIDevice *pci_dev)

{

    if(pcie_has_upstream_port(pci_dev)) {

        /* With an upstream PCIe port, we only support 1 device at slot 0 */

        return pci_dev->bus->devices[0];

    } else {

        /* Other bus types might support multiple devices at slots 0-31 */

        return pci_dev->bus->devices[PCI_DEVFN(PCI_SLOT(pci_dev->devfn), 0)];

    }

}


static CharDriverState *qemu_chr_open_stdio(ChardevStdio *opts)

{

    CharDriverState   *chr;

    WinStdioCharState *stdio;

    DWORD              dwMode;

    int                is_console = 0;

    chr   = g_malloc0(sizeof(CharDriverState));

    stdio = g_malloc0(sizeof(WinStdioCharState));

    stdio->hStdIn = GetStdHandle(STD_INPUT_HANDLE);

    if (stdio->hStdIn == INVALID_HANDLE_VALUE) {

        fprintf(stderr, "cannot open stdio: invalid handle\n");

        exit(1);

    }

    is_console = GetConsoleMode(stdio->hStdIn, &dwMode) != 0;

    chr->opaque    = stdio;

    chr->chr_write = win_stdio_write;

    chr->chr_close = win_stdio_close;

    if (is_console) {

        if (qemu_add_wait_object(stdio->hStdIn,

                                 win_stdio_wait_func, chr)) {

            fprintf(stderr, "qemu_add_wait_object: failed\n");

        }

    } else {

        DWORD   dwId;

        stdio->hInputReadyEvent = CreateEvent(NULL, FALSE, FALSE, NULL);

        stdio->hInputDoneEvent  = CreateEvent(NULL, FALSE, FALSE, NULL);

        stdio->hInputThread     = CreateThread(NULL, 0, win_stdio_thread,

                                               chr, 0, &dwId);

        if (stdio->hInputThread == INVALID_HANDLE_VALUE

            || stdio->hInputReadyEvent == INVALID_HANDLE_VALUE

            || stdio->hInputDoneEvent == INVALID_HANDLE_VALUE) {

            fprintf(stderr, "cannot create stdio thread or event\n");

            exit(1);

        }

        if (qemu_add_wait_object(stdio->hInputReadyEvent,

                                 win_stdio_thread_wait_func, chr)) {

            fprintf(stderr, "qemu_add_wait_object: failed\n");

        }

    }

    dwMode |= ENABLE_LINE_INPUT;

    if (is_console) {

        /* set the terminal in raw mode */

        /* ENABLE_QUICK_EDIT_MODE | ENABLE_EXTENDED_FLAGS */

        dwMode |= ENABLE_PROCESSED_INPUT;

    }

    SetConsoleMode(stdio->hStdIn, dwMode);

    chr->chr_set_echo = qemu_chr_set_echo_win_stdio;

    qemu_chr_fe_set_echo(chr, false);

    return chr;

}


static uint64_t spapr_io_read(void *opaque, hwaddr addr,

                              unsigned size)

{

    switch (size) {

    case 1:

        return cpu_inb(addr);

    case 2:

        return cpu_inw(addr);

    case 4:

        return cpu_inl(addr);

    }

    assert(0);

}


av_cold void ff_sws_init_input_funcs(SwsContext *c)

{

    enum AVPixelFormat srcFormat = c->srcFormat;

    c->chrToYV12 = NULL;

    switch (srcFormat) {

    case AV_PIX_FMT_YUYV422:

        c->chrToYV12 = yuy2ToUV_c;

        break;

    case AV_PIX_FMT_YVYU422:

        c->chrToYV12 = yvy2ToUV_c;

        break;

    case AV_PIX_FMT_UYVY422:

        c->chrToYV12 = uyvyToUV_c;

        break;

    case AV_PIX_FMT_NV12:

        c->chrToYV12 = nv12ToUV_c;

        break;

    case AV_PIX_FMT_NV21:

        c->chrToYV12 = nv21ToUV_c;

        break;

    case AV_PIX_FMT_RGB8:

    case AV_PIX_FMT_BGR8:

    case AV_PIX_FMT_PAL8:

    case AV_PIX_FMT_BGR4_BYTE:

    case AV_PIX_FMT_RGB4_BYTE:

        c->chrToYV12 = palToUV_c;

        break;

    case AV_PIX_FMT_GBRP9LE:

        c->readChrPlanar = planar_rgb9le_to_uv;

        break;

    case AV_PIX_FMT_GBRP10LE:

        c->readChrPlanar = planar_rgb10le_to_uv;

        break;

    case AV_PIX_FMT_GBRAP16LE:

    case AV_PIX_FMT_GBRP16LE:

        c->readChrPlanar = planar_rgb16le_to_uv;

        break;

    case AV_PIX_FMT_GBRP9BE:

        c->readChrPlanar = planar_rgb9be_to_uv;

        break;

    case AV_PIX_FMT_GBRP10BE:

        c->readChrPlanar = planar_rgb10be_to_uv;

        break;

    case AV_PIX_FMT_GBRAP16BE:

    case AV_PIX_FMT_GBRP16BE:

        c->readChrPlanar = planar_rgb16be_to_uv;

        break;

    case AV_PIX_FMT_GBRAP:

    case AV_PIX_FMT_GBRP:

        c->readChrPlanar = planar_rgb_to_uv;

        break;

#if HAVE_BIGENDIAN

    case AV_PIX_FMT_YUV444P9LE:

    case AV_PIX_FMT_YUV422P9LE:

    case AV_PIX_FMT_YUV420P9LE:

    case AV_PIX_FMT_YUV422P10LE:

    case AV_PIX_FMT_YUV444P10LE:

    case AV_PIX_FMT_YUV420P10LE:

    case AV_PIX_FMT_YUV420P16LE:

    case AV_PIX_FMT_YUV422P16LE:

    case AV_PIX_FMT_YUV444P16LE:

    case AV_PIX_FMT_YUVA444P9LE:

    case AV_PIX_FMT_YUVA422P9LE:

    case AV_PIX_FMT_YUVA420P9LE:

    case AV_PIX_FMT_YUVA422P10LE:

    case AV_PIX_FMT_YUVA444P10LE:

    case AV_PIX_FMT_YUVA420P10LE:

    case AV_PIX_FMT_YUVA420P16LE:

    case AV_PIX_FMT_YUVA422P16LE:

    case AV_PIX_FMT_YUVA444P16LE:

        c->chrToYV12 = bswap16UV_c;

        break;

#else

    case AV_PIX_FMT_YUV444P9BE:

    case AV_PIX_FMT_YUV422P9BE:

    case AV_PIX_FMT_YUV420P9BE:

    case AV_PIX_FMT_YUV444P10BE:

    case AV_PIX_FMT_YUV422P10BE:

    case AV_PIX_FMT_YUV420P10BE:

    case AV_PIX_FMT_YUV420P16BE:

    case AV_PIX_FMT_YUV422P16BE:

    case AV_PIX_FMT_YUV444P16BE:

    case AV_PIX_FMT_YUVA444P9BE:

    case AV_PIX_FMT_YUVA422P9BE:

    case AV_PIX_FMT_YUVA420P9BE:

    case AV_PIX_FMT_YUVA422P10BE:

    case AV_PIX_FMT_YUVA444P10BE:

    case AV_PIX_FMT_YUVA420P10BE:

    case AV_PIX_FMT_YUVA420P16BE:

    case AV_PIX_FMT_YUVA422P16BE:

    case AV_PIX_FMT_YUVA444P16BE:

        c->chrToYV12 = bswap16UV_c;

        break;

#endif

    case AV_PIX_FMT_P010LE:

        c->chrToYV12 = p010LEToUV_c;

        break;

    case AV_PIX_FMT_P010BE:

        c->chrToYV12 = p010BEToUV_c;

        break;

    }

    if (c->chrSrcHSubSample) {

        switch (srcFormat) {

        case AV_PIX_FMT_RGB48BE:

            c->chrToYV12 = rgb48BEToUV_half_c;

            break;

        case AV_PIX_FMT_RGB48LE:

            c->chrToYV12 = rgb48LEToUV_half_c;

            break;

        case AV_PIX_FMT_BGR48BE:

            c->chrToYV12 = bgr48BEToUV_half_c;

            break;

        case AV_PIX_FMT_BGR48LE:

            c->chrToYV12 = bgr48LEToUV_half_c;

            break;

        case AV_PIX_FMT_RGB32:

            c->chrToYV12 = bgr32ToUV_half_c;

            break;

        case AV_PIX_FMT_RGB32_1:

            c->chrToYV12 = bgr321ToUV_half_c;

            break;

        case AV_PIX_FMT_BGR24:

            c->chrToYV12 = bgr24ToUV_half_c;

            break;

        case AV_PIX_FMT_BGR565LE:

            c->chrToYV12 = bgr16leToUV_half_c;

            break;

        case AV_PIX_FMT_BGR565BE:

            c->chrToYV12 = bgr16beToUV_half_c;

            break;

        case AV_PIX_FMT_BGR555LE:

            c->chrToYV12 = bgr15leToUV_half_c;

            break;

        case AV_PIX_FMT_BGR555BE:

            c->chrToYV12 = bgr15beToUV_half_c;

            break;

        case AV_PIX_FMT_BGR444LE:

            c->chrToYV12 = bgr12leToUV_half_c;

            break;

        case AV_PIX_FMT_BGR444BE:

            c->chrToYV12 = bgr12beToUV_half_c;

            break;

        case AV_PIX_FMT_BGR32:

            c->chrToYV12 = rgb32ToUV_half_c;

            break;

        case AV_PIX_FMT_BGR32_1:

            c->chrToYV12 = rgb321ToUV_half_c;

            break;

        case AV_PIX_FMT_RGB24:

            c->chrToYV12 = rgb24ToUV_half_c;

            break;

        case AV_PIX_FMT_RGB565LE:

            c->chrToYV12 = rgb16leToUV_half_c;

            break;

        case AV_PIX_FMT_RGB565BE:

            c->chrToYV12 = rgb16beToUV_half_c;

            break;

        case AV_PIX_FMT_RGB555LE:

            c->chrToYV12 = rgb15leToUV_half_c;

            break;

        case AV_PIX_FMT_RGB555BE:

            c->chrToYV12 = rgb15beToUV_half_c;

            break;

        case AV_PIX_FMT_RGB444LE:

            c->chrToYV12 = rgb12leToUV_half_c;

            break;

        case AV_PIX_FMT_RGB444BE:

            c->chrToYV12 = rgb12beToUV_half_c;

            break;

        }

    } else {

        switch (srcFormat) {

        case AV_PIX_FMT_RGB48BE:

            c->chrToYV12 = rgb48BEToUV_c;

            break;

        case AV_PIX_FMT_RGB48LE:

            c->chrToYV12 = rgb48LEToUV_c;

            break;

        case AV_PIX_FMT_BGR48BE:

            c->chrToYV12 = bgr48BEToUV_c;

            break;

        case AV_PIX_FMT_BGR48LE:

            c->chrToYV12 = bgr48LEToUV_c;

            break;

        case AV_PIX_FMT_RGB32:

            c->chrToYV12 = bgr32ToUV_c;

            break;

        case AV_PIX_FMT_RGB32_1:

            c->chrToYV12 = bgr321ToUV_c;

            break;

        case AV_PIX_FMT_BGR24:

            c->chrToYV12 = bgr24ToUV_c;

            break;

        case AV_PIX_FMT_BGR565LE:

            c->chrToYV12 = bgr16leToUV_c;

            break;

        case AV_PIX_FMT_BGR565BE:

            c->chrToYV12 = bgr16beToUV_c;

            break;

        case AV_PIX_FMT_BGR555LE:

            c->chrToYV12 = bgr15leToUV_c;

            break;

        case AV_PIX_FMT_BGR555BE:

            c->chrToYV12 = bgr15beToUV_c;

            break;

        case AV_PIX_FMT_BGR444LE:

            c->chrToYV12 = bgr12leToUV_c;

            break;

        case AV_PIX_FMT_BGR444BE:

            c->chrToYV12 = bgr12beToUV_c;

            break;

        case AV_PIX_FMT_BGR32:

            c->chrToYV12 = rgb32ToUV_c;

            break;

        case AV_PIX_FMT_BGR32_1:

            c->chrToYV12 = rgb321ToUV_c;

            break;

        case AV_PIX_FMT_RGB24:

            c->chrToYV12 = rgb24ToUV_c;

            break;

        case AV_PIX_FMT_RGB565LE:

            c->chrToYV12 = rgb16leToUV_c;

            break;

        case AV_PIX_FMT_RGB565BE:

            c->chrToYV12 = rgb16beToUV_c;

            break;

        case AV_PIX_FMT_RGB555LE:

            c->chrToYV12 = rgb15leToUV_c;

            break;

        case AV_PIX_FMT_RGB555BE:

            c->chrToYV12 = rgb15beToUV_c;

            break;

        case AV_PIX_FMT_RGB444LE:

            c->chrToYV12 = rgb12leToUV_c;

            break;

        case AV_PIX_FMT_RGB444BE:

            c->chrToYV12 = rgb12beToUV_c;

            break;

        }

    }

    c->lumToYV12 = NULL;

    c->alpToYV12 = NULL;

    switch (srcFormat) {

    case AV_PIX_FMT_GBRP9LE:

        c->readLumPlanar = planar_rgb9le_to_y;

        break;

    case AV_PIX_FMT_GBRP10LE:

        c->readLumPlanar = planar_rgb10le_to_y;

        break;

    case AV_PIX_FMT_GBRAP16LE:

    case AV_PIX_FMT_GBRP16LE:

        c->readLumPlanar = planar_rgb16le_to_y;

        break;

    case AV_PIX_FMT_GBRP9BE:

        c->readLumPlanar = planar_rgb9be_to_y;

        break;

    case AV_PIX_FMT_GBRP10BE:

        c->readLumPlanar = planar_rgb10be_to_y;

        break;

    case AV_PIX_FMT_GBRAP16BE:

    case AV_PIX_FMT_GBRP16BE:

        c->readLumPlanar = planar_rgb16be_to_y;

        break;

    case AV_PIX_FMT_GBRAP:

        c->readAlpPlanar = planar_rgb_to_a;

    case AV_PIX_FMT_GBRP:

        c->readLumPlanar = planar_rgb_to_y;

        break;

#if HAVE_BIGENDIAN

    case AV_PIX_FMT_YUV444P9LE:

    case AV_PIX_FMT_YUV422P9LE:

    case AV_PIX_FMT_YUV420P9LE:

    case AV_PIX_FMT_YUV444P10LE:

    case AV_PIX_FMT_YUV422P10LE:

    case AV_PIX_FMT_YUV420P10LE:

    case AV_PIX_FMT_YUV420P16LE:

    case AV_PIX_FMT_YUV422P16LE:

    case AV_PIX_FMT_YUV444P16LE:

    case AV_PIX_FMT_GRAY16LE:

        c->lumToYV12 = bswap16Y_c;

        break;

    case AV_PIX_FMT_YUVA444P9LE:

    case AV_PIX_FMT_YUVA422P9LE:

    case AV_PIX_FMT_YUVA420P9LE:

    case AV_PIX_FMT_YUVA444P10LE:

    case AV_PIX_FMT_YUVA422P10LE:

    case AV_PIX_FMT_YUVA420P10LE:

    case AV_PIX_FMT_YUVA420P16LE:

    case AV_PIX_FMT_YUVA422P16LE:

    case AV_PIX_FMT_YUVA444P16LE:

        c->lumToYV12 = bswap16Y_c;

        c->alpToYV12 = bswap16Y_c;

        break;

#else

    case AV_PIX_FMT_YUV444P9BE:

    case AV_PIX_FMT_YUV422P9BE:

    case AV_PIX_FMT_YUV420P9BE:

    case AV_PIX_FMT_YUV444P10BE:

    case AV_PIX_FMT_YUV422P10BE:

    case AV_PIX_FMT_YUV420P10BE:

    case AV_PIX_FMT_YUV420P16BE:

    case AV_PIX_FMT_YUV422P16BE:

    case AV_PIX_FMT_YUV444P16BE:

    case AV_PIX_FMT_GRAY16BE:

        c->lumToYV12 = bswap16Y_c;

        break;

    case AV_PIX_FMT_YUVA444P9BE:

    case AV_PIX_FMT_YUVA422P9BE:

    case AV_PIX_FMT_YUVA420P9BE:

    case AV_PIX_FMT_YUVA444P10BE:

    case AV_PIX_FMT_YUVA422P10BE:

    case AV_PIX_FMT_YUVA420P10BE:

    case AV_PIX_FMT_YUVA420P16BE:

    case AV_PIX_FMT_YUVA422P16BE:

    case AV_PIX_FMT_YUVA444P16BE:

        c->lumToYV12 = bswap16Y_c;

        c->alpToYV12 = bswap16Y_c;

        break;

#endif

    case AV_PIX_FMT_YA16LE:

        c->lumToYV12 = read_ya16le_gray_c;

        c->alpToYV12 = read_ya16le_alpha_c;

        break;

    case AV_PIX_FMT_YA16BE:

        c->lumToYV12 = read_ya16be_gray_c;

        c->alpToYV12 = read_ya16be_alpha_c;

        break;

    case AV_PIX_FMT_YUYV422:

    case AV_PIX_FMT_YVYU422:

    case AV_PIX_FMT_YA8:

        c->lumToYV12 = yuy2ToY_c;

        break;

    case AV_PIX_FMT_UYVY422:

        c->lumToYV12 = uyvyToY_c;

        break;

    case AV_PIX_FMT_BGR24:

        c->lumToYV12 = bgr24ToY_c;

        break;

    case AV_PIX_FMT_BGR565LE:

        c->lumToYV12 = bgr16leToY_c;

        break;

    case AV_PIX_FMT_BGR565BE:

        c->lumToYV12 = bgr16beToY_c;

        break;

    case AV_PIX_FMT_BGR555LE:

        c->lumToYV12 = bgr15leToY_c;

        break;

    case AV_PIX_FMT_BGR555BE:

        c->lumToYV12 = bgr15beToY_c;

        break;

    case AV_PIX_FMT_BGR444LE:

        c->lumToYV12 = bgr12leToY_c;

        break;

    case AV_PIX_FMT_BGR444BE:

        c->lumToYV12 = bgr12beToY_c;

        break;

    case AV_PIX_FMT_RGB24:

        c->lumToYV12 = rgb24ToY_c;

        break;

    case AV_PIX_FMT_RGB565LE:

        c->lumToYV12 = rgb16leToY_c;

        break;

    case AV_PIX_FMT_RGB565BE:

        c->lumToYV12 = rgb16beToY_c;

        break;

    case AV_PIX_FMT_RGB555LE:

        c->lumToYV12 = rgb15leToY_c;

        break;

    case AV_PIX_FMT_RGB555BE:

        c->lumToYV12 = rgb15beToY_c;

        break;

    case AV_PIX_FMT_RGB444LE:

        c->lumToYV12 = rgb12leToY_c;

        break;

    case AV_PIX_FMT_RGB444BE:

        c->lumToYV12 = rgb12beToY_c;

        break;

    case AV_PIX_FMT_RGB8:

    case AV_PIX_FMT_BGR8:

    case AV_PIX_FMT_PAL8:

    case AV_PIX_FMT_BGR4_BYTE:

    case AV_PIX_FMT_RGB4_BYTE:

        c->lumToYV12 = palToY_c;

        break;

    case AV_PIX_FMT_MONOBLACK:

        c->lumToYV12 = monoblack2Y_c;

        break;

    case AV_PIX_FMT_MONOWHITE:

        c->lumToYV12 = monowhite2Y_c;

        break;

    case AV_PIX_FMT_RGB32:

        c->lumToYV12 = bgr32ToY_c;

        break;

    case AV_PIX_FMT_RGB32_1:

        c->lumToYV12 = bgr321ToY_c;

        break;

    case AV_PIX_FMT_BGR32:

        c->lumToYV12 = rgb32ToY_c;

        break;

    case AV_PIX_FMT_BGR32_1:

        c->lumToYV12 = rgb321ToY_c;

        break;

    case AV_PIX_FMT_RGB48BE:

        c->lumToYV12 = rgb48BEToY_c;

        break;

    case AV_PIX_FMT_RGB48LE:

        c->lumToYV12 = rgb48LEToY_c;

        break;

    case AV_PIX_FMT_BGR48BE:

        c->lumToYV12 = bgr48BEToY_c;

        break;

    case AV_PIX_FMT_BGR48LE:

        c->lumToYV12 = bgr48LEToY_c;

        break;

    case AV_PIX_FMT_P010LE:

        c->lumToYV12 = p010LEToY_c;

        break;

    case AV_PIX_FMT_P010BE:

        c->lumToYV12 = p010BEToY_c;

        break;

    }

    if (c->alpPixBuf) {

        switch (srcFormat) {

        case AV_PIX_FMT_BGRA:

        case AV_PIX_FMT_RGBA:

            c->alpToYV12 = rgbaToA_c;

            break;

        case AV_PIX_FMT_ABGR:

        case AV_PIX_FMT_ARGB:

            c->alpToYV12 = abgrToA_c;

            break;

        case AV_PIX_FMT_YA8:

            c->alpToYV12 = uyvyToY_c;

            break;

        }

    }

}


int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)

{

    BlockDriver *drv = bs->drv;

    if (!drv)

        return -ENOMEDIUM;

    if (!drv->bdrv_get_info)

        return -ENOTSUP;

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

    return drv->bdrv_get_info(bs, bdi);

}


static int loadvm_postcopy_handle_advise(MigrationIncomingState *mis)

{

    PostcopyState ps = postcopy_state_set(POSTCOPY_INCOMING_ADVISE);

    uint64_t remote_pagesize_summary, local_pagesize_summary, remote_tps;

    trace_loadvm_postcopy_handle_advise();

    if (ps != POSTCOPY_INCOMING_NONE) {

        error_report("CMD_POSTCOPY_ADVISE in wrong postcopy state (%d)", ps);

        return -1;

    }

    if (!migrate_postcopy_ram()) {

        return 0;

    }

    if (!postcopy_ram_supported_by_host()) {

        postcopy_state_set(POSTCOPY_INCOMING_NONE);

        return -1;

    }

    remote_pagesize_summary = qemu_get_be64(mis->from_src_file);

    local_pagesize_summary = ram_pagesize_summary();

    if (remote_pagesize_summary != local_pagesize_summary)  {

        /*

         * This detects two potential causes of mismatch:

         *   a) A mismatch in host page sizes

         *      Some combinations of mismatch are probably possible but it gets

         *      a bit more complicated.  In particular we need to place whole

         *      host pages on the dest at once, and we need to ensure that we

         *      handle dirtying to make sure we never end up sending part of

         *      a hostpage on it's own.

         *   b) The use of different huge page sizes on source/destination

         *      a more fine grain test is performed during RAM block migration

         *      but this test here causes a nice early clear failure, and

         *      also fails when passed to an older qemu that doesn't

         *      do huge pages.

         */

        error_report("Postcopy needs matching RAM page sizes (s=%" PRIx64

                                                             " d=%" PRIx64 ")",

                     remote_pagesize_summary, local_pagesize_summary);

        return -1;

    }

    remote_tps = qemu_get_be64(mis->from_src_file);

    if (remote_tps != qemu_target_page_size()) {

        /*

         * Again, some differences could be dealt with, but for now keep it

         * simple.

         */

        error_report("Postcopy needs matching target page sizes (s=%d d=%zd)",

                     (int)remote_tps, qemu_target_page_size());

        return -1;

    }

    if (ram_postcopy_incoming_init(mis)) {

        return -1;

    }

    postcopy_state_set(POSTCOPY_INCOMING_ADVISE);

    return 0;

}


coroutine_fn iscsi_co_discard(BlockDriverState *bs, int64_t sector_num,

                                   int nb_sectors)

{

    IscsiLun *iscsilun = bs->opaque;

    struct IscsiTask iTask;

    struct unmap_list list;

    uint32_t nb_blocks;

    uint32_t max_unmap;

    if (!is_request_lun_aligned(sector_num, nb_sectors, iscsilun)) {

        return -EINVAL;

    }

    if (!iscsilun->lbp.lbpu) {

        /* UNMAP is not supported by the target */

        return 0;

    }

    list.lba = sector_qemu2lun(sector_num, iscsilun);

    nb_blocks = sector_qemu2lun(nb_sectors, iscsilun);

    max_unmap = iscsilun->bl.max_unmap;

    if (max_unmap == 0xffffffff) {

        max_unmap = ISCSI_MAX_UNMAP;

    }

    while (nb_blocks > 0) {

        iscsi_co_init_iscsitask(iscsilun, &iTask);

        list.num = nb_blocks;

        if (list.num > max_unmap) {

            list.num = max_unmap;

        }

retry:

        if (iscsi_unmap_task(iscsilun->iscsi, iscsilun->lun, 0, 0, &list, 1,

                         iscsi_co_generic_cb, &iTask) == NULL) {

            return -EIO;

        }

        while (!iTask.complete) {

            iscsi_set_events(iscsilun);

            qemu_coroutine_yield();

        }

        if (iTask.task != NULL) {

            scsi_free_scsi_task(iTask.task);

            iTask.task = NULL;

        }

        if (iTask.do_retry) {

            goto retry;

        }

        if (iTask.status == SCSI_STATUS_CHECK_CONDITION) {

            /* the target might fail with a check condition if it

               is not happy with the alignment of the UNMAP request

               we silently fail in this case */

            return 0;

        }

        if (iTask.status != SCSI_STATUS_GOOD) {

            return -EIO;

        }

        list.lba += list.num;

        nb_blocks -= list.num;

    }

    return 0;

}


ssize_t qemu_sendv_packet(VLANClientState *sender, const struct iovec *iov,

                          int iovcnt)

{

    VLANState *vlan = sender->vlan;

    VLANClientState *vc;

    VLANPacket *packet;

    ssize_t max_len = 0;

    int i;

    if (sender->link_down)

        return calc_iov_length(iov, iovcnt);

    if (vlan->delivering) {

        max_len = calc_iov_length(iov, iovcnt);

        packet = qemu_malloc(sizeof(VLANPacket) + max_len);

        packet->next = vlan->send_queue;

        packet->sender = sender;

        packet->size = 0;

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

            size_t len = iov[i].iov_len;

            memcpy(packet->data + packet->size, iov[i].iov_base, len);

            packet->size += len;

        }

        vlan->send_queue = packet;

    } else {

        vlan->delivering = 1;

        for (vc = vlan->first_client; vc != NULL; vc = vc->next) {

            ssize_t len = 0;

            if (vc == sender) {

                continue;

            }

            if (vc->link_down) {

                len = calc_iov_length(iov, iovcnt);

            } else if (vc->receive_iov) {

                len = vc->receive_iov(vc->opaque, iov, iovcnt);

            } else if (vc->receive) {

                len = vc_sendv_compat(vc, iov, iovcnt);

            }

            max_len = MAX(max_len, len);

        }

        while ((packet = vlan->send_queue) != NULL) {

            vlan->send_queue = packet->next;

            qemu_deliver_packet(packet->sender, packet->data, packet->size);

            qemu_free(packet);

        }

        vlan->delivering = 0;

    }

    return max_len;

}


uint64_t float64_to_uint64 (float64 a STATUS_PARAM)

{

    int64_t v;

    v = int64_to_float64(INT64_MIN STATUS_VAR);

    v = float64_to_int64((a + v) STATUS_VAR);

    return v - INT64_MIN;

}


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

{

    XICSState *icp = XICS(dev);

    ICSState *ics = icp->ics;

    Error *error = NULL;

    int i;

    if (!icp->nr_servers) {

        error_setg(errp, "Number of servers needs to be greater 0");

        return;

    }

    /* Registration of global state belongs into realize */

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

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

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

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

    spapr_register_hypercall(H_CPPR, h_cppr);

    spapr_register_hypercall(H_IPI, h_ipi);

    spapr_register_hypercall(H_XIRR, h_xirr);

    spapr_register_hypercall(H_EOI, h_eoi);

    ics->nr_irqs = icp->nr_irqs;

    ics->offset = XICS_IRQ_BASE;

    ics->icp = icp;

    object_property_set_bool(OBJECT(icp->ics), true, "realized", &error);

    if (error) {

        error_propagate(errp, error);

        return;

    }

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

    for (i = 0; i < icp->nr_servers; i++) {

        char buffer[32];

        object_initialize(&icp->ss[i], sizeof(icp->ss[i]), TYPE_ICP);

        snprintf(buffer, sizeof(buffer), "icp[%d]", i);

        object_property_add_child(OBJECT(icp), buffer, OBJECT(&icp->ss[i]), NULL);

        object_property_set_bool(OBJECT(&icp->ss[i]), true, "realized", &error);

        if (error) {

            error_propagate(errp, error);

            return;

        }

    }

}


static void common_init(MpegEncContext * s)

{

    static int inited=0;

    switch(s->msmpeg4_version){

    case 1:

    case 2:

        s->y_dc_scale_table=

        s->c_dc_scale_table= ff_mpeg1_dc_scale_table;

        break;

    case 3:

        if(s->workaround_bugs){

            s->y_dc_scale_table= old_ff_y_dc_scale_table;

            s->c_dc_scale_table= old_ff_c_dc_scale_table;

        } else{

            s->y_dc_scale_table= ff_mpeg4_y_dc_scale_table;

            s->c_dc_scale_table= ff_mpeg4_c_dc_scale_table;

        }

        break;

    case 4:

    case 5:

        s->y_dc_scale_table= wmv1_y_dc_scale_table;

        s->c_dc_scale_table= wmv1_c_dc_scale_table;

        break;

#if defined(CONFIG_WMV3_DECODER)||defined(CONFIG_VC1_DECODER)

    case 6:

        s->y_dc_scale_table= wmv3_dc_scale_table;

        s->c_dc_scale_table= wmv3_dc_scale_table;

        break;

#endif

    }

    if(s->msmpeg4_version>=4){

        ff_init_scantable(s->dsp.idct_permutation, &s->intra_scantable  , wmv1_scantable[1]);

        ff_init_scantable(s->dsp.idct_permutation, &s->intra_h_scantable, wmv1_scantable[2]);

        ff_init_scantable(s->dsp.idct_permutation, &s->intra_v_scantable, wmv1_scantable[3]);

        ff_init_scantable(s->dsp.idct_permutation, &s->inter_scantable  , wmv1_scantable[0]);

    }

    //Note the default tables are set in common_init in mpegvideo.c

    if(!inited){

        inited=1;

        init_h263_dc_for_msmpeg4();

    }

}


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

                    const char *name, Error **errp)

{

    DeviceState *dev = DEVICE(obj);

    Property *prop = opaque;

    uint32_t *p = qdev_get_prop_ptr(dev, prop);

    bool value = (*p & qdev_get_prop_mask(prop)) != 0;

    visit_type_bool(v, &value, name, errp);

}


static uint32_t virtio_ioport_read(VirtIOPCIProxy *proxy, uint32_t addr)

{

    VirtIODevice *vdev = proxy->vdev;

    uint32_t ret = 0xFFFFFFFF;

    switch (addr) {

    case VIRTIO_PCI_HOST_FEATURES:

        ret = vdev->get_features(vdev);

        ret |= vdev->binding->get_features(proxy);

        break;

    case VIRTIO_PCI_GUEST_FEATURES:

        ret = vdev->guest_features;

        break;

    case VIRTIO_PCI_QUEUE_PFN:

        ret = virtio_queue_get_addr(vdev, vdev->queue_sel)

              >> VIRTIO_PCI_QUEUE_ADDR_SHIFT;

        break;

    case VIRTIO_PCI_QUEUE_NUM:

        ret = virtio_queue_get_num(vdev, vdev->queue_sel);

        break;

    case VIRTIO_PCI_QUEUE_SEL:

        ret = vdev->queue_sel;

        break;

    case VIRTIO_PCI_STATUS:

        ret = vdev->status;

        break;

    case VIRTIO_PCI_ISR:

        /* reading from the ISR also clears it. */

        ret = vdev->isr;

        vdev->isr = 0;

        qemu_set_irq(proxy->pci_dev.irq[0], 0);

        break;

    case VIRTIO_MSI_CONFIG_VECTOR:

        ret = vdev->config_vector;

        break;

    case VIRTIO_MSI_QUEUE_VECTOR:

        ret = virtio_queue_vector(vdev, vdev->queue_sel);

        break;

    default:

        break;

    }

    return ret;

}


static uint64_t onenand_read(void *opaque, hwaddr addr,

                             unsigned size)

{

    OneNANDState *s = (OneNANDState *) opaque;

    int offset = addr >> s->shift;

    switch (offset) {

    case 0x0000 ... 0xc000:

        return lduw_le_p(s->boot[0] + addr);

    case 0xf000:	/* Manufacturer ID */

        return s->id.man;

    case 0xf001:	/* Device ID */

        return s->id.dev;

    case 0xf002:	/* Version ID */

        return s->id.ver;

    /* TODO: get the following values from a real chip!  */

    case 0xf003:	/* Data Buffer size */

        return 1 << PAGE_SHIFT;

    case 0xf004:	/* Boot Buffer size */

        return 0x200;

    case 0xf005:	/* Amount of buffers */

        return 1 | (2 << 8);

    case 0xf006:	/* Technology */

        return 0;

    case 0xf100 ... 0xf107:	/* Start addresses */

        return s->addr[offset - 0xf100];

    case 0xf200:	/* Start buffer */

        return (s->bufaddr << 8) | ((s->count - 1) & (1 << (PAGE_SHIFT - 10)));

    case 0xf220:	/* Command */

        return s->command;

    case 0xf221:	/* System Configuration 1 */

        return s->config[0] & 0xffe0;

    case 0xf222:	/* System Configuration 2 */

        return s->config[1];

    case 0xf240:	/* Controller Status */

        return s->status;

    case 0xf241:	/* Interrupt */

        return s->intstatus;

    case 0xf24c:	/* Unlock Start Block Address */

        return s->unladdr[0];

    case 0xf24d:	/* Unlock End Block Address */

        return s->unladdr[1];

    case 0xf24e:	/* Write Protection Status */

        return s->wpstatus;

    case 0xff00:	/* ECC Status */

        return 0x00;

    case 0xff01:	/* ECC Result of main area data */

    case 0xff02:	/* ECC Result of spare area data */

    case 0xff03:	/* ECC Result of main area data */

    case 0xff04:	/* ECC Result of spare area data */

        hw_error("%s: imeplement ECC\n", __FUNCTION__);

        return 0x0000;

    }

    fprintf(stderr, "%s: unknown OneNAND register %x\n",

                    __FUNCTION__, offset);

    return 0;

}


static int handle_copied(BlockDriverState *bs, uint64_t guest_offset,

    uint64_t *host_offset, uint64_t *bytes, QCowL2Meta **m)

{

    BDRVQcow2State *s = bs->opaque;

    int l2_index;

    uint64_t cluster_offset;

    uint64_t *l2_table;

    unsigned int nb_clusters;

    unsigned int keep_clusters;

    int ret;

    trace_qcow2_handle_copied(qemu_coroutine_self(), guest_offset, *host_offset,

                              *bytes);

    assert(*host_offset == 0 ||    offset_into_cluster(s, guest_offset)

                                == offset_into_cluster(s, *host_offset));

    /*

     * Calculate the number of clusters to look for. We stop at L2 table

     * boundaries to keep things simple.

     */

    nb_clusters =

        size_to_clusters(s, offset_into_cluster(s, guest_offset) + *bytes);

    l2_index = offset_to_l2_index(s, guest_offset);

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

    /* Find L2 entry for the first involved cluster */

    ret = get_cluster_table(bs, guest_offset, &l2_table, &l2_index);

    if (ret < 0) {

        return ret;

    }

    cluster_offset = be64_to_cpu(l2_table[l2_index]);

    /* Check how many clusters are already allocated and don't need COW */

    if (qcow2_get_cluster_type(cluster_offset) == QCOW2_CLUSTER_NORMAL

        && (cluster_offset & QCOW_OFLAG_COPIED))

    {

        /* If a specific host_offset is required, check it */

        bool offset_matches =

            (cluster_offset & L2E_OFFSET_MASK) == *host_offset;

        if (offset_into_cluster(s, cluster_offset & L2E_OFFSET_MASK)) {

            qcow2_signal_corruption(bs, true, -1, -1, "Data cluster offset "

                                    "%#llx unaligned (guest offset: %#" PRIx64

                                    ")", cluster_offset & L2E_OFFSET_MASK,

                                    guest_offset);

            ret = -EIO;

            goto out;

        }

        if (*host_offset != 0 && !offset_matches) {

            *bytes = 0;

            ret = 0;

            goto out;

        }

        /* We keep all QCOW_OFLAG_COPIED clusters */

        keep_clusters =

            count_contiguous_clusters(nb_clusters, s->cluster_size,

                                      &l2_table[l2_index],

                                      QCOW_OFLAG_COPIED | QCOW_OFLAG_ZERO);

        assert(keep_clusters <= nb_clusters);

        *bytes = MIN(*bytes,

                 keep_clusters * s->cluster_size

                 - offset_into_cluster(s, guest_offset));

        ret = 1;

    } else {

        ret = 0;

    }

    /* Cleanup */

out:

    qcow2_cache_put(bs, s->l2_table_cache, (void **) &l2_table);

    /* Only return a host offset if we actually made progress. Otherwise we

     * would make requirements for handle_alloc() that it can't fulfill */

    if (ret > 0) {

        *host_offset = (cluster_offset & L2E_OFFSET_MASK)

                     + offset_into_cluster(s, guest_offset);

    }

    return ret;

}


int css_do_xsch(SubchDev *sch)

{

    SCSW *s = &sch->curr_status.scsw;

    PMCW *p = &sch->curr_status.pmcw;

    int ret;

    if (~(p->flags) & (PMCW_FLAGS_MASK_DNV | PMCW_FLAGS_MASK_ENA)) {

        ret = -ENODEV;

        goto out;

    }

    if (!(s->ctrl & SCSW_CTRL_MASK_FCTL) ||

        ((s->ctrl & SCSW_CTRL_MASK_FCTL) != SCSW_FCTL_START_FUNC) ||

        (!(s->ctrl &

           (SCSW_ACTL_RESUME_PEND | SCSW_ACTL_START_PEND | SCSW_ACTL_SUSP))) ||

        (s->ctrl & SCSW_ACTL_SUBCH_ACTIVE)) {

        ret = -EINPROGRESS;

        goto out;

    }

    if (s->ctrl & SCSW_CTRL_MASK_STCTL) {

        ret = -EBUSY;

        goto out;

    }

    /* Cancel the current operation. */

    s->ctrl &= ~(SCSW_FCTL_START_FUNC |

                 SCSW_ACTL_RESUME_PEND |

                 SCSW_ACTL_START_PEND |

                 SCSW_ACTL_SUSP);

    sch->channel_prog = 0x0;

    sch->last_cmd_valid = false;

    s->dstat = 0;

    s->cstat = 0;

    ret = 0;

out:

    return ret;

}


static int proxy_link(FsContext *ctx, V9fsPath *oldpath,

                      V9fsPath *dirpath, const char *name)

{

    int retval;

    V9fsString newpath;

    v9fs_string_init(&newpath);

    v9fs_string_sprintf(&newpath, "%s/%s", dirpath->data, name);

    retval = v9fs_request(ctx->private, T_LINK, NULL, "ss", oldpath, &newpath);

    v9fs_string_free(&newpath);

    if (retval < 0) {

        errno = -retval;

        retval = -1;

    }

    return retval;

}


static int read_packet(AVFormatContext *s,

                          AVPacket *pkt)

{

    ByteIOContext *pb = s->pb;

    PutBitContext pbo;

    uint16_t buf[8 * MAX_FRAME_SIZE + 2];

    int packet_size;

    int sync;

    uint16_t* src=buf;

    int i, j, ret;

    if(url_feof(pb))

        return AVERROR_EOF;

    sync = get_le16(pb); // sync word

    packet_size = get_le16(pb) / 8;

    assert(packet_size < 8 * MAX_FRAME_SIZE);

    ret = get_buffer(pb, (uint8_t*)buf, (8 * packet_size) * sizeof(uint16_t));

    if(ret<0)

        return ret;

    if(ret != 8 * packet_size * sizeof(uint16_t))

        return AVERROR(EIO);

    av_new_packet(pkt, packet_size);

    init_put_bits(&pbo, pkt->data, packet_size);

    for(j=0; j < packet_size; j++)

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

            put_bits(&pbo,1, AV_RL16(src++) == BIT_1 ? 1 : 0);

    flush_put_bits(&pbo);

    pkt->duration=1;

    return 0;

}


void tcg_dump_info(FILE *f,

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

{

    TCGContext *s = &tcg_ctx;

    int64_t tot;

    tot = s->interm_time + s->code_time;

    cpu_fprintf(f, "JIT cycles          %" PRId64 " (%0.3f s at 2.4 GHz)\n",

                tot, tot / 2.4e9);

    cpu_fprintf(f, "translated TBs      %" PRId64 " (aborted=%" PRId64 " %0.1f%%)\n",

                s->tb_count,

                s->tb_count1 - s->tb_count,

                s->tb_count1 ? (double)(s->tb_count1 - s->tb_count) / s->tb_count1 * 100.0 : 0);

    cpu_fprintf(f, "avg ops/TB          %0.1f max=%d\n",

                s->tb_count ? (double)s->op_count / s->tb_count : 0, s->op_count_max);

    cpu_fprintf(f, "deleted ops/TB      %0.2f\n",

                s->tb_count ?

                (double)s->del_op_count / s->tb_count : 0);

    cpu_fprintf(f, "avg temps/TB        %0.2f max=%d\n",

                s->tb_count ?

                (double)s->temp_count / s->tb_count : 0,

                s->temp_count_max);

    cpu_fprintf(f, "cycles/op           %0.1f\n",

                s->op_count ? (double)tot / s->op_count : 0);

    cpu_fprintf(f, "cycles/in byte      %0.1f\n",

                s->code_in_len ? (double)tot / s->code_in_len : 0);

    cpu_fprintf(f, "cycles/out byte     %0.1f\n",

                s->code_out_len ? (double)tot / s->code_out_len : 0);

    if (tot == 0)

        tot = 1;

    cpu_fprintf(f, "  gen_interm time   %0.1f%%\n",

                (double)s->interm_time / tot * 100.0);

    cpu_fprintf(f, "  gen_code time     %0.1f%%\n",

                (double)s->code_time / tot * 100.0);

    cpu_fprintf(f, "liveness/code time  %0.1f%%\n",

                (double)s->la_time / (s->code_time ? s->code_time : 1) * 100.0);

    cpu_fprintf(f, "cpu_restore count   %" PRId64 "\n",

                s->restore_count);

    cpu_fprintf(f, "  avg cycles        %0.1f\n",

                s->restore_count ? (double)s->restore_time / s->restore_count : 0);

    dump_op_count();

}


INLINE float32 packFloat32( flag zSign, int16 zExp, bits32 zSig )

{

    return ( ( (bits32) zSign )<<31 ) + ( ( (bits32) zExp )<<23 ) + zSig;

}


static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,

    int num_reqs, MultiwriteCB *mcb)

{

    int i, outidx;

    // Sort requests by start sector

    qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);

    // Check if adjacent requests touch the same clusters. If so, combine them,

    // filling up gaps with zero sectors.

    outidx = 0;

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

        int merge = 0;

        int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;

        // This handles the cases that are valid for all block drivers, namely

        // exactly sequential writes and overlapping writes.

        if (reqs[i].sector <= oldreq_last) {

            merge = 1;

        }

        // The block driver may decide that it makes sense to combine requests

        // even if there is a gap of some sectors between them. In this case,

        // the gap is filled with zeros (therefore only applicable for yet

        // unused space in format like qcow2).

        if (!merge && bs->drv->bdrv_merge_requests) {

            merge = bs->drv->bdrv_merge_requests(bs, &reqs[outidx], &reqs[i]);

        }

        if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {

            merge = 0;

        }

        if (merge) {

            size_t size;

            QEMUIOVector *qiov = qemu_mallocz(sizeof(*qiov));

            qemu_iovec_init(qiov,

                reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);

            // Add the first request to the merged one. If the requests are

            // overlapping, drop the last sectors of the first request.

            size = (reqs[i].sector - reqs[outidx].sector) << 9;

            qemu_iovec_concat(qiov, reqs[outidx].qiov, size);

            // We might need to add some zeros between the two requests

            if (reqs[i].sector > oldreq_last) {

                size_t zero_bytes = (reqs[i].sector - oldreq_last) << 9;

                uint8_t *buf = qemu_blockalign(bs, zero_bytes);

                memset(buf, 0, zero_bytes);

                qemu_iovec_add(qiov, buf, zero_bytes);

                mcb->callbacks[i].free_buf = buf;

            }

            // Add the second request

            qemu_iovec_concat(qiov, reqs[i].qiov, reqs[i].qiov->size);

            reqs[outidx].nb_sectors += reqs[i].nb_sectors;

            reqs[outidx].qiov = qiov;

            mcb->callbacks[i].free_qiov = reqs[outidx].qiov;

        } else {

            outidx++;

            reqs[outidx].sector     = reqs[i].sector;

            reqs[outidx].nb_sectors = reqs[i].nb_sectors;

            reqs[outidx].qiov       = reqs[i].qiov;

        }

    }

    return outidx + 1;

}


static void termsig_handler(int signum)

{

    static int sigterm_reported;

    if (!sigterm_reported) {

        sigterm_reported = (write(sigterm_wfd, "", 1) == 1);

    }

}


void HELPER(ipte)(CPUS390XState *env, uint64_t pto, uint64_t vaddr,

                  uint32_t m4)

{

    CPUState *cs = CPU(s390_env_get_cpu(env));

    uint64_t page = vaddr & TARGET_PAGE_MASK;

    uint64_t pte_addr, pte;

    /* Compute the page table entry address */

    pte_addr = (pto & _SEGMENT_ENTRY_ORIGIN);

    pte_addr += (vaddr & VADDR_PX) >> 9;

    /* Mark the page table entry as invalid */

    pte = ldq_phys(cs->as, pte_addr);

    pte |= _PAGE_INVALID;

    stq_phys(cs->as, pte_addr, pte);

    /* XXX we exploit the fact that Linux passes the exact virtual

       address here - it's not obliged to! */

    if (m4 & 1) {

        tlb_flush_page(cs, page);

    } else {

        tlb_flush_page_all_cpus_synced(cs, page);

    }

    /* XXX 31-bit hack */

    if (m4 & 1) {

        tlb_flush_page(cs, page ^ 0x80000000);

    } else {

        tlb_flush_page_all_cpus_synced(cs, page ^ 0x80000000);

    }

}


static int coroutine_fn bdrv_aligned_pwritev(BlockDriverState *bs,

    BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,

    QEMUIOVector *qiov, int flags)

{

    BlockDriver *drv = bs->drv;

    int ret;

    int64_t sector_num = offset >> BDRV_SECTOR_BITS;

    unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS;

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

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

    if (bs->copy_on_read_in_flight) {

        wait_for_overlapping_requests(bs, req, offset, bytes);

    }

    ret = notifier_with_return_list_notify(&bs->before_write_notifiers, req);

    if (ret < 0) {

        /* Do nothing, write notifier decided to fail this request */

    } else if (flags & BDRV_REQ_ZERO_WRITE) {

        ret = bdrv_co_do_write_zeroes(bs, sector_num, nb_sectors, flags);

    } else {

        ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);

    }

    if (ret == 0 && !bs->enable_write_cache) {

        ret = bdrv_co_flush(bs);

    }

    bdrv_set_dirty(bs, sector_num, nb_sectors);

    if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {

        bs->wr_highest_sector = sector_num + nb_sectors - 1;

    }

    if (bs->growable && ret >= 0) {

        bs->total_sectors = MAX(bs->total_sectors, sector_num + nb_sectors);

    }

    return ret;

}


static void handle_sync(DisasContext *s, uint32_t insn,

                        unsigned int op1, unsigned int op2, unsigned int crm)

{

    if (op1 != 3) {

        unallocated_encoding(s);

        return;

    }

    switch (op2) {

    case 2: /* CLREX */

        gen_clrex(s, insn);

        return;

    case 4: /* DSB */

    case 5: /* DMB */

    case 6: /* ISB */

        /* We don't emulate caches so barriers are no-ops */

        return;

    default:

        unallocated_encoding(s);

        return;

    }

}


static int dv_encode_video_segment(AVCodecContext *avctx, DVwork_chunk *work_chunk)

{

    DVVideoContext *s = avctx->priv_data;

    int mb_index, i, j;

    int mb_x, mb_y, c_offset, linesize;

    uint8_t*  y_ptr;

    uint8_t*  data;

    uint8_t*  dif;

    uint8_t   scratch[64];

    EncBlockInfo  enc_blks[5*DV_MAX_BPM];

    PutBitContext pbs[5*DV_MAX_BPM];

    PutBitContext* pb;

    EncBlockInfo* enc_blk;

    int       vs_bit_size = 0;

    int       qnos[5] = {15, 15, 15, 15, 15}; /* No quantization */

    int*      qnosp = &qnos[0];

    dif = &s->buf[work_chunk->buf_offset*80];

    enc_blk = &enc_blks[0];

    for (mb_index = 0; mb_index < 5; mb_index++) {

        dv_calculate_mb_xy(s, work_chunk, mb_index, &mb_x, &mb_y);

        y_ptr    = s->picture.data[0] + ((mb_y * s->picture.linesize[0] + mb_x) << 3);

        c_offset = (((mb_y >>  (s->sys->pix_fmt == PIX_FMT_YUV420P)) * s->picture.linesize[1] +

                     (mb_x >> ((s->sys->pix_fmt == PIX_FMT_YUV411P) ? 2 : 1))) << 3);

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

            if (s->sys->pix_fmt == PIX_FMT_YUV422P) { /* 4:2:2 */

                if (j == 0 || j == 2) {

                    /* Y0 Y1 */

                    data     = y_ptr + ((j >> 1) * 8);

                    linesize = s->picture.linesize[0];

                } else if (j > 3) {

                    /* Cr Cb */

                    data     = s->picture.data[6 - j] + c_offset;

                    linesize = s->picture.linesize[6 - j];

                } else {

                    /* j=1 and j=3 are "dummy" blocks, used for AC data only */

                    data     = NULL;

                    linesize = 0;

                }

            } else { /* 4:1:1 or 4:2:0 */

                if (j < 4) {  /* Four Y blocks */

                    /* NOTE: at end of line, the macroblock is handled as 420 */

                    if (s->sys->pix_fmt == PIX_FMT_YUV411P && mb_x < (704 / 8)) {

                        data = y_ptr + (j * 8);

                    } else {

                        data = y_ptr + ((j & 1) * 8) + ((j >> 1) * 8 * s->picture.linesize[0]);

                    }

                    linesize = s->picture.linesize[0];

                } else {      /* Cr and Cb blocks */

                    /* don't ask Fabrice why they inverted Cb and Cr ! */

                    data     = s->picture.data    [6 - j] + c_offset;

                    linesize = s->picture.linesize[6 - j];

                    if (s->sys->pix_fmt == PIX_FMT_YUV411P && mb_x >= (704 / 8)) {

                        uint8_t* d;

                        uint8_t* b = scratch;

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

                            d = data + 8 * linesize;

                            b[0] = data[0]; b[1] = data[1]; b[2] = data[2]; b[3] = data[3];

                            b[4] =    d[0]; b[5] =    d[1]; b[6] =    d[2]; b[7] =    d[3];

                            data += linesize;

                            b += 8;

                        }

                        data = scratch;

                        linesize = 8;

                    }

                }

            }

            vs_bit_size += dv_init_enc_block(enc_blk, data, linesize, s, j>>2);

            ++enc_blk;

        }

    }

    if (vs_total_ac_bits < vs_bit_size)

        dv_guess_qnos(&enc_blks[0], qnosp);

    /* DIF encoding process */

    for (j=0; j<5*s->sys->bpm;) {

        int start_mb = j;

        dif[3] = *qnosp++;

        dif += 4;

        /* First pass over individual cells only */

        for (i=0; i<s->sys->bpm; i++, j++) {

            int sz = s->sys->block_sizes[i]>>3;

            init_put_bits(&pbs[j], dif, sz);

            put_bits(&pbs[j], 9, (uint16_t)(((enc_blks[j].mb[0] >> 3) - 1024 + 2) >> 2));

            put_bits(&pbs[j], 1, enc_blks[j].dct_mode);

            put_bits(&pbs[j], 2, enc_blks[j].cno);

            dv_encode_ac(&enc_blks[j], &pbs[j], &pbs[j+1]);

            dif += sz;

        }

        /* Second pass over each MB space */

        pb = &pbs[start_mb];

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

            if (enc_blks[start_mb+i].partial_bit_count)

                pb = dv_encode_ac(&enc_blks[start_mb+i], pb, &pbs[start_mb+s->sys->bpm]);

        }

    }

    /* Third and final pass over the whole video segment space */

    pb = &pbs[0];

    for (j=0; j<5*s->sys->bpm; j++) {

       if (enc_blks[j].partial_bit_count)

           pb = dv_encode_ac(&enc_blks[j], pb, &pbs[s->sys->bpm*5]);

       if (enc_blks[j].partial_bit_count)

            av_log(NULL, AV_LOG_ERROR, "ac bitstream overflow\n");

    }

    for (j=0; j<5*s->sys->bpm; j++)

       flush_put_bits(&pbs[j]);

    return 0;

}


static inline int get_phys_addr(CPUARMState *env, uint32_t address,

                                int access_type, int is_user,

                                hwaddr *phys_ptr, int *prot,

                                target_ulong *page_size)

{

    /* Fast Context Switch Extension.  */

    if (address < 0x02000000)

        address += env->cp15.c13_fcse;

    if ((env->cp15.c1_sys & 1) == 0) {

        /* MMU/MPU disabled.  */

        *phys_ptr = address;

        *prot = PAGE_READ | PAGE_WRITE | PAGE_EXEC;

        *page_size = TARGET_PAGE_SIZE;

        return 0;

    } else if (arm_feature(env, ARM_FEATURE_MPU)) {

        *page_size = TARGET_PAGE_SIZE;

	return get_phys_addr_mpu(env, address, access_type, is_user, phys_ptr,

				 prot);

    } else if (extended_addresses_enabled(env)) {

        return get_phys_addr_lpae(env, address, access_type, is_user, phys_ptr,

                                  prot, page_size);

    } else if (env->cp15.c1_sys & (1 << 23)) {

        return get_phys_addr_v6(env, address, access_type, is_user, phys_ptr,

                                prot, page_size);

    } else {

        return get_phys_addr_v5(env, address, access_type, is_user, phys_ptr,

                                prot, page_size);

    }

}


static target_ulong h_protect(PowerPCCPU *cpu, sPAPRMachineState *spapr,

                              target_ulong opcode, target_ulong *args)

{

    CPUPPCState *env = &cpu->env;

    target_ulong flags = args[0];

    target_ulong pte_index = args[1];

    target_ulong avpn = args[2];

    uint64_t token;

    target_ulong v, r;

    if (!valid_pte_index(env, pte_index)) {

        return H_PARAMETER;

    }

    token = ppc_hash64_start_access(cpu, pte_index);

    v = ppc_hash64_load_hpte0(cpu, token, 0);

    r = ppc_hash64_load_hpte1(cpu, token, 0);

    ppc_hash64_stop_access(token);

    if ((v & HPTE64_V_VALID) == 0 ||

        ((flags & H_AVPN) && (v & ~0x7fULL) != avpn)) {

        return H_NOT_FOUND;

    }

    r &= ~(HPTE64_R_PP0 | HPTE64_R_PP | HPTE64_R_N |

           HPTE64_R_KEY_HI | HPTE64_R_KEY_LO);

    r |= (flags << 55) & HPTE64_R_PP0;

    r |= (flags << 48) & HPTE64_R_KEY_HI;

    r |= flags & (HPTE64_R_PP | HPTE64_R_N | HPTE64_R_KEY_LO);

    ppc_hash64_store_hpte(cpu, pte_index,

                          (v & ~HPTE64_V_VALID) | HPTE64_V_HPTE_DIRTY, 0);

    ppc_hash64_tlb_flush_hpte(cpu, pte_index, v, r);

    /* Don't need a memory barrier, due to qemu's global lock */

    ppc_hash64_store_hpte(cpu, pte_index, v | HPTE64_V_HPTE_DIRTY, r);

    return H_SUCCESS;

}


int vmstate_save_state(QEMUFile *f, const VMStateDescription *vmsd,

                        void *opaque, QJSON *vmdesc)

{

    int ret = 0;

    VMStateField *field = vmsd->fields;

    trace_vmstate_save_state_top(vmsd->name);

    if (vmsd->pre_save) {

        ret = vmsd->pre_save(opaque);

        trace_vmstate_save_state_pre_save_res(vmsd->name, ret);

        if (ret) {

            error_report("pre-save failed: %s", vmsd->name);

            return ret;

        }

    }

    if (vmdesc) {

        json_prop_str(vmdesc, "vmsd_name", vmsd->name);

        json_prop_int(vmdesc, "version", vmsd->version_id);

        json_start_array(vmdesc, "fields");

    }

    while (field->name) {

        if (!field->field_exists ||

            field->field_exists(opaque, vmsd->version_id)) {

            void *first_elem = opaque + field->offset;

            int i, n_elems = vmstate_n_elems(opaque, field);

            int size = vmstate_size(opaque, field);

            int64_t old_offset, written_bytes;

            QJSON *vmdesc_loop = vmdesc;

            trace_vmstate_save_state_loop(vmsd->name, field->name, n_elems);

            if (field->flags & VMS_POINTER) {

                first_elem = *(void **)first_elem;

                assert(first_elem || !n_elems || !size);

            }

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

                void *curr_elem = first_elem + size * i;

                vmsd_desc_field_start(vmsd, vmdesc_loop, field, i, n_elems);

                old_offset = qemu_ftell_fast(f);

                if (field->flags & VMS_ARRAY_OF_POINTER) {

                    assert(curr_elem);

                    curr_elem = *(void **)curr_elem;

                }

                if (!curr_elem && size) {

                    /* if null pointer write placeholder and do not follow */

                    assert(field->flags & VMS_ARRAY_OF_POINTER);

                    vmstate_info_nullptr.put(f, curr_elem, size, NULL, NULL);

                } else if (field->flags & VMS_STRUCT) {

                    vmstate_save_state(f, field->vmsd, curr_elem, vmdesc_loop);

                } else {

                    field->info->put(f, curr_elem, size, field, vmdesc_loop);

                }

                written_bytes = qemu_ftell_fast(f) - old_offset;

                vmsd_desc_field_end(vmsd, vmdesc_loop, field, written_bytes, i);

                /* Compressed arrays only care about the first element */

                if (vmdesc_loop && vmsd_can_compress(field)) {

                    vmdesc_loop = NULL;

                }

            }

        } else {

            if (field->flags & VMS_MUST_EXIST) {

                error_report("Output state validation failed: %s/%s",

                        vmsd->name, field->name);

                assert(!(field->flags & VMS_MUST_EXIST));

            }

        }

        field++;

    }

    if (vmdesc) {

        json_end_array(vmdesc);

    }

    vmstate_subsection_save(f, vmsd, opaque, vmdesc);

    return 0;

}


static MemoryRegionSection *phys_page_find(PhysPageEntry lp, hwaddr addr,

                                           Node *nodes, MemoryRegionSection *sections)

{

    PhysPageEntry *p;

    hwaddr index = addr >> TARGET_PAGE_BITS;

    int i;

    for (i = P_L2_LEVELS; lp.skip && (i -= lp.skip) >= 0;) {

        if (lp.ptr == PHYS_MAP_NODE_NIL) {

            return &sections[PHYS_SECTION_UNASSIGNED];

        }

        p = nodes[lp.ptr];

        lp = p[(index >> (i * P_L2_BITS)) & (P_L2_SIZE - 1)];

    }

    return &sections[lp.ptr];

}


static void icp_control_write(void *opaque, target_phys_addr_t offset,

                          uint64_t value, unsigned size)

{

    switch (offset >> 2) {

    case 1: /* CP_FLASHPROG */

    case 2: /* CP_INTREG */

    case 3: /* CP_DECODE */

        /* Nothing interesting implemented yet.  */

        break;

    default:

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

    }

}


command_loop(void)

{

	int		c, i, j = 0, done = 0;

	char		*input;

	char		**v;

	const cmdinfo_t	*ct;

	for (i = 0; !done && i < ncmdline; i++) {

		input = strdup(cmdline[i]);

		if (!input) {

			fprintf(stderr,

				_("cannot strdup command '%s': %s\n"),

				cmdline[i], strerror(errno));

			exit(1);

		}

		v = breakline(input, &c);

		if (c) {

			ct = find_command(v[0]);

			if (ct) {

				if (ct->flags & CMD_FLAG_GLOBAL)

					done = command(ct, c, v);

				else {

					j = 0;

					while (!done && (j = args_command(j)))

						done = command(ct, c, v);

				}

			} else

				fprintf(stderr, _("command \"%s\" not found\n"),

					v[0]);

		}

		doneline(input, v);

	}

	if (cmdline) {

		free(cmdline);

		return;

	}

	while (!done) {

		if ((input = fetchline()) == NULL)

			break;

		v = breakline(input, &c);

		if (c) {

			ct = find_command(v[0]);

			if (ct)

				done = command(ct, c, v);

			else

				fprintf(stderr, _("command \"%s\" not found\n"),

					v[0]);

		}

		doneline(input, v);

	}

}


void memory_region_sync_dirty_bitmap(MemoryRegion *mr)

{

    AddressSpace *as;

    FlatRange *fr;

    QTAILQ_FOREACH(as, &address_spaces, address_spaces_link) {

        FlatView *view = as->current_map;

        FOR_EACH_FLAT_RANGE(fr, view) {

            if (fr->mr == mr) {

                MEMORY_LISTENER_UPDATE_REGION(fr, as, Forward, log_sync);

            }

        }

    }

}


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

{

    DeviceClass *k = DEVICE_CLASS(klass);

    set_bit(DEVICE_CATEGORY_STORAGE, k->categories);

    k->bus_type = TYPE_SCSI_BUS;

    k->init     = scsi_qdev_init;

    k->unplug   = scsi_qdev_unplug;

    k->exit     = scsi_qdev_exit;

    k->props    = scsi_props;

}


static void mvc_fast_memmove(CPUS390XState *env, uint32_t l, uint64_t dest,

                             uint64_t src)

{

    S390CPU *cpu = s390_env_get_cpu(env);

    hwaddr dest_phys;

    hwaddr src_phys;

    hwaddr len = l;

    void *dest_p;

    void *src_p;

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

    int flags;

    if (mmu_translate(env, dest, 1, asc, &dest_phys, &flags, true)) {

        cpu_stb_data(env, dest, 0);

        cpu_abort(CPU(cpu), "should never reach here");

    }

    dest_phys |= dest & ~TARGET_PAGE_MASK;

    if (mmu_translate(env, src, 0, asc, &src_phys, &flags, true)) {

        cpu_ldub_data(env, src);

        cpu_abort(CPU(cpu), "should never reach here");

    }

    src_phys |= src & ~TARGET_PAGE_MASK;

    dest_p = cpu_physical_memory_map(dest_phys, &len, 1);

    src_p = cpu_physical_memory_map(src_phys, &len, 0);

    memmove(dest_p, src_p, len);

    cpu_physical_memory_unmap(dest_p, 1, len, len);

    cpu_physical_memory_unmap(src_p, 0, len, len);

}


static int migrate_fd_close(void *opaque)

{

    MigrationState *s = opaque;

    if (s->mon) {

        monitor_resume(s->mon);

    }

    qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);

    return s->close(s);

}