static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)

{

    AVIContext *avi = s->priv_data;

    ByteIOContext *pb = &s->pb;

    uint32_t tag, tag1, handler;

    int codec_type, stream_index, frame_period, bit_rate;

    unsigned int size, nb_frames;

    int i, n;

    AVStream *st;

    AVIStream *ast = NULL;

    int xan_video = 0;  /* hack to support Xan A/V */

    char str_track[4];

    avi->stream_index= -1;

    if (get_riff(avi, pb) < 0)

        return -1;

    /* first list tag */

    stream_index = -1;

    codec_type = -1;

    frame_period = 0;

    for(;;) {

        if (url_feof(pb))

            goto fail;

        tag = get_le32(pb);

        size = get_le32(pb);

#ifdef DEBUG

        print_tag("tag", tag, size);

#endif

        switch(tag) {

        case MKTAG('L', 'I', 'S', 'T'):

            /* ignored, except when start of video packets */

            tag1 = get_le32(pb);

#ifdef DEBUG

            print_tag("list", tag1, 0);

#endif

            if (tag1 == MKTAG('m', 'o', 'v', 'i')) {

                avi->movi_list = url_ftell(pb) - 4;

                if(size) avi->movi_end = avi->movi_list + size + (size & 1);

                else     avi->movi_end = url_fsize(pb);

#ifdef DEBUG

                printf("movi end=%"PRIx64"\n", avi->movi_end);

#endif

                goto end_of_header;

            }

            break;

        case MKTAG('d', 'm', 'l', 'h'):

            avi->is_odml = 1;

            url_fskip(pb, size + (size & 1));

            break;

        case MKTAG('a', 'v', 'i', 'h'):

            /* avi header */

            /* using frame_period is bad idea */

            frame_period = get_le32(pb);

            bit_rate = get_le32(pb) * 8;

            get_le32(pb);

            avi->non_interleaved |= get_le32(pb) & AVIF_MUSTUSEINDEX;

            url_fskip(pb, 2 * 4);

            n = get_le32(pb);

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

                AVIStream *ast;

                st = av_new_stream(s, i);

                if (!st)

                    goto fail;

                ast = av_mallocz(sizeof(AVIStream));

                if (!ast)

                    goto fail;

                st->priv_data = ast;

            }

            url_fskip(pb, size - 7 * 4);

            break;

        case MKTAG('s', 't', 'r', 'h'):

            /* stream header */

            stream_index++;

            tag1 = get_le32(pb);

            handler = get_le32(pb); /* codec tag */

#ifdef DEBUG

            print_tag("strh", tag1, -1);

#endif

            if(tag1 == MKTAG('i', 'a', 'v', 's') || tag1 == MKTAG('i', 'v', 'a', 's')){

                /*

                 * After some consideration -- I don't think we

                 * have to support anything but DV in a type1 AVIs.

                 */

                if (s->nb_streams != 1)

                    goto fail;

                if (handler != MKTAG('d', 'v', 's', 'd') &&

                    handler != MKTAG('d', 'v', 'h', 'd') &&

                    handler != MKTAG('d', 'v', 's', 'l'))

                   goto fail;

                ast = s->streams[0]->priv_data;

                av_freep(&s->streams[0]->codec->extradata);

                av_freep(&s->streams[0]);

                s->nb_streams = 0;

                if (ENABLE_DV_DEMUXER) {

                    avi->dv_demux = dv_init_demux(s);

                    if (!avi->dv_demux)

                        goto fail;

                }

                s->streams[0]->priv_data = ast;

                url_fskip(pb, 3 * 4);

                ast->scale = get_le32(pb);

                ast->rate = get_le32(pb);

                stream_index = s->nb_streams - 1;

                url_fskip(pb, size - 7*4);

                break;

            }

            if (stream_index >= s->nb_streams) {

                url_fskip(pb, size - 8);

                /* ignore padding stream */

                if (tag1 == MKTAG('p', 'a', 'd', 's'))

                    stream_index--;

                break;

            }

            st = s->streams[stream_index];

            ast = st->priv_data;

            st->codec->stream_codec_tag= handler;

            get_le32(pb); /* flags */

            get_le16(pb); /* priority */

            get_le16(pb); /* language */

            get_le32(pb); /* initial frame */

            ast->scale = get_le32(pb);

            ast->rate = get_le32(pb);

            if(ast->scale && ast->rate){

            }else if(frame_period){

                ast->rate = 1000000;

                ast->scale = frame_period;

            }else{

                ast->rate = 25;

                ast->scale = 1;

            }

            av_set_pts_info(st, 64, ast->scale, ast->rate);

            ast->cum_len=get_le32(pb); /* start */

            nb_frames = get_le32(pb);

            st->start_time = 0;

            st->duration = nb_frames;

            get_le32(pb); /* buffer size */

            get_le32(pb); /* quality */

            ast->sample_size = get_le32(pb); /* sample ssize */

            ast->cum_len *= FFMAX(1, ast->sample_size);

//            av_log(NULL, AV_LOG_DEBUG, "%d %d %d %d\n", ast->rate, ast->scale, ast->start, ast->sample_size);

            switch(tag1) {

            case MKTAG('v', 'i', 'd', 's'):

                codec_type = CODEC_TYPE_VIDEO;

                ast->sample_size = 0;

                break;

            case MKTAG('a', 'u', 'd', 's'):

                codec_type = CODEC_TYPE_AUDIO;

                break;

            case MKTAG('t', 'x', 't', 's'):

                //FIXME

                codec_type = CODEC_TYPE_DATA; //CODEC_TYPE_SUB ?  FIXME

                break;

            case MKTAG('p', 'a', 'd', 's'):

                codec_type = CODEC_TYPE_UNKNOWN;

                stream_index--;

                break;

            default:

                av_log(s, AV_LOG_ERROR, "unknown stream type %X\n", tag1);

                goto fail;

            }

            ast->frame_offset= ast->cum_len;

            url_fskip(pb, size - 12 * 4);

            break;

        case MKTAG('s', 't', 'r', 'f'):

            /* stream header */

            if (stream_index >= s->nb_streams || avi->dv_demux) {

                url_fskip(pb, size);

            } else {

                st = s->streams[stream_index];

                switch(codec_type) {

                case CODEC_TYPE_VIDEO:

                    get_le32(pb); /* size */

                    st->codec->width = get_le32(pb);

                    st->codec->height = get_le32(pb);

                    get_le16(pb); /* panes */

                    st->codec->bits_per_sample= get_le16(pb); /* depth */

                    tag1 = get_le32(pb);

                    get_le32(pb); /* ImageSize */

                    get_le32(pb); /* XPelsPerMeter */

                    get_le32(pb); /* YPelsPerMeter */

                    get_le32(pb); /* ClrUsed */

                    get_le32(pb); /* ClrImportant */

                    if(size > 10*4 && size<(1<<30)){

                        st->codec->extradata_size= size - 10*4;

                        st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);

                        get_buffer(pb, st->codec->extradata, st->codec->extradata_size);

                    }

                    if(st->codec->extradata_size & 1) //FIXME check if the encoder really did this correctly

                        get_byte(pb);

                    /* Extract palette from extradata if bpp <= 8 */

                    /* This code assumes that extradata contains only palette */

                    /* This is true for all paletted codecs implemented in ffmpeg */

                    if (st->codec->extradata_size && (st->codec->bits_per_sample <= 8)) {

                        st->codec->palctrl = av_mallocz(sizeof(AVPaletteControl));

#ifdef WORDS_BIGENDIAN

                        for (i = 0; i < FFMIN(st->codec->extradata_size, AVPALETTE_SIZE)/4; i++)

                            st->codec->palctrl->palette[i] = bswap_32(((uint32_t*)st->codec->extradata)[i]);

#else

                        memcpy(st->codec->palctrl->palette, st->codec->extradata,

                               FFMIN(st->codec->extradata_size, AVPALETTE_SIZE));

#endif

                        st->codec->palctrl->palette_changed = 1;

                    }

#ifdef DEBUG

                    print_tag("video", tag1, 0);

#endif

                    st->codec->codec_type = CODEC_TYPE_VIDEO;

                    st->codec->codec_tag = tag1;

                    st->codec->codec_id = codec_get_id(codec_bmp_tags, tag1);

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

                        xan_video = 1;

                    st->need_parsing = 2; //only parse headers dont do slower repacketization, this is needed to get the pict type which is needed for generating correct pts

//                    url_fskip(pb, size - 5 * 4);

                    break;

                case CODEC_TYPE_AUDIO:

                    get_wav_header(pb, st->codec, size);

                    if(ast->sample_size && st->codec->block_align && ast->sample_size % st->codec->block_align)

                        av_log(s, AV_LOG_DEBUG, "invalid sample size or block align detected\n");

                    if (size%2) /* 2-aligned (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */

                        url_fskip(pb, 1);

                    /* special case time: To support Xan DPCM, hardcode

                     * the format if Xxan is the video codec */

                    st->need_parsing = 1;

                    /* ADTS header is in extradata, AAC without header must be stored as exact frames, parser not needed and it will fail */

                    if (st->codec->codec_id == CODEC_ID_AAC && st->codec->extradata_size)

                        st->need_parsing = 0;

                    /* force parsing as several audio frames can be in

                       one packet */

                    if (xan_video)

                        st->codec->codec_id = CODEC_ID_XAN_DPCM;

                    break;

                default:

                    st->codec->codec_type = CODEC_TYPE_DATA;

                    st->codec->codec_id= CODEC_ID_NONE;

                    st->codec->codec_tag= 0;

                    url_fskip(pb, size);

                    break;

                }

            }

            break;

        case MKTAG('i', 'n', 'd', 'x'):

            i= url_ftell(pb);

            if(!url_is_streamed(pb) && !(s->flags & AVFMT_FLAG_IGNIDX)){

                read_braindead_odml_indx(s, 0);

            }

            url_fseek(pb, i+size, SEEK_SET);

            break;

        case MKTAG('I', 'N', 'A', 'M'):

            avi_read_tag(pb, s->title, sizeof(s->title), size);

            break;

        case MKTAG('I', 'A', 'R', 'T'):

            avi_read_tag(pb, s->author, sizeof(s->author), size);

            break;

        case MKTAG('I', 'C', 'O', 'P'):

            avi_read_tag(pb, s->copyright, sizeof(s->copyright), size);

            break;

        case MKTAG('I', 'C', 'M', 'T'):

            avi_read_tag(pb, s->comment, sizeof(s->comment), size);

            break;

        case MKTAG('I', 'G', 'N', 'R'):

            avi_read_tag(pb, s->genre, sizeof(s->genre), size);

            break;

        case MKTAG('I', 'P', 'R', 'D'):

            avi_read_tag(pb, s->album, sizeof(s->album), size);

            break;

        case MKTAG('I', 'P', 'R', 'T'):

            avi_read_tag(pb, str_track, sizeof(str_track), size);

            sscanf(str_track, "%d", &s->track);

            break;

        default:

            /* skip tag */

            size += (size & 1);

            url_fskip(pb, size);

            break;

        }

    }

 end_of_header:

    /* check stream number */

    if (stream_index != s->nb_streams - 1) {

    fail:

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

            av_freep(&s->streams[i]->codec->extradata);

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

        }

        return -1;

    }

    if(!avi->index_loaded && !url_is_streamed(pb))

        avi_load_index(s);

    avi->index_loaded = 1;

    avi->non_interleaved |= guess_ni_flag(s);

    if(avi->non_interleaved)

        clean_index(s);

    return 0;

}


static int ffserver_parse_config_feed(FFServerConfig *config, const char *cmd, const char **p,

                                      FFServerStream **pfeed)

