static void qemu_chr_parse_socket(QemuOpts *opts, ChardevBackend *backend,

                                  Error **errp)

{

    bool is_listen      = qemu_opt_get_bool(opts, "server", false);

    bool is_waitconnect = is_listen && qemu_opt_get_bool(opts, "wait", true);

    bool is_telnet      = qemu_opt_get_bool(opts, "telnet", false);

    bool is_tn3270      = qemu_opt_get_bool(opts, "tn3270", false);

    bool do_nodelay     = !qemu_opt_get_bool(opts, "delay", true);

    int64_t reconnect   = qemu_opt_get_number(opts, "reconnect", 0);

    const char *path = qemu_opt_get(opts, "path");

    const char *host = qemu_opt_get(opts, "host");

    const char *port = qemu_opt_get(opts, "port");

    const char *tls_creds = qemu_opt_get(opts, "tls-creds");

    SocketAddress *addr;

    ChardevSocket *sock;

    backend->type = CHARDEV_BACKEND_KIND_SOCKET;

    if (!path) {

        if (!host) {

            error_setg(errp, "chardev: socket: no host given");

            return;

        }

        if (!port) {

            error_setg(errp, "chardev: socket: no port given");

            return;

        }

    } else {

        if (tls_creds) {

            error_setg(errp, "TLS can only be used over TCP socket");

            return;

        }

    }

    sock = backend->u.socket.data = g_new0(ChardevSocket, 1);

    qemu_chr_parse_common(opts, qapi_ChardevSocket_base(sock));

    sock->has_nodelay = true;

    sock->nodelay = do_nodelay;

    sock->has_server = true;

    sock->server = is_listen;

    sock->has_telnet = true;

    sock->telnet = is_telnet;

    sock->has_tn3270 = true;

    sock->tn3270 = is_tn3270;

    sock->has_wait = true;

    sock->wait = is_waitconnect;

    sock->has_reconnect = true;

    sock->reconnect = reconnect;

    sock->tls_creds = g_strdup(tls_creds);

    addr = g_new0(SocketAddress, 1);

    if (path) {

        UnixSocketAddress *q_unix;

        addr->type = SOCKET_ADDRESS_KIND_UNIX;

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

        q_unix->path = g_strdup(path);

    } else {

        addr->type = SOCKET_ADDRESS_KIND_INET;

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

        *addr->u.inet.data = (InetSocketAddress) {

            .host = g_strdup(host),

            .port = g_strdup(port),

            .has_to = qemu_opt_get(opts, "to"),

            .to = qemu_opt_get_number(opts, "to", 0),

            .has_ipv4 = qemu_opt_get(opts, "ipv4"),

            .ipv4 = qemu_opt_get_bool(opts, "ipv4", 0),

            .has_ipv6 = qemu_opt_get(opts, "ipv6"),

            .ipv6 = qemu_opt_get_bool(opts, "ipv6", 0),

        };

    }

    sock->addr = addr;

}


void ppc_tb_set_jmp_target(uintptr_t jmp_addr, uintptr_t addr)

{

    tcg_insn_unit i1, i2;

    uint64_t pair;

    intptr_t diff = addr - jmp_addr;

    if (in_range_b(diff)) {

        i1 = B | (diff & 0x3fffffc);

        i2 = NOP;

    } else if (USE_REG_RA) {

        intptr_t lo, hi;

        diff = addr - (uintptr_t)tb_ret_addr;

        lo = (int16_t)diff;

        hi = (int32_t)(diff - lo);

        assert(diff == hi + lo);

        i1 = ADDIS | TAI(TCG_REG_TMP1, TCG_REG_RA, hi >> 16);

        i2 = ADDI | TAI(TCG_REG_TMP1, TCG_REG_TMP1, lo);

    } else {

        assert(TCG_TARGET_REG_BITS == 32 || addr == (int32_t)addr);

        i1 = ADDIS | TAI(TCG_REG_TMP1, 0, addr >> 16);

        i2 = ORI | SAI(TCG_REG_TMP1, TCG_REG_TMP1, addr);

    }

#ifdef HOST_WORDS_BIGENDIAN

    pair = (uint64_t)i1 << 32 | i2;

#else

    pair = (uint64_t)i2 << 32 | i1;

#endif

    /* ??? __atomic_store_8, presuming there's some way to do that

       for 32-bit, otherwise this is good enough for 64-bit.  */

    *(uint64_t *)jmp_addr = pair;

    flush_icache_range(jmp_addr, jmp_addr + 8);

}


int qcow2_update_header(BlockDriverState *bs)

{

    BDRVQcowState *s = bs->opaque;

    QCowHeader *header;

    char *buf;

    size_t buflen = s->cluster_size;

    int ret;

    uint64_t total_size;

    uint32_t refcount_table_clusters;

    size_t header_length;

    Qcow2UnknownHeaderExtension *uext;

    buf = qemu_blockalign(bs, buflen);

    /* Header structure */

    header = (QCowHeader*) buf;

    if (buflen < sizeof(*header)) {

        ret = -ENOSPC;

        goto fail;

    }

    header_length = sizeof(*header) + s->unknown_header_fields_size;

    total_size = bs->total_sectors * BDRV_SECTOR_SIZE;

    refcount_table_clusters = s->refcount_table_size >> (s->cluster_bits - 3);

    *header = (QCowHeader) {

        /* Version 2 fields */

        .magic                  = cpu_to_be32(QCOW_MAGIC),

        .version                = cpu_to_be32(s->qcow_version),

        .backing_file_offset    = 0,

        .backing_file_size      = 0,

        .cluster_bits           = cpu_to_be32(s->cluster_bits),

        .size                   = cpu_to_be64(total_size),

        .crypt_method           = cpu_to_be32(s->crypt_method_header),

        .l1_size                = cpu_to_be32(s->l1_size),

        .l1_table_offset        = cpu_to_be64(s->l1_table_offset),

        .refcount_table_offset  = cpu_to_be64(s->refcount_table_offset),

        .refcount_table_clusters = cpu_to_be32(refcount_table_clusters),

        .nb_snapshots           = cpu_to_be32(s->nb_snapshots),

        .snapshots_offset       = cpu_to_be64(s->snapshots_offset),

        /* Version 3 fields */

        .incompatible_features  = cpu_to_be64(s->incompatible_features),

        .compatible_features    = cpu_to_be64(s->compatible_features),

        .autoclear_features     = cpu_to_be64(s->autoclear_features),

        .refcount_order         = cpu_to_be32(s->refcount_order),

        .header_length          = cpu_to_be32(header_length),

    };

    /* For older versions, write a shorter header */

    switch (s->qcow_version) {

    case 2:

        ret = offsetof(QCowHeader, incompatible_features);

        break;

    case 3:

        ret = sizeof(*header);

        break;

    default:

        ret = -EINVAL;

        goto fail;

    }

    buf += ret;

    buflen -= ret;

    memset(buf, 0, buflen);

    /* Preserve any unknown field in the header */

    if (s->unknown_header_fields_size) {

        if (buflen < s->unknown_header_fields_size) {

            ret = -ENOSPC;

            goto fail;

        }

        memcpy(buf, s->unknown_header_fields, s->unknown_header_fields_size);

        buf += s->unknown_header_fields_size;

        buflen -= s->unknown_header_fields_size;

    }

    /* Backing file format header extension */

    if (*bs->backing_format) {

        ret = header_ext_add(buf, QCOW2_EXT_MAGIC_BACKING_FORMAT,

                             bs->backing_format, strlen(bs->backing_format),

                             buflen);

        if (ret < 0) {

            goto fail;

        }

        buf += ret;

        buflen -= ret;

    }

    /* Feature table */

    Qcow2Feature features[] = {

        {

            .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,

            .bit  = QCOW2_INCOMPAT_DIRTY_BITNR,

            .name = "dirty bit",

        },

        {

            .type = QCOW2_FEAT_TYPE_INCOMPATIBLE,

            .bit  = QCOW2_INCOMPAT_CORRUPT_BITNR,

            .name = "corrupt bit",

        },

        {

            .type = QCOW2_FEAT_TYPE_COMPATIBLE,

            .bit  = QCOW2_COMPAT_LAZY_REFCOUNTS_BITNR,

            .name = "lazy refcounts",

        },

    };

    ret = header_ext_add(buf, QCOW2_EXT_MAGIC_FEATURE_TABLE,

                         features, sizeof(features), buflen);

    if (ret < 0) {

        goto fail;

    }

    buf += ret;

    buflen -= ret;

    /* Keep unknown header extensions */

    QLIST_FOREACH(uext, &s->unknown_header_ext, next) {

        ret = header_ext_add(buf, uext->magic, uext->data, uext->len, buflen);

        if (ret < 0) {

            goto fail;

        }

        buf += ret;

        buflen -= ret;

    }

    /* End of header extensions */

    ret = header_ext_add(buf, QCOW2_EXT_MAGIC_END, NULL, 0, buflen);

    if (ret < 0) {

        goto fail;

    }

    buf += ret;

    buflen -= ret;

    /* Backing file name */

    if (*bs->backing_file) {

        size_t backing_file_len = strlen(bs->backing_file);

        if (buflen < backing_file_len) {

            ret = -ENOSPC;

            goto fail;

        }

        /* Using strncpy is ok here, since buf is not NUL-terminated. */

        strncpy(buf, bs->backing_file, buflen);

        header->backing_file_offset = cpu_to_be64(buf - ((char*) header));

        header->backing_file_size   = cpu_to_be32(backing_file_len);

    }

    /* Write the new header */

    ret = bdrv_pwrite(bs->file, 0, header, s->cluster_size);

    if (ret < 0) {

        goto fail;

    }

    ret = 0;

fail:

    qemu_vfree(header);

    return ret;

}


