static uint64_t icp_pic_read(void *opaque, target_phys_addr_t offset,

                             unsigned size)

{

    icp_pic_state *s = (icp_pic_state *)opaque;

    switch (offset >> 2) {

    case 0: /* IRQ_STATUS */

        return s->level & s->irq_enabled;

    case 1: /* IRQ_RAWSTAT */

        return s->level;

    case 2: /* IRQ_ENABLESET */

        return s->irq_enabled;

    case 4: /* INT_SOFTSET */

        return s->level & 1;

    case 8: /* FRQ_STATUS */

        return s->level & s->fiq_enabled;

    case 9: /* FRQ_RAWSTAT */

        return s->level;

    case 10: /* FRQ_ENABLESET */

        return s->fiq_enabled;

    case 3: /* IRQ_ENABLECLR */

    case 5: /* INT_SOFTCLR */

    case 11: /* FRQ_ENABLECLR */

    default:

        printf ("icp_pic_read: Bad register offset 0x%x\n", (int)offset);

        return 0;

    }

}


static int vmsvga_post_load(void *opaque, int version_id)

{

    struct vmsvga_state_s *s = opaque;

    s->invalidated = 1;

    if (s->config)

        s->fifo = (uint32_t *) s->fifo_ptr;

    return 0;

}


static inline void check_alignment(CPUS390XState *env, uint64_t v,

                                   int wordsize, uintptr_t ra)

{

    if (v % wordsize) {

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

        cpu_restore_state(cs, ra);

        program_interrupt(env, PGM_SPECIFICATION, 6);

    }

}


static void print_codec(const AVCodec *c)

{

    int encoder = av_codec_is_encoder(c);

    printf("%s %s [%s]:\n", encoder ? "Encoder" : "Decoder", c->name,

           c->long_name ? c->long_name : "");

    printf("    General capabilities: ");

    if (c->capabilities & AV_CODEC_CAP_DRAW_HORIZ_BAND)

        printf("horizband ");

    if (c->capabilities & AV_CODEC_CAP_DR1)

        printf("dr1 ");

    if (c->capabilities & AV_CODEC_CAP_TRUNCATED)

        printf("trunc ");

    if (c->capabilities & AV_CODEC_CAP_DELAY)

        printf("delay ");

    if (c->capabilities & AV_CODEC_CAP_SMALL_LAST_FRAME)

        printf("small ");

    if (c->capabilities & AV_CODEC_CAP_SUBFRAMES)

        printf("subframes ");

    if (c->capabilities & AV_CODEC_CAP_EXPERIMENTAL)

        printf("exp ");

    if (c->capabilities & AV_CODEC_CAP_CHANNEL_CONF)

        printf("chconf ");

    if (c->capabilities & AV_CODEC_CAP_PARAM_CHANGE)

        printf("small ");

    if (c->capabilities & AV_CODEC_CAP_PARAM_CHANGE)

        printf("variable ");

    if (c->capabilities & (AV_CODEC_CAP_FRAME_THREADS |

                           AV_CODEC_CAP_SLICE_THREADS |

                           AV_CODEC_CAP_AUTO_THREADS))

        printf("threads ");

    if (!c->capabilities)

        printf("none");

    printf("\n");

    if (c->type == AVMEDIA_TYPE_VIDEO) {

        printf("    Threading capabilities: ");

        switch (c->capabilities & (AV_CODEC_CAP_FRAME_THREADS |

                                   AV_CODEC_CAP_SLICE_THREADS |

                                   AV_CODEC_CAP_AUTO_THREADS)) {

        case AV_CODEC_CAP_FRAME_THREADS |

             AV_CODEC_CAP_SLICE_THREADS: printf("frame and slice"); break;

        case AV_CODEC_CAP_FRAME_THREADS: printf("frame");           break;

        case AV_CODEC_CAP_SLICE_THREADS: printf("slice");           break;

        case AV_CODEC_CAP_AUTO_THREADS : printf("auto");            break;

        default:                         printf("none");            break;

        }

        printf("\n");

    }

    if (c->supported_framerates) {

        const AVRational *fps = c->supported_framerates;

        printf("    Supported framerates:");

        while (fps->num) {

            printf(" %d/%d", fps->num, fps->den);

            fps++;

        }

        printf("\n");

    }

    PRINT_CODEC_SUPPORTED(c, pix_fmts, enum AVPixelFormat, "pixel formats",

                          AV_PIX_FMT_NONE, GET_PIX_FMT_NAME);

    PRINT_CODEC_SUPPORTED(c, supported_samplerates, int, "sample rates", 0,

                          GET_SAMPLE_RATE_NAME);

    PRINT_CODEC_SUPPORTED(c, sample_fmts, enum AVSampleFormat, "sample formats",

                          AV_SAMPLE_FMT_NONE, GET_SAMPLE_FMT_NAME);

    PRINT_CODEC_SUPPORTED(c, channel_layouts, uint64_t, "channel layouts",

                          0, GET_CH_LAYOUT_DESC);

    if (c->priv_class) {

        show_help_children(c->priv_class,

                           AV_OPT_FLAG_ENCODING_PARAM |

                           AV_OPT_FLAG_DECODING_PARAM);

    }

}


static int mm_start_timer(struct qemu_alarm_timer *t)

{

    TIMECAPS tc;

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

    timeGetDevCaps(&tc, sizeof(tc));

    mm_period = tc.wPeriodMin;

    timeBeginPeriod(mm_period);

    mm_timer = timeSetEvent(1,                  /* interval (ms) */

                            mm_period,          /* resolution */

                            mm_alarm_handler,   /* function */

                            (DWORD_PTR)t,       /* parameter */

                            TIME_ONESHOT | TIME_CALLBACK_FUNCTION);

    if (!mm_timer) {

        fprintf(stderr, "Failed to initialize win32 alarm timer: %ld\n",

                GetLastError());

        timeEndPeriod(mm_period);

        return -1;

    }

    return 0;

}


static void test_validate_fail_union_native_list(TestInputVisitorData *data,

                                                 const void *unused)

{

    UserDefNativeListUnion *tmp = NULL;

    Error *err = NULL;

    Visitor *v;

    v = validate_test_init(data,

                           "{ 'type': 'integer', 'data' : [ 'string' ] }");

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

    g_assert(err);

    qapi_free_UserDefNativeListUnion(tmp);

}


static int init_processing_chain(AVFilterContext *ctx, int in_width, int in_height,

                                 int out_width, int out_height)

{

    NPPScaleContext *s = ctx->priv;

    AVHWFramesContext *in_frames_ctx;

    enum AVPixelFormat in_format;

    enum AVPixelFormat out_format;

    enum AVPixelFormat in_deinterleaved_format;

    enum AVPixelFormat out_deinterleaved_format;

    int i, ret, last_stage = -1;

    /* check that we have a hw context */

    if (!ctx->inputs[0]->hw_frames_ctx) {

        av_log(ctx, AV_LOG_ERROR, "No hw context provided on input\n");

        return AVERROR(EINVAL);

    }

    in_frames_ctx = (AVHWFramesContext*)ctx->inputs[0]->hw_frames_ctx->data;

    in_format     = in_frames_ctx->sw_format;

    out_format    = (s->format == AV_PIX_FMT_NONE) ? in_format : s->format;

    if (!format_is_supported(in_format)) {

        av_log(ctx, AV_LOG_ERROR, "Unsupported input format: %s\n",

               av_get_pix_fmt_name(in_format));

        return AVERROR(ENOSYS);

    }

    if (!format_is_supported(out_format)) {

        av_log(ctx, AV_LOG_ERROR, "Unsupported output format: %s\n",

               av_get_pix_fmt_name(out_format));

        return AVERROR(ENOSYS);

    }

    in_deinterleaved_format  = get_deinterleaved_format(in_format);

    out_deinterleaved_format = get_deinterleaved_format(out_format);

    if (in_deinterleaved_format  == AV_PIX_FMT_NONE ||

        out_deinterleaved_format == AV_PIX_FMT_NONE)

        return AVERROR_BUG;

    /* figure out which stages need to be done */

    if (in_width != out_width || in_height != out_height ||

        in_deinterleaved_format != out_deinterleaved_format) {

        s->stages[STAGE_RESIZE].stage_needed = 1;

        if (s->interp_algo == NPPI_INTER_SUPER &&

            (out_width > in_width && out_height > in_height)) {

            s->interp_algo = NPPI_INTER_LANCZOS;

            av_log(ctx, AV_LOG_WARNING, "super-sampling not supported for output dimensions, using lanczos instead.\n");

        }

        if (s->interp_algo == NPPI_INTER_SUPER &&

            !(out_width < in_width && out_height < in_height)) {

            s->interp_algo = NPPI_INTER_CUBIC;

            av_log(ctx, AV_LOG_WARNING, "super-sampling not supported for output dimensions, using cubic instead.\n");

        }

    }

    if (!s->stages[STAGE_RESIZE].stage_needed && in_format == out_format)

        s->passthrough = 1;

    if (!s->passthrough) {

        if (in_format != in_deinterleaved_format)

            s->stages[STAGE_DEINTERLEAVE].stage_needed = 1;

        if (out_format != out_deinterleaved_format)

            s->stages[STAGE_INTERLEAVE].stage_needed = 1;

    }

    s->stages[STAGE_DEINTERLEAVE].in_fmt              = in_format;

    s->stages[STAGE_DEINTERLEAVE].out_fmt             = in_deinterleaved_format;

    s->stages[STAGE_DEINTERLEAVE].planes_in[0].width  = in_width;

    s->stages[STAGE_DEINTERLEAVE].planes_in[0].height = in_height;

    s->stages[STAGE_RESIZE].in_fmt               = in_deinterleaved_format;

    s->stages[STAGE_RESIZE].out_fmt              = out_deinterleaved_format;

    s->stages[STAGE_RESIZE].planes_in[0].width   = in_width;

    s->stages[STAGE_RESIZE].planes_in[0].height  = in_height;

    s->stages[STAGE_RESIZE].planes_out[0].width  = out_width;

    s->stages[STAGE_RESIZE].planes_out[0].height = out_height;

    s->stages[STAGE_INTERLEAVE].in_fmt              = out_deinterleaved_format;

    s->stages[STAGE_INTERLEAVE].out_fmt             = out_format;

    s->stages[STAGE_INTERLEAVE].planes_in[0].width  = out_width;

    s->stages[STAGE_INTERLEAVE].planes_in[0].height = out_height;

    /* init the hardware contexts */

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

        if (!s->stages[i].stage_needed)

            continue;

        ret = init_stage(&s->stages[i], in_frames_ctx->device_ref);

        if (ret < 0)

            return ret;

        last_stage = i;

    }

    if (last_stage < 0)

    {

        ctx->outputs[0]->hw_frames_ctx = av_buffer_ref(ctx->inputs[0]->hw_frames_ctx);

        return 0;

    }

    ctx->outputs[0]->hw_frames_ctx = av_buffer_ref(s->stages[last_stage].frames_ctx);

    if (!ctx->outputs[0]->hw_frames_ctx)

        return AVERROR(ENOMEM);

    return 0;

}


static int read_uncompressed_sgi(unsigned char* out_buf, uint8_t* out_end,

                const uint8_t *in_buf, const uint8_t *in_end, SgiState* s)

{

    int x, y, z;

    const uint8_t *ptr;

    unsigned int offset = s->height * s->width * s->bytes_per_channel;

    /* Test buffer size. */

    if (offset * s->depth > in_end - in_buf) {

       return -1;

    }

    for (y = s->height - 1; y >= 0; y--) {

        out_end = out_buf + (y * s->linesize);

        for (x = s->width; x > 0; x--) {

            ptr = in_buf += s->bytes_per_channel;

            for(z = 0; z < s->depth; z ++) {

                memcpy(out_end, ptr, s->bytes_per_channel);

                out_end += s->bytes_per_channel;

                ptr += offset;

            }

        }

    }

    return 0;

}


int ff_mov_write_packet(AVFormatContext *s, AVPacket *pkt)