{

    FFServerStream *feed;

    char arg[1024];

    av_assert0(pfeed);

    feed = *pfeed;

    if (!av_strcasecmp(cmd, "<Feed")) {

        char *q;

        FFServerStream *s;

        feed = av_mallocz(sizeof(FFServerStream));

        if (!feed)

            return AVERROR(ENOMEM);

        ffserver_get_arg(feed->filename, sizeof(feed->filename), p);

        q = strrchr(feed->filename, '>');

        if (*q)

            *q = '\0';

        for (s = config->first_feed; s; s = s->next) {

            if (!strcmp(feed->filename, s->filename))

                ERROR("Feed '%s' already registered\n", s->filename);

        }

        feed->fmt = av_guess_format("ffm", NULL, NULL);

        /* default feed file */

        snprintf(feed->feed_filename, sizeof(feed->feed_filename),

                 "/tmp/%s.ffm", feed->filename);

        feed->feed_max_size = 5 * 1024 * 1024;

        feed->is_feed = 1;

        feed->feed = feed; /* self feeding :-) */

        *pfeed = feed;

        return 0;

    }

    av_assert0(feed);

    if (!av_strcasecmp(cmd, "Launch")) {

        int i;

        feed->child_argv = av_mallocz(64 * sizeof(char *));

        if (!feed->child_argv)

            return AVERROR(ENOMEM);

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

            ffserver_get_arg(arg, sizeof(arg), p);

            if (!arg[0])

                break;

            feed->child_argv[i] = av_strdup(arg);

            if (!feed->child_argv[i])

                return AVERROR(ENOMEM);

        }

        feed->child_argv[i] =

            av_asprintf("http://%s:%d/%s",

                        (config->http_addr.sin_addr.s_addr == INADDR_ANY) ? "127.0.0.1" :

                        inet_ntoa(config->http_addr.sin_addr), ntohs(config->http_addr.sin_port),

                        feed->filename);

        if (!feed->child_argv[i])

            return AVERROR(ENOMEM);

    } else if (!av_strcasecmp(cmd, "ACL")) {

        ffserver_parse_acl_row(NULL, feed, NULL, *p, config->filename,

                config->line_num);

    } else if (!av_strcasecmp(cmd, "File") || !av_strcasecmp(cmd, "ReadOnlyFile")) {

        ffserver_get_arg(feed->feed_filename, sizeof(feed->feed_filename), p);

        feed->readonly = !av_strcasecmp(cmd, "ReadOnlyFile");

    } else if (!av_strcasecmp(cmd, "Truncate")) {

        ffserver_get_arg(arg, sizeof(arg), p);

        /* assume Truncate is true in case no argument is specified */

        if (!arg[0]) {

            feed->truncate = 1;

        } else {

            WARNING("Truncate N syntax in configuration file is deprecated, "

                    "use Truncate alone with no arguments\n");

            feed->truncate = strtod(arg, NULL);

        }

    } else if (!av_strcasecmp(cmd, "FileMaxSize")) {

        char *p1;

        double fsize;

        ffserver_get_arg(arg, sizeof(arg), p);

        p1 = arg;

        fsize = strtod(p1, &p1);

        switch(av_toupper(*p1)) {

        case 'K':

            fsize *= 1024;

            break;

        case 'M':

            fsize *= 1024 * 1024;

            break;

        case 'G':

            fsize *= 1024 * 1024 * 1024;

            break;

        default:

            ERROR("Invalid file size: %s\n", arg);

            break;

        }

        feed->feed_max_size = (int64_t)fsize;

        if (feed->feed_max_size < FFM_PACKET_SIZE*4)

            ERROR("Feed max file size is too small, must be at least %d\n",

                    FFM_PACKET_SIZE*4);

    } else if (!av_strcasecmp(cmd, "</Feed>")) {

        *pfeed = NULL;

    } else {

        ERROR("Invalid entry '%s' inside <Feed></Feed>\n", cmd);

    }

    return 0;

}


static void build_feed_streams(void)

{

    FFServerStream *stream, *feed;

    int i;

    /* gather all streams */

    for(stream = config.first_stream; stream; stream = stream->next) {

        feed = stream->feed;

        if (feed) {

            if (stream->is_feed) {

                for(i=0;i<stream->nb_streams;i++)

                    stream->feed_streams[i] = i;

            } else {

                /* we handle a stream coming from a feed */

                for(i=0;i<stream->nb_streams;i++)

                    stream->feed_streams[i] = add_av_stream(feed,

                                                            stream->streams[i]);

            }

        }

    }

    /* create feed files if needed */

    for(feed = config.first_feed; feed; feed = feed->next_feed) {

        int fd;

        if (avio_check(feed->feed_filename, AVIO_FLAG_READ) > 0) {

            /* See if it matches */

            AVFormatContext *s = NULL;

            int matches = 0;

            if (avformat_open_input(&s, feed->feed_filename, NULL, NULL) >= 0) {

                /* set buffer size */

                ffio_set_buf_size(s->pb, FFM_PACKET_SIZE);

                /* Now see if it matches */

                if (s->nb_streams == feed->nb_streams) {

                    matches = 1;

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

                        AVStream *sf, *ss;

                        sf = feed->streams[i];

                        ss = s->streams[i];

                        if (sf->index != ss->index ||

                            sf->id != ss->id) {

                            http_log("Index & Id do not match for stream %d (%s)\n",

                                   i, feed->feed_filename);

                            matches = 0;

                        } else {

                            AVCodecContext *ccf, *ccs;

                            ccf = sf->codec;

                            ccs = ss->codec;

#define CHECK_CODEC(x)  (ccf->x != ccs->x)

                            if (CHECK_CODEC(codec_id) || CHECK_CODEC(codec_type)) {

                                http_log("Codecs do not match for stream %d\n", i);

                                matches = 0;

                            } else if (CHECK_CODEC(bit_rate) || CHECK_CODEC(flags)) {

                                http_log("Codec bitrates do not match for stream %d\n", i);

                                matches = 0;

                            } else if (ccf->codec_type == AVMEDIA_TYPE_VIDEO) {

                                if (CHECK_CODEC(time_base.den) ||

                                    CHECK_CODEC(time_base.num) ||

                                    CHECK_CODEC(width) ||

                                    CHECK_CODEC(height)) {

                                    http_log("Codec width, height and framerate do not match for stream %d\n", i);

                                    matches = 0;

                                }

                            } else if (ccf->codec_type == AVMEDIA_TYPE_AUDIO) {

                                if (CHECK_CODEC(sample_rate) ||

                                    CHECK_CODEC(channels) ||

                                    CHECK_CODEC(frame_size)) {

                                    http_log("Codec sample_rate, channels, frame_size do not match for stream %d\n", i);

                                    matches = 0;

                                }

                            } else {

                                http_log("Unknown codec type\n");

                                matches = 0;

                            }

                        }

                        if (!matches)

                            break;

                    }

                } else

                    http_log("Deleting feed file '%s' as stream counts differ (%d != %d)\n",

                        feed->feed_filename, s->nb_streams, feed->nb_streams);

                avformat_close_input(&s);

            } else

                http_log("Deleting feed file '%s' as it appears to be corrupt\n",

                        feed->feed_filename);

            if (!matches) {

                if (feed->readonly) {

                    http_log("Unable to delete feed file '%s' as it is marked readonly\n",

                        feed->feed_filename);

                    exit(1);

                }

                unlink(feed->feed_filename);

            }

        }

        if (avio_check(feed->feed_filename, AVIO_FLAG_WRITE) <= 0) {

            AVFormatContext *s = avformat_alloc_context();

            if (!s) {

                http_log("Failed to allocate context\n");

                exit(1);

            }

            if (feed->readonly) {

                http_log("Unable to create feed file '%s' as it is marked readonly\n",

                    feed->feed_filename);

                exit(1);

            }

            /* only write the header of the ffm file */

            if (avio_open(&s->pb, feed->feed_filename, AVIO_FLAG_WRITE) < 0) {

                http_log("Could not open output feed file '%s'\n",

                         feed->feed_filename);

                exit(1);

            }

            s->oformat = feed->fmt;

            s->nb_streams = feed->nb_streams;

            s->streams = feed->streams;

            if (avformat_write_header(s, NULL) < 0) {

                http_log("Container doesn't support the required parameters\n");

                exit(1);

            }

            /* XXX: need better API */

            av_freep(&s->priv_data);

            avio_closep(&s->pb);

            s->streams = NULL;

            s->nb_streams = 0;

            avformat_free_context(s);

        }

        /* get feed size and write index */

        fd = open(feed->feed_filename, O_RDONLY);

        if (fd < 0) {

            http_log("Could not open output feed file '%s'\n",

                    feed->feed_filename);

            exit(1);

        }

        feed->feed_write_index = FFMAX(ffm_read_write_index(fd), FFM_PACKET_SIZE);

        feed->feed_size = lseek(fd, 0, SEEK_END);

        /* ensure that we do not wrap before the end of file */

        if (feed->feed_max_size && feed->feed_max_size < feed->feed_size)

            feed->feed_max_size = feed->feed_size;

        close(fd);

    }

}


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

{

    VirtIODevice *vdev = VIRTIO_DEVICE(dev);

    VirtIOBalloon *s = VIRTIO_BALLOON(dev);

    int ret;

    virtio_init(vdev, "virtio-balloon", VIRTIO_ID_BALLOON,

                sizeof(struct virtio_balloon_config));

    ret = qemu_add_balloon_handler(virtio_balloon_to_target,

                                   virtio_balloon_stat, s);

    if (ret < 0) {

        error_setg(errp, "Adding balloon handler failed");

        virtio_cleanup(vdev);

        return;

    }

    s->ivq = virtio_add_queue(vdev, 128, virtio_balloon_handle_output);

    s->dvq = virtio_add_queue(vdev, 128, virtio_balloon_handle_output);

    s->svq = virtio_add_queue(vdev, 128, virtio_balloon_receive_stats);

    reset_stats(s);

    register_savevm(dev, "virtio-balloon", -1, 1,

                    virtio_balloon_save, virtio_balloon_load, s);

    object_property_add(OBJECT(dev), "guest-stats", "guest statistics",

                        balloon_stats_get_all, NULL, NULL, s, NULL);

    object_property_add(OBJECT(dev), "guest-stats-polling-interval", "int",

                        balloon_stats_get_poll_interval,

                        balloon_stats_set_poll_interval,

                        NULL, s, NULL);

}


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

{

#if COMPILE_TEMPLATE_MMX

    __asm__ volatile(

        "mov                    %0, %%"REG_a"       \n\t"

        "1:                                         \n\t"

        "movq    (%1, %%"REG_a",2), %%mm0           \n\t"

        "movq   8(%1, %%"REG_a",2), %%mm1           \n\t"

        "movq    (%2, %%"REG_a",2), %%mm2           \n\t"

        "movq   8(%2, %%"REG_a",2), %%mm3           \n\t"

        "psrlw                  $8, %%mm0           \n\t"

        "psrlw                  $8, %%mm1           \n\t"

        "psrlw                  $8, %%mm2           \n\t"

        "psrlw                  $8, %%mm3           \n\t"

        "packuswb            %%mm1, %%mm0           \n\t"

        "packuswb            %%mm3, %%mm2           \n\t"

        "movq                %%mm0, (%3, %%"REG_a") \n\t"

        "movq                %%mm2, (%4, %%"REG_a") \n\t"

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

        " js                    1b                  \n\t"

        : : "g" ((x86_reg)-width), "r" (src1+width*2), "r" (src2+width*2), "r" (dstU+width), "r" (dstV+width)

        : "%"REG_a

    );

#else

    int i;

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

        dstU[i]= src1[2*i + 1];

        dstV[i]= src2[2*i + 1];

    }

#endif

}


static int qcow_snapshot_create(BlockDriverState *bs,

                                QEMUSnapshotInfo *sn_info)