static void gd_update_cursor(GtkDisplayState *s, gboolean override)

{

    GdkWindow *window;

    bool on_vga;

    window = gtk_widget_get_window(GTK_WIDGET(s->drawing_area));

    on_vga = (gtk_notebook_get_current_page(GTK_NOTEBOOK(s->notebook)) == 0);

    if ((override || on_vga) && kbd_mouse_is_absolute()) {

        gdk_window_set_cursor(window, s->null_cursor);

    } else {

        gdk_window_set_cursor(window, NULL);

    }

}


static int load_input_picture(MpegEncContext *s, const AVFrame *pic_arg)

{

    Picture *pic = NULL;

    int64_t pts;

    int i, display_picture_number = 0, ret;

    const int encoding_delay = s->max_b_frames ? s->max_b_frames :

                                                 (s->low_delay ? 0 : 1);

    int direct = 1;

    if (pic_arg) {

        pts = pic_arg->pts;

        display_picture_number = s->input_picture_number++;

        if (pts != AV_NOPTS_VALUE) {

            if (s->user_specified_pts != AV_NOPTS_VALUE) {

                int64_t time = pts;

                int64_t last = s->user_specified_pts;

                if (time <= last) {

                    av_log(s->avctx, AV_LOG_ERROR,

                           "Error, Invalid timestamp=%"PRId64", "

                           "last=%"PRId64"\n", pts, s->user_specified_pts);

                    return -1;

                }

                if (!s->low_delay && display_picture_number == 1)

                    s->dts_delta = time - last;

            }

            s->user_specified_pts = pts;

        } else {

            if (s->user_specified_pts != AV_NOPTS_VALUE) {

                s->user_specified_pts =

                pts = s->user_specified_pts + 1;

                av_log(s->avctx, AV_LOG_INFO,

                       "Warning: AVFrame.pts=? trying to guess (%"PRId64")\n",

                       pts);

            } else {

                pts = display_picture_number;

            }

        }

    }

    if (pic_arg) {

        if (!pic_arg->buf[0])

            direct = 0;

        if (pic_arg->linesize[0] != s->linesize)

            direct = 0;

        if (pic_arg->linesize[1] != s->uvlinesize)

            direct = 0;

        if (pic_arg->linesize[2] != s->uvlinesize)

            direct = 0;

        av_dlog(s->avctx, "%d %d %d %d\n", pic_arg->linesize[0],

                pic_arg->linesize[1], s->linesize, s->uvlinesize);

        if (direct) {

            i = ff_find_unused_picture(s, 1);

            if (i < 0)

                return i;

            pic = &s->picture[i];

            pic->reference = 3;

            if ((ret = av_frame_ref(&pic->f, pic_arg)) < 0)

                return ret;

            if (ff_alloc_picture(s, pic, 1) < 0) {

                return -1;

            }

        } else {

            i = ff_find_unused_picture(s, 0);

            if (i < 0)

                return i;

            pic = &s->picture[i];

            pic->reference = 3;

            if (ff_alloc_picture(s, pic, 0) < 0) {

                return -1;

            }

            if (pic->f.data[0] + INPLACE_OFFSET == pic_arg->data[0] &&

                pic->f.data[1] + INPLACE_OFFSET == pic_arg->data[1] &&

                pic->f.data[2] + INPLACE_OFFSET == pic_arg->data[2]) {

                // empty

            } else {

                int h_chroma_shift, v_chroma_shift;

                av_pix_fmt_get_chroma_sub_sample(s->avctx->pix_fmt,

                                                 &h_chroma_shift,

                                                 &v_chroma_shift);

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

                    int src_stride = pic_arg->linesize[i];

                    int dst_stride = i ? s->uvlinesize : s->linesize;

                    int h_shift = i ? h_chroma_shift : 0;

                    int v_shift = i ? v_chroma_shift : 0;

                    int w = s->width  >> h_shift;

                    int h = s->height >> v_shift;

                    uint8_t *src = pic_arg->data[i];

                    uint8_t *dst = pic->f.data[i];

                    if (s->codec_id == AV_CODEC_ID_AMV && !(s->avctx->flags & CODEC_FLAG_EMU_EDGE)) {

                        h = ((s->height + 15)/16*16) >> v_shift;

                    }

                    if (!s->avctx->rc_buffer_size)

                        dst += INPLACE_OFFSET;

                    if (src_stride == dst_stride)

                        memcpy(dst, src, src_stride * h);

                    else {

                        int h2 = h;

                        uint8_t *dst2 = dst;

                        while (h2--) {

                            memcpy(dst2, src, w);

                            dst2 += dst_stride;

                            src += src_stride;

                        }

                    }

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

                        s->dsp.draw_edges(dst, dst_stride,

                                          w, h,

                                          16>>h_shift,

                                          16>>v_shift,

                                          EDGE_BOTTOM);

                    }

                }

            }

        }

        copy_picture_attributes(s, &pic->f, pic_arg);

        pic->f.display_picture_number = display_picture_number;

        pic->f.pts = pts; // we set this here to avoid modifiying pic_arg

    }

    /* shift buffer entries */

    for (i = 1; i < MAX_PICTURE_COUNT /*s->encoding_delay + 1*/; i++)

        s->input_picture[i - 1] = s->input_picture[i];

    s->input_picture[encoding_delay] = (Picture*) pic;

    return 0;

}


static void pc_i440fx_2_4_machine_options(MachineClass *m)

{

    PCMachineClass *pcmc = PC_MACHINE_CLASS(m);

    pc_i440fx_2_5_machine_options(m);

    m->alias = NULL;

    m->is_default = 0;

    pcmc->broken_reserved_end = true;

    pcmc->inter_dimm_gap = false;

    SET_MACHINE_COMPAT(m, PC_COMPAT_2_4);

}