{

    MOVMuxContext *mov = s->priv_data;

    AVIOContext *pb = s->pb;

    MOVTrack *trk = &mov->tracks[pkt->stream_index];

    AVCodecContext *enc = trk->enc;

    unsigned int samples_in_chunk = 0;

    int size = pkt->size;

    uint8_t *reformatted_data = NULL;

    if (mov->flags & FF_MOV_FLAG_FRAGMENT) {

        int ret;

        if (mov->fragments > 0) {

            if (!trk->mdat_buf) {

                if ((ret = avio_open_dyn_buf(&trk->mdat_buf)) < 0)

                    return ret;

            }

            pb = trk->mdat_buf;

        } else {

            if (!mov->mdat_buf) {

                if ((ret = avio_open_dyn_buf(&mov->mdat_buf)) < 0)

                    return ret;

            }

            pb = mov->mdat_buf;

        }

    }

    if (enc->codec_id == AV_CODEC_ID_AMR_NB) {

        /* We must find out how many AMR blocks there are in one packet */

        static uint16_t packed_size[16] =

            {13, 14, 16, 18, 20, 21, 27, 32, 6, 0, 0, 0, 0, 0, 0, 1};

        int len = 0;

        while (len < size && samples_in_chunk < 100) {

            len += packed_size[(pkt->data[len] >> 3) & 0x0F];

            samples_in_chunk++;

        }

        if (samples_in_chunk > 1) {

            av_log(s, AV_LOG_ERROR, "fatal error, input is not a single packet, implement a AVParser for it\n");

            return -1;

        }

    } else if (trk->sample_size)

        samples_in_chunk = size / trk->sample_size;

    else

        samples_in_chunk = 1;

    /* copy extradata if it exists */

    if (trk->vos_len == 0 && enc->extradata_size > 0) {

        trk->vos_len  = enc->extradata_size;

        trk->vos_data = av_malloc(trk->vos_len);

        memcpy(trk->vos_data, enc->extradata, trk->vos_len);

    }

    if (enc->codec_id == AV_CODEC_ID_H264 && trk->vos_len > 0 && *(uint8_t *)trk->vos_data != 1) {

        /* from x264 or from bytestream h264 */

        /* nal reformating needed */

        if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {

            ff_avc_parse_nal_units_buf(pkt->data, &reformatted_data,

                                       &size);

            avio_write(pb, reformatted_data, size);

        } else {

            size = ff_avc_parse_nal_units(pb, pkt->data, pkt->size);

        }

    } else if (enc->codec_id == AV_CODEC_ID_HEVC && trk->vos_len > 6 &&

               (AV_RB24(trk->vos_data) == 1 || AV_RB32(trk->vos_data) == 1)) {

        /* extradata is Annex B, assume the bitstream is too and convert it */

        if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams) {

            ff_hevc_annexb2mp4_buf(pkt->data, &reformatted_data, &size, 0, NULL);

            avio_write(pb, reformatted_data, size);

        } else {

            size = ff_hevc_annexb2mp4(pb, pkt->data, pkt->size, 0, NULL);

        }

    } else {

        avio_write(pb, pkt->data, size);

    }

    if ((enc->codec_id == AV_CODEC_ID_DNXHD ||

         enc->codec_id == AV_CODEC_ID_AC3) && !trk->vos_len) {

        /* copy frame to create needed atoms */

        trk->vos_len  = size;

        trk->vos_data = av_malloc(size);

        if (!trk->vos_data)

            return AVERROR(ENOMEM);

        memcpy(trk->vos_data, pkt->data, size);

    }

    if (trk->entry >= trk->cluster_capacity) {

        unsigned new_capacity = 2 * (trk->entry + MOV_INDEX_CLUSTER_SIZE);

        if (av_reallocp_array(&trk->cluster, new_capacity,

                              sizeof(*trk->cluster)))

            return AVERROR(ENOMEM);

        trk->cluster_capacity = new_capacity;

    }

    trk->cluster[trk->entry].pos              = avio_tell(pb) - size;

    trk->cluster[trk->entry].samples_in_chunk = samples_in_chunk;

    trk->cluster[trk->entry].size             = size;

    trk->cluster[trk->entry].entries          = samples_in_chunk;

    trk->cluster[trk->entry].dts              = pkt->dts;

    if (!trk->entry && trk->start_dts != AV_NOPTS_VALUE) {

        /* First packet of a new fragment. We already wrote the duration

         * of the last packet of the previous fragment based on track_duration,

         * which might not exactly match our dts. Therefore adjust the dts

         * of this packet to be what the previous packets duration implies. */

        trk->cluster[trk->entry].dts = trk->start_dts + trk->track_duration;

    }

    if (!trk->entry && trk->start_dts == AV_NOPTS_VALUE && !mov->use_editlist &&

        s->avoid_negative_ts == AVFMT_AVOID_NEG_TS_MAKE_ZERO) {

        /* Not using edit lists and shifting the first track to start from zero.

         * If the other streams start from a later timestamp, we won't be able

         * to signal the difference in starting time without an edit list.

         * Thus move the timestamp for this first sample to 0, increasing

         * its duration instead. */

        trk->cluster[trk->entry].dts = trk->start_dts = 0;

    }

    if (trk->start_dts == AV_NOPTS_VALUE) {

        trk->start_dts = pkt->dts;

        if (pkt->dts && mov->flags & FF_MOV_FLAG_EMPTY_MOOV)

            av_log(s, AV_LOG_WARNING,

                   "Track %d starts with a nonzero dts %"PRId64". This "

                   "currently isn't handled correctly in combination with "

                   "empty_moov.\n", pkt->stream_index, pkt->dts);

    }

    trk->track_duration = pkt->dts - trk->start_dts + pkt->duration;

    if (pkt->pts == AV_NOPTS_VALUE) {

        av_log(s, AV_LOG_WARNING, "pts has no value\n");

        pkt->pts = pkt->dts;

    }

    if (pkt->dts != pkt->pts)

        trk->flags |= MOV_TRACK_CTTS;

    trk->cluster[trk->entry].cts   = pkt->pts - pkt->dts;

    trk->cluster[trk->entry].flags = 0;

    if (enc->codec_id == AV_CODEC_ID_VC1) {

        mov_parse_vc1_frame(pkt, trk, mov->fragments);

    } else if (pkt->flags & AV_PKT_FLAG_KEY) {

        if (mov->mode == MODE_MOV && enc->codec_id == AV_CODEC_ID_MPEG2VIDEO &&

            trk->entry > 0) { // force sync sample for the first key frame

            mov_parse_mpeg2_frame(pkt, &trk->cluster[trk->entry].flags);

            if (trk->cluster[trk->entry].flags & MOV_PARTIAL_SYNC_SAMPLE)

                trk->flags |= MOV_TRACK_STPS;

        } else {

            trk->cluster[trk->entry].flags = MOV_SYNC_SAMPLE;

        }

        if (trk->cluster[trk->entry].flags & MOV_SYNC_SAMPLE)

            trk->has_keyframes++;

    }

    trk->entry++;

    trk->sample_count += samples_in_chunk;

    mov->mdat_size    += size;

    if (trk->hint_track >= 0 && trk->hint_track < mov->nb_streams)

        ff_mov_add_hinted_packet(s, pkt, trk->hint_track, trk->entry,

                                 reformatted_data, size);

    av_free(reformatted_data);

    return 0;

}


static CURLState *curl_init_state(BDRVCURLState *s)

{

    CURLState *state = NULL;

    int i, j;

    do {

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

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

                if (s->states[i].acb[j])

                    continue;

            if (s->states[i].in_use)

                continue;

            state = &s->states[i];

            state->in_use = 1;

            break;

        }

        if (!state) {

            g_usleep(100);

            curl_multi_do(s);

        }

    } while(!state);

    if (state->curl)

        goto has_curl;

    state->curl = curl_easy_init();

    if (!state->curl)

        return NULL;

    curl_easy_setopt(state->curl, CURLOPT_URL, s->url);

    curl_easy_setopt(state->curl, CURLOPT_TIMEOUT, 5);

    curl_easy_setopt(state->curl, CURLOPT_WRITEFUNCTION, (void *)curl_read_cb);

    curl_easy_setopt(state->curl, CURLOPT_WRITEDATA, (void *)state);

    curl_easy_setopt(state->curl, CURLOPT_PRIVATE, (void *)state);

    curl_easy_setopt(state->curl, CURLOPT_AUTOREFERER, 1);

    curl_easy_setopt(state->curl, CURLOPT_FOLLOWLOCATION, 1);

    curl_easy_setopt(state->curl, CURLOPT_NOSIGNAL, 1);

    curl_easy_setopt(state->curl, CURLOPT_ERRORBUFFER, state->errmsg);

    curl_easy_setopt(state->curl, CURLOPT_FAILONERROR, 1);

    /* Restrict supported protocols to avoid security issues in the more

     * obscure protocols.  For example, do not allow POP3/SMTP/IMAP see

     * CVE-2013-0249.

     */

    curl_easy_setopt(state->curl, CURLOPT_PROTOCOLS, PROTOCOLS);

    curl_easy_setopt(state->curl, CURLOPT_REDIR_PROTOCOLS, PROTOCOLS);

#ifdef DEBUG_VERBOSE

    curl_easy_setopt(state->curl, CURLOPT_VERBOSE, 1);

has_curl:

    state->s = s;

    return state;

}


static int send_mono_rect(VncState *vs, int w, int h, uint32_t bg, uint32_t fg)

{

    size_t bytes;

    int stream = 1;

    int level = tight_conf[vs->tight_compression].mono_zlib_level;

    bytes = ((w + 7) / 8) * h;

    vnc_write_u8(vs, (stream | VNC_TIGHT_EXPLICIT_FILTER) << 4);

    vnc_write_u8(vs, VNC_TIGHT_FILTER_PALETTE);

    vnc_write_u8(vs, 1);

    switch(vs->clientds.pf.bytes_per_pixel) {

    case 4:

    {

        uint32_t buf[2] = {bg, fg};

        size_t ret = sizeof (buf);

        if (vs->tight_pixel24) {

            tight_pack24(vs, (unsigned char*)buf, 2, &ret);

        }

        vnc_write(vs, buf, ret);

        tight_encode_mono_rect32(vs->tight.buffer, w, h, bg, fg);

        break;

    }

    case 2:

        vnc_write(vs, &bg, 2);

        vnc_write(vs, &fg, 2);

        tight_encode_mono_rect16(vs->tight.buffer, w, h, bg, fg);

        break;

    default:

        vnc_write_u8(vs, bg);

        vnc_write_u8(vs, fg);

        tight_encode_mono_rect8(vs->tight.buffer, w, h, bg, fg);

        break;

    }

    vs->tight.offset = bytes;

    bytes = tight_compress_data(vs, stream, bytes, level, Z_DEFAULT_STRATEGY);

    return (bytes >= 0);

}


static void do_video_out(AVFormatContext *s,

                         OutputStream *ost,

                         AVFrame *in_picture,

                         int *frame_size)

{

    int ret, format_video_sync;

    AVPacket pkt;

    AVCodecContext *enc = ost->enc_ctx;

    *frame_size = 0;

    format_video_sync = video_sync_method;

    if (format_video_sync == VSYNC_AUTO)

        format_video_sync = (s->oformat->flags & AVFMT_NOTIMESTAMPS) ? VSYNC_PASSTHROUGH :

                            (s->oformat->flags & AVFMT_VARIABLE_FPS) ? VSYNC_VFR : VSYNC_CFR;

    if (format_video_sync != VSYNC_PASSTHROUGH &&

        ost->frame_number &&

        in_picture->pts != AV_NOPTS_VALUE &&

        in_picture->pts < ost->sync_opts) {

        nb_frames_drop++;

        av_log(NULL, AV_LOG_WARNING,

               "*** dropping frame %d from stream %d at ts %"PRId64"\n",

               ost->frame_number, ost->st->index, in_picture->pts);

        return;

    }

    if (in_picture->pts == AV_NOPTS_VALUE)

        in_picture->pts = ost->sync_opts;

    ost->sync_opts = in_picture->pts;

    if (!ost->frame_number)

        ost->first_pts = in_picture->pts;

    av_init_packet(&pkt);

    pkt.data = NULL;

    pkt.size = 0;

    if (ost->frame_number >= ost->max_frames)

        return;

    if (enc->flags & (AV_CODEC_FLAG_INTERLACED_DCT | AV_CODEC_FLAG_INTERLACED_ME) &&

        ost->top_field_first >= 0)

        in_picture->top_field_first = !!ost->top_field_first;

    in_picture->quality = enc->global_quality;

    in_picture->pict_type = 0;

    if (ost->forced_kf_index < ost->forced_kf_count &&

        in_picture->pts >= ost->forced_kf_pts[ost->forced_kf_index]) {

        in_picture->pict_type = AV_PICTURE_TYPE_I;

        ost->forced_kf_index++;

    }

    ost->frames_encoded++;

    ret = avcodec_send_frame(enc, in_picture);

    if (ret < 0)

        goto error;

    /*

     * For video, there may be reordering, so we can't throw away frames on

     * encoder flush, we need to limit them here, before they go into encoder.

     */

    ost->frame_number++;

    while (1) {

        ret = avcodec_receive_packet(enc, &pkt);

        if (ret == AVERROR(EAGAIN))

            break;

        if (ret < 0)

            goto error;

        av_packet_rescale_ts(&pkt, enc->time_base, ost->st->time_base);

        output_packet(s, &pkt, ost);

        *frame_size = pkt.size;

        /* if two pass, output log */

        if (ost->logfile && enc->stats_out) {

            fprintf(ost->logfile, "%s", enc->stats_out);

        }

        ost->sync_opts++;

    }

    return;

error:

    av_assert0(ret != AVERROR(EAGAIN) && ret != AVERROR_EOF);

    av_log(NULL, AV_LOG_FATAL, "Video encoding failed\n");

    exit_program(1);

}


void qmp_screendump(const char *filename, Error **errp)

{

    QemuConsole *previous_active_console;

    bool cswitch;

    previous_active_console = active_console;

    cswitch = previous_active_console && previous_active_console->index != 0;

    /* There is currently no way of specifying which screen we want to dump,

       so always dump the first one.  */

    if (cswitch) {

        console_select(0);

    }

    if (consoles[0] && consoles[0]->hw_screen_dump) {

        consoles[0]->hw_screen_dump(consoles[0]->hw, filename, cswitch, errp);

    } else {

        error_setg(errp, "device doesn't support screendump");

    }

    if (cswitch) {

        console_select(previous_active_console->index);

    }

}