{

    BDRVQcowState *s = bs->opaque;

    QCowSnapshot *snapshots1, sn1, *sn = &sn1;

    int i, ret;

    uint64_t *l1_table = NULL;

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

    if (sn_info->id_str[0] == '\0') {

        /* compute a new id */

        find_new_snapshot_id(bs, sn_info->id_str, sizeof(sn_info->id_str));

    }

    /* check that the ID is unique */

    if (find_snapshot_by_id(bs, sn_info->id_str) >= 0)

        return -ENOENT;

    sn->id_str = qemu_strdup(sn_info->id_str);

    if (!sn->id_str)

        goto fail;

    sn->name = qemu_strdup(sn_info->name);

    if (!sn->name)

        goto fail;

    sn->vm_state_size = sn_info->vm_state_size;

    sn->date_sec = sn_info->date_sec;

    sn->date_nsec = sn_info->date_nsec;

    sn->vm_clock_nsec = sn_info->vm_clock_nsec;

    ret = update_snapshot_refcount(bs, s->l1_table_offset, s->l1_size, 1);

    if (ret < 0)

        goto fail;

    /* create the L1 table of the snapshot */

    sn->l1_table_offset = alloc_clusters(bs, s->l1_size * sizeof(uint64_t));

    sn->l1_size = s->l1_size;

    l1_table = qemu_malloc(s->l1_size * sizeof(uint64_t));

    if (!l1_table)

        goto fail;

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

        l1_table[i] = cpu_to_be64(s->l1_table[i]);

    }

    if (bdrv_pwrite(s->hd, sn->l1_table_offset,

                    l1_table, s->l1_size * sizeof(uint64_t)) !=

        (s->l1_size * sizeof(uint64_t)))

        goto fail;

    qemu_free(l1_table);

    l1_table = NULL;

    snapshots1 = qemu_malloc((s->nb_snapshots + 1) * sizeof(QCowSnapshot));

    if (!snapshots1)

        goto fail;

    memcpy(snapshots1, s->snapshots, s->nb_snapshots * sizeof(QCowSnapshot));

    s->snapshots = snapshots1;

    s->snapshots[s->nb_snapshots++] = *sn;

    if (qcow_write_snapshots(bs) < 0)

        goto fail;

#ifdef DEBUG_ALLOC

    check_refcounts(bs);

#endif

    return 0;

 fail:

    qemu_free(sn->name);

    qemu_free(l1_table);

    return -1;

}


static int resize_peers(IVShmemState *s, int new_min_size)

{

    int j, old_size;

    /* limit number of max peers */

    if (new_min_size <= 0 || new_min_size > IVSHMEM_MAX_PEERS) {

        return -1;

    }

    if (new_min_size <= s->nb_peers) {

        return 0;

    }

    old_size = s->nb_peers;

    s->nb_peers = new_min_size;

    IVSHMEM_DPRINTF("bumping storage to %d peers\n", s->nb_peers);

    s->peers = g_realloc(s->peers, s->nb_peers * sizeof(Peer));

    for (j = old_size; j < s->nb_peers; j++) {

        s->peers[j].eventfds = g_new0(EventNotifier, s->vectors);

        s->peers[j].nb_eventfds = 0;

    }

    return 0;

}


static int s390_virtio_blk_init(VirtIOS390Device *s390_dev)

{

    VirtIOBlkS390 *dev = VIRTIO_BLK_S390(s390_dev);

    DeviceState *vdev = DEVICE(&dev->vdev);

    virtio_blk_set_conf(vdev, &(dev->blk));

    qdev_set_parent_bus(vdev, BUS(&s390_dev->bus));

    if (qdev_init(vdev) < 0) {

        return -1;

    }

    return s390_virtio_device_init(s390_dev, VIRTIO_DEVICE(vdev));

}


static void aarch64_cpu_class_init(ObjectClass *oc, void *data)

{

    CPUClass *cc = CPU_CLASS(oc);

    cc->dump_state = aarch64_cpu_dump_state;

    cc->set_pc = aarch64_cpu_set_pc;

    cc->gdb_read_register = aarch64_cpu_gdb_read_register;

    cc->gdb_write_register = aarch64_cpu_gdb_write_register;

    cc->gdb_num_core_regs = 34;

    cc->gdb_core_xml_file = "aarch64-core.xml";

}


void ppc_hw_interrupt(CPUPPCState *env)

{

    PowerPCCPU *cpu = ppc_env_get_cpu(env);

    int hdice;

#if 0

    CPUState *cs = CPU(cpu);

    qemu_log_mask(CPU_LOG_INT, "%s: %p pending %08x req %08x me %d ee %d\n",

                  __func__, env, env->pending_interrupts,

                  cs->interrupt_request, (int)msr_me, (int)msr_ee);

#endif

    /* External reset */

    if (env->pending_interrupts & (1 << PPC_INTERRUPT_RESET)) {

        env->pending_interrupts &= ~(1 << PPC_INTERRUPT_RESET);

        powerpc_excp(cpu, env->excp_model, POWERPC_EXCP_RESET);

        return;

    }

    /* Machine check exception */

    if (env->pending_interrupts & (1 << PPC_INTERRUPT_MCK)) {

        env->pending_interrupts &= ~(1 << PPC_INTERRUPT_MCK);

        powerpc_excp(cpu, env->excp_model, POWERPC_EXCP_MCHECK);

        return;

    }

#if 0 /* TODO */

    /* External debug exception */

    if (env->pending_interrupts & (1 << PPC_INTERRUPT_DEBUG)) {

        env->pending_interrupts &= ~(1 << PPC_INTERRUPT_DEBUG);

        powerpc_excp(cpu, env->excp_model, POWERPC_EXCP_DEBUG);

        return;

    }

#endif

    if (0) {

        /* XXX: find a suitable condition to enable the hypervisor mode */

        hdice = env->spr[SPR_LPCR] & 1;

    } else {

        hdice = 0;

    }

    if ((msr_ee != 0 || msr_hv == 0 || msr_pr != 0) && hdice != 0) {

        /* Hypervisor decrementer exception */

        if (env->pending_interrupts & (1 << PPC_INTERRUPT_HDECR)) {

            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_HDECR);

            powerpc_excp(cpu, env->excp_model, POWERPC_EXCP_HDECR);

            return;

        }

    }

    if (msr_ce != 0) {

        /* External critical interrupt */

        if (env->pending_interrupts & (1 << PPC_INTERRUPT_CEXT)) {

            /* Taking a critical external interrupt does not clear the external

             * critical interrupt status

             */

#if 0

            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_CEXT);

#endif

            powerpc_excp(cpu, env->excp_model, POWERPC_EXCP_CRITICAL);

            return;

        }

    }

    if (msr_ee != 0) {

        /* Watchdog timer on embedded PowerPC */

        if (env->pending_interrupts & (1 << PPC_INTERRUPT_WDT)) {

            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_WDT);

            powerpc_excp(cpu, env->excp_model, POWERPC_EXCP_WDT);

            return;

        }

        if (env->pending_interrupts & (1 << PPC_INTERRUPT_CDOORBELL)) {

            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_CDOORBELL);

            powerpc_excp(cpu, env->excp_model, POWERPC_EXCP_DOORCI);

            return;

        }

        /* Fixed interval timer on embedded PowerPC */

        if (env->pending_interrupts & (1 << PPC_INTERRUPT_FIT)) {

            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_FIT);

            powerpc_excp(cpu, env->excp_model, POWERPC_EXCP_FIT);

            return;

        }

        /* Programmable interval timer on embedded PowerPC */

        if (env->pending_interrupts & (1 << PPC_INTERRUPT_PIT)) {

            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_PIT);

            powerpc_excp(cpu, env->excp_model, POWERPC_EXCP_PIT);

            return;

        }

        /* Decrementer exception */

        if (env->pending_interrupts & (1 << PPC_INTERRUPT_DECR)) {

            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_DECR);

            powerpc_excp(cpu, env->excp_model, POWERPC_EXCP_DECR);

            return;

        }

        /* External interrupt */

        if (env->pending_interrupts & (1 << PPC_INTERRUPT_EXT)) {

            /* Taking an external interrupt does not clear the external

             * interrupt status

             */

#if 0

            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_EXT);

#endif

            powerpc_excp(cpu, env->excp_model, POWERPC_EXCP_EXTERNAL);

            return;

        }

        if (env->pending_interrupts & (1 << PPC_INTERRUPT_DOORBELL)) {

            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_DOORBELL);

            powerpc_excp(cpu, env->excp_model, POWERPC_EXCP_DOORI);

            return;

        }

        if (env->pending_interrupts & (1 << PPC_INTERRUPT_PERFM)) {

            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_PERFM);

            powerpc_excp(cpu, env->excp_model, POWERPC_EXCP_PERFM);

            return;

        }

        /* Thermal interrupt */

        if (env->pending_interrupts & (1 << PPC_INTERRUPT_THERM)) {

            env->pending_interrupts &= ~(1 << PPC_INTERRUPT_THERM);

            powerpc_excp(cpu, env->excp_model, POWERPC_EXCP_THERM);

            return;

        }

    }

}


static int mjpeg_decode_dht(MJpegDecodeContext *s)

{

    int len, index, i, class, n, v, code_max;

    uint8_t bits_table[17];

    uint8_t val_table[256];

    len = get_bits(&s->gb, 16) - 2;

    while (len > 0) {

        if (len < 17)

            return -1;

        class = get_bits(&s->gb, 4);

        if (class >= 2)

            return -1;

        index = get_bits(&s->gb, 4);

        if (index >= 4)

            return -1;

        n = 0;

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

            bits_table[i] = get_bits(&s->gb, 8);

            n += bits_table[i];

        }

        len -= 17;

        if (len < n || n > 256)

            return -1;

        code_max = 0;

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

            v = get_bits(&s->gb, 8);

            if (v > code_max)

                code_max = v;

            val_table[i] = v;

        }

        len -= n;

        /* build VLC and flush previous vlc if present */

        free_vlc(&s->vlcs[class][index]);

        dprintf("class=%d index=%d nb_codes=%d\n",

               class, index, code_max + 1);

        build_vlc(&s->vlcs[class][index], bits_table, val_table, code_max + 1);

    }

    return 0;

}


static int usb_net_handle_dataout(USBNetState *s, USBPacket *p)

{

    int ret = p->len;

    int sz = sizeof(s->out_buf) - s->out_ptr;

    struct rndis_packet_msg_type *msg =

            (struct rndis_packet_msg_type *) s->out_buf;

    uint32_t len;

#ifdef TRAFFIC_DEBUG

    fprintf(stderr, "usbnet: data out len %u\n", p->len);

    {

        int i;

        fprintf(stderr, ":");

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

            if (!(i & 15))

                fprintf(stderr, "\n%04x:", i);

            fprintf(stderr, " %02x", p->data[i]);

        }

        fprintf(stderr, "\n\n");

    }

#endif

    if (sz > ret)

        sz = ret;

    memcpy(&s->out_buf[s->out_ptr], p->data, sz);

    s->out_ptr += sz;

    if (!s->rndis) {

        if (ret < 64) {

            qemu_send_packet(&s->nic->nc, s->out_buf, s->out_ptr);

            s->out_ptr = 0;

        }

        return ret;

    }

    len = le32_to_cpu(msg->MessageLength);

    if (s->out_ptr < 8 || s->out_ptr < len)

        return ret;

    if (le32_to_cpu(msg->MessageType) == RNDIS_PACKET_MSG) {

        uint32_t offs = 8 + le32_to_cpu(msg->DataOffset);

        uint32_t size = le32_to_cpu(msg->DataLength);

        if (offs + size <= len)

            qemu_send_packet(&s->nic->nc, s->out_buf + offs, size);

    }

    s->out_ptr -= len;

    memmove(s->out_buf, &s->out_buf[len], s->out_ptr);

    return ret;

}