static int vc1_decode_frame(AVCodecContext *avctx, void *data,
                            int *data_size, AVPacket *avpkt)
{
    const uint8_t *buf = avpkt->data;
    int buf_size = avpkt->size, n_slices = 0, i;
    VC1Context *v = avctx->priv_data;
    MpegEncContext *s = &v->s;
    AVFrame *pict = data;
    uint8_t *buf2 = NULL;
    const uint8_t *buf_start = buf, *buf_start_second_field = NULL;
    int mb_height, n_slices1=-1;
    struct {
        uint8_t *buf;
        GetBitContext gb;
        int mby_start;
    } *slices = NULL, *tmp;
    v->second_field = 0;
    if(s->flags & CODEC_FLAG_LOW_DELAY)
        s->low_delay = 1;
    /* no supplementary picture */
    if (buf_size == 0 || (buf_size == 4 && AV_RB32(buf) == VC1_CODE_ENDOFSEQ)) {
        /* special case for last picture */
        if (s->low_delay == 0 && s->next_picture_ptr) {
            *pict = s->next_picture_ptr->f;
            s->next_picture_ptr = NULL;
            *data_size = sizeof(AVFrame);
        return buf_size;
    if (s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU) {
        if (v->profile < PROFILE_ADVANCED)
            avctx->pix_fmt = AV_PIX_FMT_VDPAU_WMV3;
        else
            avctx->pix_fmt = AV_PIX_FMT_VDPAU_VC1;
    //for advanced profile we may need to parse and unescape data
    if (avctx->codec_id == AV_CODEC_ID_VC1 || avctx->codec_id == AV_CODEC_ID_VC1IMAGE) {
        int buf_size2 = 0;
        buf2 = av_mallocz(buf_size + FF_INPUT_BUFFER_PADDING_SIZE);
        if (IS_MARKER(AV_RB32(buf))) { /* frame starts with marker and needs to be parsed */
            const uint8_t *start, *end, *next;
            int size;
            next = buf;
            for (start = buf, end = buf + buf_size; next < end; start = next) {
                next = find_next_marker(start + 4, end);
                size = next - start - 4;
                if (size <= 0) continue;
                switch (AV_RB32(start)) {
                case VC1_CODE_FRAME:
                    if (avctx->hwaccel ||
                        s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
                        buf_start = start;
                    buf_size2 = vc1_unescape_buffer(start + 4, size, buf2);
                    break;
                case VC1_CODE_FIELD: {
                    int buf_size3;
                    if (avctx->hwaccel ||
                        s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
                        buf_start_second_field = start;
                    tmp = av_realloc(slices, sizeof(*slices) * (n_slices+1));
                    if (!tmp)
                    slices = tmp;
                    slices[n_slices].buf = av_mallocz(buf_size + FF_INPUT_BUFFER_PADDING_SIZE);
                    if (!slices[n_slices].buf)
                    buf_size3 = vc1_unescape_buffer(start + 4, size,
                                                    slices[n_slices].buf);
                    init_get_bits(&slices[n_slices].gb, slices[n_slices].buf,
                                  buf_size3 << 3);
                    /* assuming that the field marker is at the exact middle,
                       hope it's correct */
                    slices[n_slices].mby_start = s->mb_height >> 1;
                    n_slices1 = n_slices - 1; // index of the last slice of the first field
                    n_slices++;
                    break;
                case VC1_CODE_ENTRYPOINT: /* it should be before frame data */
                    buf_size2 = vc1_unescape_buffer(start + 4, size, buf2);
                    init_get_bits(&s->gb, buf2, buf_size2 * 8);
                    ff_vc1_decode_entry_point(avctx, v, &s->gb);
                    break;
                case VC1_CODE_SLICE: {
                    int buf_size3;
                    tmp = av_realloc(slices, sizeof(*slices) * (n_slices+1));
                    if (!tmp)
                    slices = tmp;
                    slices[n_slices].buf = av_mallocz(buf_size + FF_INPUT_BUFFER_PADDING_SIZE);
                    if (!slices[n_slices].buf)
                    buf_size3 = vc1_unescape_buffer(start + 4, size,
                                                    slices[n_slices].buf);
                    init_get_bits(&slices[n_slices].gb, slices[n_slices].buf,
                                  buf_size3 << 3);
                    slices[n_slices].mby_start = get_bits(&slices[n_slices].gb, 9);
                    n_slices++;
                    break;
        } else if (v->interlace && ((buf[0] & 0xC0) == 0xC0)) { /* WVC1 interlaced stores both fields divided by marker */
            const uint8_t *divider;
            int buf_size3;
            divider = find_next_marker(buf, buf + buf_size);
            if ((divider == (buf + buf_size)) || AV_RB32(divider) != VC1_CODE_FIELD) {
                av_log(avctx, AV_LOG_ERROR, "Error in WVC1 interlaced frame\n");
            } else { // found field marker, unescape second field
                if (avctx->hwaccel ||
                    s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
                    buf_start_second_field = divider;
                tmp = av_realloc(slices, sizeof(*slices) * (n_slices+1));
                if (!tmp)
                slices = tmp;
                slices[n_slices].buf = av_mallocz(buf_size + FF_INPUT_BUFFER_PADDING_SIZE);
                if (!slices[n_slices].buf)
                buf_size3 = vc1_unescape_buffer(divider + 4, buf + buf_size - divider - 4, slices[n_slices].buf);
                init_get_bits(&slices[n_slices].gb, slices[n_slices].buf,
                              buf_size3 << 3);
                slices[n_slices].mby_start = s->mb_height >> 1;
                n_slices1 = n_slices - 1;
                n_slices++;
            buf_size2 = vc1_unescape_buffer(buf, divider - buf, buf2);
        } else {
            buf_size2 = vc1_unescape_buffer(buf, buf_size, buf2);
        init_get_bits(&s->gb, buf2, buf_size2*8);
    } else
        init_get_bits(&s->gb, buf, buf_size*8);
    if (v->res_sprite) {
        v->new_sprite  = !get_bits1(&s->gb);
        v->two_sprites =  get_bits1(&s->gb);
        /* res_sprite means a Windows Media Image stream, AV_CODEC_ID_*IMAGE means
           we're using the sprite compositor. These are intentionally kept separate
           so you can get the raw sprites by using the wmv3 decoder for WMVP or
           the vc1 one for WVP2 */
        if (avctx->codec_id == AV_CODEC_ID_WMV3IMAGE || avctx->codec_id == AV_CODEC_ID_VC1IMAGE) {
            if (v->new_sprite) {
                // switch AVCodecContext parameters to those of the sprites
                avctx->width  = avctx->coded_width  = v->sprite_width;
                avctx->height = avctx->coded_height = v->sprite_height;
            } else {
                goto image;
    if (s->context_initialized &&
        (s->width  != avctx->coded_width ||
         s->height != avctx->coded_height)) {
        ff_vc1_decode_end(avctx);
    if (!s->context_initialized) {
        if (ff_msmpeg4_decode_init(avctx) < 0 || ff_vc1_decode_init_alloc_tables(v) < 0)
        s->low_delay = !avctx->has_b_frames || v->res_sprite;
        if (v->profile == PROFILE_ADVANCED) {
            s->h_edge_pos = avctx->coded_width;
            s->v_edge_pos = avctx->coded_height;
    /* We need to set current_picture_ptr before reading the header,
     * otherwise we cannot store anything in there. */
    if (s->current_picture_ptr == NULL || s->current_picture_ptr->f.data[0]) {
        int i = ff_find_unused_picture(s, 0);
        if (i < 0)
        s->current_picture_ptr = &s->picture[i];
    // do parse frame header
    v->pic_header_flag = 0;
    if (v->profile < PROFILE_ADVANCED) {
        if (ff_vc1_parse_frame_header(v, &s->gb) < 0) {
    } else {
        if (ff_vc1_parse_frame_header_adv(v, &s->gb) < 0) {
    if (avctx->debug & FF_DEBUG_PICT_INFO)
        av_log(v->s.avctx, AV_LOG_DEBUG, "pict_type: %c\n", av_get_picture_type_char(s->pict_type));
    if ((avctx->codec_id == AV_CODEC_ID_WMV3IMAGE || avctx->codec_id == AV_CODEC_ID_VC1IMAGE)
        && s->pict_type != AV_PICTURE_TYPE_I) {
        av_log(v->s.avctx, AV_LOG_ERROR, "Sprite decoder: expected I-frame\n");
    // process pulldown flags
    s->current_picture_ptr->f.repeat_pict = 0;
    // Pulldown flags are only valid when 'broadcast' has been set.
    // So ticks_per_frame will be 2
    if (v->rff) {
        // repeat field
        s->current_picture_ptr->f.repeat_pict = 1;
    } else if (v->rptfrm) {
        // repeat frames
        s->current_picture_ptr->f.repeat_pict = v->rptfrm * 2;
    // for skipping the frame
    s->current_picture.f.pict_type = s->pict_type;
    s->current_picture.f.key_frame = s->pict_type == AV_PICTURE_TYPE_I;
    /* skip B-frames if we don't have reference frames */
    if (s->last_picture_ptr == NULL && (s->pict_type == AV_PICTURE_TYPE_B || s->dropable)) {
    if ((avctx->skip_frame >= AVDISCARD_NONREF && s->pict_type == AV_PICTURE_TYPE_B) ||
        (avctx->skip_frame >= AVDISCARD_NONKEY && s->pict_type != AV_PICTURE_TYPE_I) ||
         avctx->skip_frame >= AVDISCARD_ALL) {
        goto end;
    if (s->next_p_frame_damaged) {
        if (s->pict_type == AV_PICTURE_TYPE_B)
            goto end;
        else
            s->next_p_frame_damaged = 0;
    if (ff_MPV_frame_start(s, avctx) < 0) {
    v->s.current_picture_ptr->f.interlaced_frame = (v->fcm != PROGRESSIVE);
    v->s.current_picture_ptr->f.top_field_first  = v->tff;
    s->me.qpel_put = s->dsp.put_qpel_pixels_tab;
    s->me.qpel_avg = s->dsp.avg_qpel_pixels_tab;
    if ((CONFIG_VC1_VDPAU_DECODER)
        &&s->avctx->codec->capabilities&CODEC_CAP_HWACCEL_VDPAU)
        ff_vdpau_vc1_decode_picture(s, buf_start, (buf + buf_size) - buf_start);
    else if (avctx->hwaccel) {
        if (v->field_mode && buf_start_second_field) {
            // decode first field
            s->picture_structure = PICT_BOTTOM_FIELD - v->tff;
            if (avctx->hwaccel->start_frame(avctx, buf_start, buf_start_second_field - buf_start) < 0)
            if (avctx->hwaccel->decode_slice(avctx, buf_start, buf_start_second_field - buf_start) < 0)
            if (avctx->hwaccel->end_frame(avctx) < 0)
            // decode second field
            s->gb = slices[n_slices1 + 1].gb;
            s->picture_structure = PICT_TOP_FIELD + v->tff;
            v->second_field = 1;
            v->pic_header_flag = 0;
            if (ff_vc1_parse_frame_header_adv(v, &s->gb) < 0) {
                av_log(avctx, AV_LOG_ERROR, "parsing header for second field failed");
            v->s.current_picture_ptr->f.pict_type = v->s.pict_type;
            if (avctx->hwaccel->start_frame(avctx, buf_start_second_field, (buf + buf_size) - buf_start_second_field) < 0)
            if (avctx->hwaccel->decode_slice(avctx, buf_start_second_field, (buf + buf_size) - buf_start_second_field) < 0)
            if (avctx->hwaccel->end_frame(avctx) < 0)
        } else {
            s->picture_structure = PICT_FRAME;
            if (avctx->hwaccel->start_frame(avctx, buf_start, (buf + buf_size) - buf_start) < 0)
            if (avctx->hwaccel->decode_slice(avctx, buf_start, (buf + buf_size) - buf_start) < 0)
            if (avctx->hwaccel->end_frame(avctx) < 0)
    } else {
        if (v->fcm == ILACE_FRAME && s->pict_type == AV_PICTURE_TYPE_B)
            goto err; // This codepath is still incomplete thus it is disabled
        ff_er_frame_start(s);
        v->bits = buf_size * 8;
        v->end_mb_x = s->mb_width;
        if (v->field_mode) {
            uint8_t *tmp[2];
            s->current_picture.f.linesize[0] <<= 1;
            s->current_picture.f.linesize[1] <<= 1;
            s->current_picture.f.linesize[2] <<= 1;
            s->linesize                      <<= 1;
            s->uvlinesize                    <<= 1;
            tmp[0]          = v->mv_f_last[0];
            tmp[1]          = v->mv_f_last[1];
            v->mv_f_last[0] = v->mv_f_next[0];
            v->mv_f_last[1] = v->mv_f_next[1];
            v->mv_f_next[0] = v->mv_f[0];
            v->mv_f_next[1] = v->mv_f[1];
            v->mv_f[0] = tmp[0];
            v->mv_f[1] = tmp[1];
        mb_height = s->mb_height >> v->field_mode;
        for (i = 0; i <= n_slices; i++) {
            if (i > 0 &&  slices[i - 1].mby_start >= mb_height) {
                if (v->field_mode <= 0) {
                    av_log(v->s.avctx, AV_LOG_ERROR, "Slice %d starts beyond "
                           "picture boundary (%d >= %d)\n", i,
                           slices[i - 1].mby_start, mb_height);
                    continue;
                v->second_field = 1;
                v->blocks_off   = s->mb_width  * s->mb_height << 1;
                v->mb_off       = s->mb_stride * s->mb_height >> 1;
            } else {
                v->second_field = 0;
                v->blocks_off   = 0;
                v->mb_off       = 0;
            if (i) {
                v->pic_header_flag = 0;
                if (v->field_mode && i == n_slices1 + 2) {
                    if (ff_vc1_parse_frame_header_adv(v, &s->gb) < 0) {
                        av_log(v->s.avctx, AV_LOG_ERROR, "Field header damaged\n");
                        continue;
                } else if (get_bits1(&s->gb)) {
                    v->pic_header_flag = 1;
                    if (ff_vc1_parse_frame_header_adv(v, &s->gb) < 0) {
                        av_log(v->s.avctx, AV_LOG_ERROR, "Slice header damaged\n");
                        continue;
            s->start_mb_y = (i == 0) ? 0 : FFMAX(0, slices[i-1].mby_start % mb_height);
            if (!v->field_mode || v->second_field)
                s->end_mb_y = (i == n_slices     ) ? mb_height : FFMIN(mb_height, slices[i].mby_start % mb_height);
            else
                s->end_mb_y = (i <= n_slices1 + 1) ? mb_height : FFMIN(mb_height, slices[i].mby_start % mb_height);
            if (s->end_mb_y <= s->start_mb_y) {
                av_log(v->s.avctx, AV_LOG_ERROR, "end mb y %d %d invalid\n", s->end_mb_y, s->start_mb_y);
                continue;
            ff_vc1_decode_blocks(v);
            if (i != n_slices)
                s->gb = slices[i].gb;
        if (v->field_mode) {
            v->second_field = 0;
            if (s->pict_type == AV_PICTURE_TYPE_B) {
                memcpy(v->mv_f_base, v->mv_f_next_base,
                       2 * (s->b8_stride * (s->mb_height * 2 + 1) + s->mb_stride * (s->mb_height + 1) * 2));
            s->current_picture.f.linesize[0] >>= 1;
            s->current_picture.f.linesize[1] >>= 1;
            s->current_picture.f.linesize[2] >>= 1;
            s->linesize                      >>= 1;
            s->uvlinesize                    >>= 1;
        av_dlog(s->avctx, "Consumed %i/%i bits\n",
                get_bits_count(&s->gb), s->gb.size_in_bits);
//  if (get_bits_count(&s->gb) > buf_size * 8)
//      return -1;
        if(s->error_occurred && s->pict_type == AV_PICTURE_TYPE_B)
        if(!v->field_mode)
            ff_er_frame_end(s);
    ff_MPV_frame_end(s);
    if (avctx->codec_id == AV_CODEC_ID_WMV3IMAGE || avctx->codec_id == AV_CODEC_ID_VC1IMAGE) {
image:
        avctx->width  = avctx->coded_width  = v->output_width;
        avctx->height = avctx->coded_height = v->output_height;
        if (avctx->skip_frame >= AVDISCARD_NONREF)
            goto end;
#if CONFIG_WMV3IMAGE_DECODER || CONFIG_VC1IMAGE_DECODER
        if (vc1_decode_sprites(v, &s->gb))
#endif
        *pict      = v->sprite_output_frame;
        *data_size = sizeof(AVFrame);
    } else {
        if (s->pict_type == AV_PICTURE_TYPE_B || s->low_delay) {
            *pict = s->current_picture_ptr->f;
        } else if (s->last_picture_ptr != NULL) {
            *pict = s->last_picture_ptr->f;
        if (s->last_picture_ptr || s->low_delay) {
            *data_size = sizeof(AVFrame);
            ff_print_debug_info(s, pict);
end:
    av_free(buf2);
    for (i = 0; i < n_slices; i++)
        av_free(slices[i].buf);
    av_free(slices);
    return buf_size;
err:
    av_free(buf2);
    for (i = 0; i < n_slices; i++)
        av_free(slices[i].buf);
    av_free(slices);
    return -1;


static int local_mknod(FsContext *fs_ctx, V9fsPath *dir_path,

                       const char *name, FsCred *credp)

{

    char *path;

    int err = -1;

    int serrno = 0;

    V9fsString fullname;

    char *buffer;

    v9fs_string_init(&fullname);

    v9fs_string_sprintf(&fullname, "%s/%s", dir_path->data, name);

    path = fullname.data;

    /* Determine the security model */

    if (fs_ctx->export_flags & V9FS_SM_MAPPED) {

        buffer = rpath(fs_ctx, path);

        err = mknod(buffer, SM_LOCAL_MODE_BITS|S_IFREG, 0);

        if (err == -1) {

            g_free(buffer);

            goto out;

        }

        err = local_set_xattr(buffer, credp);

        if (err == -1) {

            serrno = errno;

            goto err_end;

        }

    } else if (fs_ctx->export_flags & V9FS_SM_MAPPED_FILE) {

        buffer = rpath(fs_ctx, path);

        err = mknod(buffer, SM_LOCAL_MODE_BITS|S_IFREG, 0);

        if (err == -1) {

            g_free(buffer);

            goto out;

        }

        err = local_set_mapped_file_attr(fs_ctx, path, credp);

        if (err == -1) {

            serrno = errno;

            goto err_end;

        }

    } else if ((fs_ctx->export_flags & V9FS_SM_PASSTHROUGH) ||

               (fs_ctx->export_flags & V9FS_SM_NONE)) {

        buffer = rpath(fs_ctx, path);

        err = mknod(buffer, credp->fc_mode, credp->fc_rdev);

        if (err == -1) {

            g_free(buffer);

            goto out;

        }

        err = local_post_create_passthrough(fs_ctx, path, credp);

        if (err == -1) {

            serrno = errno;

            goto err_end;

        }

    }

    goto out;

err_end:

    remove(buffer);

    errno = serrno;

    g_free(buffer);

out:

    v9fs_string_free(&fullname);

    return err;

}


static int flv_set_video_codec(AVFormatContext *s, AVStream *vstream, int flv_codecid) {

    FLVContext *flv = s->priv_data;

    AVCodecContext *vcodec = vstream->codec;

    switch(flv_codecid) {

        case FLV_CODECID_H263  : vcodec->codec_id = CODEC_ID_FLV1   ; break;

        case FLV_CODECID_SCREEN: vcodec->codec_id = CODEC_ID_FLASHSV; break;

        case FLV_CODECID_VP6A  :

            if (!flv->alpha_stream) {

                AVCodecContext *alpha_codec;

                flv->alpha_stream = av_new_stream(s, 2);

                if (flv->alpha_stream) {

                    av_set_pts_info(flv->alpha_stream, 24, 1, 1000);

                    alpha_codec = flv->alpha_stream->codec;

                    alpha_codec->codec_type = CODEC_TYPE_VIDEO;

                    alpha_codec->codec_id = CODEC_ID_VP6F;

                    alpha_codec->extradata_size = 1;

                    alpha_codec->extradata = av_malloc(1);

                }

            }

        case FLV_CODECID_VP6   : vcodec->codec_id = CODEC_ID_VP6F   ;

            if(vcodec->extradata_size != 1) {

                vcodec->extradata_size = 1;

                vcodec->extradata = av_malloc(1);

            }

            vcodec->extradata[0] = get_byte(&s->pb);

            if (flv->alpha_stream)

                flv->alpha_stream->codec->extradata[0] = vcodec->extradata[0];

            return 1; // 1 byte body size adjustment for flv_read_packet()

        default:

            av_log(s, AV_LOG_INFO, "Unsupported video codec (%x)\n", flv_codecid);

            vcodec->codec_tag = flv_codecid;

    }

    return 0;

}


void wdt_ib700_init(void)

{

    watchdog_add_model(&model);

    timer = qemu_new_timer(vm_clock, ib700_timer_expired, NULL);

}


static int sub2video_prepare(InputStream *ist, InputFilter *ifilter)

{

    AVFormatContext *avf = input_files[ist->file_index]->ctx;

    int i, w, h;

    /* Compute the size of the canvas for the subtitles stream.

       If the subtitles codecpar has set a size, use it. Otherwise use the

       maximum dimensions of the video streams in the same file. */

    w = ifilter->width;

    h = ifilter->height;

    if (!(w && h)) {

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

            if (avf->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {

                w = FFMAX(w, avf->streams[i]->codecpar->width);

                h = FFMAX(h, avf->streams[i]->codecpar->height);

            }

        }

        if (!(w && h)) {

            w = FFMAX(w, 720);

            h = FFMAX(h, 576);

        }

        av_log(avf, AV_LOG_INFO, "sub2video: using %dx%d canvas\n", w, h);

    }

    ist->sub2video.w = ist->resample_width  = w;

    ist->sub2video.h = ist->resample_height = h;

    /* rectangles are AV_PIX_FMT_PAL8, but we have no guarantee that the

       palettes for all rectangles are identical or compatible */

    ist->resample_pix_fmt = ifilter->format = AV_PIX_FMT_RGB32;

    ist->sub2video.frame = av_frame_alloc();

    if (!ist->sub2video.frame)

        return AVERROR(ENOMEM);

    ist->sub2video.last_pts = INT64_MIN;

    return 0;

}


static int parse_inputs(const char **buf, AVFilterInOut **curr_inputs,

                        AVFilterInOut **open_outputs, AVClass *log_ctx)

{

    int pad = 0;

    while (**buf == '[') {

        char *name = parse_link_name(buf, log_ctx);

        AVFilterInOut *match;

        if (!name)

            return -1;

        /* First check if the label is not in the open_outputs list */

        match = extract_inout(name, open_outputs);

        if (match) {

            av_free(name);

        } else {

            /* Not in the list, so add it as an input */

            match = av_mallocz(sizeof(AVFilterInOut));

            match->name    = name;

            match->pad_idx = pad;

        }

        insert_inout(curr_inputs, match);

        *buf += strspn(*buf, WHITESPACES);

        pad++;

    }

    return pad;

}


static int dnxhd_mb_var_thread(AVCodecContext *avctx, void *arg, int jobnr, int threadnr)

{

    DNXHDEncContext *ctx = avctx->priv_data;

    int mb_y = jobnr, mb_x;

    ctx = ctx->thread[threadnr];

    if (ctx->cid_table->bit_depth == 8) {

        uint8_t *pix = ctx->thread[0]->src[0] + ((mb_y<<4) * ctx->m.linesize);

        for (mb_x = 0; mb_x < ctx->m.mb_width; ++mb_x, pix += 16) {

            unsigned mb  = mb_y * ctx->m.mb_width + mb_x;

            int sum = ctx->m.dsp.pix_sum(pix, ctx->m.linesize);

            int varc = (ctx->m.dsp.pix_norm1(pix, ctx->m.linesize) - (((unsigned)(sum*sum))>>8)+128)>>8;

            ctx->mb_cmp[mb].value = varc;

            ctx->mb_cmp[mb].mb = mb;

        }

    } else { // 10-bit

        int const linesize = ctx->m.linesize >> 1;

        for (mb_x = 0; mb_x < ctx->m.mb_width; ++mb_x) {

            uint16_t *pix = (uint16_t*)ctx->thread[0]->src[0] + ((mb_y << 4) * linesize) + (mb_x << 4);

            unsigned mb  = mb_y * ctx->m.mb_width + mb_x;

            int sum = 0;

            int sqsum = 0;

            int mean, sqmean;

            int i, j;

            // Macroblocks are 16x16 pixels, unlike DCT blocks which are 8x8.

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

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

                    // Turn 16-bit pixels into 10-bit ones.

                    int const sample = (unsigned)pix[j] >> 6;

                    sum += sample;

                    sqsum += sample * sample;

                    // 2^10 * 2^10 * 16 * 16 = 2^28, which is less than INT_MAX

                }

                pix += linesize;

            }

            mean = sum >> 8; // 16*16 == 2^8

            sqmean = sqsum >> 8;

            ctx->mb_cmp[mb].value = sqmean - mean * mean;

            ctx->mb_cmp[mb].mb = mb;

        }

    }

    return 0;

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    VirtioDeviceClass *vdc = VIRTIO_DEVICE_CLASS(klass);

    dc->exit = virtio_blk_device_exit;

    dc->props = virtio_blk_properties;

    set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);

    vdc->init = virtio_blk_device_init;

    vdc->get_config = virtio_blk_update_config;

    vdc->set_config = virtio_blk_set_config;

    vdc->get_features = virtio_blk_get_features;

    vdc->set_status = virtio_blk_set_status;

    vdc->reset = virtio_blk_reset;

}


static int cirrus_vga_load(QEMUFile *f, void *opaque, int version_id)

{

    CirrusVGAState *s = opaque;

    int ret;

    if (version_id > 2)

        return -EINVAL;

    if (s->pci_dev && version_id >= 2) {

        ret = pci_device_load(s->pci_dev, f);

        if (ret < 0)

            return ret;

    }

    qemu_get_be32s(f, &s->latch);

    qemu_get_8s(f, &s->sr_index);

    qemu_get_buffer(f, s->sr, 256);

    qemu_get_8s(f, &s->gr_index);

    qemu_get_8s(f, &s->cirrus_shadow_gr0);

    qemu_get_8s(f, &s->cirrus_shadow_gr1);

    s->gr[0x00] = s->cirrus_shadow_gr0 & 0x0f;

    s->gr[0x01] = s->cirrus_shadow_gr1 & 0x0f;

    qemu_get_buffer(f, s->gr + 2, 254);

    qemu_get_8s(f, &s->ar_index);

    qemu_get_buffer(f, s->ar, 21);

    s->ar_flip_flop=qemu_get_be32(f);

    qemu_get_8s(f, &s->cr_index);

    qemu_get_buffer(f, s->cr, 256);

    qemu_get_8s(f, &s->msr);

    qemu_get_8s(f, &s->fcr);

    qemu_get_8s(f, &s->st00);

    qemu_get_8s(f, &s->st01);

    qemu_get_8s(f, &s->dac_state);

    qemu_get_8s(f, &s->dac_sub_index);

    qemu_get_8s(f, &s->dac_read_index);

    qemu_get_8s(f, &s->dac_write_index);

    qemu_get_buffer(f, s->dac_cache, 3);

    qemu_get_buffer(f, s->palette, 768);

    s->bank_offset=qemu_get_be32(f);

    qemu_get_8s(f, &s->cirrus_hidden_dac_lockindex);

    qemu_get_8s(f, &s->cirrus_hidden_dac_data);

    qemu_get_be32s(f, &s->hw_cursor_x);

    qemu_get_be32s(f, &s->hw_cursor_y);

    cirrus_update_memory_access(s);

    /* force refresh */

    s->graphic_mode = -1;

    cirrus_update_bank_ptr(s, 0);

    cirrus_update_bank_ptr(s, 1);

    return 0;

}


static int ide_dev_initfn(IDEDevice *dev, IDEDriveKind kind)
{
    IDEBus *bus = DO_UPCAST(IDEBus, qbus, dev->qdev.parent_bus);
    IDEState *s = bus->ifs + dev->unit;
    Error *err = NULL;
    if (dev->conf.discard_granularity == -1) {
        dev->conf.discard_granularity = 512;
    } else if (dev->conf.discard_granularity &&
               dev->conf.discard_granularity != 512) {
        error_report("discard_granularity must be 512 for ide");
    blkconf_serial(&dev->conf, &dev->serial);
    if (kind != IDE_CD) {
        blkconf_geometry(&dev->conf, &dev->chs_trans, 65536, 16, 255, &err);
        if (err) {
            error_report("%s", error_get_pretty(err));
            error_free(err);
    if (ide_init_drive(s, dev->conf.blk, kind,
                       dev->version, dev->serial, dev->model, dev->wwn,
                       dev->conf.cyls, dev->conf.heads, dev->conf.secs,
                       dev->chs_trans) < 0) {
    if (!dev->version) {
        dev->version = g_strdup(s->version);
    if (!dev->serial) {
        dev->serial = g_strdup(s->drive_serial_str);
    add_boot_device_path(dev->conf.bootindex, &dev->qdev,
                         dev->unit ? "/disk@1" : "/disk@0");
    return 0;


static int writer_open(WriterContext **wctx, const Writer *writer, const char *args,

                       const struct section *sections, int nb_sections)

{

    int i, ret = 0;

    if (!(*wctx = av_malloc(sizeof(WriterContext)))) {

        ret = AVERROR(ENOMEM);

        goto fail;

    }

    if (!((*wctx)->priv = av_mallocz(writer->priv_size))) {

        ret = AVERROR(ENOMEM);

        goto fail;

    }

    (*wctx)->class = &writer_class;

    (*wctx)->writer = writer;

    (*wctx)->level = -1;

    (*wctx)->sections = sections;

    (*wctx)->nb_sections = nb_sections;

    if (writer->priv_class) {

        void *priv_ctx = (*wctx)->priv;

        *((const AVClass **)priv_ctx) = writer->priv_class;

        av_opt_set_defaults(priv_ctx);

        if (args &&

            (ret = av_set_options_string(priv_ctx, args, "=", ":")) < 0)

            goto fail;

    }

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

        av_bprint_init(&(*wctx)->section_pbuf[i], 1, AV_BPRINT_SIZE_UNLIMITED);

    if ((*wctx)->writer->init)

        ret = (*wctx)->writer->init(*wctx);

    if (ret < 0)

        goto fail;

    return 0;

fail:

    writer_close(wctx);

    return ret;

}


int cpu_ppc_handle_mmu_fault (CPUState *env, uint32_t address, int rw,

                              int is_user, int is_softmmu)

{

    mmu_ctx_t ctx;

    int exception = 0, error_code = 0;

    int access_type;

    int ret = 0;

    if (rw == 2) {

        /* code access */

        rw = 0;

        access_type = ACCESS_CODE;

    } else {

        /* data access */

        /* XXX: put correct access by using cpu_restore_state()

           correctly */

        access_type = ACCESS_INT;

        //        access_type = env->access_type;

    }

    ret = get_physical_address(env, &ctx, address, rw, access_type, 1);

    if (ret == 0) {

        ret = tlb_set_page(env, address & TARGET_PAGE_MASK,

                           ctx.raddr & TARGET_PAGE_MASK, ctx.prot,

                           is_user, is_softmmu);

    } else if (ret < 0) {

#if defined (DEBUG_MMU)

        if (loglevel > 0)

            cpu_dump_state(env, logfile, fprintf, 0);

#endif

        if (access_type == ACCESS_CODE) {

            exception = EXCP_ISI;

            switch (ret) {

            case -1:

                /* No matches in page tables or TLB */

                if (unlikely(PPC_MMU(env) == PPC_FLAGS_MMU_SOFT_6xx)) {

                    exception = EXCP_I_TLBMISS;

                    env->spr[SPR_IMISS] = address;

                    env->spr[SPR_ICMP] = 0x80000000 | ctx.ptem;

                    error_code = 1 << 18;

                    goto tlb_miss;

                } else if (unlikely(PPC_MMU(env) == PPC_FLAGS_MMU_SOFT_4xx)) {

                    /* XXX: TODO */

                } else {

                    error_code = 0x40000000;

                }

                break;

            case -2:

                /* Access rights violation */

                error_code = 0x08000000;

                break;

            case -3:

                /* No execute protection violation */

                error_code = 0x10000000;

                break;

            case -4:

                /* Direct store exception */

                /* No code fetch is allowed in direct-store areas */

                error_code = 0x10000000;

                break;

            case -5:

                /* No match in segment table */

                exception = EXCP_ISEG;

                error_code = 0;

                break;

            }

        } else {

            exception = EXCP_DSI;

            switch (ret) {

            case -1:

                /* No matches in page tables or TLB */

                if (unlikely(PPC_MMU(env) == PPC_FLAGS_MMU_SOFT_6xx)) {

                    if (rw == 1) {

                        exception = EXCP_DS_TLBMISS;

                        error_code = 1 << 16;

                    } else {

                        exception = EXCP_DL_TLBMISS;

                        error_code = 0;

                    }

                    env->spr[SPR_DMISS] = address;

                    env->spr[SPR_DCMP] = 0x80000000 | ctx.ptem;

                tlb_miss:

                    error_code |= ctx.key << 19;

                    env->spr[SPR_HASH1] = ctx.pg_addr[0];

                    env->spr[SPR_HASH2] = ctx.pg_addr[1];

                    /* Do not alter DAR nor DSISR */

                    goto out;

                } else if (unlikely(PPC_MMU(env) == PPC_FLAGS_MMU_SOFT_4xx)) {

                    /* XXX: TODO */

                } else {

                    error_code = 0x40000000;

                }

                break;

            case -2:

                /* Access rights violation */

                error_code = 0x08000000;

                break;

            case -4:

                /* Direct store exception */

                switch (access_type) {

                case ACCESS_FLOAT:

                    /* Floating point load/store */

                    exception = EXCP_ALIGN;

                    error_code = EXCP_ALIGN_FP;

                    break;

                case ACCESS_RES:

                    /* lwarx, ldarx or srwcx. */

                    error_code = 0x04000000;

                    break;

                case ACCESS_EXT:

                    /* eciwx or ecowx */

                    error_code = 0x04100000;

                    break;

                default:

                    printf("DSI: invalid exception (%d)\n", ret);

                    exception = EXCP_PROGRAM;

                    error_code = EXCP_INVAL | EXCP_INVAL_INVAL;

                    break;

                }

                break;

            case -5:

                /* No match in segment table */

                exception = EXCP_DSEG;

                error_code = 0;

                break;

            }

            if (exception == EXCP_DSI && rw == 1)

                error_code |= 0x02000000;

            /* Store fault address */

            env->spr[SPR_DAR] = address;

            env->spr[SPR_DSISR] = error_code;

        }

    out:

#if 0

        printf("%s: set exception to %d %02x\n",

               __func__, exception, error_code);

#endif

        env->exception_index = exception;

        env->error_code = error_code;

        ret = 1;

    }

    return ret;

}


static PCIINTxRoute gpex_route_intx_pin_to_irq(void *opaque, int pin)

{

    PCIINTxRoute route;

    GPEXHost *s = opaque;

    route.mode = PCI_INTX_ENABLED;

    route.irq = s->irq_num[pin];

    return route;

}


static void cuda_writeb(void *opaque, target_phys_addr_t addr, uint32_t val)

{

    CUDAState *s = opaque;

    addr = (addr >> 9) & 0xf;

    CUDA_DPRINTF("write: reg=0x%x val=%02x\n", (int)addr, val);

    switch(addr) {

    case 0:

        s->b = val;

        cuda_update(s);

        break;

    case 1:

        s->a = val;

        break;

    case 2:

        s->dirb = val;

        break;

    case 3:

        s->dira = val;

        break;

    case 4:

        s->timers[0].latch = (s->timers[0].latch & 0xff00) | val;

        cuda_timer_update(s, &s->timers[0], qemu_get_clock_ns(vm_clock));

        break;

    case 5:

        s->timers[0].latch = (s->timers[0].latch & 0xff) | (val << 8);

        s->ifr &= ~T1_INT;

        set_counter(s, &s->timers[0], s->timers[0].latch);

        break;

    case 6:

        s->timers[0].latch = (s->timers[0].latch & 0xff00) | val;

        cuda_timer_update(s, &s->timers[0], qemu_get_clock_ns(vm_clock));

        break;

    case 7:

        s->timers[0].latch = (s->timers[0].latch & 0xff) | (val << 8);

        s->ifr &= ~T1_INT;

        cuda_timer_update(s, &s->timers[0], qemu_get_clock_ns(vm_clock));

        break;

    case 8:

        s->timers[1].latch = val;

        set_counter(s, &s->timers[1], val);

        break;

    case 9:

        set_counter(s, &s->timers[1], (val << 8) | s->timers[1].latch);

        break;

    case 10:

        s->sr = val;

        break;

    case 11:

        s->acr = val;

        cuda_timer_update(s, &s->timers[0], qemu_get_clock_ns(vm_clock));

        cuda_update(s);

        break;

    case 12:

        s->pcr = val;

        break;

    case 13:

        /* reset bits */

        s->ifr &= ~val;

        cuda_update_irq(s);

        break;

    case 14:

        if (val & IER_SET) {

            /* set bits */

            s->ier |= val & 0x7f;

        } else {

            /* reset bits */

            s->ier &= ~val;

        }

        cuda_update_irq(s);

        break;

    default:

    case 15:

        s->anh = val;

        break;

    }

}


int pci_add_capability(PCIDevice *pdev, uint8_t cap_id,

                       uint8_t offset, uint8_t size,

                       Error **errp)

{

    uint8_t *config;

    int i, overlapping_cap;

    if (!offset) {

        offset = pci_find_space(pdev, size);

        /* out of PCI config space is programming error */

        assert(offset);

    } else {

        /* Verify that capabilities don't overlap.  Note: device assignment

         * depends on this check to verify that the device is not broken.

         * Should never trigger for emulated devices, but it's helpful

         * for debugging these. */

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

            overlapping_cap = pci_find_capability_at_offset(pdev, i);

            if (overlapping_cap) {

                error_setg(errp, "%s:%02x:%02x.%x "

                           "Attempt to add PCI capability %x at offset "

                           "%x overlaps existing capability %x at offset %x",

                           pci_root_bus_path(pdev), pci_bus_num(pdev->bus),

                           PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn),

                           cap_id, offset, overlapping_cap, i);

                return -EINVAL;

            }

        }

    }

    config = pdev->config + offset;

    config[PCI_CAP_LIST_ID] = cap_id;

    config[PCI_CAP_LIST_NEXT] = pdev->config[PCI_CAPABILITY_LIST];

    pdev->config[PCI_CAPABILITY_LIST] = offset;

    pdev->config[PCI_STATUS] |= PCI_STATUS_CAP_LIST;

    memset(pdev->used + offset, 0xFF, QEMU_ALIGN_UP(size, 4));

    /* Make capability read-only by default */

    memset(pdev->wmask + offset, 0, size);

    /* Check capability by default */

    memset(pdev->cmask + offset, 0xFF, size);

    return offset;

}


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

{

    MigrationParameters *params;

    params = qmp_query_migrate_parameters(NULL);

    if (params) {

        assert(params->has_compress_level);

        monitor_printf(mon, "%s: %" PRId64 "\n",

            MigrationParameter_str(MIGRATION_PARAMETER_COMPRESS_LEVEL),

            params->compress_level);

        assert(params->has_compress_threads);

        monitor_printf(mon, "%s: %" PRId64 "\n",

            MigrationParameter_str(MIGRATION_PARAMETER_COMPRESS_THREADS),

            params->compress_threads);

        assert(params->has_decompress_threads);

        monitor_printf(mon, "%s: %" PRId64 "\n",

            MigrationParameter_str(MIGRATION_PARAMETER_DECOMPRESS_THREADS),

            params->decompress_threads);

        assert(params->has_cpu_throttle_initial);

        monitor_printf(mon, "%s: %" PRId64 "\n",

            MigrationParameter_str(MIGRATION_PARAMETER_CPU_THROTTLE_INITIAL),

            params->cpu_throttle_initial);

        assert(params->has_cpu_throttle_increment);

        monitor_printf(mon, "%s: %" PRId64 "\n",

            MigrationParameter_str(MIGRATION_PARAMETER_CPU_THROTTLE_INCREMENT),

            params->cpu_throttle_increment);

        assert(params->has_tls_creds);

        monitor_printf(mon, "%s: '%s'\n",

            MigrationParameter_str(MIGRATION_PARAMETER_TLS_CREDS),

            params->tls_creds);

        assert(params->has_tls_hostname);

        monitor_printf(mon, "%s: '%s'\n",

            MigrationParameter_str(MIGRATION_PARAMETER_TLS_HOSTNAME),

            params->tls_hostname);

        assert(params->has_max_bandwidth);

        monitor_printf(mon, "%s: %" PRId64 " bytes/second\n",

            MigrationParameter_str(MIGRATION_PARAMETER_MAX_BANDWIDTH),

            params->max_bandwidth);

        assert(params->has_downtime_limit);

        monitor_printf(mon, "%s: %" PRId64 " milliseconds\n",

            MigrationParameter_str(MIGRATION_PARAMETER_DOWNTIME_LIMIT),

            params->downtime_limit);

        assert(params->has_x_checkpoint_delay);

        monitor_printf(mon, "%s: %" PRId64 "\n",

            MigrationParameter_str(MIGRATION_PARAMETER_X_CHECKPOINT_DELAY),

            params->x_checkpoint_delay);

        assert(params->has_block_incremental);

        monitor_printf(mon, "%s: %s\n",

            MigrationParameter_str(MIGRATION_PARAMETER_BLOCK_INCREMENTAL),

            params->block_incremental ? "on" : "off");

        monitor_printf(mon, "%s: %" PRId64 "\n",

            MigrationParameter_str(MIGRATION_PARAMETER_X_MULTIFD_CHANNELS),

            params->x_multifd_channels);

        monitor_printf(mon, "%s: %" PRId64 "\n",

            MigrationParameter_str(MIGRATION_PARAMETER_X_MULTIFD_PAGE_COUNT),

            params->x_multifd_page_count);

        monitor_printf(mon, "%s: %" PRId64 "\n",

            MigrationParameter_str(MIGRATION_PARAMETER_XBZRLE_CACHE_SIZE),

            params->xbzrle_cache_size);

    }

    qapi_free_MigrationParameters(params);

}


static void pxb_dev_realize_common(PCIDevice *dev, bool pcie, Error **errp)

{

    PXBDev *pxb = convert_to_pxb(dev);

    DeviceState *ds, *bds = NULL;

    PCIBus *bus;

    const char *dev_name = NULL;

    Error *local_err = NULL;

    if (pxb->numa_node != NUMA_NODE_UNASSIGNED &&

        pxb->numa_node >= nb_numa_nodes) {

        error_setg(errp, "Illegal numa node %d", pxb->numa_node);

        return;

    }

    if (dev->qdev.id && *dev->qdev.id) {

        dev_name = dev->qdev.id;

    }

    ds = qdev_create(NULL, TYPE_PXB_HOST);

    if (pcie) {

        bus = pci_root_bus_new(ds, dev_name, NULL, NULL, 0, TYPE_PXB_PCIE_BUS);

    } else {

        bus = pci_root_bus_new(ds, "pxb-internal", NULL, NULL, 0, TYPE_PXB_BUS);

        bds = qdev_create(BUS(bus), "pci-bridge");

        bds->id = dev_name;

        qdev_prop_set_uint8(bds, PCI_BRIDGE_DEV_PROP_CHASSIS_NR, pxb->bus_nr);

        qdev_prop_set_bit(bds, PCI_BRIDGE_DEV_PROP_SHPC, false);

    }

    bus->parent_dev = dev;

    bus->address_space_mem = dev->bus->address_space_mem;

    bus->address_space_io = dev->bus->address_space_io;

    bus->map_irq = pxb_map_irq_fn;

    PCI_HOST_BRIDGE(ds)->bus = bus;

    pxb_register_bus(dev, bus, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        goto err_register_bus;

    }

    qdev_init_nofail(ds);

    if (bds) {

        qdev_init_nofail(bds);

    }

    pci_word_test_and_set_mask(dev->config + PCI_STATUS,

                               PCI_STATUS_66MHZ | PCI_STATUS_FAST_BACK);

    pci_config_set_class(dev->config, PCI_CLASS_BRIDGE_HOST);

    pxb_dev_list = g_list_insert_sorted(pxb_dev_list, pxb, pxb_compare);

    return;

err_register_bus:

    object_unref(OBJECT(bds));

    object_unparent(OBJECT(bus));

    object_unref(OBJECT(ds));

}


int qemu_read_config_file(const char *filename)

{

    FILE *f = fopen(filename, "r");

    int ret;

    if (f == NULL) {

        return -errno;

    }

    ret = qemu_config_parse(f, vm_config_groups, filename);

    fclose(f);

    if (ret == 0) {

        return 0;

    } else {

        return -EINVAL;

    }

}


SocketAddress *socket_parse(const char *str, Error **errp)

{

    SocketAddress *addr;

    addr = g_new0(SocketAddress, 1);

    if (strstart(str, "unix:", NULL)) {

        if (str[5] == '\0') {

            error_setg(errp, "invalid Unix socket address");

            goto fail;

        } else {

            addr->type = SOCKET_ADDRESS_KIND_UNIX;

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

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

        }

    } else if (strstart(str, "fd:", NULL)) {

        if (str[3] == '\0') {

            error_setg(errp, "invalid file descriptor address");

            goto fail;

        } else {

            addr->type = SOCKET_ADDRESS_KIND_FD;

            addr->u.fd.data = g_new(String, 1);

            addr->u.fd.data->str = g_strdup(str + 3);

        }

    } else if (strstart(str, "vsock:", NULL)) {

        addr->type = SOCKET_ADDRESS_KIND_VSOCK;

        addr->u.vsock.data = g_new(VsockSocketAddress, 1);

        if (vsock_parse(addr->u.vsock.data, str + strlen("vsock:"), errp)) {

            goto fail;

        }

    } else {

        addr->type = SOCKET_ADDRESS_KIND_INET;

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

        if (inet_parse(addr->u.inet.data, str, errp)) {

            goto fail;

        }

    }

    return addr;

fail:

    qapi_free_SocketAddress(addr);

    return NULL;

}