static int decode_frame_mp3on4(AVCodecContext * avctx,

                        void *data, int *data_size,

                        AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    MP3On4DecodeContext *s = avctx->priv_data;

    MPADecodeContext *m;

    int fsize, len = buf_size, out_size = 0;

    uint32_t header;

    OUT_INT *out_samples = data;

    OUT_INT *outptr, *bp;

    int fr, j, n;

    if(*data_size < MPA_FRAME_SIZE * MPA_MAX_CHANNELS * s->frames * sizeof(OUT_INT))

        return -1;

    *data_size = 0;

    // Discard too short frames

    if (buf_size < HEADER_SIZE)

        return -1;

    // If only one decoder interleave is not needed

    outptr = s->frames == 1 ? out_samples : s->decoded_buf;

    avctx->bit_rate = 0;

    for (fr = 0; fr < s->frames; fr++) {

        fsize = AV_RB16(buf) >> 4;

        fsize = FFMIN3(fsize, len, MPA_MAX_CODED_FRAME_SIZE);

        m = s->mp3decctx[fr];

        assert (m != NULL);

        header = (AV_RB32(buf) & 0x000fffff) | s->syncword; // patch header

        if (ff_mpa_check_header(header) < 0) // Bad header, discard block

            break;

        avpriv_mpegaudio_decode_header((MPADecodeHeader *)m, header);

        out_size += mp_decode_frame(m, outptr, buf, fsize);

        buf += fsize;

        len -= fsize;

        if(s->frames > 1) {

            n = m->avctx->frame_size*m->nb_channels;

            /* interleave output data */

            bp = out_samples + s->coff[fr];

            if(m->nb_channels == 1) {

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

                    *bp = s->decoded_buf[j];

                    bp += avctx->channels;

                }

            } else {

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

                    bp[0] = s->decoded_buf[j++];

                    bp[1] = s->decoded_buf[j];

                    bp += avctx->channels;

                }

            }

        }

        avctx->bit_rate += m->bit_rate;

    }

    /* update codec info */

    avctx->sample_rate = s->mp3decctx[0]->sample_rate;

    *data_size = out_size;

    return buf_size;

}


DISAS_INSN(cas2l)

{

    uint16_t ext1, ext2;

    TCGv addr1, addr2, regs;

    /* cas2 Dc1:Dc2,Du1:Du2,(Rn1):(Rn2) */

    ext1 = read_im16(env, s);

    if (ext1 & 0x8000) {

        /* Address Register */

        addr1 = AREG(ext1, 12);

    } else {

        /* Data Register */

        addr1 = DREG(ext1, 12);

    }

    ext2 = read_im16(env, s);

    if (ext2 & 0x8000) {

        /* Address Register */

        addr2 = AREG(ext2, 12);

    } else {

        /* Data Register */

        addr2 = DREG(ext2, 12);

    }

    /* if (R1) == Dc1 && (R2) == Dc2 then

     *     (R1) = Du1

     *     (R2) = Du2

     * else

     *     Dc1 = (R1)

     *     Dc2 = (R2)

     */

    regs = tcg_const_i32(REG(ext2, 6) |

                         (REG(ext1, 6) << 3) |

                         (REG(ext2, 0) << 6) |

                         (REG(ext1, 0) << 9));

    gen_helper_cas2l(cpu_env, regs, addr1, addr2);

    tcg_temp_free(regs);

    /* Note that cas2l also assigned to env->cc_op.  */

    s->cc_op = CC_OP_CMPL;

    s->cc_op_synced = 1;

}


static void cirrus_bitblt_rop_nop(CirrusVGAState *s,

                                  uint8_t *dst,const uint8_t *src,

                                  int dstpitch,int srcpitch,

                                  int bltwidth,int bltheight)

{

}


static void page_flush_tb(void)

{

    int i;

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

        page_flush_tb_1(V_L1_SHIFT / L2_BITS - 1, l1_map + i);

    }

}


static void tcg_out_tlb_read(TCGContext *s, TCGReg addr_reg, TCGMemOp opc,

                             tcg_insn_unit **label_ptr, int mem_index,

                             bool is_read)

{

    int tlb_offset = is_read ?

        offsetof(CPUArchState, tlb_table[mem_index][0].addr_read)

        : offsetof(CPUArchState, tlb_table[mem_index][0].addr_write);

    int s_mask = (1 << (opc & MO_SIZE)) - 1;

    TCGReg base = TCG_AREG0, x3;

    uint64_t tlb_mask;

    /* For aligned accesses, we check the first byte and include the alignment

       bits within the address.  For unaligned access, we check that we don't

       cross pages using the address of the last byte of the access.  */

    if ((opc & MO_AMASK) == MO_ALIGN || s_mask == 0) {

        tlb_mask = TARGET_PAGE_MASK | s_mask;

        x3 = addr_reg;

    } else {

        tcg_out_insn(s, 3401, ADDI, TARGET_LONG_BITS == 64,

                     TCG_REG_X3, addr_reg, s_mask);

        tlb_mask = TARGET_PAGE_MASK;

        x3 = TCG_REG_X3;

    }

    /* Extract the TLB index from the address into X0.

       X0<CPU_TLB_BITS:0> =

       addr_reg<TARGET_PAGE_BITS+CPU_TLB_BITS:TARGET_PAGE_BITS> */

    tcg_out_ubfm(s, TARGET_LONG_BITS == 64, TCG_REG_X0, addr_reg,

                 TARGET_PAGE_BITS, TARGET_PAGE_BITS + CPU_TLB_BITS);

    /* Store the page mask part of the address into X3.  */

    tcg_out_logicali(s, I3404_ANDI, TARGET_LONG_BITS == 64,

                     TCG_REG_X3, x3, tlb_mask);

    /* Add any "high bits" from the tlb offset to the env address into X2,

       to take advantage of the LSL12 form of the ADDI instruction.

       X2 = env + (tlb_offset & 0xfff000) */

    if (tlb_offset & 0xfff000) {

        tcg_out_insn(s, 3401, ADDI, TCG_TYPE_I64, TCG_REG_X2, base,

                     tlb_offset & 0xfff000);

        base = TCG_REG_X2;

    }

    /* Merge the tlb index contribution into X2.

       X2 = X2 + (X0 << CPU_TLB_ENTRY_BITS) */

    tcg_out_insn(s, 3502S, ADD_LSL, TCG_TYPE_I64, TCG_REG_X2, base,

                 TCG_REG_X0, CPU_TLB_ENTRY_BITS);

    /* Merge "low bits" from tlb offset, load the tlb comparator into X0.

       X0 = load [X2 + (tlb_offset & 0x000fff)] */

    tcg_out_ldst(s, TARGET_LONG_BITS == 32 ? I3312_LDRW : I3312_LDRX,

                 TCG_REG_X0, TCG_REG_X2, tlb_offset & 0xfff);

    /* Load the tlb addend. Do that early to avoid stalling.

       X1 = load [X2 + (tlb_offset & 0xfff) + offsetof(addend)] */

    tcg_out_ldst(s, I3312_LDRX, TCG_REG_X1, TCG_REG_X2,

                 (tlb_offset & 0xfff) + (offsetof(CPUTLBEntry, addend)) -

                 (is_read ? offsetof(CPUTLBEntry, addr_read)

                  : offsetof(CPUTLBEntry, addr_write)));

    /* Perform the address comparison. */

    tcg_out_cmp(s, (TARGET_LONG_BITS == 64), TCG_REG_X0, TCG_REG_X3, 0);

    /* If not equal, we jump to the slow path. */

    *label_ptr = s->code_ptr;

    tcg_out_goto_cond_noaddr(s, TCG_COND_NE);

}


static int usb_host_scan_sys(void *opaque, USBScanFunc *func)

{

    DIR *dir = 0;

    char line[1024];

    int bus_num, addr, speed, class_id, product_id, vendor_id;

    int ret = 0;

    char product_name[512];

    struct dirent *de;

    dir = opendir(USBSYSBUS_PATH "/devices");

    if (!dir) {

        perror("husb: cannot open devices directory");

        goto the_end;

    }

    while ((de = readdir(dir))) {

        if (de->d_name[0] != '.' && !strchr(de->d_name, ':')) {

            char *tmpstr = de->d_name;

            if (!strncmp(de->d_name, "usb", 3))

                tmpstr += 3;

            bus_num = atoi(tmpstr);

            if (!usb_host_read_file(line, sizeof(line), USBSYSBUS_PATH "/devices/%s/devnum", de->d_name))

                goto the_end;

            if (sscanf(line, "%d", &addr) != 1)

                goto the_end;

            if (!usb_host_read_file(line, sizeof(line), USBSYSBUS_PATH "/devices/%s/bDeviceClass", de->d_name))

                goto the_end;

            if (sscanf(line, "%x", &class_id) != 1)

                goto the_end;

            if (!usb_host_read_file(line, sizeof(line), USBSYSBUS_PATH "/devices/%s/idVendor", de->d_name))

                goto the_end;

            if (sscanf(line, "%x", &vendor_id) != 1)

                goto the_end;

            if (!usb_host_read_file(line, sizeof(line), USBSYSBUS_PATH "/devices/%s/idProduct", de->d_name))

                goto the_end;

            if (sscanf(line, "%x", &product_id) != 1)

                goto the_end;

            if (!usb_host_read_file(line, sizeof(line), USBSYSBUS_PATH "/devices/%s/product", de->d_name)) {

                *product_name = 0;

            } else {

                if (strlen(line) > 0)

                    line[strlen(line) - 1] = '\0';

                pstrcpy(product_name, sizeof(product_name), line);

            }

            if (!usb_host_read_file(line, sizeof(line), USBSYSBUS_PATH "/devices/%s/speed", de->d_name))

                goto the_end;

            if (!strcmp(line, "480\n"))

                speed = USB_SPEED_HIGH;

            else if (!strcmp(line, "1.5\n"))

                speed = USB_SPEED_LOW;

            else

                speed = USB_SPEED_FULL;

            ret = func(opaque, bus_num, addr, class_id, vendor_id,

                       product_id, product_name, speed);

            if (ret)

                goto the_end;

        }

    }

 the_end:

    if (dir)

        closedir(dir);

    return ret;

}


int svm_check_intercept_param(uint32_t type, uint64_t param)

{

    switch(type) {

    case SVM_EXIT_READ_CR0 ... SVM_EXIT_READ_CR0 + 8:

        if (INTERCEPTEDw(_cr_read, (1 << (type - SVM_EXIT_READ_CR0)))) {

            vmexit(type, param);

            return 1;

        }

        break;

    case SVM_EXIT_READ_DR0 ... SVM_EXIT_READ_DR0 + 8:

        if (INTERCEPTEDw(_dr_read, (1 << (type - SVM_EXIT_READ_DR0)))) {

            vmexit(type, param);

            return 1;

        }

        break;

    case SVM_EXIT_WRITE_CR0 ... SVM_EXIT_WRITE_CR0 + 8:

        if (INTERCEPTEDw(_cr_write, (1 << (type - SVM_EXIT_WRITE_CR0)))) {

            vmexit(type, param);

            return 1;

        }

        break;

    case SVM_EXIT_WRITE_DR0 ... SVM_EXIT_WRITE_DR0 + 8:

        if (INTERCEPTEDw(_dr_write, (1 << (type - SVM_EXIT_WRITE_DR0)))) {

            vmexit(type, param);

            return 1;

        }

        break;

    case SVM_EXIT_EXCP_BASE ... SVM_EXIT_EXCP_BASE + 16:

        if (INTERCEPTEDl(_exceptions, (1 << (type - SVM_EXIT_EXCP_BASE)))) {

            vmexit(type, param);

            return 1;

        }

        break;

    case SVM_EXIT_IOIO:

        if (INTERCEPTED(1ULL << INTERCEPT_IOIO_PROT)) {

            /* FIXME: this should be read in at vmrun (faster this way?) */

            uint64_t addr = ldq_phys(env->vm_vmcb + offsetof(struct vmcb, control.iopm_base_pa));

            uint16_t port = (uint16_t) (param >> 16);

            if(ldub_phys(addr + port / 8) & (1 << (port % 8)))

                vmexit(type, param);

        }

        break;

    case SVM_EXIT_MSR:

        if (INTERCEPTED(1ULL << INTERCEPT_MSR_PROT)) {

            /* FIXME: this should be read in at vmrun (faster this way?) */

            uint64_t addr = ldq_phys(env->vm_vmcb + offsetof(struct vmcb, control.msrpm_base_pa));

            switch((uint32_t)ECX) {

            case 0 ... 0x1fff:

                T0 = (ECX * 2) % 8;

                T1 = ECX / 8;

                break;

            case 0xc0000000 ... 0xc0001fff:

                T0 = (8192 + ECX - 0xc0000000) * 2;

                T1 = (T0 / 8);

                T0 %= 8;

                break;

            case 0xc0010000 ... 0xc0011fff:

                T0 = (16384 + ECX - 0xc0010000) * 2;

                T1 = (T0 / 8);

                T0 %= 8;

                break;

            default:

                vmexit(type, param);

                return 1;

            }

            if (ldub_phys(addr + T1) & ((1 << param) << T0))

                vmexit(type, param);

            return 1;

        }

        break;

    default:

        if (INTERCEPTED((1ULL << ((type - SVM_EXIT_INTR) + INTERCEPT_INTR)))) {

            vmexit(type, param);

            return 1;

        }

        break;

    }

    return 0;

}


int kvm_arch_get_registers(CPUState *env)