int bdrv_get_backing_file_depth(BlockDriverState *bs)

{

    if (!bs->drv) {

        return 0;

    }

    if (!bs->backing_hd) {

        return 0;

    }

    return 1 + bdrv_get_backing_file_depth(bs->backing_hd);

}


static int parallels_create(const char *filename, QemuOpts *opts, Error **errp)

{

    int64_t total_size, cl_size;

    uint8_t tmp[BDRV_SECTOR_SIZE];

    Error *local_err = NULL;

    BlockDriverState *file;

    uint32_t cat_entries, cat_sectors;

    ParallelsHeader header;

    int ret;

    total_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),

                          BDRV_SECTOR_SIZE);

    cl_size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_CLUSTER_SIZE,

                          DEFAULT_CLUSTER_SIZE), BDRV_SECTOR_SIZE);

    ret = bdrv_create_file(filename, opts, &local_err);

    if (ret < 0) {

        error_propagate(errp, local_err);

        return ret;

    }

    file = NULL;

    ret = bdrv_open(&file, filename, NULL, NULL,

                    BDRV_O_RDWR | BDRV_O_PROTOCOL, NULL, &local_err);

    if (ret < 0) {

        error_propagate(errp, local_err);

        return ret;

    }

    ret = bdrv_truncate(file, 0);

    if (ret < 0) {

        goto exit;

    }

    cat_entries = DIV_ROUND_UP(total_size, cl_size);

    cat_sectors = DIV_ROUND_UP(cat_entries * sizeof(uint32_t) +

                               sizeof(ParallelsHeader), cl_size);

    cat_sectors = (cat_sectors *  cl_size) >> BDRV_SECTOR_BITS;

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

    memcpy(header.magic, HEADER_MAGIC2, sizeof(header.magic));

    header.version = cpu_to_le32(HEADER_VERSION);

    /* don't care much about geometry, it is not used on image level */

    header.heads = cpu_to_le32(16);

    header.cylinders = cpu_to_le32(total_size / BDRV_SECTOR_SIZE / 16 / 32);

    header.tracks = cpu_to_le32(cl_size >> BDRV_SECTOR_BITS);

    header.catalog_entries = cpu_to_le32(cat_entries);

    header.nb_sectors = cpu_to_le64(DIV_ROUND_UP(total_size, BDRV_SECTOR_SIZE));

    header.data_off = cpu_to_le32(cat_sectors);

    /* write all the data */

    memset(tmp, 0, sizeof(tmp));

    memcpy(tmp, &header, sizeof(header));

    ret = bdrv_pwrite(file, 0, tmp, BDRV_SECTOR_SIZE);

    if (ret < 0) {

        goto exit;

    }

    ret = bdrv_write_zeroes(file, 1, cat_sectors - 1, 0);

    if (ret < 0) {

        goto exit;

    }

    ret = 0;

done:

    bdrv_unref(file);

    return ret;

exit:

    error_setg_errno(errp, -ret, "Failed to create Parallels image");

    goto done;

}


static void pxa2xx_pwrmode_write(CPUARMState *env, const ARMCPRegInfo *ri,

                                 uint64_t value)

{

    PXA2xxState *s = (PXA2xxState *)ri->opaque;

    static const char *pwrmode[8] = {

        "Normal", "Idle", "Deep-idle", "Standby",

        "Sleep", "reserved (!)", "reserved (!)", "Deep-sleep",

    };

    if (value & 8) {

        printf("%s: CPU voltage change attempt\n", __func__);

    }

    switch (value & 7) {

    case 0:

        /* Do nothing */

        break;

    case 1:

        /* Idle */

        if (!(s->cm_regs[CCCR >> 2] & (1U << 31))) { /* CPDIS */

            cpu_interrupt(CPU(s->cpu), CPU_INTERRUPT_HALT);

            break;

        }

        /* Fall through.  */

    case 2:

        /* Deep-Idle */

        cpu_interrupt(CPU(s->cpu), CPU_INTERRUPT_HALT);

        s->pm_regs[RCSR >> 2] |= 0x8; /* Set GPR */

        goto message;

    case 3:

        s->cpu->env.uncached_cpsr = ARM_CPU_MODE_SVC;

        s->cpu->env.daif = PSTATE_A | PSTATE_F | PSTATE_I;

        s->cpu->env.cp15.sctlr_ns = 0;

        s->cpu->env.cp15.c1_coproc = 0;

        s->cpu->env.cp15.ttbr0_el[1] = 0;

        s->cpu->env.cp15.c3 = 0;

        s->pm_regs[PSSR >> 2] |= 0x8; /* Set STS */

        s->pm_regs[RCSR >> 2] |= 0x8; /* Set GPR */

        /*

         * The scratch-pad register is almost universally used

         * for storing the return address on suspend.  For the

         * lack of a resuming bootloader, perform a jump

         * directly to that address.

         */

        memset(s->cpu->env.regs, 0, 4 * 15);

        s->cpu->env.regs[15] = s->pm_regs[PSPR >> 2];

#if 0

        buffer = 0xe59ff000; /* ldr     pc, [pc, #0] */

        cpu_physical_memory_write(0, &buffer, 4);

        buffer = s->pm_regs[PSPR >> 2];

        cpu_physical_memory_write(8, &buffer, 4);

#endif

        /* Suspend */

        cpu_interrupt(current_cpu, CPU_INTERRUPT_HALT);

        goto message;

    default:

    message:

        printf("%s: machine entered %s mode\n", __func__,

               pwrmode[value & 7]);

    }

}


static void hmp_change_read_arg(Monitor *mon, const char *password,

                                void *opaque)

{

    qmp_change_vnc_password(password, NULL);

    monitor_read_command(mon, 1);

}


static int readv_f(int argc, char **argv)

{

    struct timeval t1, t2;

    int Cflag = 0, qflag = 0, vflag = 0;

    int c, cnt;

    char *buf;

    int64_t offset;

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

    int total = 0;

    int nr_iov;

    QEMUIOVector qiov;

    int pattern = 0;

    int Pflag = 0;

    while ((c = getopt(argc, argv, "CP:qv")) != EOF) {

        switch (c) {

        case 'C':

            Cflag = 1;

            break;

        case 'P':

            Pflag = 1;

            pattern = parse_pattern(optarg);

            if (pattern < 0) {

                return 0;

            }

            break;

        case 'q':

            qflag = 1;

            break;

        case 'v':

            vflag = 1;

            break;

        default:

            return command_usage(&readv_cmd);

        }

    }

    if (optind > argc - 2) {

        return command_usage(&readv_cmd);

    }

    offset = cvtnum(argv[optind]);

    if (offset < 0) {

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

        return 0;

    }

    optind++;

    if (offset & 0x1ff) {

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

               offset);

        return 0;

    }

    nr_iov = argc - optind;

    buf = create_iovec(&qiov, &argv[optind], nr_iov, 0xab);

    if (buf == NULL) {

        return 0;

    }

    gettimeofday(&t1, NULL);

    cnt = do_aio_readv(&qiov, offset, &total);

    gettimeofday(&t2, NULL);

    if (cnt < 0) {

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

        goto out;

    }

    if (Pflag) {

        void *cmp_buf = g_malloc(qiov.size);

        memset(cmp_buf, pattern, qiov.size);

        if (memcmp(buf, cmp_buf, qiov.size)) {

            printf("Pattern verification failed at offset %"

                   PRId64 ", %zd bytes\n", offset, qiov.size);

        }

        g_free(cmp_buf);

    }

    if (qflag) {

        goto out;

    }

    if (vflag) {

        dump_buffer(buf, offset, qiov.size);

    }

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

    t2 = tsub(t2, t1);

    print_report("read", &t2, offset, qiov.size, total, cnt, Cflag);

out:

    qemu_io_free(buf);

    return 0;

}


ssize_t pcnet_receive(NetClientState *nc, const uint8_t *buf, size_t size_)

{

    PCNetState *s = qemu_get_nic_opaque(nc);

    int is_padr = 0, is_bcast = 0, is_ladr = 0;

    uint8_t buf1[60];

    int remaining;

    int crc_err = 0;

    int size = size_;

    if (CSR_DRX(s) || CSR_STOP(s) || CSR_SPND(s) || !size ||

        (CSR_LOOP(s) && !s->looptest)) {

        return -1;

    }

#ifdef PCNET_DEBUG

    printf("pcnet_receive size=%d\n", size);

#endif

    /* if too small buffer, then expand it */

    if (size < MIN_BUF_SIZE) {

        memcpy(buf1, buf, size);

        memset(buf1 + size, 0, MIN_BUF_SIZE - size);

        buf = buf1;

        size = MIN_BUF_SIZE;

    }

    if (CSR_PROM(s)

        || (is_padr=padr_match(s, buf, size))

        || (is_bcast=padr_bcast(s, buf, size))

        || (is_ladr=ladr_match(s, buf, size))) {

        pcnet_rdte_poll(s);

        if (!(CSR_CRST(s) & 0x8000) && s->rdra) {

            struct pcnet_RMD rmd;

            int rcvrc = CSR_RCVRC(s)-1,i;

            hwaddr nrda;

            for (i = CSR_RCVRL(s)-1; i > 0; i--, rcvrc--) {

                if (rcvrc <= 1)

                    rcvrc = CSR_RCVRL(s);

                nrda = s->rdra +

                    (CSR_RCVRL(s) - rcvrc) *

                    (BCR_SWSTYLE(s) ? 16 : 8 );

                RMDLOAD(&rmd, nrda);

                if (GET_FIELD(rmd.status, RMDS, OWN)) {

#ifdef PCNET_DEBUG_RMD

                    printf("pcnet - scan buffer: RCVRC=%d PREV_RCVRC=%d\n",

                                rcvrc, CSR_RCVRC(s));

#endif

                    CSR_RCVRC(s) = rcvrc;

                    pcnet_rdte_poll(s);

                    break;

                }

            }

        }

        if (!(CSR_CRST(s) & 0x8000)) {

#ifdef PCNET_DEBUG_RMD

            printf("pcnet - no buffer: RCVRC=%d\n", CSR_RCVRC(s));

#endif

            s->csr[0] |= 0x1000; /* Set MISS flag */

            CSR_MISSC(s)++;

        } else {

            uint8_t *src = s->buffer;

            hwaddr crda = CSR_CRDA(s);

            struct pcnet_RMD rmd;

            int pktcount = 0;

            if (!s->looptest) {

                memcpy(src, buf, size);

                /* no need to compute the CRC */

                src[size] = 0;

                src[size + 1] = 0;

                src[size + 2] = 0;

                src[size + 3] = 0;

                size += 4;

            } else if (s->looptest == PCNET_LOOPTEST_CRC ||

                       !CSR_DXMTFCS(s) || size < MIN_BUF_SIZE+4) {

                uint32_t fcs = ~0;

                uint8_t *p = src;

                while (p != &src[size])

                    CRC(fcs, *p++);

                *(uint32_t *)p = htonl(fcs);

                size += 4;

            } else {

                uint32_t fcs = ~0;

                uint8_t *p = src;

                while (p != &src[size-4])

                    CRC(fcs, *p++);

                crc_err = (*(uint32_t *)p != htonl(fcs));

            }

#ifdef PCNET_DEBUG_MATCH

            PRINT_PKTHDR(buf);

#endif

            RMDLOAD(&rmd, PHYSADDR(s,crda));

            /*if (!CSR_LAPPEN(s))*/

                SET_FIELD(&rmd.status, RMDS, STP, 1);

#define PCNET_RECV_STORE() do {                                 \

    int count = MIN(4096 - GET_FIELD(rmd.buf_length, RMDL, BCNT),remaining); \

    hwaddr rbadr = PHYSADDR(s, rmd.rbadr);          \

    s->phys_mem_write(s->dma_opaque, rbadr, src, count, CSR_BSWP(s)); \

    src += count; remaining -= count;                           \

    SET_FIELD(&rmd.status, RMDS, OWN, 0);                       \

    RMDSTORE(&rmd, PHYSADDR(s,crda));                           \

    pktcount++;                                                 \

} while (0)

            remaining = size;

            PCNET_RECV_STORE();

            if ((remaining > 0) && CSR_NRDA(s)) {

                hwaddr nrda = CSR_NRDA(s);

#ifdef PCNET_DEBUG_RMD

                PRINT_RMD(&rmd);

#endif

                RMDLOAD(&rmd, PHYSADDR(s,nrda));

                if (GET_FIELD(rmd.status, RMDS, OWN)) {

                    crda = nrda;

                    PCNET_RECV_STORE();

#ifdef PCNET_DEBUG_RMD

                    PRINT_RMD(&rmd);

#endif

                    if ((remaining > 0) && (nrda=CSR_NNRD(s))) {

                        RMDLOAD(&rmd, PHYSADDR(s,nrda));

                        if (GET_FIELD(rmd.status, RMDS, OWN)) {

                            crda = nrda;

                            PCNET_RECV_STORE();

                        }

                    }

                }

            }

#undef PCNET_RECV_STORE

            RMDLOAD(&rmd, PHYSADDR(s,crda));

            if (remaining == 0) {

                SET_FIELD(&rmd.msg_length, RMDM, MCNT, size);

                SET_FIELD(&rmd.status, RMDS, ENP, 1);

                SET_FIELD(&rmd.status, RMDS, PAM, !CSR_PROM(s) && is_padr);

                SET_FIELD(&rmd.status, RMDS, LFAM, !CSR_PROM(s) && is_ladr);

                SET_FIELD(&rmd.status, RMDS, BAM, !CSR_PROM(s) && is_bcast);

                if (crc_err) {

                    SET_FIELD(&rmd.status, RMDS, CRC, 1);

                    SET_FIELD(&rmd.status, RMDS, ERR, 1);

                }

            } else {

                SET_FIELD(&rmd.status, RMDS, OFLO, 1);

                SET_FIELD(&rmd.status, RMDS, BUFF, 1);

                SET_FIELD(&rmd.status, RMDS, ERR, 1);

            }

            RMDSTORE(&rmd, PHYSADDR(s,crda));

            s->csr[0] |= 0x0400;

#ifdef PCNET_DEBUG

            printf("RCVRC=%d CRDA=0x%08x BLKS=%d\n",

                CSR_RCVRC(s), PHYSADDR(s,CSR_CRDA(s)), pktcount);

#endif

#ifdef PCNET_DEBUG_RMD

            PRINT_RMD(&rmd);

#endif

            while (pktcount--) {

                if (CSR_RCVRC(s) <= 1)

                    CSR_RCVRC(s) = CSR_RCVRL(s);

                else

                    CSR_RCVRC(s)--;

            }

            pcnet_rdte_poll(s);

        }

    }

    pcnet_poll(s);

    pcnet_update_irq(s);

    return size_;

}