{

    struct kvm_regs regs;

    struct kvm_sregs sregs;

    int i, ret;

    ret = kvm_vcpu_ioctl(env, KVM_GET_REGS, &regs);

    if (ret < 0)

        return ret;

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

    if (ret < 0)

        return ret;

    env->ctr = regs.ctr;

    env->lr = regs.lr;

    env->xer = regs.xer;

    env->msr = regs.msr;

    env->nip = regs.pc;

    env->spr[SPR_SRR0] = regs.srr0;

    env->spr[SPR_SRR1] = regs.srr1;

    env->spr[SPR_SPRG0] = regs.sprg0;

    env->spr[SPR_SPRG1] = regs.sprg1;

    env->spr[SPR_SPRG2] = regs.sprg2;

    env->spr[SPR_SPRG3] = regs.sprg3;

    env->spr[SPR_SPRG4] = regs.sprg4;

    env->spr[SPR_SPRG5] = regs.sprg5;

    env->spr[SPR_SPRG6] = regs.sprg6;

    env->spr[SPR_SPRG7] = regs.sprg7;

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

        env->gpr[i] = regs.gpr[i];

#ifdef KVM_CAP_PPC_SEGSTATE

    if (kvm_check_extension(env->kvm_state, KVM_CAP_PPC_SEGSTATE)) {

        env->sdr1 = sregs.u.s.sdr1;

        /* Sync SLB */

#ifdef TARGET_PPC64

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

            ppc_store_slb(env, sregs.u.s.ppc64.slb[i].slbe,

                               sregs.u.s.ppc64.slb[i].slbv);

        }

#endif

        /* Sync SRs */

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

            env->sr[i] = sregs.u.s.ppc32.sr[i];

        }

        /* Sync BATs */

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

            env->DBAT[0][i] = sregs.u.s.ppc32.dbat[i] & 0xffffffff;

            env->DBAT[1][i] = sregs.u.s.ppc32.dbat[i] >> 32;

            env->IBAT[0][i] = sregs.u.s.ppc32.ibat[i] & 0xffffffff;

            env->IBAT[1][i] = sregs.u.s.ppc32.ibat[i] >> 32;

        }

    }

#endif

    return 0;

}


void qemu_cond_wait(QemuCond *cond, QemuMutex *mutex)

{

    /*

     * This access is protected under the mutex.

     */

    cond->waiters++;

    /*

     * Unlock external mutex and wait for signal.

     * NOTE: we've held mutex locked long enough to increment

     * waiters count above, so there's no problem with

     * leaving mutex unlocked before we wait on semaphore.

     */

    qemu_mutex_unlock(mutex);

    WaitForSingleObject(cond->sema, INFINITE);

    /* Now waiters must rendez-vous with the signaling thread and

     * let it continue.  For cond_broadcast this has heavy contention

     * and triggers thundering herd.  So goes life.

     *

     * Decrease waiters count.  The mutex is not taken, so we have

     * to do this atomically.

     *

     * All waiters contend for the mutex at the end of this function

     * until the signaling thread relinquishes it.  To ensure

     * each waiter consumes exactly one slice of the semaphore,

     * the signaling thread stops until it is told by the last

     * waiter that it can go on.

     */

    if (InterlockedDecrement(&cond->waiters) == cond->target) {

        SetEvent(cond->continue_event);

    }

    qemu_mutex_lock(mutex);

}


static void gen_wsr(DisasContext *dc, uint32_t sr, TCGv_i32 s)

{

    static void (* const wsr_handler[256])(DisasContext *dc,

            uint32_t sr, TCGv_i32 v) = {

        [LBEG] = gen_wsr_lbeg,

        [LEND] = gen_wsr_lend,

        [SAR] = gen_wsr_sar,

        [BR] = gen_wsr_br,

        [LITBASE] = gen_wsr_litbase,

        [ACCHI] = gen_wsr_acchi,

        [WINDOW_BASE] = gen_wsr_windowbase,

        [WINDOW_START] = gen_wsr_windowstart,

        [PTEVADDR] = gen_wsr_ptevaddr,

        [RASID] = gen_wsr_rasid,

        [ITLBCFG] = gen_wsr_tlbcfg,

        [DTLBCFG] = gen_wsr_tlbcfg,

        [IBREAKENABLE] = gen_wsr_ibreakenable,

        [ATOMCTL] = gen_wsr_atomctl,

        [IBREAKA] = gen_wsr_ibreaka,

        [IBREAKA + 1] = gen_wsr_ibreaka,

        [DBREAKA] = gen_wsr_dbreaka,

        [DBREAKA + 1] = gen_wsr_dbreaka,

        [DBREAKC] = gen_wsr_dbreakc,

        [DBREAKC + 1] = gen_wsr_dbreakc,

        [CPENABLE] = gen_wsr_cpenable,

        [INTSET] = gen_wsr_intset,

        [INTCLEAR] = gen_wsr_intclear,

        [INTENABLE] = gen_wsr_intenable,

        [PS] = gen_wsr_ps,

        [DEBUGCAUSE] = gen_wsr_debugcause,

        [PRID] = gen_wsr_prid,

        [ICOUNT] = gen_wsr_icount,

        [ICOUNTLEVEL] = gen_wsr_icountlevel,

        [CCOMPARE] = gen_wsr_ccompare,

        [CCOMPARE + 1] = gen_wsr_ccompare,

        [CCOMPARE + 2] = gen_wsr_ccompare,

    };

    if (sregnames[sr]) {

        if (wsr_handler[sr]) {

            wsr_handler[sr](dc, sr, s);

        } else {

            tcg_gen_mov_i32(cpu_SR[sr], s);

        }

    } else {

        qemu_log("WSR %d not implemented, ", sr);

    }

}


static int connect_namedsocket(const char *path)

{

    int sockfd, size;

    struct sockaddr_un helper;

    if (strlen(path) >= sizeof(helper.sun_path)) {

        fprintf(stderr, "Socket name too large\n");

        return -1;

    }

    sockfd = socket(AF_UNIX, SOCK_STREAM, 0);

    if (sockfd < 0) {

        fprintf(stderr, "failed to create socket: %s\n", strerror(errno));

        return -1;

    }

    strcpy(helper.sun_path, path);

    helper.sun_family = AF_UNIX;

    size = strlen(helper.sun_path) + sizeof(helper.sun_family);

    if (connect(sockfd, (struct sockaddr *)&helper, size) < 0) {

        fprintf(stderr, "failed to connect to %s: %s\n", path, strerror(errno));

        close(sockfd);

        return -1;

    }

    /* remove the socket for security reasons */

    unlink(path);

    return sockfd;

}


static void guest_file_init(void)

{

    QTAILQ_INIT(&guest_file_state.filehandles);

}


static void pchip_write(void *opaque, target_phys_addr_t addr,

                        uint64_t v32, unsigned size)

{

    TyphoonState *s = opaque;

    uint64_t val, oldval;

    if (addr & 4) {

        val = v32 << 32 | s->latch_tmp;

        addr ^= 4;

    } else {

        s->latch_tmp = v32;

        return;

    }

    switch (addr) {

    case 0x0000:

        /* WSBA0: Window Space Base Address Register.  */

        s->pchip.win[0].base_addr = val;

        break;

    case 0x0040:

        /* WSBA1 */

        s->pchip.win[1].base_addr = val;

        break;

    case 0x0080:

        /* WSBA2 */

        s->pchip.win[2].base_addr = val;

        break;

    case 0x00c0:

        /* WSBA3 */

        s->pchip.win[3].base_addr = val;

        break;

    case 0x0100:

        /* WSM0: Window Space Mask Register.  */

        s->pchip.win[0].mask = val;

        break;

    case 0x0140:

        /* WSM1 */

        s->pchip.win[1].mask = val;

        break;

    case 0x0180:

        /* WSM2 */

        s->pchip.win[2].mask = val;

        break;

    case 0x01c0:

        /* WSM3 */

        s->pchip.win[3].mask = val;

        break;

    case 0x0200:

        /* TBA0: Translated Base Address Register.  */

        s->pchip.win[0].translated_base_pfn = val >> 10;

        break;

    case 0x0240:

        /* TBA1 */

        s->pchip.win[1].translated_base_pfn = val >> 10;

        break;

    case 0x0280:

        /* TBA2 */

        s->pchip.win[2].translated_base_pfn = val >> 10;

        break;

    case 0x02c0:

        /* TBA3 */

        s->pchip.win[3].translated_base_pfn = val >> 10;

        break;

    case 0x0300:

        /* PCTL: Pchip Control Register.  */

        oldval = s->pchip.ctl;

        oldval &= ~0x00001cff0fc7ffull;       /* RW fields */

        oldval |= val & 0x00001cff0fc7ffull;

        s->pchip.ctl = oldval;

        break;

    case 0x0340:

        /* PLAT: Pchip Master Latency Register.  */

        break;

    case 0x03c0:

        /* PERROR: Pchip Error Register.  */

        break;

    case 0x0400:

        /* PERRMASK: Pchip Error Mask Register.  */

        break;

    case 0x0440:

        /* PERRSET: Pchip Error Set Register.  */

        break;

    case 0x0480:

        /* TLBIV: Translation Buffer Invalidate Virtual Register.  */

        break;

    case 0x04c0:

        /* TLBIA: Translation Buffer Invalidate All Register (WO).  */

        break;

    case 0x0500:

        /* PMONCTL */

    case 0x0540:

        /* PMONCNT */

    case 0x0800:

        /* SPRST */

        break;

    default:

        cpu_unassigned_access(cpu_single_env, addr, 1, 0, 0, size);

        return;

    }

}


static int usb_host_handle_data(USBDevice *dev, USBPacket *p)

{

    USBHostDevice *s = (USBHostDevice *)dev;

    int ret, fd, mode;

    int one = 1, shortpacket = 0, timeout = 50;

    sigset_t new_mask, old_mask;

    uint8_t devep = p->devep;

    /* protect data transfers from SIGALRM signal */

    sigemptyset(&new_mask);

    sigaddset(&new_mask, SIGALRM);

    sigprocmask(SIG_BLOCK, &new_mask, &old_mask);

    if (p->pid == USB_TOKEN_IN) {

        devep |= 0x80;

        mode = O_RDONLY;

        shortpacket = 1;

    } else {

        mode = O_WRONLY;

    }

    fd = ensure_ep_open(s, devep, mode);

    if (fd < 0) {

        sigprocmask(SIG_SETMASK, &old_mask, NULL);

        return USB_RET_NODEV;

    }

    if (ioctl(fd, USB_SET_TIMEOUT, &timeout) < 0) {

#ifdef DEBUG

        printf("handle_data: failed to set timeout - %s\n",

               strerror(errno));

#endif

    }

    if (shortpacket) {

        if (ioctl(fd, USB_SET_SHORT_XFER, &one) < 0) {

#ifdef DEBUG

            printf("handle_data: failed to set short xfer mode - %s\n",

                   strerror(errno));

#endif

            sigprocmask(SIG_SETMASK, &old_mask, NULL);

        }

    }

    if (p->pid == USB_TOKEN_IN)

        ret = read(fd, p->data, p->len);

    else

        ret = write(fd, p->data, p->len);

    sigprocmask(SIG_SETMASK, &old_mask, NULL);

    if (ret < 0) {

#ifdef DEBUG

        printf("handle_data: error after %s data - %s\n",

               pid == USB_TOKEN_IN ? "reading" : "writing", strerror(errno));

#endif

        switch(errno) {

        case ETIMEDOUT:

        case EINTR:

            return USB_RET_NAK;

        default:

            return USB_RET_STALL;

        }

    } else {

        return ret;

    }

}


int ff_mpv_common_frame_size_change(MpegEncContext *s)

{

    int i, err = 0;

    if (!s->context_initialized)

        return AVERROR(EINVAL);

    if (s->slice_context_count > 1) {

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

            free_duplicate_context(s->thread_context[i]);

        }

        for (i = 1; i < s->slice_context_count; i++) {

            av_freep(&s->thread_context[i]);

        }

    } else

        free_duplicate_context(s);

    free_context_frame(s);

    if (s->picture)

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

                s->picture[i].needs_realloc = 1;

        }

    s->last_picture_ptr         =

    s->next_picture_ptr         =

    s->current_picture_ptr      = NULL;

    // init

    if (s->codec_id == AV_CODEC_ID_MPEG2VIDEO && !s->progressive_sequence)

        s->mb_height = (s->height + 31) / 32 * 2;

    else

        s->mb_height = (s->height + 15) / 16;

    if ((s->width || s->height) &&

        (err = av_image_check_size(s->width, s->height, 0, s->avctx)) < 0)

        goto fail;

    if ((err = init_context_frame(s)))

        goto fail;

    memset(s->thread_context, 0, sizeof(s->thread_context));

    s->thread_context[0]   = s;

    if (s->width && s->height) {

        int nb_slices = s->slice_context_count;

        if (nb_slices > 1) {

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

                if (i) {

                    s->thread_context[i] = av_malloc(sizeof(MpegEncContext));

                    memcpy(s->thread_context[i], s, sizeof(MpegEncContext));

                }

                if ((err = init_duplicate_context(s->thread_context[i])) < 0)

                    goto fail;

                    s->thread_context[i]->start_mb_y =

                        (s->mb_height * (i) + nb_slices / 2) / nb_slices;

                    s->thread_context[i]->end_mb_y   =

                        (s->mb_height * (i + 1) + nb_slices / 2) / nb_slices;

            }

        } else {

            err = init_duplicate_context(s);

            if (err < 0)

                goto fail;

            s->start_mb_y = 0;

            s->end_mb_y   = s->mb_height;

        }

        s->slice_context_count = nb_slices;

    }

    return 0;

 fail:

    ff_mpv_common_end(s);

    return err;

}


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 |= (1 << VIRTIO_F_NOTIFY_ON_EMPTY);

        ret |= (1 << VIRTIO_RING_F_INDIRECT_DESC);

        ret |= (1 << VIRTIO_F_BAD_FEATURE);

        break;

    case VIRTIO_PCI_GUEST_FEATURES:

        ret = vdev->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 int dvbsub_parse_display_definition_segment(AVCodecContext *avctx,

                                                   const uint8_t *buf,

                                                   int buf_size)