static bool pcie_has_upstream_port(PCIDevice *dev)

{

    PCIDevice *parent_dev = pci_bridge_get_device(dev->bus);

    /* Device associated with an upstream port.

     * As there are several types of these, it's easier to check the

     * parent device: upstream ports are always connected to

     * root or downstream ports.

     */

    return parent_dev &&

        pci_is_express(parent_dev) &&

        parent_dev->exp.exp_cap &&

        (pcie_cap_get_type(parent_dev) == PCI_EXP_TYPE_ROOT_PORT ||

         pcie_cap_get_type(parent_dev) == PCI_EXP_TYPE_DOWNSTREAM);

}


int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries)

{

    AVStream *st;

    MOVStreamContext *sc;

    int j, pseudo_stream_id;

    if (c->fc->nb_streams < 1)

        return 0;

    st = c->fc->streams[c->fc->nb_streams-1];

    sc = st->priv_data;

    for (pseudo_stream_id=0; pseudo_stream_id<entries; pseudo_stream_id++) {

        //Parsing Sample description table

        enum AVCodecID id;

        int dref_id = 1;

        MOVAtom a = { AV_RL32("stsd") };

        int64_t start_pos = avio_tell(pb);

        int size = avio_rb32(pb); /* size */

        uint32_t format = avio_rl32(pb); /* data format */

        if (size >= 16) {

            avio_rb32(pb); /* reserved */

            avio_rb16(pb); /* reserved */

            dref_id = avio_rb16(pb);

        }

        if (st->codec->codec_tag &&

            st->codec->codec_tag != format &&

            (c->fc->video_codec_id ? ff_codec_get_id(ff_codec_movvideo_tags, format) != c->fc->video_codec_id

                                   : st->codec->codec_tag != MKTAG('j','p','e','g'))

           ){

            /* Multiple fourcc, we skip JPEG. This is not correct, we should

             * export it as a separate AVStream but this needs a few changes

             * in the MOV demuxer, patch welcome. */

        multiple_stsd:

            av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n");

            avio_skip(pb, size - (avio_tell(pb) - start_pos));

            continue;

        }

        /* we cannot demux concatenated h264 streams because of different extradata */

        if (st->codec->codec_tag && st->codec->codec_tag == AV_RL32("avc1"))

            goto multiple_stsd;

        sc->pseudo_stream_id = st->codec->codec_tag ? -1 : pseudo_stream_id;

        sc->dref_id= dref_id;

        st->codec->codec_tag = format;

        id = ff_codec_get_id(ff_codec_movaudio_tags, format);

        if (id<=0 && ((format&0xFFFF) == 'm'+('s'<<8) || (format&0xFFFF) == 'T'+('S'<<8)))

            id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format)&0xFFFF);

        if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) {

            st->codec->codec_type = AVMEDIA_TYPE_AUDIO;

        } else if (st->codec->codec_type != AVMEDIA_TYPE_AUDIO && /* do not overwrite codec type */

                   format && format != MKTAG('m','p','4','s')) { /* skip old asf mpeg4 tag */

            id = ff_codec_get_id(ff_codec_movvideo_tags, format);

            if (id <= 0)

                id = ff_codec_get_id(ff_codec_bmp_tags, format);

            if (id > 0)

                st->codec->codec_type = AVMEDIA_TYPE_VIDEO;

            else if (st->codec->codec_type == AVMEDIA_TYPE_DATA){

                id = ff_codec_get_id(ff_codec_movsubtitle_tags, format);

                if (id > 0)

                    st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;

            }

        }

        av_dlog(c->fc, "size=%d 4CC= %c%c%c%c codec_type=%d\n", size,

                (format >> 0) & 0xff, (format >> 8) & 0xff, (format >> 16) & 0xff,

                (format >> 24) & 0xff, st->codec->codec_type);

        if (st->codec->codec_type==AVMEDIA_TYPE_VIDEO) {

            unsigned int color_depth, len;

            int color_greyscale;

            int color_table_id;

            st->codec->codec_id = id;

            avio_rb16(pb); /* version */

            avio_rb16(pb); /* revision level */

            avio_rb32(pb); /* vendor */

            avio_rb32(pb); /* temporal quality */

            avio_rb32(pb); /* spatial quality */

            st->codec->width = avio_rb16(pb); /* width */

            st->codec->height = avio_rb16(pb); /* height */

            avio_rb32(pb); /* horiz resolution */

            avio_rb32(pb); /* vert resolution */

            avio_rb32(pb); /* data size, always 0 */

            avio_rb16(pb); /* frames per samples */

            len = avio_r8(pb); /* codec name, pascal string */

            if (len > 31)

                len = 31;

            mov_read_mac_string(c, pb, len, st->codec->codec_name, 32);

            if (len < 31)

                avio_skip(pb, 31 - len);

            /* codec_tag YV12 triggers an UV swap in rawdec.c */

            if (!memcmp(st->codec->codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25))

                st->codec->codec_tag=MKTAG('I', '4', '2', '0');

            st->codec->bits_per_coded_sample = avio_rb16(pb); /* depth */

            color_table_id = avio_rb16(pb); /* colortable id */

            av_dlog(c->fc, "depth %d, ctab id %d\n",

                   st->codec->bits_per_coded_sample, color_table_id);

            /* figure out the palette situation */

            color_depth = st->codec->bits_per_coded_sample & 0x1F;

            color_greyscale = st->codec->bits_per_coded_sample & 0x20;

            /* if the depth is 2, 4, or 8 bpp, file is palettized */

            if ((color_depth == 2) || (color_depth == 4) ||

                (color_depth == 8)) {

                /* for palette traversal */

                unsigned int color_start, color_count, color_end;

                unsigned char r, g, b;

                if (color_greyscale) {

                    int color_index, color_dec;

                    /* compute the greyscale palette */

                    st->codec->bits_per_coded_sample = color_depth;

                    color_count = 1 << color_depth;

                    color_index = 255;

                    color_dec = 256 / (color_count - 1);

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

                        r = g = b = color_index;

                        sc->palette[j] =

                            (r << 16) | (g << 8) | (b);

                        color_index -= color_dec;

                        if (color_index < 0)

                            color_index = 0;

                    }

                } else if (color_table_id) {

                    const uint8_t *color_table;

                    /* if flag bit 3 is set, use the default palette */

                    color_count = 1 << color_depth;

                    if (color_depth == 2)

                        color_table = ff_qt_default_palette_4;

                    else if (color_depth == 4)

                        color_table = ff_qt_default_palette_16;

                    else

                        color_table = ff_qt_default_palette_256;

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

                        r = color_table[j * 3 + 0];

                        g = color_table[j * 3 + 1];

                        b = color_table[j * 3 + 2];

                        sc->palette[j] =

                            (r << 16) | (g << 8) | (b);

                    }

                } else {

                    /* load the palette from the file */

                    color_start = avio_rb32(pb);

                    color_count = avio_rb16(pb);

                    color_end = avio_rb16(pb);

                    if ((color_start <= 255) &&

                        (color_end <= 255)) {

                        for (j = color_start; j <= color_end; j++) {

                            /* each R, G, or B component is 16 bits;

                             * only use the top 8 bits; skip alpha bytes

                             * up front */

                            avio_r8(pb);

                            avio_r8(pb);

                            r = avio_r8(pb);

                            avio_r8(pb);

                            g = avio_r8(pb);

                            avio_r8(pb);

                            b = avio_r8(pb);

                            avio_r8(pb);

                            sc->palette[j] =

                                (r << 16) | (g << 8) | (b);

                        }

                    }

                }

                sc->has_palette = 1;

            }

        } else if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO) {

            int bits_per_sample, flags;

            uint16_t version = avio_rb16(pb);

            st->codec->codec_id = id;

            avio_rb16(pb); /* revision level */

            avio_rb32(pb); /* vendor */

            st->codec->channels = avio_rb16(pb);             /* channel count */

            av_dlog(c->fc, "audio channels %d\n", st->codec->channels);

            st->codec->bits_per_coded_sample = avio_rb16(pb);      /* sample size */

            sc->audio_cid = avio_rb16(pb);

            avio_rb16(pb); /* packet size = 0 */

            st->codec->sample_rate = ((avio_rb32(pb) >> 16));

            //Read QT version 1 fields. In version 0 these do not exist.

            av_dlog(c->fc, "version =%d, isom =%d\n",version,c->isom);

            if (!c->isom) {

                if (version==1) {

                    sc->samples_per_frame = avio_rb32(pb);

                    avio_rb32(pb); /* bytes per packet */

                    sc->bytes_per_frame = avio_rb32(pb);

                    avio_rb32(pb); /* bytes per sample */

                } else if (version==2) {

                    avio_rb32(pb); /* sizeof struct only */

                    st->codec->sample_rate = av_int2double(avio_rb64(pb)); /* float 64 */

                    st->codec->channels = avio_rb32(pb);

                    avio_rb32(pb); /* always 0x7F000000 */

                    st->codec->bits_per_coded_sample = avio_rb32(pb); /* bits per channel if sound is uncompressed */

                    flags = avio_rb32(pb); /* lpcm format specific flag */

                    sc->bytes_per_frame = avio_rb32(pb); /* bytes per audio packet if constant */

                    sc->samples_per_frame = avio_rb32(pb); /* lpcm frames per audio packet if constant */

                    if (format == MKTAG('l','p','c','m'))

                        st->codec->codec_id = ff_mov_get_lpcm_codec_id(st->codec->bits_per_coded_sample, flags);

                }

            }

            switch (st->codec->codec_id) {

            case AV_CODEC_ID_PCM_S8:

            case AV_CODEC_ID_PCM_U8:

                if (st->codec->bits_per_coded_sample == 16)

                    st->codec->codec_id = AV_CODEC_ID_PCM_S16BE;

                break;

            case AV_CODEC_ID_PCM_S16LE:

            case AV_CODEC_ID_PCM_S16BE:

                if (st->codec->bits_per_coded_sample == 8)

                    st->codec->codec_id = AV_CODEC_ID_PCM_S8;

                else if (st->codec->bits_per_coded_sample == 24)

                    st->codec->codec_id =

                        st->codec->codec_id == AV_CODEC_ID_PCM_S16BE ?

                        AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE;

                break;

            /* set values for old format before stsd version 1 appeared */

            case AV_CODEC_ID_MACE3:

                sc->samples_per_frame = 6;

                sc->bytes_per_frame = 2*st->codec->channels;

                break;

            case AV_CODEC_ID_MACE6:

                sc->samples_per_frame = 6;

                sc->bytes_per_frame = 1*st->codec->channels;

                break;

            case AV_CODEC_ID_ADPCM_IMA_QT:

                sc->samples_per_frame = 64;

                sc->bytes_per_frame = 34*st->codec->channels;

                break;

            case AV_CODEC_ID_GSM:

                sc->samples_per_frame = 160;

                sc->bytes_per_frame = 33;

                break;

            default:

                break;

            }

            bits_per_sample = av_get_bits_per_sample(st->codec->codec_id);

            if (bits_per_sample) {

                st->codec->bits_per_coded_sample = bits_per_sample;

                sc->sample_size = (bits_per_sample >> 3) * st->codec->channels;

            }

        } else if (st->codec->codec_type==AVMEDIA_TYPE_SUBTITLE){

            // ttxt stsd contains display flags, justification, background

            // color, fonts, and default styles, so fake an atom to read it

            MOVAtom fake_atom = { .size = size - (avio_tell(pb) - start_pos) };

            if (format != AV_RL32("mp4s")) // mp4s contains a regular esds atom

                mov_read_glbl(c, pb, fake_atom);

            st->codec->codec_id= id;

            st->codec->width = sc->width;

            st->codec->height = sc->height;

        } else {

            /* other codec type, just skip (rtp, mp4s, tmcd ...) */

            avio_skip(pb, size - (avio_tell(pb) - start_pos));

        }

        /* this will read extra atoms at the end (wave, alac, damr, avcC, SMI ...) */

        a.size = size - (avio_tell(pb) - start_pos);

        if (a.size > 8) {

            int ret;

            if ((ret = mov_read_default(c, pb, a)) < 0)

                return ret;

        } else if (a.size > 0)

            avio_skip(pb, a.size);

    }

    if (st->codec->codec_type==AVMEDIA_TYPE_AUDIO && st->codec->sample_rate==0 && sc->time_scale>1)

        st->codec->sample_rate= sc->time_scale;

    /* special codec parameters handling */

    switch (st->codec->codec_id) {

#if CONFIG_DV_DEMUXER

    case AV_CODEC_ID_DVAUDIO:

        c->dv_fctx = avformat_alloc_context();

        c->dv_demux = avpriv_dv_init_demux(c->dv_fctx);

        if (!c->dv_demux) {

            av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n");

            return AVERROR(ENOMEM);

        }

        sc->dv_audio_container = 1;

        st->codec->codec_id = AV_CODEC_ID_PCM_S16LE;

        break;

#endif

    /* no ifdef since parameters are always those */

    case AV_CODEC_ID_QCELP:

        // force sample rate for qcelp when not stored in mov

        if (st->codec->codec_tag != MKTAG('Q','c','l','p'))

            st->codec->sample_rate = 8000;

        st->codec->channels= 1; /* really needed */

        break;

    case AV_CODEC_ID_AMR_NB:

        st->codec->channels= 1; /* really needed */

        /* force sample rate for amr, stsd in 3gp does not store sample rate */

        st->codec->sample_rate = 8000;

        break;

    case AV_CODEC_ID_AMR_WB:

        st->codec->channels    = 1;

        st->codec->sample_rate = 16000;

        break;

    case AV_CODEC_ID_MP2:

    case AV_CODEC_ID_MP3:

        st->codec->codec_type = AVMEDIA_TYPE_AUDIO; /* force type after stsd for m1a hdlr */

        st->need_parsing = AVSTREAM_PARSE_FULL;

        break;

    case AV_CODEC_ID_GSM:

    case AV_CODEC_ID_ADPCM_MS:

    case AV_CODEC_ID_ADPCM_IMA_WAV:

    case AV_CODEC_ID_ILBC:

        st->codec->block_align = sc->bytes_per_frame;

        break;

    case AV_CODEC_ID_ALAC:

        if (st->codec->extradata_size == 36) {

            st->codec->channels   = AV_RB8 (st->codec->extradata+21);

            st->codec->sample_rate = AV_RB32(st->codec->extradata+32);

        }

        break;

    case AV_CODEC_ID_VC1:

        st->need_parsing = AVSTREAM_PARSE_FULL;

        break;

    default:

        break;

    }

    return 0;

}