{

    DVBSubContext *ctx = avctx->priv_data;

    DVBSubDisplayDefinition *display_def = ctx->display_definition;

    int dds_version, info_byte;

    if (buf_size < 5)

        return AVERROR_INVALIDDATA;

    info_byte   = bytestream_get_byte(&buf);

    dds_version = info_byte >> 4;

    if (display_def && display_def->version == dds_version)

        return 0; // already have this display definition version

    if (!display_def) {

        display_def             = av_mallocz(sizeof(*display_def));

        if (!display_def)

            return AVERROR(ENOMEM);

        ctx->display_definition = display_def;

    }

    display_def->version = dds_version;

    display_def->x       = 0;

    display_def->y       = 0;

    display_def->width   = bytestream_get_be16(&buf) + 1;

    display_def->height  = bytestream_get_be16(&buf) + 1;

    if (!avctx->width || !avctx->height) {

        avctx->width  = display_def->width;

        avctx->height = display_def->height;

    }

    if (buf_size < 13)

        return AVERROR_INVALIDDATA;

    if (info_byte & 1<<3) { // display_window_flag

        display_def->x = bytestream_get_be16(&buf);

        display_def->width  = bytestream_get_be16(&buf) - display_def->x + 1;

        display_def->y = bytestream_get_be16(&buf);

        display_def->height = bytestream_get_be16(&buf) - display_def->y + 1;

    }

    return 0;

}


static void gen_st (DisasContext *ctx, uint32_t opc, int rt,

                    int base, int16_t offset)

{

    TCGv t0 = tcg_temp_new();

    TCGv t1 = tcg_temp_new();

    int mem_idx = ctx->mem_idx;

    gen_base_offset_addr(ctx, t0, base, offset);

    gen_load_gpr(t1, rt);

    switch (opc) {

#if defined(TARGET_MIPS64)

    case OPC_SD:

        tcg_gen_qemu_st_tl(t1, t0, mem_idx, MO_TEQ |

                           ctx->default_tcg_memop_mask);

        break;

    case OPC_SDL:

        gen_helper_0e2i(sdl, t1, t0, mem_idx);

        break;

    case OPC_SDR:

        gen_helper_0e2i(sdr, t1, t0, mem_idx);

        break;

#endif

    case OPC_SW:

        tcg_gen_qemu_st_tl(t1, t0, mem_idx, MO_TEUL |

                           ctx->default_tcg_memop_mask);

        break;

    case OPC_SH:

        tcg_gen_qemu_st_tl(t1, t0, mem_idx, MO_TEUW |

                           ctx->default_tcg_memop_mask);

        break;

    case OPC_SB:

        tcg_gen_qemu_st_tl(t1, t0, mem_idx, MO_8);

        break;

    case OPC_SWL:

        gen_helper_0e2i(swl, t1, t0, mem_idx);

        break;

    case OPC_SWR:

        gen_helper_0e2i(swr, t1, t0, mem_idx);

        break;

    }

    tcg_temp_free(t0);

    tcg_temp_free(t1);

}


static void *qpa_audio_init (void)

{

    return &conf;

}


void timer_deinit(QEMUTimer *ts)

{

    assert(ts->expire_time == -1);

    ts->timer_list = NULL;

}


int ide_init_drive(IDEState *s, BlockDriverState *bs, IDEDriveKind kind,

                   const char *version, const char *serial, const char *model,

                   uint64_t wwn)

{

    int cylinders, heads, secs;

    uint64_t nb_sectors;

    s->bs = bs;

    s->drive_kind = kind;

    bdrv_get_geometry(bs, &nb_sectors);

    bdrv_guess_geometry(bs, &cylinders, &heads, &secs);

    if (cylinders < 1 || cylinders > 16383) {

        error_report("cyls must be between 1 and 16383");

        return -1;

    }

    if (heads < 1 || heads > 16) {

        error_report("heads must be between 1 and 16");

        return -1;

    }

    if (secs < 1 || secs > 63) {

        error_report("secs must be between 1 and 63");

        return -1;

    }

    s->cylinders = cylinders;

    s->heads = heads;

    s->sectors = secs;

    s->nb_sectors = nb_sectors;

    s->wwn = wwn;

    /* The SMART values should be preserved across power cycles

       but they aren't.  */

    s->smart_enabled = 1;

    s->smart_autosave = 1;

    s->smart_errors = 0;

    s->smart_selftest_count = 0;

    if (kind == IDE_CD) {

        bdrv_set_dev_ops(bs, &ide_cd_block_ops, s);

        bdrv_set_buffer_alignment(bs, 2048);

    } else {

        if (!bdrv_is_inserted(s->bs)) {

            error_report("Device needs media, but drive is empty");

            return -1;

        }

        if (bdrv_is_read_only(bs)) {

            error_report("Can't use a read-only drive");

            return -1;

        }

    }

    if (serial) {

        pstrcpy(s->drive_serial_str, sizeof(s->drive_serial_str), serial);

    } else {

        snprintf(s->drive_serial_str, sizeof(s->drive_serial_str),

                 "QM%05d", s->drive_serial);

    }

    if (model) {

        pstrcpy(s->drive_model_str, sizeof(s->drive_model_str), model);

    } else {

        switch (kind) {

        case IDE_CD:

            strcpy(s->drive_model_str, "QEMU DVD-ROM");

            break;

        case IDE_CFATA:

            strcpy(s->drive_model_str, "QEMU MICRODRIVE");

            break;

        default:

            strcpy(s->drive_model_str, "QEMU HARDDISK");

            break;

        }

    }

    if (version) {

        pstrcpy(s->version, sizeof(s->version), version);

    } else {

        pstrcpy(s->version, sizeof(s->version), qemu_get_version());

    }

    ide_reset(s);

    bdrv_iostatus_enable(bs);

    return 0;

}


static QDict *qmp_check_input_obj(QObject *input_obj, Error **errp)

{

    const QDictEntry *ent;

    int has_exec_key = 0;

    QDict *input_dict;

    if (qobject_type(input_obj) != QTYPE_QDICT) {

        error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT, "object");

        return NULL;

    }

    input_dict = qobject_to_qdict(input_obj);

    for (ent = qdict_first(input_dict); ent; ent = qdict_next(input_dict, ent)){

        const char *arg_name = qdict_entry_key(ent);

        const QObject *arg_obj = qdict_entry_value(ent);

        if (!strcmp(arg_name, "execute")) {

            if (qobject_type(arg_obj) != QTYPE_QSTRING) {

                error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT_MEMBER,

                           "execute", "string");

                return NULL;

            }

            has_exec_key = 1;

        } else if (!strcmp(arg_name, "arguments")) {

            if (qobject_type(arg_obj) != QTYPE_QDICT) {

                error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT_MEMBER,

                           "arguments", "object");

                return NULL;

            }

        } else if (!strcmp(arg_name, "id")) {

            /* Any string is acceptable as "id", so nothing to check */

        } else {

            error_setg(errp, QERR_QMP_EXTRA_MEMBER, arg_name);

            return NULL;

        }

    }

    if (!has_exec_key) {

        error_setg(errp, QERR_QMP_BAD_INPUT_OBJECT, "execute");

        return NULL;

    }

    return input_dict;

}


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

{

    int i;

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

        term_handle_byte(buf[i]);

}


static void test_validate_fail_struct_missing(TestInputVisitorData *data,

                                              const void *unused)

{

    Error *err = NULL;

    Visitor *v;

    QObject *any;

    GenericAlternate *alt;

    bool present;

    int en;

    int64_t i64;

    uint32_t u32;

    int8_t i8;

    char *str;

    double dbl;

    v = validate_test_init(data, "{}");

    visit_start_struct(v, NULL, NULL, 0, &error_abort);

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

    error_free_or_abort(&err);

    visit_start_list(v, "list", NULL, 0, &err);

    error_free_or_abort(&err);

    visit_start_alternate(v, "alternate", &alt, sizeof(*alt), false, &err);

    error_free_or_abort(&err);

    visit_optional(v, "optional", &present);

    g_assert(!present);

    visit_type_enum(v, "enum", &en, EnumOne_lookup, &err);

    error_free_or_abort(&err);

    visit_type_int(v, "i64", &i64, &err);

    error_free_or_abort(&err);

    visit_type_uint32(v, "u32", &u32, &err);

    error_free_or_abort(&err);

    visit_type_int8(v, "i8", &i8, &err);

    error_free_or_abort(&err);

    visit_type_str(v, "i8", &str, &err);

    error_free_or_abort(&err);

    visit_type_number(v, "dbl", &dbl, &err);

    error_free_or_abort(&err);

    visit_type_any(v, "any", &any, &err);

    error_free_or_abort(&err);

    visit_type_null(v, "null", &err);

    error_free_or_abort(&err);

    visit_end_struct(v, NULL);

}


void dma_acct_start(BlockDriverState *bs, BlockAcctCookie *cookie,

                    QEMUSGList *sg, enum BlockAcctType type)

{

    block_acct_start(bdrv_get_stats(bs), cookie, sg->size, type);

}


xilinx_axienet_data_stream_push(StreamSlave *obj, uint8_t *buf, size_t size,

                                uint32_t *hdr)

{

    XilinxAXIEnetStreamSlave *ds = XILINX_AXI_ENET_DATA_STREAM(obj);

    XilinxAXIEnet *s = ds->enet;

    /* TX enable ?  */

    if (!(s->tc & TC_TX)) {

        return size;

    }

    /* Jumbo or vlan sizes ?  */

    if (!(s->tc & TC_JUM)) {

        if (size > 1518 && size <= 1522 && !(s->tc & TC_VLAN)) {

            return size;

        }

    }

    if (hdr[0] & 1) {

        unsigned int start_off = hdr[1] >> 16;

        unsigned int write_off = hdr[1] & 0xffff;

        uint32_t tmp_csum;

        uint16_t csum;

        tmp_csum = net_checksum_add(size - start_off,

                                    (uint8_t *)buf + start_off);

        /* Accumulate the seed.  */

        tmp_csum += hdr[2] & 0xffff;

        /* Fold the 32bit partial checksum.  */

        csum = net_checksum_finish(tmp_csum);

        /* Writeback.  */

        buf[write_off] = csum >> 8;

        buf[write_off + 1] = csum & 0xff;

    }

    qemu_send_packet(qemu_get_queue(s->nic), buf, size);

    s->stats.tx_bytes += size;

    s->regs[R_IS] |= IS_TX_COMPLETE;

    enet_update_irq(s);

    return size;

}


void cpu_x86_set_a20(CPUX86State *env, int a20_state)

{

    a20_state = (a20_state != 0);

    if (a20_state != a20_enabled) {

#if defined(DEBUG_MMU)

        printf("A20 update: a20=%d\n", a20_state);

#endif

        /* if the cpu is currently executing code, we must unlink it and

           all the potentially executing TB */

        cpu_interrupt(env, 0);

        /* when a20 is changed, all the MMU mappings are invalid, so

           we must flush everything */

        tlb_flush(env);

        a20_enabled = a20_state;

        if (a20_enabled)

            a20_mask = 0xffffffff;

        else

            a20_mask = 0xffefffff;

    }

}


uint64_t HELPER(cvd)(int32_t bin)

{

    /* positive 0 */

    uint64_t dec = 0x0c;

    int shift = 4;

    if (bin < 0) {

        bin = -bin;

        dec = 0x0d;

    }

    for (shift = 4; (shift < 64) && bin; shift += 4) {

        int current_number = bin % 10;

        dec |= (current_number) << shift;

        bin /= 10;

    }

    return dec;

}


static void tcg_target_qemu_prologue(TCGContext *s)

{

    int frame_size, i;

    /* Allocate space for the fixed frame marker.  */

    frame_size = -TCG_TARGET_CALL_STACK_OFFSET;

    frame_size += TCG_TARGET_STATIC_CALL_ARGS_SIZE;

    /* Allocate space for the saved registers.  */

    frame_size += ARRAY_SIZE(tcg_target_callee_save_regs) * 4;

    /* Align the allocated space.  */

    frame_size = ((frame_size + TCG_TARGET_STACK_ALIGN - 1)

                  & -TCG_TARGET_STACK_ALIGN);

    /* The return address is stored in the caller's frame.  */

    tcg_out_st(s, TCG_TYPE_PTR, TCG_REG_RP, TCG_REG_SP, -20);

    /* Allocate stack frame, saving the first register at the same time.  */

    tcg_out_ldst(s, tcg_target_callee_save_regs[0],

                 TCG_REG_SP, frame_size, INSN_STWM);

    /* Save all callee saved registers.  */

    for (i = 1; i < ARRAY_SIZE(tcg_target_callee_save_regs); i++) {

        tcg_out_st(s, TCG_TYPE_PTR, tcg_target_callee_save_regs[i],

                   TCG_REG_SP, -frame_size + i * 4);

    }

#ifdef CONFIG_USE_GUEST_BASE

    if (GUEST_BASE != 0) {

        tcg_out_movi(s, TCG_TYPE_PTR, TCG_GUEST_BASE_REG, GUEST_BASE);

        tcg_regset_set_reg(s->reserved_regs, TCG_GUEST_BASE_REG);

    }

#endif

    /* Jump to TB, and adjust R18 to be the return address.  */

    tcg_out32(s, INSN_BLE_SR4 | INSN_R2(TCG_REG_R26));

    tcg_out_mov(s, TCG_TYPE_I32, TCG_REG_R18, TCG_REG_R31);

    /* Restore callee saved registers.  */

    tcg_out_ld(s, TCG_TYPE_PTR, TCG_REG_RP, TCG_REG_SP, -frame_size - 20);

    for (i = 1; i < ARRAY_SIZE(tcg_target_callee_save_regs); i++) {

        tcg_out_ld(s, TCG_TYPE_PTR, tcg_target_callee_save_regs[i],

                   TCG_REG_SP, -frame_size + i * 4);

    }

    /* Deallocate stack frame and return.  */

    tcg_out32(s, INSN_BV | INSN_R2(TCG_REG_RP));

    tcg_out_ldst(s, tcg_target_callee_save_regs[0],

                 TCG_REG_SP, -frame_size, INSN_LDWM);

}


bool io_mem_read(MemoryRegion *mr, hwaddr addr, uint64_t *pval, unsigned size)

{

    return memory_region_dispatch_read(mr, addr, pval, size);

}


static void init_scan_tables(H264Context *h)

{

    int i;

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

#define TRANSPOSE(x) (x >> 2) | ((x << 2) & 0xF)

        h->zigzag_scan[i] = TRANSPOSE(ff_zigzag_scan[i]);

        h->field_scan[i]  = TRANSPOSE(field_scan[i]);

#undef TRANSPOSE

    }

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

#define TRANSPOSE(x) (x >> 3) | ((x & 7) << 3)

        h->zigzag_scan8x8[i]       = TRANSPOSE(ff_zigzag_direct[i]);

        h->zigzag_scan8x8_cavlc[i] = TRANSPOSE(zigzag_scan8x8_cavlc[i]);

        h->field_scan8x8[i]        = TRANSPOSE(field_scan8x8[i]);

        h->field_scan8x8_cavlc[i]  = TRANSPOSE(field_scan8x8_cavlc[i]);

#undef TRANSPOSE

    }

    if (h->sps.transform_bypass) { // FIXME same ugly

        h->zigzag_scan_q0          = ff_zigzag_scan;

        h->zigzag_scan8x8_q0       = ff_zigzag_direct;

        h->zigzag_scan8x8_cavlc_q0 = zigzag_scan8x8_cavlc;

        h->field_scan_q0           = field_scan;

        h->field_scan8x8_q0        = field_scan8x8;

        h->field_scan8x8_cavlc_q0  = field_scan8x8_cavlc;

    } else {

        h->zigzag_scan_q0          = h->zigzag_scan;

        h->zigzag_scan8x8_q0       = h->zigzag_scan8x8;

        h->zigzag_scan8x8_cavlc_q0 = h->zigzag_scan8x8_cavlc;

        h->field_scan_q0           = h->field_scan;

        h->field_scan8x8_q0        = h->field_scan8x8;

        h->field_scan8x8_cavlc_q0  = h->field_scan8x8_cavlc;

    }

}


void avg_pixels8_altivec(uint8_t * block, const uint8_t * pixels, int line_size, int h)

{

POWERPC_TBL_DECLARE(altivec_avg_pixels8_num, 1);

#ifdef ALTIVEC_USE_REFERENCE_C_CODE

    int i;

POWERPC_TBL_START_COUNT(altivec_avg_pixels8_num, 1);

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

        *((uint32_t *) (block)) =

            (((*((uint32_t *) (block))) |

              ((((const struct unaligned_32 *) (pixels))->l))) -

             ((((*((uint32_t *) (block))) ^

                ((((const struct unaligned_32 *) (pixels))->

                  l))) & 0xFEFEFEFEUL) >> 1));

        *((uint32_t *) (block + 4)) =

            (((*((uint32_t *) (block + 4))) |

              ((((const struct unaligned_32 *) (pixels + 4))->l))) -

             ((((*((uint32_t *) (block + 4))) ^

                ((((const struct unaligned_32 *) (pixels +

                                                  4))->

                  l))) & 0xFEFEFEFEUL) >> 1));

        pixels += line_size;

        block += line_size;

    }

POWERPC_TBL_STOP_COUNT(altivec_avg_pixels8_num, 1);

#else /* ALTIVEC_USE_REFERENCE_C_CODE */

    register vector unsigned char pixelsv1, pixelsv2, pixelsv, blockv;

    int i;

POWERPC_TBL_START_COUNT(altivec_avg_pixels8_num, 1);

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

     /*

       block is 8 bytes-aligned, so we're either in the

       left block (16 bytes-aligned) or in the right block (not)

     */

     int rightside = ((unsigned long)block & 0x0000000F);

     blockv = vec_ld(0, block);

     pixelsv1 = vec_ld(0, (unsigned char*)pixels);

     pixelsv2 = vec_ld(16, (unsigned char*)pixels);

     pixelsv = vec_perm(pixelsv1, pixelsv2, vec_lvsl(0, pixels));

     if (rightside)

     {

       pixelsv = vec_perm(blockv, pixelsv, vcprm(0,1,s0,s1));

     }

     else

     {

       pixelsv = vec_perm(blockv, pixelsv, vcprm(s0,s1,2,3));

     }

     blockv = vec_avg(blockv, pixelsv);

     vec_st(blockv, 0, block);

     pixels += line_size;

     block += line_size;

   }

POWERPC_TBL_STOP_COUNT(altivec_avg_pixels8_num, 1);

#endif /* ALTIVEC_USE_REFERENCE_C_CODE */

}


int avformat_open_input(AVFormatContext **ps, const char *filename,

                        AVInputFormat *fmt, AVDictionary **options)

{

    AVFormatContext *s = *ps;

    int ret = 0;

    AVDictionary *tmp = NULL;

    ID3v2ExtraMeta *id3v2_extra_meta = NULL;

    if (!s && !(s = avformat_alloc_context()))

        return AVERROR(ENOMEM);

    if (!s->av_class) {

        av_log(NULL, AV_LOG_ERROR, "Input context has not been properly allocated by avformat_alloc_context() and is not NULL either\n");

        return AVERROR(EINVAL);

    }

    if (fmt)

        s->iformat = fmt;

    if (options)

        av_dict_copy(&tmp, *options, 0);

    if ((ret = av_opt_set_dict(s, &tmp)) < 0)

        goto fail;

    if ((ret = init_input(s, filename, &tmp)) < 0)

        goto fail;

    s->probe_score = ret;

    avio_skip(s->pb, s->skip_initial_bytes);

    /* Check filename in case an image number is expected. */

    if (s->iformat->flags & AVFMT_NEEDNUMBER) {

        if (!av_filename_number_test(filename)) {

            ret = AVERROR(EINVAL);

            goto fail;

        }

    }

    s->duration = s->start_time = AV_NOPTS_VALUE;

    av_strlcpy(s->filename, filename ? filename : "", sizeof(s->filename));

    /* Allocate private data. */

    if (s->iformat->priv_data_size > 0) {

        if (!(s->priv_data = av_mallocz(s->iformat->priv_data_size))) {

            ret = AVERROR(ENOMEM);

            goto fail;

        }

        if (s->iformat->priv_class) {

            *(const AVClass **) s->priv_data = s->iformat->priv_class;

            av_opt_set_defaults(s->priv_data);

            if ((ret = av_opt_set_dict(s->priv_data, &tmp)) < 0)

                goto fail;

        }

    }

    /* e.g. AVFMT_NOFILE formats will not have a AVIOContext */

    if (s->pb)

        ff_id3v2_read(s, ID3v2_DEFAULT_MAGIC, &id3v2_extra_meta);

    if (!(s->flags&AVFMT_FLAG_PRIV_OPT) && s->iformat->read_header)

        if ((ret = s->iformat->read_header(s)) < 0)

            goto fail;

    if (id3v2_extra_meta) {

        if (!strcmp(s->iformat->name, "mp3") || !strcmp(s->iformat->name, "aac") ||

            !strcmp(s->iformat->name, "tta")) {

            if ((ret = ff_id3v2_parse_apic(s, &id3v2_extra_meta)) < 0)

                goto fail;

        } else

            av_log(s, AV_LOG_DEBUG, "demuxer does not support additional id3 data, skipping\n");

    }

    ff_id3v2_free_extra_meta(&id3v2_extra_meta);

    if ((ret = avformat_queue_attached_pictures(s)) < 0)

        goto fail;

    if (!(s->flags&AVFMT_FLAG_PRIV_OPT) && s->pb && !s->data_offset)

        s->data_offset = avio_tell(s->pb);

    s->raw_packet_buffer_remaining_size = RAW_PACKET_BUFFER_SIZE;

    if (options) {

        av_dict_free(options);

        *options = tmp;

    }

    *ps = s;

    return 0;

fail:

    ff_id3v2_free_extra_meta(&id3v2_extra_meta);

    av_dict_free(&tmp);

    if (s->pb && !(s->flags & AVFMT_FLAG_CUSTOM_IO))

        avio_close(s->pb);

    avformat_free_context(s);

    *ps = NULL;

    return ret;

}


static av_always_inline void hl_decode_mb_predict_luma(const H264Context *h,

                                                       H264SliceContext *sl,

                                                       int mb_type, int simple,

                                                       int transform_bypass,

                                                       int pixel_shift,

                                                       const int *block_offset,

                                                       int linesize,

                                                       uint8_t *dest_y, int p)

{

    void (*idct_add)(uint8_t *dst, int16_t *block, int stride);

    void (*idct_dc_add)(uint8_t *dst, int16_t *block, int stride);

    int i;

    int qscale = p == 0 ? sl->qscale : sl->chroma_qp[p - 1];

    block_offset += 16 * p;

    if (IS_INTRA4x4(mb_type)) {

        if (IS_8x8DCT(mb_type)) {

            if (transform_bypass) {

                idct_dc_add =

                idct_add    = h->h264dsp.h264_add_pixels8_clear;

            } else {

                idct_dc_add = h->h264dsp.h264_idct8_dc_add;

                idct_add    = h->h264dsp.h264_idct8_add;

            }

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

                uint8_t *const ptr = dest_y + block_offset[i];

                const int dir      = sl->intra4x4_pred_mode_cache[scan8[i]];

                if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {

                    h->hpc.pred8x8l_add[dir](ptr, sl->mb + (i * 16 + p * 256 << pixel_shift), linesize);

                } else {

                    const int nnz = sl->non_zero_count_cache[scan8[i + p * 16]];

                    h->hpc.pred8x8l[dir](ptr, (sl->topleft_samples_available << i) & 0x8000,

                                         (sl->topright_samples_available << i) & 0x4000, linesize);

                    if (nnz) {

                        if (nnz == 1 && dctcoef_get(sl->mb, pixel_shift, i * 16 + p * 256))

                            idct_dc_add(ptr, sl->mb + (i * 16 + p * 256 << pixel_shift), linesize);

                        else

                            idct_add(ptr, sl->mb + (i * 16 + p * 256 << pixel_shift), linesize);

                    }

                }

            }

        } else {

            if (transform_bypass) {

                idct_dc_add  =

                idct_add     = h->h264dsp.h264_add_pixels4_clear;

            } else {

                idct_dc_add = h->h264dsp.h264_idct_dc_add;

                idct_add    = h->h264dsp.h264_idct_add;

            }

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

                uint8_t *const ptr = dest_y + block_offset[i];

                const int dir      = sl->intra4x4_pred_mode_cache[scan8[i]];

                if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {

                    h->hpc.pred4x4_add[dir](ptr, sl->mb + (i * 16 + p * 256 << pixel_shift), linesize);

                } else {

                    uint8_t *topright;

                    int nnz, tr;

                    uint64_t tr_high;

                    if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) {

                        const int topright_avail = (sl->topright_samples_available << i) & 0x8000;

                        assert(sl->mb_y || linesize <= block_offset[i]);

                        if (!topright_avail) {

                            if (pixel_shift) {

                                tr_high  = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL;

                                topright = (uint8_t *)&tr_high;

                            } else {

                                tr       = ptr[3 - linesize] * 0x01010101u;

                                topright = (uint8_t *)&tr;

                            }

                        } else

                            topright = ptr + (4 << pixel_shift) - linesize;

                    } else

                        topright = NULL;

                    h->hpc.pred4x4[dir](ptr, topright, linesize);

                    nnz = sl->non_zero_count_cache[scan8[i + p * 16]];

                    if (nnz) {

                        if (nnz == 1 && dctcoef_get(sl->mb, pixel_shift, i * 16 + p * 256))

                            idct_dc_add(ptr, sl->mb + (i * 16 + p * 256 << pixel_shift), linesize);

                        else

                            idct_add(ptr, sl->mb + (i * 16 + p * 256 << pixel_shift), linesize);

                    }

                }

            }

        }

    } else {

        h->hpc.pred16x16[sl->intra16x16_pred_mode](dest_y, linesize);

        if (sl->non_zero_count_cache[scan8[LUMA_DC_BLOCK_INDEX + p]]) {

            if (!transform_bypass)

                h->h264dsp.h264_luma_dc_dequant_idct(sl->mb + (p * 256 << pixel_shift),

                                                     sl->mb_luma_dc[p],

                                                     h->dequant4_coeff[p][qscale][0]);

            else {

                static const uint8_t dc_mapping[16] = {

                     0 * 16,  1 * 16,  4 * 16,  5 * 16,

                     2 * 16,  3 * 16,  6 * 16,  7 * 16,

                     8 * 16,  9 * 16, 12 * 16, 13 * 16,

                    10 * 16, 11 * 16, 14 * 16, 15 * 16

                };

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

                    dctcoef_set(sl->mb + (p * 256 << pixel_shift),

                                pixel_shift, dc_mapping[i],

                                dctcoef_get(sl->mb_luma_dc[p],

                                            pixel_shift, i));

            }

        }

    }

}