build_gtdt(GArray *table_data, GArray *linker)

{

    int gtdt_start = table_data->len;

    AcpiGenericTimerTable *gtdt;

    gtdt = acpi_data_push(table_data, sizeof *gtdt);

    /* The interrupt values are the same with the device tree when adding 16 */

    gtdt->secure_el1_interrupt = ARCH_TIMER_S_EL1_IRQ + 16;

    gtdt->secure_el1_flags = ACPI_EDGE_SENSITIVE;

    gtdt->non_secure_el1_interrupt = ARCH_TIMER_NS_EL1_IRQ + 16;

    gtdt->non_secure_el1_flags = ACPI_EDGE_SENSITIVE;

    gtdt->virtual_timer_interrupt = ARCH_TIMER_VIRT_IRQ + 16;

    gtdt->virtual_timer_flags = ACPI_EDGE_SENSITIVE;

    gtdt->non_secure_el2_interrupt = ARCH_TIMER_NS_EL2_IRQ + 16;

    gtdt->non_secure_el2_flags = ACPI_EDGE_SENSITIVE;

    build_header(linker, table_data,

                 (void *)(table_data->data + gtdt_start), "GTDT",

                 table_data->len - gtdt_start, 2, NULL);

}


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

                             target_ulong opcode, target_ulong *args)

{

    sPAPRRngState *rngstate;

    HRandomData hrdata;

    rngstate = SPAPR_RNG(object_resolve_path_type("", TYPE_SPAPR_RNG, NULL));

    if (!rngstate || !rngstate->backend) {

        return H_HARDWARE;

    }

    qemu_sem_init(&hrdata.sem, 0);

    hrdata.val.v64 = 0;

    hrdata.received = 0;

    qemu_mutex_unlock_iothread();

    while (hrdata.received < 8) {

        rng_backend_request_entropy(rngstate->backend, 8 - hrdata.received,

                                    random_recv, &hrdata);

        qemu_sem_wait(&hrdata.sem);

    }

    qemu_mutex_lock_iothread();

    qemu_sem_destroy(&hrdata.sem);

    args[0] = hrdata.val.v64;

    return H_SUCCESS;

}


static int normalize_bits(int num, int width)

{

    int i = 0;

    int bits = (width) ? 31 : 15;

    int limit = 1 << (bits - 1);

    if (num) {

        if (num == -1)

            return bits;

        if (num < 0)

            num = ~num;

        for (i = 0; num < limit; i++)

            num <<= 1;

    }

    return i;

}


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

{

    SDHCIState *s = SYSBUS_SDHCI(dev);

    SysBusDevice *sbd = SYS_BUS_DEVICE(dev);

    sdhci_common_realize(s, errp);

    if (errp && *errp) {

        return;

    }

    if (s->dma_mr) {

        address_space_init(s->dma_as, s->dma_mr, "sdhci-dma");

    } else {

        /* use system_memory() if property "dma" not set */

        s->dma_as = &address_space_memory;

    }

    sysbus_init_irq(sbd, &s->irq);

    sysbus_init_mmio(sbd, &s->iomem);

}