static void peak_write_chunk(AVFormatContext *s)

{

    WAVMuxContext *wav = s->priv_data;

    AVIOContext *pb = s->pb;

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

    int64_t peak = ff_start_tag(s->pb, "levl");

    int64_t now0;

    time_t now_secs;

    char timestamp[28];

    /* Peak frame of incomplete block at end */

    if (wav->peak_block_pos)

        peak_write_frame(s);

    memset(timestamp, 0, sizeof(timestamp));

    if (!(s->flags & AVFMT_FLAG_BITEXACT)) {

        struct tm tmpbuf;

        av_log(s, AV_LOG_INFO, "Writing local time and date to Peak Envelope Chunk\n");

        now0 = av_gettime();

        now_secs = now0 / 1000000;

        strftime(timestamp, sizeof(timestamp), "%Y:%m:%d:%H:%M:%S:", localtime_r(&now_secs, &tmpbuf));

        av_strlcatf(timestamp, sizeof(timestamp), "%03d", (int)((now0 / 1000) % 1000));

    }

    avio_wl32(pb, 1);                           /* version */

    avio_wl32(pb, wav->peak_format);            /* 8 or 16 bit */

    avio_wl32(pb, wav->peak_ppv);               /* positive and negative */

    avio_wl32(pb, wav->peak_block_size);        /* frames per value */

    avio_wl32(pb, enc->channels);               /* number of channels */

    avio_wl32(pb, wav->peak_num_frames);        /* number of peak frames */

    avio_wl32(pb, wav->peak_pos_pop);           /* audio sample frame index */

    avio_wl32(pb, 128);                         /* equal to size of header */

    avio_write(pb, timestamp, 28);              /* ASCII time stamp */

    ffio_fill(pb, 0, 60);

    avio_write(pb, wav->peak_output, wav->peak_outbuf_bytes);

    ff_end_tag(pb, peak);

    if (!wav->data)

        wav->data = peak;

}


static void qmp_input_end_list(Visitor *v)

{

    QmpInputVisitor *qiv = to_qiv(v);

    qmp_input_pop(qiv, &error_abort);

}


static int get_uint32(QEMUFile *f, void *pv, size_t size)

{

    uint32_t *v = pv;

    qemu_get_be32s(f, v);

    return 0;

}


static void *data_plane_thread(void *opaque)

{

    VirtIOBlockDataPlane *s = opaque;

    do {

        event_poll(&s->event_poll);

    } while (s->started || s->num_reqs > 0);

    return NULL;

}


void bdrv_close_all(void)

{

    BlockDriverState *bs;

    QTAILQ_FOREACH(bs, &bdrv_states, device_list) {

        AioContext *aio_context = bdrv_get_aio_context(bs);

        aio_context_acquire(aio_context);

        bdrv_close(bs);

        aio_context_release(aio_context);

    }

}


void monitor_init(CharDriverState *chr, int flags)

{

    static int is_first_init = 1;

    Monitor *mon;

    if (is_first_init) {

        monitor_qapi_event_init();

        sortcmdlist();

        is_first_init = 0;

    }

    mon = g_malloc(sizeof(*mon));

    monitor_data_init(mon);

    mon->chr = chr;

    mon->flags = flags;

    if (flags & MONITOR_USE_READLINE) {

        mon->rs = readline_init(monitor_readline_printf,

                                monitor_readline_flush,

                                mon,

                                monitor_find_completion);

        monitor_read_command(mon, 0);

    }

    if (monitor_is_qmp(mon)) {

        qemu_chr_add_handlers(chr, monitor_can_read, monitor_qmp_read,

                              monitor_qmp_event, mon);

        qemu_chr_fe_set_echo(chr, true);

        json_message_parser_init(&mon->qmp.parser, handle_qmp_command);

    } else {

        qemu_chr_add_handlers(chr, monitor_can_read, monitor_read,

                              monitor_event, mon);

    }

    qemu_mutex_lock(&monitor_lock);

    QLIST_INSERT_HEAD(&mon_list, mon, entry);

    qemu_mutex_unlock(&monitor_lock);

    if (!default_mon || (flags & MONITOR_IS_DEFAULT))

        default_mon = mon;

}


static sPAPRDRConnector *spapr_phb_get_pci_drc(sPAPRPHBState *phb,

                                               PCIDevice *pdev)

{

    uint32_t busnr = pci_bus_num(PCI_BUS(qdev_get_parent_bus(DEVICE(pdev))));

    return spapr_dr_connector_by_id(SPAPR_DR_CONNECTOR_TYPE_PCI,

                                    (phb->index << 16) |

                                    (busnr << 8) |

                                    pdev->devfn);

}


int ff_socket_nonblock(int socket, int enable)

{

#ifdef __MINGW32__

   return ioctlsocket(socket, FIONBIO, &enable);

#else

   if (enable)

      return fcntl(socket, F_SETFL, fcntl(socket, F_GETFL) | O_NONBLOCK);

   else

      return fcntl(socket, F_SETFL, fcntl(socket, F_GETFL) & ~O_NONBLOCK);

#endif

}


static void adb_kbd_put_keycode(void *opaque, int keycode)

{

    KBDState *s = opaque;

    if (s->count < sizeof(s->data)) {

        s->data[s->wptr] = keycode;

        if (++s->wptr == sizeof(s->data))

            s->wptr = 0;

        s->count++;

    }

}


static void nvdimm_build_nfit(GSList *device_list, GArray *table_offsets,

                              GArray *table_data, GArray *linker)

{

    GArray *structures = nvdimm_build_device_structure(device_list);

    void *header;

    acpi_add_table(table_offsets, table_data);

    /* NFIT header. */

    header = acpi_data_push(table_data, sizeof(NvdimmNfitHeader));

    /* NVDIMM device structures. */

    g_array_append_vals(table_data, structures->data, structures->len);

    build_header(linker, table_data, header, "NFIT",

                 sizeof(NvdimmNfitHeader) + structures->len, 1, NULL);

    g_array_free(structures, true);

}


static int v9fs_do_mksock(V9fsState *s, V9fsString *path)

{

    return s->ops->mksock(&s->ctx, path->data);

}


static ram_addr_t ram_block_add(RAMBlock *new_block, Error **errp)

{

    RAMBlock *block;

    ram_addr_t old_ram_size, new_ram_size;

    old_ram_size = last_ram_offset() >> TARGET_PAGE_BITS;

    /* This assumes the iothread lock is taken here too.  */

    qemu_mutex_lock_ramlist();

    new_block->offset = find_ram_offset(new_block->max_length);

    if (!new_block->host) {

        if (xen_enabled()) {

            xen_ram_alloc(new_block->offset, new_block->max_length,

                          new_block->mr);

        } else {

            new_block->host = phys_mem_alloc(new_block->max_length,

                                             &new_block->mr->align);

            if (!new_block->host) {

                error_setg_errno(errp, errno,

                                 "cannot set up guest memory '%s'",

                                 memory_region_name(new_block->mr));

                qemu_mutex_unlock_ramlist();

                return -1;

            }

            memory_try_enable_merging(new_block->host, new_block->max_length);

        }

    }

    /* Keep the list sorted from biggest to smallest block.  */

    QTAILQ_FOREACH(block, &ram_list.blocks, next) {

        if (block->max_length < new_block->max_length) {

            break;

        }

    }

    if (block) {

        QTAILQ_INSERT_BEFORE(block, new_block, next);

    } else {

        QTAILQ_INSERT_TAIL(&ram_list.blocks, new_block, next);

    }

    ram_list.mru_block = NULL;

    ram_list.version++;

    qemu_mutex_unlock_ramlist();

    new_ram_size = last_ram_offset() >> TARGET_PAGE_BITS;

    if (new_ram_size > old_ram_size) {

        int i;

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

            ram_list.dirty_memory[i] =

                bitmap_zero_extend(ram_list.dirty_memory[i],

                                   old_ram_size, new_ram_size);

       }

    }

    cpu_physical_memory_set_dirty_range(new_block->offset,

                                        new_block->used_length);

    qemu_ram_setup_dump(new_block->host, new_block->max_length);

    qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_HUGEPAGE);

    qemu_madvise(new_block->host, new_block->max_length, QEMU_MADV_DONTFORK);

    if (kvm_enabled()) {

        kvm_setup_guest_memory(new_block->host, new_block->max_length);

    }

    return new_block->offset;

}


static void filter(FSPPContext *p, uint8_t *dst, uint8_t *src,

                   int dst_stride, int src_stride,

                   int width, int height,

                   uint8_t *qp_store, int qp_stride, int is_luma)

{

    int x, x0, y, es, qy, t;

    const int stride = is_luma ? p->temp_stride : (width + 16);

    const int step = 6 - p->log2_count;

    const int qpsh = 4 - p->hsub * !is_luma;

    const int qpsv = 4 - p->vsub * !is_luma;

    DECLARE_ALIGNED(32, int32_t, block_align)[4 * 8 * BLOCKSZ + 4 * 8 * BLOCKSZ];

    int16_t *block  = (int16_t *)block_align;

    int16_t *block3 = (int16_t *)(block_align + 4 * 8 * BLOCKSZ);

    memset(block3, 0, 4 * 8 * BLOCKSZ);

    if (!src || !dst) return;

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

        int index = 8 + 8 * stride + y * stride;

        memcpy(p->src + index, src + y * src_stride, width);

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

            p->src[index         - x - 1] = p->src[index +         x    ];

            p->src[index + width + x    ] = p->src[index + width - x - 1];

        }

    }

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

        memcpy(p->src + (     7 - y    ) * stride, p->src + (     y + 8    ) * stride, stride);

        memcpy(p->src + (height + 8 + y) * stride, p->src + (height - y + 7) * stride, stride);

    }

    //FIXME (try edge emu)

    for (y = 8; y < 24; y++)

        memset(p->temp + 8 + y * stride, 0, width * sizeof(int16_t));

    for (y = step; y < height + 8; y += step) {    //step= 1,2

        const int y1 = y - 8 + step;                 //l5-7  l4-6;

        qy = y - 4;

        if (qy > height - 1) qy = height - 1;

        if (qy < 0) qy = 0;

        qy = (qy >> qpsv) * qp_stride;

        p->row_fdct(block, p->src + y * stride + 2 - (y&1), stride, 2);

        for (x0 = 0; x0 < width + 8 - 8 * (BLOCKSZ - 1); x0 += 8 * (BLOCKSZ - 1)) {

            p->row_fdct(block + 8 * 8, p->src + y * stride + 8 + x0 + 2 - (y&1), stride, 2 * (BLOCKSZ - 1));

            if (p->qp)

                p->column_fidct((int16_t *)(&p->threshold_mtx[0]), block + 0 * 8, block3 + 0 * 8, 8 * (BLOCKSZ - 1)); //yes, this is a HOTSPOT

            else

                for (x = 0; x < 8 * (BLOCKSZ - 1); x += 8) {

                    t = x + x0 - 2;                    //correct t=x+x0-2-(y&1), but its the same

                    if (t < 0) t = 0;                   //t always < width-2

                    t = qp_store[qy + (t >> qpsh)];

                    t = ff_norm_qscale(t, p->qscale_type);

                    if (t != p->prev_q) p->prev_q = t, p->mul_thrmat((int16_t *)(&p->threshold_mtx_noq[0]), (int16_t *)(&p->threshold_mtx[0]), t);

                    p->column_fidct((int16_t *)(&p->threshold_mtx[0]), block + x * 8, block3 + x * 8, 8); //yes, this is a HOTSPOT

                }

            p->row_idct(block3 + 0 * 8, p->temp + (y & 15) * stride + x0 + 2 - (y & 1), stride, 2 * (BLOCKSZ - 1));

            memmove(block,  block  + (BLOCKSZ - 1) * 64, 8 * 8 * sizeof(int16_t)); //cycling

            memmove(block3, block3 + (BLOCKSZ - 1) * 64, 6 * 8 * sizeof(int16_t));

        }

        es = width + 8 - x0; //  8, ...

        if (es > 8)

            p->row_fdct(block + 8 * 8, p->src + y * stride + 8 + x0 + 2 - (y & 1), stride, (es - 4) >> 2);

        p->column_fidct((int16_t *)(&p->threshold_mtx[0]), block, block3, es&(~1));

        p->row_idct(block3 + 0 * 8, p->temp + (y & 15) * stride + x0 + 2 - (y & 1), stride, es >> 2);

        if (!(y1 & 7) && y1) {

            if (y1 & 8)

                p->store_slice(dst + (y1 - 8) * dst_stride, p->temp + 8 + 8 * stride,

                               dst_stride, stride, width, 8, 5 - p->log2_count);

            else

                p->store_slice2(dst + (y1 - 8) * dst_stride, p->temp + 8 + 0 * stride,

                                dst_stride, stride, width, 8, 5 - p->log2_count);

        }

    }

    if (y & 7) {  // height % 8 != 0

        if (y & 8)

            p->store_slice(dst + ((y - 8) & ~7) * dst_stride, p->temp + 8 + 8 * stride,

                           dst_stride, stride, width, y&7, 5 - p->log2_count);

        else

            p->store_slice2(dst + ((y - 8) & ~7) * dst_stride, p->temp + 8 + 0 * stride,

                            dst_stride, stride, width, y&7, 5 - p->log2_count);

    }

}


static void make_dirty(uint8_t device)

{

    QPCIDevice *dev;

    QPCIBar bmdma_bar, ide_bar;

    uint8_t status;

    size_t len = 512;

    uintptr_t guest_buf;

    void* buf;

    dev = get_pci_device(&bmdma_bar, &ide_bar);

    guest_buf = guest_alloc(guest_malloc, len);

    buf = g_malloc(len);

    memset(buf, rand() % 255 + 1, len);

    g_assert(guest_buf);

    g_assert(buf);

    memwrite(guest_buf, buf, len);

    PrdtEntry prdt[] = {

        {

            .addr = cpu_to_le32(guest_buf),

            .size = cpu_to_le32(len | PRDT_EOT),

        },

    };

    status = send_dma_request(CMD_WRITE_DMA, 1, 1, prdt,

                              ARRAY_SIZE(prdt), NULL);

    g_assert_cmphex(status, ==, BM_STS_INTR);

    assert_bit_clear(qpci_io_readb(dev, ide_bar, reg_status), DF | ERR);

    g_free(buf);

}


unsigned long find_next_bit(const unsigned long *addr, unsigned long size,

			    unsigned long offset)

{

    const unsigned long *p = addr + BITOP_WORD(offset);

    unsigned long result = offset & ~(BITS_PER_LONG-1);

    unsigned long tmp;

    if (offset >= size) {

        return size;

    }

    size -= result;

    offset %= BITS_PER_LONG;

    if (offset) {

        tmp = *(p++);

        tmp &= (~0UL << offset);

        if (size < BITS_PER_LONG) {

            goto found_first;

        }

        if (tmp) {

            goto found_middle;

        }

        size -= BITS_PER_LONG;

        result += BITS_PER_LONG;

    }

    while (size & ~(BITS_PER_LONG-1)) {

        if ((tmp = *(p++))) {

            goto found_middle;

        }

        result += BITS_PER_LONG;

        size -= BITS_PER_LONG;

    }

    if (!size) {

        return result;

    }

    tmp = *p;

found_first:

    tmp &= (~0UL >> (BITS_PER_LONG - size));

    if (tmp == 0UL) {		/* Are any bits set? */

        return result + size;	/* Nope. */

    }

found_middle:

    return result + ctzl(tmp);

}


uint64_t helper_cmpbge(uint64_t op1, uint64_t op2)

{

    uint8_t opa, opb, res;

    int i;

    res = 0;

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

        opa = op1 >> (i * 8);

        opb = op2 >> (i * 8);

        if (opa >= opb) {

            res |= 1 << i;

        }

    }

    return res;

}


void helper_check_iol(CPUX86State *env, uint32_t t0)

{

    check_io(env, t0, 4);

}


static void ccid_card_vscard_handle_message(PassthruState *card,

    VSCMsgHeader *scr_msg_header)

{

    uint8_t *data = (uint8_t *)&scr_msg_header[1];

    switch (scr_msg_header->type) {

    case VSC_ATR:

        DPRINTF(card, D_INFO, "VSC_ATR %d\n", scr_msg_header->length);

        if (scr_msg_header->length > MAX_ATR_SIZE) {

            error_report("ATR size exceeds spec, ignoring");

            ccid_card_vscard_send_error(card, scr_msg_header->reader_id,

                                        VSC_GENERAL_ERROR);

        }

        memcpy(card->atr, data, scr_msg_header->length);

        card->atr_length = scr_msg_header->length;

        ccid_card_card_inserted(&card->base);

        ccid_card_vscard_send_error(card, scr_msg_header->reader_id,

                                    VSC_SUCCESS);

    case VSC_APDU:

        ccid_card_send_apdu_to_guest(

            &card->base, data, scr_msg_header->length);

    case VSC_CardRemove:

        DPRINTF(card, D_INFO, "VSC_CardRemove\n");

        ccid_card_card_removed(&card->base);

        ccid_card_vscard_send_error(card,

            scr_msg_header->reader_id, VSC_SUCCESS);

    case VSC_Init:

        ccid_card_vscard_handle_init(

            card, scr_msg_header, (VSCMsgInit *)data);

    case VSC_Error:

        ccid_card_card_error(&card->base, *(uint32_t *)data);

    case VSC_ReaderAdd:

        if (ccid_card_ccid_attach(&card->base) < 0) {

            ccid_card_vscard_send_error(card, VSCARD_UNDEFINED_READER_ID,

                                      VSC_CANNOT_ADD_MORE_READERS);

        } else {

            ccid_card_vscard_send_error(card, VSCARD_MINIMAL_READER_ID,

                                        VSC_SUCCESS);

        }

    case VSC_ReaderRemove:

        ccid_card_ccid_detach(&card->base);

        ccid_card_vscard_send_error(card,

            scr_msg_header->reader_id, VSC_SUCCESS);

    default:

        printf("usb-ccid: chardev: unexpected message of type %X\n",

               scr_msg_header->type);

        ccid_card_vscard_send_error(card, scr_msg_header->reader_id,

            VSC_GENERAL_ERROR);

    }

}


static inline uint64_t do_fri(CPUPPCState *env, uint64_t arg,

                              int rounding_mode)

{

    CPU_DoubleU farg;

    farg.ll = arg;

    if (unlikely(float64_is_signaling_nan(farg.d))) {

        /* sNaN round */

        farg.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXSNAN |

                                        POWERPC_EXCP_FP_VXCVI);

    } else if (unlikely(float64_is_quiet_nan(farg.d) ||

                        float64_is_infinity(farg.d))) {

        /* qNan / infinity round */

        farg.ll = fload_invalid_op_excp(env, POWERPC_EXCP_FP_VXCVI);

    } else {

        set_float_rounding_mode(rounding_mode, &env->fp_status);

        farg.ll = float64_round_to_int(farg.d, &env->fp_status);

        /* Restore rounding mode from FPSCR */

        fpscr_set_rounding_mode(env);

    }

    return farg.ll;

}


int DMA_write_memory (int nchan, void *buf, int pos, int len)

{

    struct dma_regs *r = &dma_controllers[nchan > 3].regs[nchan & 3];

    target_phys_addr_t addr = ((r->pageh & 0x7f) << 24) | (r->page << 16) | r->now[ADDR];

    if (r->mode & 0x20) {

        int i;

        uint8_t *p = buf;

        cpu_physical_memory_write (addr - pos - len, buf, len);

        /* What about 16bit transfers? */

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

            uint8_t b = p[len - i - 1];

            p[i] = b;

        }

    }

    else

        cpu_physical_memory_write (addr + pos, buf, len);

    return len;

}


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

{

    SysBusDevice *sbd = SYS_BUS_DEVICE(dev);

    TCXState *s = TCX(dev);

    ram_addr_t vram_offset = 0;

    int size, ret;

    uint8_t *vram_base;

    char *fcode_filename;

    memory_region_init_ram(&s->vram_mem, OBJECT(s), "tcx.vram",

                           s->vram_size * (1 + 4 + 4), &error_fatal);

    vmstate_register_ram_global(&s->vram_mem);

    memory_region_set_log(&s->vram_mem, true, DIRTY_MEMORY_VGA);

    vram_base = memory_region_get_ram_ptr(&s->vram_mem);

    /* 10/ROM : FCode ROM */

    vmstate_register_ram_global(&s->rom);

    fcode_filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, TCX_ROM_FILE);

    if (fcode_filename) {

        ret = load_image_targphys(fcode_filename, s->prom_addr,

                                  FCODE_MAX_ROM_SIZE);

        g_free(fcode_filename);

        if (ret < 0 || ret > FCODE_MAX_ROM_SIZE) {

            error_report("tcx: could not load prom '%s'", TCX_ROM_FILE);

        }

    }

    /* 0/DFB8 : 8-bit plane */

    s->vram = vram_base;

    size = s->vram_size;

    memory_region_init_alias(&s->vram_8bit, OBJECT(s), "tcx.vram.8bit",

                             &s->vram_mem, vram_offset, size);

    sysbus_init_mmio(sbd, &s->vram_8bit);

    vram_offset += size;

    vram_base += size;

    /* 1/DFB24 : 24bit plane */

    size = s->vram_size * 4;

    s->vram24 = (uint32_t *)vram_base;

    s->vram24_offset = vram_offset;

    memory_region_init_alias(&s->vram_24bit, OBJECT(s), "tcx.vram.24bit",

                             &s->vram_mem, vram_offset, size);

    sysbus_init_mmio(sbd, &s->vram_24bit);

    vram_offset += size;

    vram_base += size;

    /* 4/RDFB32 : Raw Framebuffer */

    size = s->vram_size * 4;

    s->cplane = (uint32_t *)vram_base;

    s->cplane_offset = vram_offset;

    memory_region_init_alias(&s->vram_cplane, OBJECT(s), "tcx.vram.cplane",

                             &s->vram_mem, vram_offset, size);

    sysbus_init_mmio(sbd, &s->vram_cplane);

    /* 9/THC24bits : NetBSD writes here even with 8-bit display: dummy */

    if (s->depth == 8) {

        memory_region_init_io(&s->thc24, OBJECT(s), &tcx_dummy_ops, s,

                              "tcx.thc24", TCX_THC_NREGS);

        sysbus_init_mmio(sbd, &s->thc24);

    }

    sysbus_init_irq(sbd, &s->irq);

    if (s->depth == 8) {

        s->con = graphic_console_init(DEVICE(dev), 0, &tcx_ops, s);

    } else {

        s->con = graphic_console_init(DEVICE(dev), 0, &tcx24_ops, s);

    }

    s->thcmisc = 0;

    qemu_console_resize(s->con, s->width, s->height);

}


LinuxAioState *aio_get_linux_aio(AioContext *ctx)

{

    if (!ctx->linux_aio) {

        ctx->linux_aio = laio_init();

        laio_attach_aio_context(ctx->linux_aio, ctx);

    }

    return ctx->linux_aio;

}


static int replaygain_export(AVStream *st,

                             const uint8_t *track_gain, const uint8_t *track_peak,

                             const uint8_t *album_gain, const uint8_t *album_peak)

{

    AVPacketSideData *sd, *tmp;

    AVReplayGain *replaygain;

    int32_t tg, ag;

    uint32_t tp, ap;

    tg = parse_value(track_gain, INT32_MIN);

    ag = parse_value(album_gain, INT32_MIN);

    tp = parse_value(track_peak, 0);

    ap = parse_value(album_peak, 0);

    if (tg == INT32_MIN && ag == INT32_MIN)

        return 0;

    replaygain = av_mallocz(sizeof(*replaygain));

    if (!replaygain)

        return AVERROR(ENOMEM);

    tmp = av_realloc_array(st->side_data, st->nb_side_data + 1, sizeof(*tmp));

    if (!tmp) {

        av_freep(&replaygain);

        return AVERROR(ENOMEM);

    }

    st->side_data = tmp;

    st->nb_side_data++;

    sd = &st->side_data[st->nb_side_data - 1];

    sd->type = AV_PKT_DATA_REPLAYGAIN;

    sd->data = (uint8_t*)replaygain;

    sd->size = sizeof(*replaygain);

    replaygain->track_gain = tg;

    replaygain->track_peak = tp;

    replaygain->album_gain = ag;

    replaygain->album_peak = ap;

    return 0;

}


static int gif_read_header1(GifState *s)

{

    uint8_t sig[6];

    int v, n;

    int background_color_index;

    if (bytestream2_get_bytes_left(&s->gb) < 13)

        return AVERROR_INVALIDDATA;

    /* read gif signature */

    bytestream2_get_bufferu(&s->gb, sig, 6);

    if (memcmp(sig, gif87a_sig, 6) != 0 &&

        memcmp(sig, gif89a_sig, 6) != 0)

        return AVERROR_INVALIDDATA;

    /* read screen header */

    s->transparent_color_index = -1;

    s->screen_width = bytestream2_get_le16u(&s->gb);

    s->screen_height = bytestream2_get_le16u(&s->gb);

    if(   (unsigned)s->screen_width  > 32767

       || (unsigned)s->screen_height > 32767){

        av_log(s->avctx, AV_LOG_ERROR, "picture size too large\n");

        return AVERROR_INVALIDDATA;

    }

    av_fast_malloc(&s->idx_line, &s->idx_line_size, s->screen_width);

    if (!s->idx_line)

        return AVERROR(ENOMEM);

    v = bytestream2_get_byteu(&s->gb);

    s->color_resolution = ((v & 0x70) >> 4) + 1;

    s->has_global_palette = (v & 0x80);

    s->bits_per_pixel = (v & 0x07) + 1;

    background_color_index = bytestream2_get_byteu(&s->gb);

    n = bytestream2_get_byteu(&s->gb);

    if (n) {

        s->avctx->sample_aspect_ratio.num = n + 15;

        s->avctx->sample_aspect_ratio.den = 64;

    }

    av_dlog(s->avctx, "screen_w=%d screen_h=%d bpp=%d global_palette=%d\n",

           s->screen_width, s->screen_height, s->bits_per_pixel,

           s->has_global_palette);

    if (s->has_global_palette) {

        s->background_color_index = background_color_index;

        n = 1 << s->bits_per_pixel;

        if (bytestream2_get_bytes_left(&s->gb) < n * 3)

            return AVERROR_INVALIDDATA;

        gif_read_palette(s, s->global_palette, n);

        s->bg_color = s->global_palette[s->background_color_index];

    } else

        s->background_color_index = -1;

    return 0;

}