static int decode_vop_header(MpegEncContext *s, GetBitContext *gb){

    int time_incr, time_increment;

    s->pict_type = get_bits(gb, 2) + AV_PICTURE_TYPE_I;        /* pict type: I = 0 , P = 1 */

    if(s->pict_type==AV_PICTURE_TYPE_B && s->low_delay && s->vol_control_parameters==0 && !(s->flags & CODEC_FLAG_LOW_DELAY)){

        av_log(s->avctx, AV_LOG_ERROR, "low_delay flag incorrectly, clearing it\n");

        s->low_delay=0;

    }

    s->partitioned_frame= s->data_partitioning && s->pict_type!=AV_PICTURE_TYPE_B;

    if(s->partitioned_frame)

        s->decode_mb= mpeg4_decode_partitioned_mb;

    else

        s->decode_mb= mpeg4_decode_mb;

    time_incr=0;

    while (get_bits1(gb) != 0)

        time_incr++;

    check_marker(gb, "before time_increment");

    if(s->time_increment_bits==0 || !(show_bits(gb, s->time_increment_bits+1)&1)){

        av_log(s->avctx, AV_LOG_ERROR, "hmm, seems the headers are not complete, trying to guess time_increment_bits\n");

        for(s->time_increment_bits=1 ;s->time_increment_bits<16; s->time_increment_bits++){

            if (    s->pict_type == AV_PICTURE_TYPE_P

                || (s->pict_type == AV_PICTURE_TYPE_S && s->vol_sprite_usage==GMC_SPRITE)) {

                if((show_bits(gb, s->time_increment_bits+6)&0x37) == 0x30) break;

            }else

                if((show_bits(gb, s->time_increment_bits+5)&0x1F) == 0x18) break;

        }

        av_log(s->avctx, AV_LOG_ERROR, "my guess is %d bits ;)\n",s->time_increment_bits);

    }

    if(IS_3IV1) time_increment= get_bits1(gb); //FIXME investigate further

    else time_increment= get_bits(gb, s->time_increment_bits);

    if(s->pict_type!=AV_PICTURE_TYPE_B){

        s->last_time_base= s->time_base;

        s->time_base+= time_incr;

        s->time= s->time_base*s->avctx->time_base.den + time_increment;

        if(s->workaround_bugs&FF_BUG_UMP4){

            if(s->time < s->last_non_b_time){

                /* header is not mpeg-4-compatible, broken encoder,

                 * trying to workaround */

                s->time_base++;

                s->time+= s->avctx->time_base.den;

            }

        }

        s->pp_time= s->time - s->last_non_b_time;

        s->last_non_b_time= s->time;

    }else{

        s->time= (s->last_time_base + time_incr)*s->avctx->time_base.den + time_increment;

        s->pb_time= s->pp_time - (s->last_non_b_time - s->time);

        if(s->pp_time <=s->pb_time || s->pp_time <= s->pp_time - s->pb_time || s->pp_time<=0){

            /* messed up order, maybe after seeking? skipping current b-frame */

            return FRAME_SKIPPED;

        }

        ff_mpeg4_init_direct_mv(s);

        if(s->t_frame==0) s->t_frame= s->pb_time;

        if(s->t_frame==0) s->t_frame=1; // 1/0 protection

        s->pp_field_time= (  ROUNDED_DIV(s->last_non_b_time, s->t_frame)

                           - ROUNDED_DIV(s->last_non_b_time - s->pp_time, s->t_frame))*2;

        s->pb_field_time= (  ROUNDED_DIV(s->time, s->t_frame)

                           - ROUNDED_DIV(s->last_non_b_time - s->pp_time, s->t_frame))*2;

        if(!s->progressive_sequence){

            if(s->pp_field_time <= s->pb_field_time || s->pb_field_time <= 1)

                return FRAME_SKIPPED;

        }

    }

    if(s->avctx->time_base.num)

        s->current_picture_ptr->f.pts = (s->time + s->avctx->time_base.num / 2) / s->avctx->time_base.num;

    else

        s->current_picture_ptr->f.pts = AV_NOPTS_VALUE;

    if(s->avctx->debug&FF_DEBUG_PTS)

        av_log(s->avctx, AV_LOG_DEBUG, "MPEG4 PTS: %"PRId64"\n",

               s->current_picture_ptr->f.pts);

    check_marker(gb, "before vop_coded");

    /* vop coded */

    if (get_bits1(gb) != 1){

        if(s->avctx->debug&FF_DEBUG_PICT_INFO)

            av_log(s->avctx, AV_LOG_ERROR, "vop not coded\n");

        return FRAME_SKIPPED;

    }

    if (s->shape != BIN_ONLY_SHAPE && ( s->pict_type == AV_PICTURE_TYPE_P

                          || (s->pict_type == AV_PICTURE_TYPE_S && s->vol_sprite_usage==GMC_SPRITE))) {

        /* rounding type for motion estimation */

        s->no_rounding = get_bits1(gb);

    } else {

        s->no_rounding = 0;

    }

//FIXME reduced res stuff

     if (s->shape != RECT_SHAPE) {

         if (s->vol_sprite_usage != 1 || s->pict_type != AV_PICTURE_TYPE_I) {

             skip_bits(gb, 13); /* width */

             skip_bits1(gb);   /* marker */

             skip_bits(gb, 13); /* height */

             skip_bits1(gb);   /* marker */

             skip_bits(gb, 13); /* hor_spat_ref */

             skip_bits1(gb);   /* marker */

             skip_bits(gb, 13); /* ver_spat_ref */

         }

         skip_bits1(gb); /* change_CR_disable */

         if (get_bits1(gb) != 0) {

             skip_bits(gb, 8); /* constant_alpha_value */

         }

     }

//FIXME complexity estimation stuff

     if (s->shape != BIN_ONLY_SHAPE) {

         skip_bits_long(gb, s->cplx_estimation_trash_i);

         if(s->pict_type != AV_PICTURE_TYPE_I)

            skip_bits_long(gb, s->cplx_estimation_trash_p);

         if(s->pict_type == AV_PICTURE_TYPE_B)

            skip_bits_long(gb, s->cplx_estimation_trash_b);

         s->intra_dc_threshold= ff_mpeg4_dc_threshold[ get_bits(gb, 3) ];

         if(!s->progressive_sequence){

             s->top_field_first= get_bits1(gb);

             s->alternate_scan= get_bits1(gb);

         }else

             s->alternate_scan= 0;

     }

     if(s->alternate_scan){

         ff_init_scantable(s->dsp.idct_permutation, &s->inter_scantable  , ff_alternate_vertical_scan);

         ff_init_scantable(s->dsp.idct_permutation, &s->intra_scantable  , ff_alternate_vertical_scan);

         ff_init_scantable(s->dsp.idct_permutation, &s->intra_h_scantable, ff_alternate_vertical_scan);

         ff_init_scantable(s->dsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);

     } else{

         ff_init_scantable(s->dsp.idct_permutation, &s->inter_scantable  , ff_zigzag_direct);

         ff_init_scantable(s->dsp.idct_permutation, &s->intra_scantable  , ff_zigzag_direct);

         ff_init_scantable(s->dsp.idct_permutation, &s->intra_h_scantable, ff_alternate_horizontal_scan);

         ff_init_scantable(s->dsp.idct_permutation, &s->intra_v_scantable, ff_alternate_vertical_scan);

     }

     if(s->pict_type == AV_PICTURE_TYPE_S && (s->vol_sprite_usage==STATIC_SPRITE || s->vol_sprite_usage==GMC_SPRITE)){

         mpeg4_decode_sprite_trajectory(s, gb);

         if(s->sprite_brightness_change) av_log(s->avctx, AV_LOG_ERROR, "sprite_brightness_change not supported\n");

         if(s->vol_sprite_usage==STATIC_SPRITE) av_log(s->avctx, AV_LOG_ERROR, "static sprite not supported\n");

     }

     if (s->shape != BIN_ONLY_SHAPE) {

         s->chroma_qscale= s->qscale = get_bits(gb, s->quant_precision);

         if(s->qscale==0){

             av_log(s->avctx, AV_LOG_ERROR, "Error, header damaged or not MPEG4 header (qscale=0)\n");

             return -1; // makes no sense to continue, as there is nothing left from the image then

         }

         if (s->pict_type != AV_PICTURE_TYPE_I) {

             s->f_code = get_bits(gb, 3);       /* fcode_for */

             if(s->f_code==0){

                 av_log(s->avctx, AV_LOG_ERROR, "Error, header damaged or not MPEG4 header (f_code=0)\n");

                 return -1; // makes no sense to continue, as the MV decoding will break very quickly

             }

         }else

             s->f_code=1;

         if (s->pict_type == AV_PICTURE_TYPE_B) {

             s->b_code = get_bits(gb, 3);

         }else

             s->b_code=1;

         if(s->avctx->debug&FF_DEBUG_PICT_INFO){

             av_log(s->avctx, AV_LOG_DEBUG, "qp:%d fc:%d,%d %s size:%d pro:%d alt:%d top:%d %spel part:%d resync:%d w:%d a:%d rnd:%d vot:%d%s dc:%d ce:%d/%d/%d\n",

                 s->qscale, s->f_code, s->b_code,

                 s->pict_type == AV_PICTURE_TYPE_I ? "I" : (s->pict_type == AV_PICTURE_TYPE_P ? "P" : (s->pict_type == AV_PICTURE_TYPE_B ? "B" : "S")),

                 gb->size_in_bits,s->progressive_sequence, s->alternate_scan, s->top_field_first,

                 s->quarter_sample ? "q" : "h", s->data_partitioning, s->resync_marker, s->num_sprite_warping_points,

                 s->sprite_warping_accuracy, 1-s->no_rounding, s->vo_type, s->vol_control_parameters ? " VOLC" : " ", s->intra_dc_threshold, s->cplx_estimation_trash_i, s->cplx_estimation_trash_p, s->cplx_estimation_trash_b);

         }

         if(!s->scalability){

             if (s->shape!=RECT_SHAPE && s->pict_type!=AV_PICTURE_TYPE_I) {

                 skip_bits1(gb); // vop shape coding type

             }

         }else{

             if(s->enhancement_type){

                 int load_backward_shape= get_bits1(gb);

                 if(load_backward_shape){

                     av_log(s->avctx, AV_LOG_ERROR, "load backward shape isn't supported\n");

                 }

             }

             skip_bits(gb, 2); //ref_select_code

         }

     }

     /* detect buggy encoders which don't set the low_delay flag (divx4/xvid/opendivx)*/

     // note we cannot detect divx5 without b-frames easily (although it's buggy too)

     if(s->vo_type==0 && s->vol_control_parameters==0 && s->divx_version==-1 && s->picture_number==0){

         av_log(s->avctx, AV_LOG_WARNING, "looks like this file was encoded with (divx4/(old)xvid/opendivx) -> forcing low_delay flag\n");

         s->low_delay=1;

     }

     s->picture_number++; // better than pic number==0 always ;)

     s->y_dc_scale_table= ff_mpeg4_y_dc_scale_table; //FIXME add short header support

     s->c_dc_scale_table= ff_mpeg4_c_dc_scale_table;

     if(s->workaround_bugs&FF_BUG_EDGE){

         s->h_edge_pos= s->width;

         s->v_edge_pos= s->height;

     }

     return 0;

}


static int handle_cmd(AHCIState *s, int port, int slot)

{

    IDEState *ide_state;

    uint32_t opts;

    uint64_t tbl_addr;

    AHCICmdHdr *cmd;

    uint8_t *cmd_fis;

    dma_addr_t cmd_len;

    if (s->dev[port].port.ifs[0].status & (BUSY_STAT|DRQ_STAT)) {

        /* Engine currently busy, try again later */

        DPRINTF(port, "engine busy\n");

        return -1;

    }

    cmd = &((AHCICmdHdr *)s->dev[port].lst)[slot];

    if (!s->dev[port].lst) {

        DPRINTF(port, "error: lst not given but cmd handled");

        return -1;

    }

    /* remember current slot handle for later */

    s->dev[port].cur_cmd = cmd;

    opts = le32_to_cpu(cmd->opts);

    tbl_addr = le64_to_cpu(cmd->tbl_addr);

    cmd_len = 0x80;

    cmd_fis = dma_memory_map(s->as, tbl_addr, &cmd_len,

                             DMA_DIRECTION_FROM_DEVICE);

    if (!cmd_fis) {

        DPRINTF(port, "error: guest passed us an invalid cmd fis\n");

        return -1;

    }

    /* The device we are working for */

    ide_state = &s->dev[port].port.ifs[0];

    if (!ide_state->blk) {

        DPRINTF(port, "error: guest accessed unused port");

        goto out;

    }

    debug_print_fis(cmd_fis, 0x90);

    //debug_print_fis(cmd_fis, (opts & AHCI_CMD_HDR_CMD_FIS_LEN) * 4);

    switch (cmd_fis[0]) {

        case SATA_FIS_TYPE_REGISTER_H2D:

            break;

        default:

            DPRINTF(port, "unknown command cmd_fis[0]=%02x cmd_fis[1]=%02x "

                          "cmd_fis[2]=%02x\n", cmd_fis[0], cmd_fis[1],

                          cmd_fis[2]);

            goto out;

            break;

    }

    switch (cmd_fis[1]) {

        case SATA_FIS_REG_H2D_UPDATE_COMMAND_REGISTER:

            break;

        case 0:

            break;

        default:

            DPRINTF(port, "unknown command cmd_fis[0]=%02x cmd_fis[1]=%02x "

                          "cmd_fis[2]=%02x\n", cmd_fis[0], cmd_fis[1],

                          cmd_fis[2]);

            goto out;

            break;

    }

    if (!(cmd_fis[1] & SATA_FIS_REG_H2D_UPDATE_COMMAND_REGISTER)) {

        switch (s->dev[port].port_state) {

        case STATE_RUN:

            if (cmd_fis[15] & ATA_SRST) {

                s->dev[port].port_state = STATE_RESET;

            }

            break;

        case STATE_RESET:

            if (!(cmd_fis[15] & ATA_SRST)) {

                ahci_reset_port(s, port);

            }

            break;

        }

    }

    else if (cmd_fis[1] & SATA_FIS_REG_H2D_UPDATE_COMMAND_REGISTER) {

        /* Check for NCQ command */

        if (is_ncq(cmd_fis[2])) {

            process_ncq_command(s, port, cmd_fis, slot);

            goto out;

        }

        /* Decompose the FIS:

         * AHCI does not interpret FIS packets, it only forwards them.

         * SATA 1.0 describes how to decode LBA28 and CHS FIS packets.

         * Later specifications, e.g, SATA 3.2, describe LBA48 FIS packets.

         *

         * ATA4 describes sector number for LBA28/CHS commands.

         * ATA6 describes sector number for LBA48 commands.

         * ATA8 deprecates CHS fully, describing only LBA28/48.

         *

         * We dutifully convert the FIS into IDE registers, and allow the

         * core layer to interpret them as needed. */

        ide_state->feature = cmd_fis[3];

        ide_state->sector = cmd_fis[4];     /* LBA 7:0 */

        ide_state->lcyl = cmd_fis[5];       /* LBA 15:8  */

        ide_state->hcyl = cmd_fis[6];       /* LBA 23:16 */

        ide_state->select = cmd_fis[7];     /* LBA 27:24 (LBA28) */

        ide_state->hob_sector = cmd_fis[8]; /* LBA 31:24 */

        ide_state->hob_lcyl = cmd_fis[9];   /* LBA 39:32 */

        ide_state->hob_hcyl = cmd_fis[10];  /* LBA 47:40 */

        ide_state->hob_feature = cmd_fis[11];

        ide_state->nsector = (int64_t)((cmd_fis[13] << 8) | cmd_fis[12]);

        /* 14, 16, 17, 18, 19: Reserved (SATA 1.0) */

        /* 15: Only valid when UPDATE_COMMAND not set. */

        /* Copy the ACMD field (ATAPI packet, if any) from the AHCI command

         * table to ide_state->io_buffer

         */

        if (opts & AHCI_CMD_ATAPI) {

            memcpy(ide_state->io_buffer, &cmd_fis[AHCI_COMMAND_TABLE_ACMD], 0x10);

            debug_print_fis(ide_state->io_buffer, 0x10);

            s->dev[port].done_atapi_packet = false;

            /* XXX send PIO setup FIS */

        }

        ide_state->error = 0;

        /* Reset transferred byte counter */

        cmd->status = 0;

        /* We're ready to process the command in FIS byte 2. */

        ide_exec_cmd(&s->dev[port].port, cmd_fis[2]);

    }

out:

    dma_memory_unmap(s->as, cmd_fis, cmd_len, DMA_DIRECTION_FROM_DEVICE,

                     cmd_len);

    if (s->dev[port].port.ifs[0].status & (BUSY_STAT|DRQ_STAT)) {

        /* async command, complete later */

        s->dev[port].busy_slot = slot;

        return -1;

    }

    /* done handling the command */

    return 0;

}


static int decompress_p(AVCodecContext *avctx,

                        uint32_t *dst, int linesize,

                        uint32_t *prev, int plinesize)

{

    SCPRContext *s = avctx->priv_data;

    GetByteContext *gb = &s->gb;

    int ret, temp, min, max, x, y, cx = 0, cx1 = 0;

    int backstep = linesize - avctx->width;

    const int cxshift = s->cxshift;

    if (bytestream2_get_byte(gb) == 0)

        return 0;

    bytestream2_skip(gb, 1);

    init_rangecoder(&s->rc, gb);

    ret  = decode_value(s, s->range_model, 256, 1, &min);

    ret |= decode_value(s, s->range_model, 256, 1, &temp);

    min += temp << 8;

    ret |= decode_value(s, s->range_model, 256, 1, &max);

    ret |= decode_value(s, s->range_model, 256, 1, &temp);

    if (ret < 0)

        return ret;

    max += temp << 8;

    memset(s->blocks, 0, sizeof(*s->blocks) * s->nbcount);

    while (min <= max) {

        int fill, count;

        ret  = decode_value(s, s->fill_model,  5,   10, &fill);

        ret |= decode_value(s, s->count_model, 256, 20, &count);

        if (ret < 0)

            return ret;

        while (min < s->nbcount && count-- > 0) {

            s->blocks[min++] = fill;

        }

    }

    for (y = 0; y < s->nby; y++) {

        for (x = 0; x < s->nbx; x++) {

            int sy1 = 0, sy2 = 16, sx1 = 0, sx2 = 16;

            if (s->blocks[y * s->nbx + x] == 0)

                continue;

            if (((s->blocks[y * s->nbx + x] - 1) & 1) > 0) {

                ret  = decode_value(s, s->sxy_model[0], 16, 100, &sx1);

                ret |= decode_value(s, s->sxy_model[1], 16, 100, &sy1);

                ret |= decode_value(s, s->sxy_model[2], 16, 100, &sx2);

                ret |= decode_value(s, s->sxy_model[3], 16, 100, &sy2);

                if (ret < 0)

                    return ret;

                sx2++;

                sy2++;

            }

            if (((s->blocks[y * s->nbx + x] - 1) & 2) > 0) {

                int i, j, by = y * 16, bx = x * 16;

                int mvx, mvy;

                ret  = decode_value(s, s->mv_model[0], 512, 100, &mvx);

                ret |= decode_value(s, s->mv_model[1], 512, 100, &mvy);

                if (ret < 0)

                    return ret;

                mvx -= 256;

                mvy -= 256;

                if (by + mvy + sy1 < 0 || bx + mvx + sx1 < 0)

                    return AVERROR_INVALIDDATA;

                for (i = 0; i < sy2 - sy1 && (by + sy1 + i) < avctx->height; i++) {

                    for (j = 0; j < sx2 - sx1 && (bx + sx1 + j) < avctx->width; j++) {

                        dst[(by + i + sy1) * linesize + bx + sx1 + j] = prev[(by + mvy + sy1 + i) * plinesize + bx + sx1 + mvx + j];

                    }

                }

            } else {

                int run, r, g, b, z, bx = x * 16 + sx1, by = y * 16 + sy1;

                unsigned clr, ptype = 0;

                for (; by < y * 16 + sy2 && by < avctx->height;) {

                    ret = decode_value(s, s->op_model[ptype], 6, 1000, &ptype);

                    if (ptype == 0) {

                        ret = decode_unit(s, &s->pixel_model[0][cx + cx1], 400, &r);

                        if (ret < 0)

                            return ret;

                        cx1 = (cx << 6) & 0xFC0;

                        cx = r >> cxshift;

                        ret = decode_unit(s, &s->pixel_model[1][cx + cx1], 400, &g);

                        if (ret < 0)

                            return ret;

                        cx1 = (cx << 6) & 0xFC0;

                        cx = g >> cxshift;

                        ret = decode_unit(s, &s->pixel_model[2][cx + cx1], 400, &b);

                        if (ret < 0)

                            return ret;

                        cx1 = (cx << 6) & 0xFC0;

                        cx = b >> cxshift;

                        clr = (b << 16) + (g << 8) + r;

                    }

                    if (ptype > 5)

                        return AVERROR_INVALIDDATA;

                    ret = decode_value(s, s->run_model[ptype], 256, 400, &run);

                    if (ret < 0)

                        return ret;

                    switch (ptype) {

                    case 0:

                        while (run-- > 0) {

                            if (by >= avctx->height)

                                return AVERROR_INVALIDDATA;

                            dst[by * linesize + bx] = clr;

                            bx++;

                            if (bx >= x * 16 + sx2 || bx >= avctx->width) {

                                bx = x * 16 + sx1;

                                by++;

                            }

                        }

                        break;

                    case 1:

                        while (run-- > 0) {

                            if (bx == 0) {

                                if (by < 1)

                                    return AVERROR_INVALIDDATA;

                                z = backstep;

                            } else {

                                z = 0;

                            }

                            if (by >= avctx->height)

                                return AVERROR_INVALIDDATA;

                            clr = dst[by * linesize + bx - 1 - z];

                            dst[by * linesize + bx] = clr;

                            bx++;

                            if (bx >= x * 16 + sx2 || bx >= avctx->width) {

                                bx = x * 16 + sx1;

                                by++;

                            }

                        }

                        break;

                    case 2:

                        while (run-- > 0) {

                            if (by < 1 || by >= avctx->height)

                                return AVERROR_INVALIDDATA;

                            clr = dst[(by - 1) * linesize + bx];

                            dst[by * linesize + bx] = clr;

                            bx++;

                            if (bx >= x * 16 + sx2 || bx >= avctx->width) {

                                bx = x * 16 + sx1;

                                by++;

                            }

                        }

                        break;

                    case 3:

                        while (run-- > 0) {

                            if (by >= avctx->height)

                                return AVERROR_INVALIDDATA;

                            clr = prev[by * linesize + bx];

                            dst[by * linesize + bx] = clr;

                            bx++;

                            if (bx >= x * 16 + sx2 || bx >= avctx->width) {

                                bx = x * 16 + sx1;

                                by++;

                            }

                        }

                        break;

                    case 4:

                        while (run-- > 0) {

                            uint8_t *odst = (uint8_t *)dst;

                            if (by < 1 || by >= avctx->height)

                                return AVERROR_INVALIDDATA;

                            if (bx == 0) {

                                z = backstep;

                            } else {

                                z = 0;

                            }

                            r = odst[((by - 1) * linesize + bx) * 4] +

                                odst[(by * linesize + bx - 1 - z) * 4] -

                                odst[((by - 1) * linesize + bx - 1 - z) * 4];

                            g = odst[((by - 1) * linesize + bx) * 4 + 1] +

                                odst[(by * linesize + bx - 1 - z) * 4 + 1] -

                                odst[((by - 1) * linesize + bx - 1 - z) * 4 + 1];

                            b = odst[((by - 1) * linesize + bx) * 4 + 2] +

                                odst[(by * linesize + bx - 1 - z) * 4 + 2] -

                                odst[((by - 1) * linesize + bx - 1 - z) * 4 + 2];

                            clr = ((b & 0xFF) << 16) + ((g & 0xFF) << 8) + (r & 0xFF);

                            dst[by * linesize + bx] = clr;

                            bx++;

                            if (bx >= x * 16 + sx2 || bx >= avctx->width) {

                                bx = x * 16 + sx1;

                                by++;

                            }

                        }

                        break;

                    case 5:

                        while (run-- > 0) {

                            if (by < 1 || by >= avctx->height)

                                return AVERROR_INVALIDDATA;

                            if (bx == 0) {

                                z = backstep;

                            } else {

                                z = 0;

                            }

                            clr = dst[(by - 1) * linesize + bx - 1 - z];

                            dst[by * linesize + bx] = clr;

                            bx++;

                            if (bx >= x * 16 + sx2 || bx >= avctx->width) {

                                bx = x * 16 + sx1;

                                by++;

                            }

                        }

                        break;

                    }

                    if (avctx->bits_per_coded_sample == 16) {

                        cx1 = (clr & 0xFF00) >> 2;

                        cx = (clr & 0xFFFFFF) >> 16;

                    } else {

                        cx1 = (clr & 0xFC00) >> 4;

                        cx = (clr & 0xFFFFFF) >> 18;

                    }

                }

            }

        }

    }

    return 0;

}


static void *rndis_queue_response(USBNetState *s, unsigned int length)

{

    struct rndis_response *r =

            qemu_mallocz(sizeof(struct rndis_response) + length);

    TAILQ_INSERT_TAIL(&s->rndis_resp, r, entries);

    r->length = length;

    return &r->buf[0];

}


static char *visitor_get(TestOutputVisitorData *data)

{

    data->str = string_output_get_string(data->sov);

    g_assert(data->str);

    return data->str;

}


static void do_change_vnc(const char *target)

{

    if (strcmp(target, "passwd") == 0 ||

	strcmp(target, "password") == 0) {

	char password[9];

	monitor_readline("Password: ", 1, password, sizeof(password));

	if (vnc_display_password(NULL, password) < 0)

	    term_printf("could not set VNC server password\n");

    } else {

	if (vnc_display_open(NULL, target) < 0)

	    term_printf("could not start VNC server on %s\n", target);

    }

}