static int xwd_decode_frame(AVCodecContext *avctx, void *data,

                            int *got_frame, AVPacket *avpkt)

{

    AVFrame *p = data;

    const uint8_t *buf = avpkt->data;

    int i, ret, buf_size = avpkt->size;

    uint32_t version, header_size, vclass, ncolors;

    uint32_t xoffset, be, bpp, lsize, rsize;

    uint32_t pixformat, pixdepth, bunit, bitorder, bpad;

    uint32_t rgb[3];

    uint8_t *ptr;

    GetByteContext gb;

    if (buf_size < XWD_HEADER_SIZE)

        return AVERROR_INVALIDDATA;

    bytestream2_init(&gb, buf, buf_size);

    header_size = bytestream2_get_be32u(&gb);

    version = bytestream2_get_be32u(&gb);

    if (version != XWD_VERSION) {

        av_log(avctx, AV_LOG_ERROR, "unsupported version\n");

        return AVERROR_INVALIDDATA;

    }

    if (buf_size < header_size || header_size < XWD_HEADER_SIZE) {

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

        return AVERROR_INVALIDDATA;

    }

    pixformat     = bytestream2_get_be32u(&gb);

    pixdepth      = bytestream2_get_be32u(&gb);

    avctx->width  = bytestream2_get_be32u(&gb);

    avctx->height = bytestream2_get_be32u(&gb);

    xoffset       = bytestream2_get_be32u(&gb);

    be            = bytestream2_get_be32u(&gb);

    bunit         = bytestream2_get_be32u(&gb);

    bitorder      = bytestream2_get_be32u(&gb);

    bpad          = bytestream2_get_be32u(&gb);

    bpp           = bytestream2_get_be32u(&gb);

    lsize         = bytestream2_get_be32u(&gb);

    vclass        = bytestream2_get_be32u(&gb);

    rgb[0]        = bytestream2_get_be32u(&gb);

    rgb[1]        = bytestream2_get_be32u(&gb);

    rgb[2]        = bytestream2_get_be32u(&gb);

    bytestream2_skipu(&gb, 8);

    ncolors       = bytestream2_get_be32u(&gb);

    bytestream2_skipu(&gb, header_size - (XWD_HEADER_SIZE - 20));

    av_log(avctx, AV_LOG_DEBUG,

           "pixformat %"PRIu32", pixdepth %"PRIu32", bunit %"PRIu32", bitorder %"PRIu32", bpad %"PRIu32"\n",

           pixformat, pixdepth, bunit, bitorder, bpad);

    av_log(avctx, AV_LOG_DEBUG,

           "vclass %"PRIu32", ncolors %"PRIu32", bpp %"PRIu32", be %"PRIu32", lsize %"PRIu32", xoffset %"PRIu32"\n",

           vclass, ncolors, bpp, be, lsize, xoffset);

    av_log(avctx, AV_LOG_DEBUG,

           "red %0"PRIx32", green %0"PRIx32", blue %0"PRIx32"\n",

           rgb[0], rgb[1], rgb[2]);

    if (pixformat > XWD_Z_PIXMAP) {

        av_log(avctx, AV_LOG_ERROR, "invalid pixmap format\n");

        return AVERROR_INVALIDDATA;

    }

    if (pixdepth == 0 || pixdepth > 32) {

        av_log(avctx, AV_LOG_ERROR, "invalid pixmap depth\n");

        return AVERROR_INVALIDDATA;

    }

    if (xoffset) {

        avpriv_request_sample(avctx, "xoffset %"PRIu32"", xoffset);

        return AVERROR_PATCHWELCOME;

    }

    if (be > 1) {

        av_log(avctx, AV_LOG_ERROR, "invalid byte order\n");

        return AVERROR_INVALIDDATA;

    }

    if (bitorder > 1) {

        av_log(avctx, AV_LOG_ERROR, "invalid bitmap bit order\n");

        return AVERROR_INVALIDDATA;

    }

    if (bunit != 8 && bunit != 16 && bunit != 32) {

        av_log(avctx, AV_LOG_ERROR, "invalid bitmap unit\n");

        return AVERROR_INVALIDDATA;

    }

    if (bpad != 8 && bpad != 16 && bpad != 32) {

        av_log(avctx, AV_LOG_ERROR, "invalid bitmap scan-line pad\n");

        return AVERROR_INVALIDDATA;

    }

    if (bpp == 0 || bpp > 32) {

        av_log(avctx, AV_LOG_ERROR, "invalid bits per pixel\n");

        return AVERROR_INVALIDDATA;

    }

    if (ncolors > 256) {

        av_log(avctx, AV_LOG_ERROR, "invalid number of entries in colormap\n");

        return AVERROR_INVALIDDATA;

    }

    if ((ret = av_image_check_size(avctx->width, avctx->height, 0, NULL)) < 0)

        return ret;

    rsize = FFALIGN(avctx->width * bpp, bpad) / 8;

    if (lsize < rsize) {

        av_log(avctx, AV_LOG_ERROR, "invalid bytes per scan-line\n");

        return AVERROR_INVALIDDATA;

    }

    if (bytestream2_get_bytes_left(&gb) < ncolors * XWD_CMAP_SIZE + (uint64_t)avctx->height * lsize) {

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

        return AVERROR_INVALIDDATA;

    }

    if (pixformat != XWD_Z_PIXMAP) {

        avpriv_report_missing_feature(avctx, "Pixmap format %"PRIu32, pixformat);

        return AVERROR_PATCHWELCOME;

    }

    avctx->pix_fmt = AV_PIX_FMT_NONE;

    switch (vclass) {

    case XWD_STATIC_GRAY:

    case XWD_GRAY_SCALE:

        if (bpp != 1 && bpp != 8)

            return AVERROR_INVALIDDATA;

        if (pixdepth == 1) {

            avctx->pix_fmt = AV_PIX_FMT_MONOWHITE;

        } else if (pixdepth == 8) {

            avctx->pix_fmt = AV_PIX_FMT_GRAY8;

        }

        break;

    case XWD_STATIC_COLOR:

    case XWD_PSEUDO_COLOR:

        if (bpp == 8)

            avctx->pix_fmt = AV_PIX_FMT_PAL8;

        break;

    case XWD_TRUE_COLOR:

    case XWD_DIRECT_COLOR:

        if (bpp != 16 && bpp != 24 && bpp != 32)

            return AVERROR_INVALIDDATA;

        if (bpp == 16 && pixdepth == 15) {

            if (rgb[0] == 0x7C00 && rgb[1] == 0x3E0 && rgb[2] == 0x1F)

                avctx->pix_fmt = be ? AV_PIX_FMT_RGB555BE : AV_PIX_FMT_RGB555LE;

            else if (rgb[0] == 0x1F && rgb[1] == 0x3E0 && rgb[2] == 0x7C00)

                avctx->pix_fmt = be ? AV_PIX_FMT_BGR555BE : AV_PIX_FMT_BGR555LE;

        } else if (bpp == 16 && pixdepth == 16) {

            if (rgb[0] == 0xF800 && rgb[1] == 0x7E0 && rgb[2] == 0x1F)

                avctx->pix_fmt = be ? AV_PIX_FMT_RGB565BE : AV_PIX_FMT_RGB565LE;

            else if (rgb[0] == 0x1F && rgb[1] == 0x7E0 && rgb[2] == 0xF800)

                avctx->pix_fmt = be ? AV_PIX_FMT_BGR565BE : AV_PIX_FMT_BGR565LE;

        } else if (bpp == 24) {

            if (rgb[0] == 0xFF0000 && rgb[1] == 0xFF00 && rgb[2] == 0xFF)

                avctx->pix_fmt = be ? AV_PIX_FMT_RGB24 : AV_PIX_FMT_BGR24;

            else if (rgb[0] == 0xFF && rgb[1] == 0xFF00 && rgb[2] == 0xFF0000)

                avctx->pix_fmt = be ? AV_PIX_FMT_BGR24 : AV_PIX_FMT_RGB24;

        } else if (bpp == 32) {

            if (rgb[0] == 0xFF0000 && rgb[1] == 0xFF00 && rgb[2] == 0xFF)

                avctx->pix_fmt = be ? AV_PIX_FMT_ARGB : AV_PIX_FMT_BGRA;

            else if (rgb[0] == 0xFF && rgb[1] == 0xFF00 && rgb[2] == 0xFF0000)

                avctx->pix_fmt = be ? AV_PIX_FMT_ABGR : AV_PIX_FMT_RGBA;

        }

        bytestream2_skipu(&gb, ncolors * XWD_CMAP_SIZE);

        break;

    default:

        av_log(avctx, AV_LOG_ERROR, "invalid visual class\n");

        return AVERROR_INVALIDDATA;

    }

    if (avctx->pix_fmt == AV_PIX_FMT_NONE) {

        avpriv_request_sample(avctx,

                              "Unknown file: bpp %"PRIu32", pixdepth %"PRIu32", vclass %"PRIu32"",

                              bpp, pixdepth, vclass);

        return AVERROR_PATCHWELCOME;

    }

    if ((ret = ff_get_buffer(avctx, p, 0)) < 0)

        return ret;

    p->key_frame = 1;

    p->pict_type = AV_PICTURE_TYPE_I;

    if (avctx->pix_fmt == AV_PIX_FMT_PAL8) {

        uint32_t *dst = (uint32_t *)p->data[1];

        uint8_t red, green, blue;

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

            bytestream2_skipu(&gb, 4); // skip colormap entry number

            red    = bytestream2_get_byteu(&gb);

            bytestream2_skipu(&gb, 1);

            green  = bytestream2_get_byteu(&gb);

            bytestream2_skipu(&gb, 1);

            blue   = bytestream2_get_byteu(&gb);

            bytestream2_skipu(&gb, 3); // skip bitmask flag and padding

            dst[i] = red << 16 | green << 8 | blue;

        }

    }

    ptr = p->data[0];

    for (i = 0; i < avctx->height; i++) {

        bytestream2_get_bufferu(&gb, ptr, rsize);

        bytestream2_skipu(&gb, lsize - rsize);

        ptr += p->linesize[0];

    }

    *got_frame       = 1;

    return buf_size;

}


vmxnet3_init_msi(VMXNET3State *s)

{

    PCIDevice *d = PCI_DEVICE(s);

    int res;

    res = msi_init(d, VMXNET3_MSI_OFFSET, VMXNET3_MSI_NUM_VECTORS,

                   VMXNET3_USE_64BIT, VMXNET3_PER_VECTOR_MASK);

    if (0 > res) {

        VMW_WRPRN("Failed to initialize MSI, error %d", res);

        s->msi_used = false;

    } else {

        s->msi_used = true;

    }

    return s->msi_used;

}


static int decode_frame(AVCodecContext *avctx,

                        void *data, int *got_frame,

                        AVPacket *avpkt)

{

    PicContext *s = avctx->priv_data;

    AVFrame *frame = data;

    uint32_t *palette;

    int bits_per_plane, bpp, etype, esize, npal, pos_after_pal;

    int i, x, y, plane, tmp, ret, val;

    bytestream2_init(&s->g, avpkt->data, avpkt->size);

    if (bytestream2_get_bytes_left(&s->g) < 11)

        return AVERROR_INVALIDDATA;

    if (bytestream2_get_le16u(&s->g) != 0x1234)

        return AVERROR_INVALIDDATA;

    s->width       = bytestream2_get_le16u(&s->g);

    s->height      = bytestream2_get_le16u(&s->g);

    bytestream2_skip(&s->g, 4);

    tmp            = bytestream2_get_byteu(&s->g);

    bits_per_plane = tmp & 0xF;

    s->nb_planes   = (tmp >> 4) + 1;

    bpp            = bits_per_plane * s->nb_planes;

    if (bits_per_plane > 8 || bpp < 1 || bpp > 32) {

        avpriv_request_sample(avctx, "Unsupported bit depth");

        return AVERROR_PATCHWELCOME;

    }

    if (bytestream2_peek_byte(&s->g) == 0xFF || bpp == 1 || bpp == 4 || bpp == 8) {

        bytestream2_skip(&s->g, 2);

        etype = bytestream2_get_le16(&s->g);

        esize = bytestream2_get_le16(&s->g);

        if (bytestream2_get_bytes_left(&s->g) < esize)

            return AVERROR_INVALIDDATA;

    } else {

        etype = -1;

        esize = 0;

    }

    avctx->pix_fmt = AV_PIX_FMT_PAL8;

    if (s->width != avctx->width && s->height != avctx->height) {

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

            return -1;

        avcodec_set_dimensions(avctx, s->width, s->height);

    }

    if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)

        return ret;

    memset(frame->data[0], 0, s->height * frame->linesize[0]);

    frame->pict_type           = AV_PICTURE_TYPE_I;

    frame->palette_has_changed = 1;

    pos_after_pal = bytestream2_tell(&s->g) + esize;

    palette = (uint32_t*)frame->data[1];

    if (etype == 1 && esize > 1 && bytestream2_peek_byte(&s->g) < 6) {

        int idx = bytestream2_get_byte(&s->g);

        npal = 4;

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

            palette[i] = ff_cga_palette[ cga_mode45_index[idx][i] ];

    } else if (etype == 2) {

        npal = FFMIN(esize, 16);

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

            int pal_idx = bytestream2_get_byte(&s->g);

            palette[i]  = ff_cga_palette[FFMIN(pal_idx, 15)];

        }

    } else if (etype == 3) {

        npal = FFMIN(esize, 16);

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

            int pal_idx = bytestream2_get_byte(&s->g);

            palette[i]  = ff_ega_palette[FFMIN(pal_idx, 63)];

        }

    } else if (etype == 4 || etype == 5) {

        npal = FFMIN(esize / 3, 256);

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

            palette[i] = bytestream2_get_be24(&s->g) << 2;

            palette[i] |= 0xFFU << 24 | palette[i] >> 6 & 0x30303;

        }

    } else {

        if (bpp == 1) {

            npal = 2;

            palette[0] = 0xFF000000;

            palette[1] = 0xFFFFFFFF;

        } else if (bpp == 2) {

            npal = 4;

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

                palette[i] = ff_cga_palette[ cga_mode45_index[0][i] ];

        } else {

            npal = 16;

            memcpy(palette, ff_cga_palette, npal * 4);

        }

    }

    // fill remaining palette entries

    memset(palette + npal, 0, AVPALETTE_SIZE - npal * 4);

    // skip remaining palette bytes

    bytestream2_seek(&s->g, pos_after_pal, SEEK_SET);

    val = 0;

    y = s->height - 1;

    if (bytestream2_get_le16(&s->g)) {

        x = 0;

        plane = 0;

        while (y >= 0 && bytestream2_get_bytes_left(&s->g) >= 6) {

            int stop_size, marker, t1, t2;

            t1        = bytestream2_get_bytes_left(&s->g);

            t2        = bytestream2_get_le16(&s->g);

            stop_size = t1 - FFMIN(t1, t2);

            // ignore uncompressed block size

            bytestream2_skip(&s->g, 2);

            marker    = bytestream2_get_byte(&s->g);

            while (plane < s->nb_planes && y >= 0 &&

                   bytestream2_get_bytes_left(&s->g) > stop_size) {

                int run = 1;

                val = bytestream2_get_byte(&s->g);

                if (val == marker) {

                    run = bytestream2_get_byte(&s->g);

                    if (run == 0)

                        run = bytestream2_get_le16(&s->g);

                    val = bytestream2_get_byte(&s->g);

                }

                if (!bytestream2_get_bytes_left(&s->g))

                    break;

                if (bits_per_plane == 8) {

                    picmemset_8bpp(s, frame, val, run, &x, &y);

                    if (y < 0)

                        goto finish;

                } else {

                    picmemset(s, frame, val, run, &x, &y, &plane, bits_per_plane);

                }

            }

        }

        if (x < avctx->width && y >= 0) {

            int run = (y + 1) * avctx->width - x;

            if (bits_per_plane == 8)

                picmemset_8bpp(s, frame, val, run, &x, &y);

            else

                picmemset(s, frame, val, run / (8 / bits_per_plane), &x, &y, &plane, bits_per_plane);

        }

    } else {

        while (y >= 0 && bytestream2_get_bytes_left(&s->g) > 0) {

            memcpy(frame->data[0] + y * frame->linesize[0], s->g.buffer, FFMIN(avctx->width, bytestream2_get_bytes_left(&s->g)));

            bytestream2_skip(&s->g, avctx->width);

            y--;

        }

    }

finish:

    *got_frame      = 1;

    return avpkt->size;

}


static int ram_save_compressed_page(RAMState *rs, PageSearchStatus *pss,

                                    bool last_stage)

{

    int pages = -1;

    uint64_t bytes_xmit = 0;

    uint8_t *p;

    int ret, blen;

    RAMBlock *block = pss->block;

    ram_addr_t offset = pss->page << TARGET_PAGE_BITS;

    p = block->host + offset;

    ret = ram_control_save_page(rs->f, block->offset,

                                offset, TARGET_PAGE_SIZE, &bytes_xmit);

    if (bytes_xmit) {

        rs->bytes_transferred += bytes_xmit;

        pages = 1;

    }

    if (ret != RAM_SAVE_CONTROL_NOT_SUPP) {

        if (ret != RAM_SAVE_CONTROL_DELAYED) {

            if (bytes_xmit > 0) {

                rs->norm_pages++;

            } else if (bytes_xmit == 0) {

                rs->zero_pages++;

            }

        }

    } else {

        /* When starting the process of a new block, the first page of

         * the block should be sent out before other pages in the same

         * block, and all the pages in last block should have been sent

         * out, keeping this order is important, because the 'cont' flag

         * is used to avoid resending the block name.

         */

        if (block != rs->last_sent_block) {

            flush_compressed_data(rs);

            pages = save_zero_page(rs, block, offset, p);

            if (pages == -1) {

                /* Make sure the first page is sent out before other pages */

                bytes_xmit = save_page_header(rs, block, offset |

                                              RAM_SAVE_FLAG_COMPRESS_PAGE);

                blen = qemu_put_compression_data(rs->f, p, TARGET_PAGE_SIZE,

                                                 migrate_compress_level());

                if (blen > 0) {

                    rs->bytes_transferred += bytes_xmit + blen;

                    rs->norm_pages++;

                    pages = 1;

                } else {

                    qemu_file_set_error(rs->f, blen);

                    error_report("compressed data failed!");

                }

            }

            if (pages > 0) {

                ram_release_pages(block->idstr, offset, pages);

            }

        } else {

            pages = save_zero_page(rs, block, offset, p);

            if (pages == -1) {

                pages = compress_page_with_multi_thread(rs, block, offset);

            } else {

                ram_release_pages(block->idstr, offset, pages);

            }

        }

    }

    return pages;

}


static int open_self_cmdline(void *cpu_env, int fd)

{

    int fd_orig = -1;

    bool word_skipped = false;

    fd_orig = open("/proc/self/cmdline", O_RDONLY);

    if (fd_orig < 0) {

        return fd_orig;

    }

    while (true) {

        ssize_t nb_read;

        char buf[128];

        char *cp_buf = buf;

        nb_read = read(fd_orig, buf, sizeof(buf));

        if (nb_read < 0) {

            fd_orig = close(fd_orig);

            return -1;

        } else if (nb_read == 0) {

            break;

        }

        if (!word_skipped) {

            /* Skip the first string, which is the path to qemu-*-static

               instead of the actual command. */

            cp_buf = memchr(buf, 0, sizeof(buf));

            if (cp_buf) {

                /* Null byte found, skip one string */

                cp_buf++;

                nb_read -= cp_buf - buf;

                word_skipped = true;

            }

        }

        if (word_skipped) {

            if (write(fd, cp_buf, nb_read) != nb_read) {

                return -1;

            }

        }

    }

    return close(fd_orig);

}


int bdrv_create(BlockDriver *drv, const char* filename,

    QEMUOptionParameter *options)

{

    int ret;

    Coroutine *co;

    CreateCo cco = {

        .drv = drv,

        .filename = g_strdup(filename),

        .options = options,

        .ret = NOT_DONE,

    };

    if (!drv->bdrv_create) {

        return -ENOTSUP;

    }

    if (qemu_in_coroutine()) {

        /* Fast-path if already in coroutine context */

        bdrv_create_co_entry(&cco);

    } else {

        co = qemu_coroutine_create(bdrv_create_co_entry);

        qemu_coroutine_enter(co, &cco);

        while (cco.ret == NOT_DONE) {

            qemu_aio_wait();

        }

    }

    ret = cco.ret;

    g_free(cco.filename);

    return ret;

}


static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *cur_buf)

{

    AlphaExtractContext *extract = inlink->dst->priv;

    AVFilterLink *outlink = inlink->dst->outputs[0];

    AVFilterBufferRef *out_buf =

        ff_get_video_buffer(outlink, AV_PERM_WRITE, outlink->w, outlink->h);

    int ret;

    if (!out_buf) {

        ret = AVERROR(ENOMEM);

        goto end;

    }

    avfilter_copy_buffer_ref_props(out_buf, cur_buf);

    if (extract->is_packed_rgb) {

        int x, y;

        uint8_t *pin, *pout;

        for (y = 0; y < out_buf->video->h; y++) {

            pin = cur_buf->data[0] + y * cur_buf->linesize[0] + extract->rgba_map[A];

            pout = out_buf->data[0] + y * out_buf->linesize[0];

            for (x = 0; x < out_buf->video->w; x++) {

                *pout = *pin;

                pout += 1;

                pin += 4;

            }

        }

    } else {

        const int linesize = FFMIN(out_buf->linesize[Y], cur_buf->linesize[A]);

        int y;

        for (y = 0; y < out_buf->video->h; y++) {

            memcpy(out_buf->data[Y] + y * out_buf->linesize[Y],

                   cur_buf->data[A] + y * cur_buf->linesize[A],

                   linesize);

        }

    }

    ret = ff_filter_frame(outlink, out_buf);

end:

    avfilter_unref_buffer(cur_buf);

    return ret;

}


static av_cold int alac_decode_init(AVCodecContext * avctx)

{

    ALACContext *alac = avctx->priv_data;

    alac->avctx = avctx;

    alac->context_initialized = 0;

    alac->numchannels = alac->avctx->channels;

    return 0;

}


static always_inline void gen_405_mulladd_insn (DisasContext *ctx,

                                                int opc2, int opc3,

                                                int ra, int rb, int rt, int Rc)

{

    gen_op_load_gpr_T0(ra);

    gen_op_load_gpr_T1(rb);

    switch (opc3 & 0x0D) {

    case 0x05:

        /* macchw    - macchw.    - macchwo   - macchwo.   */

        /* macchws   - macchws.   - macchwso  - macchwso.  */

        /* nmacchw   - nmacchw.   - nmacchwo  - nmacchwo.  */

        /* nmacchws  - nmacchws.  - nmacchwso - nmacchwso. */

        /* mulchw - mulchw. */

        gen_op_405_mulchw();

        break;

    case 0x04:

        /* macchwu   - macchwu.   - macchwuo  - macchwuo.  */

        /* macchwsu  - macchwsu.  - macchwsuo - macchwsuo. */

        /* mulchwu - mulchwu. */

        gen_op_405_mulchwu();

        break;

    case 0x01:

        /* machhw    - machhw.    - machhwo   - machhwo.   */

        /* machhws   - machhws.   - machhwso  - machhwso.  */

        /* nmachhw   - nmachhw.   - nmachhwo  - nmachhwo.  */

        /* nmachhws  - nmachhws.  - nmachhwso - nmachhwso. */

        /* mulhhw - mulhhw. */

        gen_op_405_mulhhw();

        break;

    case 0x00:

        /* machhwu   - machhwu.   - machhwuo  - machhwuo.  */

        /* machhwsu  - machhwsu.  - machhwsuo - machhwsuo. */

        /* mulhhwu - mulhhwu. */

        gen_op_405_mulhhwu();

        break;

    case 0x0D:

        /* maclhw    - maclhw.    - maclhwo   - maclhwo.   */

        /* maclhws   - maclhws.   - maclhwso  - maclhwso.  */

        /* nmaclhw   - nmaclhw.   - nmaclhwo  - nmaclhwo.  */

        /* nmaclhws  - nmaclhws.  - nmaclhwso - nmaclhwso. */

        /* mullhw - mullhw. */

        gen_op_405_mullhw();

        break;

    case 0x0C:

        /* maclhwu   - maclhwu.   - maclhwuo  - maclhwuo.  */

        /* maclhwsu  - maclhwsu.  - maclhwsuo - maclhwsuo. */

        /* mullhwu - mullhwu. */

        gen_op_405_mullhwu();

        break;

    }

    if (opc2 & 0x02) {

        /* nmultiply-and-accumulate (0x0E) */

        gen_op_neg();

    }

    if (opc2 & 0x04) {

        /* (n)multiply-and-accumulate (0x0C - 0x0E) */

        gen_op_load_gpr_T2(rt);

        gen_op_move_T1_T0();

        gen_op_405_add_T0_T2();

    }

    if (opc3 & 0x10) {

        /* Check overflow */

        if (opc3 & 0x01)

            gen_op_405_check_ov();

        else

            gen_op_405_check_ovu();

    }

    if (opc3 & 0x02) {

        /* Saturate */

        if (opc3 & 0x01)

            gen_op_405_check_sat();

        else

            gen_op_405_check_satu();

    }

    gen_op_store_T0_gpr(rt);

    if (unlikely(Rc) != 0) {

        /* Update Rc0 */

        gen_set_Rc0(ctx);

    }

}


uint64_t helper_subqv (uint64_t op1, uint64_t op2)

{

    uint64_t res;

    res = op1 - op2;

    if (unlikely((op1 ^ op2) & (res ^ op1) & (1ULL << 63))) {

        arith_excp(env, GETPC(), EXC_M_IOV, 0);

    }

    return res;

}


static int cinepak_decode_vectors (CinepakContext *s, cvid_strip *strip,

                                   int chunk_id, int size, const uint8_t *data)

{

    const uint8_t   *eod = (data + size);

    uint32_t         flag, mask;

    uint8_t         *cb0, *cb1, *cb2, *cb3;

    unsigned int     x, y;

    char            *ip0, *ip1, *ip2, *ip3;

    flag = 0;

    mask = 0;

    for (y=strip->y1; y < strip->y2; y+=4) {

/* take care of y dimension not being multiple of 4, such streams exist */

        ip0 = ip1 = ip2 = ip3 = s->frame->data[0] +

          (s->palette_video?strip->x1:strip->x1*3) + (y * s->frame->linesize[0]);

        if(s->avctx->height - y > 1) {

            ip1 = ip0 + s->frame->linesize[0];

            if(s->avctx->height - y > 2) {

                ip2 = ip1 + s->frame->linesize[0];

                if(s->avctx->height - y > 3) {

                    ip3 = ip2 + s->frame->linesize[0];

                }

            }

        }

/* to get the correct picture for not-multiple-of-4 cases let us fill

 * each block from the bottom up, thus possibly overwriting the top line

 * more than once but ending with the correct data in place

 * (instead of in-loop checking) */

        for (x=strip->x1; x < strip->x2; x+=4) {

            if ((chunk_id & 0x01) && !(mask >>= 1)) {

                if ((data + 4) > eod)

                    return AVERROR_INVALIDDATA;

                flag  = AV_RB32 (data);

                data += 4;

                mask  = 0x80000000;

            }

            if (!(chunk_id & 0x01) || (flag & mask)) {

                if (!(chunk_id & 0x02) && !(mask >>= 1)) {

                    if ((data + 4) > eod)

                        return AVERROR_INVALIDDATA;

                    flag  = AV_RB32 (data);

                    data += 4;

                    mask  = 0x80000000;

                }

                if ((chunk_id & 0x02) || (~flag & mask)) {

                    uint8_t *p;

                    if (data >= eod)

                        return AVERROR_INVALIDDATA;

                    p = strip->v1_codebook[*data++];

                    if (s->palette_video) {

                        ip3[0] = ip3[1] = ip2[0] = ip2[1] = p[6];

                        ip3[2] = ip3[3] = ip2[2] = ip2[3] = p[9];

                        ip1[0] = ip1[1] = ip0[0] = ip0[1] = p[0];

                        ip1[2] = ip1[3] = ip0[2] = ip0[3] = p[3];

                    } else {

                        p += 6;

                        memcpy(ip3 + 0, p, 3); memcpy(ip3 + 3, p, 3);

                        memcpy(ip2 + 0, p, 3); memcpy(ip2 + 3, p, 3);

                        p += 3; /* ... + 9 */

                        memcpy(ip3 + 6, p, 3); memcpy(ip3 + 9, p, 3);

                        memcpy(ip2 + 6, p, 3); memcpy(ip2 + 9, p, 3);

                        p -= 9; /* ... + 0 */

                        memcpy(ip1 + 0, p, 3); memcpy(ip1 + 3, p, 3);

                        memcpy(ip0 + 0, p, 3); memcpy(ip0 + 3, p, 3);

                        p += 3; /* ... + 3 */

                        memcpy(ip1 + 6, p, 3); memcpy(ip1 + 9, p, 3);

                        memcpy(ip0 + 6, p, 3); memcpy(ip0 + 9, p, 3);

                    }

                } else if (flag & mask) {

                    if ((data + 4) > eod)

                        return AVERROR_INVALIDDATA;

                    cb0 = strip->v4_codebook[*data++];

                    cb1 = strip->v4_codebook[*data++];

                    cb2 = strip->v4_codebook[*data++];

                    cb3 = strip->v4_codebook[*data++];

                    if (s->palette_video) {

                        uint8_t *p;

                        p = ip3;

                        *p++ = cb2[6];

                        *p++ = cb2[9];

                        *p++ = cb3[6];

                        *p   = cb3[9];

                        p = ip2;

                        *p++ = cb2[0];

                        *p++ = cb2[3];

                        *p++ = cb3[0];

                        *p   = cb3[3];

                        p = ip1;

                        *p++ = cb0[6];

                        *p++ = cb0[9];

                        *p++ = cb1[6];

                        *p   = cb1[9];

                        p = ip0;

                        *p++ = cb0[0];

                        *p++ = cb0[3];

                        *p++ = cb1[0];

                        *p   = cb1[3];

                    } else {

                        memcpy(ip3 + 0, cb2 + 6, 6);

                        memcpy(ip3 + 6, cb3 + 6, 6);

                        memcpy(ip2 + 0, cb2 + 0, 6);

                        memcpy(ip2 + 6, cb3 + 0, 6);

                        memcpy(ip1 + 0, cb0 + 6, 6);

                        memcpy(ip1 + 6, cb1 + 6, 6);

                        memcpy(ip0 + 0, cb0 + 0, 6);

                        memcpy(ip0 + 6, cb1 + 0, 6);

                    }

                }

            }

            if (s->palette_video) {

                ip0 += 4;  ip1 += 4;

                ip2 += 4;  ip3 += 4;

            } else {

                ip0 += 12;  ip1 += 12;

                ip2 += 12;  ip3 += 12;

            }

        }

    }

    return 0;

}


AVRational av_d2q(double d, int max)

{

    AVRational a;

#define LOG2  0.69314718055994530941723212145817656807550013436025

    int exponent;

    int64_t den;

    if (isnan(d))

        return (AVRational) { 0,0 };

    if (isinf(d))

        return (AVRational) { d < 0 ? -1 : 1, 0 };

    exponent = FFMAX( (int)(log(fabs(d) + 1e-20)/LOG2), 0);

    den = 1LL << (61 - exponent);

    av_reduce(&a.num, &a.den, (int64_t)(d * den + 0.5), den, max);

    return a;

}


static void selfTest(uint8_t *src[3], int stride[3], int w, int h){

	enum PixelFormat srcFormat, dstFormat;

	int srcW, srcH, dstW, dstH;

	int flags;

	for(srcFormat = 0; srcFormat < PIX_FMT_NB; srcFormat++) {

		for(dstFormat = 0; dstFormat < PIX_FMT_NB; dstFormat++) {

			printf("%s -> %s\n",

					sws_format_name(srcFormat),

					sws_format_name(dstFormat));

			srcW= w;

			srcH= h;

			for(dstW=w - w/3; dstW<= 4*w/3; dstW+= w/3){

				for(dstH=h - h/3; dstH<= 4*h/3; dstH+= h/3){

					for(flags=1; flags<33; flags*=2) {

						int res;

						res = doTest(src, stride, w, h, srcFormat, dstFormat,

							srcW, srcH, dstW, dstH, flags);

						if (res < 0) {

							dstW = 4 * w / 3;

							dstH = 4 * h / 3;

							flags = 33;

						}

					}

				}

			}

		}

	}

}


static int dct_max8x8_c(MpegEncContext *s, uint8_t *src1,

                        uint8_t *src2, ptrdiff_t stride, int h)

{

    LOCAL_ALIGNED_16(int16_t, temp, [64]);

    int sum = 0, i;

    av_assert2(h == 8);

    s->pdsp.diff_pixels(temp, src1, src2, stride);

    s->fdsp.fdct(temp);

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

        sum = FFMAX(sum, FFABS(temp[i]));

    return sum;

}


static void intra_predict_mad_cow_dc_l00_8x8_msa(uint8_t *src, int32_t stride)

{

    uint8_t lp_cnt;

    uint32_t src0 = 0;

    uint64_t out0, out1;

    for (lp_cnt = 0; lp_cnt < 4; lp_cnt++) {

        src0 += src[lp_cnt * stride - 1];

    }

    src0 = (src0 + 2) >> 2;

    out0 = src0 * 0x0101010101010101;

    out1 = 0x8080808080808080;

    for (lp_cnt = 4; lp_cnt--;) {

        SD(out0, src);

        SD(out1, src + stride * 4);

        src += stride;

    }

}


static void copy_parameter_set(void **to, void **from, int count, int size)

{

    int i;

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

        if (to[i] && !from[i])

            av_freep(&to[i]);

        else if (from[i] && !to[i])

            to[i] = av_malloc(size);

        if (from[i])

            memcpy(to[i], from[i], size);

    }

}


av_cold void swri_resample_dsp_x86_init(ResampleContext *c)

{

    int av_unused mm_flags = av_get_cpu_flags();

    switch(c->format){

    case AV_SAMPLE_FMT_S16P:

        if (ARCH_X86_32 && EXTERNAL_MMXEXT(mm_flags)) {

            c->dsp.resample = c->linear ? ff_resample_linear_int16_mmxext

                                        : ff_resample_common_int16_mmxext;

        }

        if (EXTERNAL_SSE2(mm_flags)) {

            c->dsp.resample = c->linear ? ff_resample_linear_int16_sse2

                                        : ff_resample_common_int16_sse2;

        }

        if (EXTERNAL_XOP(mm_flags)) {

            c->dsp.resample = c->linear ? ff_resample_linear_int16_xop

                                        : ff_resample_common_int16_xop;

        }

        break;

    case AV_SAMPLE_FMT_FLTP:

        if (EXTERNAL_SSE(mm_flags)) {

            c->dsp.resample = c->linear ? ff_resample_linear_float_sse

                                        : ff_resample_common_float_sse;

        }

        if (EXTERNAL_AVX(mm_flags)) {

            c->dsp.resample = c->linear ? ff_resample_linear_float_avx

                                        : ff_resample_common_float_avx;

        }

        if (EXTERNAL_FMA3(mm_flags)) {

            c->dsp.resample = c->linear ? ff_resample_linear_float_fma3

                                        : ff_resample_common_float_fma3;

        }

        if (EXTERNAL_FMA4(mm_flags)) {

            c->dsp.resample = c->linear ? ff_resample_linear_float_fma4

                                        : ff_resample_common_float_fma4;

        }

        break;

    case AV_SAMPLE_FMT_DBLP:

        if (EXTERNAL_SSE2(mm_flags)) {

            c->dsp.resample = c->linear ? ff_resample_linear_double_sse2

                                        : ff_resample_common_double_sse2;

        }

        break;

    }

}


alloc_parameter_set(H264Context *h, void **vec, const unsigned int id, const unsigned int max,

                    const size_t size, const char *name)

{

    if(id>=max) {

        av_log(h->s.avctx, AV_LOG_ERROR, "%s_id (%d) out of range\n", name, id);

        return NULL;

    }

    if(!vec[id]) {

        vec[id] = av_mallocz(size);

        if(vec[id] == NULL)

            av_log(h->s.avctx, AV_LOG_ERROR, "cannot allocate memory for %s\n", name);

    }

    return vec[id];

}


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

{

    FrameStepContext *framestep = inlink->dst->priv;

    if (!(framestep->frame_count++ % framestep->frame_step)) {

        framestep->frame_selected = 1;

        return ff_filter_frame(inlink->dst->outputs[0], ref);

    } else {

        framestep->frame_selected = 0;

        av_frame_free(&ref);

        return 0;

    }

}


static int cris_mmu_translate_page(struct cris_mmu_result_t *res,

				   CPUState *env, uint32_t vaddr,

				   int rw, int usermode)

{

	unsigned int vpage;

	unsigned int idx;

	uint32_t lo, hi;

	uint32_t tlb_vpn, tlb_pfn = 0;

	int tlb_pid, tlb_g, tlb_v, tlb_k, tlb_w, tlb_x;

	int cfg_v, cfg_k, cfg_w, cfg_x;

	int set, match = 0;

	uint32_t r_cause;

	uint32_t r_cfg;

	int rwcause;

	int mmu = 1; /* Data mmu is default.  */

	int vect_base;

	r_cause = env->sregs[SFR_R_MM_CAUSE];

	r_cfg = env->sregs[SFR_RW_MM_CFG];

	switch (rw) {

		case 2: rwcause = CRIS_MMU_ERR_EXEC; mmu = 0; break;

		case 1: rwcause = CRIS_MMU_ERR_WRITE; break;

		default:

		case 0: rwcause = CRIS_MMU_ERR_READ; break;

	}

	/* I exception vectors 4 - 7, D 8 - 11.  */

	vect_base = (mmu + 1) * 4;

	vpage = vaddr >> 13;

	/* We know the index which to check on each set.

	   Scan both I and D.  */

#if 0

	for (set = 0; set < 4; set++) {

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

			lo = env->tlbsets[mmu][set][idx].lo;

			hi = env->tlbsets[mmu][set][idx].hi;

			tlb_vpn = EXTRACT_FIELD(hi, 13, 31);

			tlb_pfn = EXTRACT_FIELD(lo, 13, 31);

			printf ("TLB: [%d][%d] hi=%x lo=%x v=%x p=%x\n",

					set, idx, hi, lo, tlb_vpn, tlb_pfn);

		}

	}

#endif

	idx = vpage & 15;

	for (set = 0; set < 4; set++)

	{

		lo = env->tlbsets[mmu][set][idx].lo;

		hi = env->tlbsets[mmu][set][idx].hi;

		tlb_vpn = EXTRACT_FIELD(hi, 13, 31);

		tlb_pfn = EXTRACT_FIELD(lo, 13, 31);

		D(printf("TLB[%d][%d] v=%x vpage=%x -> pfn=%x lo=%x hi=%x\n",

				i, idx, tlb_vpn, vpage, tlb_pfn, lo, hi));

		if (tlb_vpn == vpage) {

			match = 1;

			break;

		}

	}

	res->bf_vec = vect_base;

	if (match) {

		cfg_w  = EXTRACT_FIELD(r_cfg, 19, 19);

		cfg_k  = EXTRACT_FIELD(r_cfg, 18, 18);

		cfg_x  = EXTRACT_FIELD(r_cfg, 17, 17);

		cfg_v  = EXTRACT_FIELD(r_cfg, 16, 16);

		tlb_pid = EXTRACT_FIELD(hi, 0, 7);

		tlb_pfn = EXTRACT_FIELD(lo, 13, 31);

		tlb_g  = EXTRACT_FIELD(lo, 4, 4);

		tlb_v = EXTRACT_FIELD(lo, 3, 3);

		tlb_k = EXTRACT_FIELD(lo, 2, 2);

		tlb_w = EXTRACT_FIELD(lo, 1, 1);

		tlb_x = EXTRACT_FIELD(lo, 0, 0);

		/*

		set_exception_vector(0x04, i_mmu_refill);

		set_exception_vector(0x05, i_mmu_invalid);

		set_exception_vector(0x06, i_mmu_access);

		set_exception_vector(0x07, i_mmu_execute);

		set_exception_vector(0x08, d_mmu_refill);

		set_exception_vector(0x09, d_mmu_invalid);

		set_exception_vector(0x0a, d_mmu_access);

		set_exception_vector(0x0b, d_mmu_write);

		*/

		if (!tlb_g

		    && tlb_pid != (env->pregs[PR_PID] & 0xff)) {

			D(printf ("tlb: wrong pid %x %x pc=%x\n",

				 tlb_pid, env->pregs[PR_PID], env->pc));

			match = 0;

			res->bf_vec = vect_base;

		} else if (rw == 1 && cfg_w && !tlb_w) {

			D(printf ("tlb: write protected %x lo=%x\n",

				vaddr, lo));

			match = 0;

			res->bf_vec = vect_base + 3;

		} else if (cfg_v && !tlb_v) {

			D(printf ("tlb: invalid %x\n", vaddr));

			set_field(&r_cause, rwcause, 8, 9);

			match = 0;

			res->bf_vec = vect_base + 1;

		}

		res->prot = 0;

		if (match) {

			res->prot |= PAGE_READ;

			if (tlb_w)

				res->prot |= PAGE_WRITE;

			if (tlb_x)

				res->prot |= PAGE_EXEC;

		}

		else

			D(dump_tlb(env, mmu));

		env->sregs[SFR_RW_MM_TLB_HI] = hi;

		env->sregs[SFR_RW_MM_TLB_LO] = lo;

	}

	if (!match) {

		/* miss.  */

		idx = vpage & 15;

		set = 0;

		/* Update RW_MM_TLB_SEL.  */

		env->sregs[SFR_RW_MM_TLB_SEL] = 0;

		set_field(&env->sregs[SFR_RW_MM_TLB_SEL], idx, 0, 4);

		set_field(&env->sregs[SFR_RW_MM_TLB_SEL], set, 4, 5);

		/* Update RW_MM_CAUSE.  */

		set_field(&r_cause, rwcause, 8, 2);

		set_field(&r_cause, vpage, 13, 19);

		set_field(&r_cause, env->pregs[PR_PID], 0, 8);

		env->sregs[SFR_R_MM_CAUSE] = r_cause;

		D(printf("refill vaddr=%x pc=%x\n", vaddr, env->pc));

	}

	D(printf ("%s rw=%d mtch=%d pc=%x va=%x vpn=%x tlbvpn=%x pfn=%x pid=%x"

		  " %x cause=%x sel=%x sp=%x %x %x\n",

		  __func__, rw, match, env->pc,

		  vaddr, vpage,

		  tlb_vpn, tlb_pfn, tlb_pid,

		  env->pregs[PR_PID],

		  r_cause,

		  env->sregs[SFR_RW_MM_TLB_SEL],

		  env->regs[R_SP], env->pregs[PR_USP], env->ksp));

	res->pfn = tlb_pfn;

	return !match;

}


static int proxy_chmod(FsContext *fs_ctx, V9fsPath *fs_path, FsCred *credp)

{

    int retval;

    retval = v9fs_request(fs_ctx->private, T_CHMOD, NULL, "sd",

                          fs_path, credp->fc_mode);

    if (retval < 0) {

        errno = -retval;

    }

    return retval;

}


void qmp_blockdev_mirror(const char *device, const char *target,

                         bool has_replaces, const char *replaces,

                         MirrorSyncMode sync,

                         bool has_speed, int64_t speed,

                         bool has_granularity, uint32_t granularity,

                         bool has_buf_size, int64_t buf_size,

                         bool has_on_source_error,

                         BlockdevOnError on_source_error,

                         bool has_on_target_error,

                         BlockdevOnError on_target_error,

                         Error **errp)

{

    BlockDriverState *bs;

    BlockBackend *blk;

    BlockDriverState *target_bs;

    AioContext *aio_context;

    BlockMirrorBackingMode backing_mode = MIRROR_LEAVE_BACKING_CHAIN;

    Error *local_err = NULL;

    blk = blk_by_name(device);

    if (!blk) {

        error_setg(errp, "Device '%s' not found", device);

        return;

    }

    bs = blk_bs(blk);

    if (!bs) {

        error_setg(errp, "Device '%s' has no media", device);

        return;

    }

    target_bs = bdrv_lookup_bs(target, target, errp);

    if (!target_bs) {

        return;

    }

    aio_context = bdrv_get_aio_context(bs);

    aio_context_acquire(aio_context);

    bdrv_set_aio_context(target_bs, aio_context);

    blockdev_mirror_common(bs, target_bs,

                           has_replaces, replaces, sync, backing_mode,

                           has_speed, speed,

                           has_granularity, granularity,

                           has_buf_size, buf_size,

                           has_on_source_error, on_source_error,

                           has_on_target_error, on_target_error,

                           true, true,

                           &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

    }

    aio_context_release(aio_context);

}


static X86CPU *pc_new_cpu(const char *cpu_model, int64_t apic_id,

                          DeviceState *icc_bridge, Error **errp)

{

    X86CPU *cpu = NULL;

    Error *local_err = NULL;

    if (icc_bridge == NULL) {

        error_setg(&local_err, "Invalid icc-bridge value");

        goto out;

    }

    cpu = cpu_x86_create(cpu_model, &local_err);

    if (local_err != NULL) {

        goto out;

    }

    qdev_set_parent_bus(DEVICE(cpu), qdev_get_child_bus(icc_bridge, "icc"));

    object_property_set_int(OBJECT(cpu), apic_id, "apic-id", &local_err);

    object_property_set_bool(OBJECT(cpu), true, "realized", &local_err);

out:

    if (local_err) {

        error_propagate(errp, local_err);

        object_unref(OBJECT(cpu));

        cpu = NULL;

    }

    return cpu;

}


static uint64_t lsi_ram_read(void *opaque, target_phys_addr_t addr,

                             unsigned size)

{

    LSIState *s = opaque;

    uint32_t val;

    uint32_t mask;

    val = s->script_ram[addr >> 2];

    mask = ((uint64_t)1 << (size * 8)) - 1;

    val >>= (addr & 3) * 8;

    return val & mask;

}


void visit_start_list(Visitor *v, const char *name, Error **errp)

{

    v->start_list(v, name, errp);

}


static void scsi_write_same_complete(void *opaque, int ret)

{

    WriteSameCBData *data = opaque;

    SCSIDiskReq *r = data->r;

    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, r->req.dev);

    assert(r->req.aiocb != NULL);

    r->req.aiocb = NULL;

    if (r->req.io_canceled) {

        scsi_req_cancel_complete(&r->req);

        goto done;

    }

    if (ret < 0) {

        if (scsi_handle_rw_error(r, -ret, true)) {

            goto done;

        }

    }

    block_acct_done(blk_get_stats(s->qdev.conf.blk), &r->acct);

    data->nb_sectors -= data->iov.iov_len / 512;

    data->sector += data->iov.iov_len / 512;

    data->iov.iov_len = MIN(data->nb_sectors * 512, data->iov.iov_len);

    if (data->iov.iov_len) {

        block_acct_start(blk_get_stats(s->qdev.conf.blk), &r->acct,

                         data->iov.iov_len, BLOCK_ACCT_WRITE);

        /* Reinitialize qiov, to handle unaligned WRITE SAME request

         * where final qiov may need smaller size */

        qemu_iovec_init_external(&data->qiov, &data->iov, 1);

        r->req.aiocb = blk_aio_pwritev(s->qdev.conf.blk,

                                       data->sector << BDRV_SECTOR_BITS,

                                       &data->qiov, 0,

                                       scsi_write_same_complete, data);

        return;

    }

    scsi_req_complete(&r->req, GOOD);

done:

    scsi_req_unref(&r->req);

    qemu_vfree(data->iov.iov_base);

    g_free(data);

}


static inline void gen_op_evslw(TCGv_i32 ret, TCGv_i32 arg1, TCGv_i32 arg2)

{

    TCGv_i32 t0;

    int l1, l2;

    l1 = gen_new_label();

    l2 = gen_new_label();

    t0 = tcg_temp_local_new_i32();

    /* No error here: 6 bits are used */

    tcg_gen_andi_i32(t0, arg2, 0x3F);

    tcg_gen_brcondi_i32(TCG_COND_GE, t0, 32, l1);

    tcg_gen_shl_i32(ret, arg1, t0);

    tcg_gen_br(l2);

    gen_set_label(l1);

    tcg_gen_movi_i32(ret, 0);

    gen_set_label(l2);

    tcg_temp_free_i32(t0);

}


static inline void gen_efsabs(DisasContext *ctx)

{

    if (unlikely(!ctx->spe_enabled)) {

        gen_exception(ctx, POWERPC_EXCP_APU);

        return;

    }

    tcg_gen_andi_tl(cpu_gpr[rD(ctx->opcode)], cpu_gpr[rA(ctx->opcode)], (target_long)~0x80000000LL);

}


static void vfio_exitfn(PCIDevice *pdev)

{

    VFIOPCIDevice *vdev = DO_UPCAST(VFIOPCIDevice, pdev, pdev);

    vfio_unregister_err_notifier(vdev);

    pci_device_set_intx_routing_notifier(&vdev->pdev, NULL);

    vfio_disable_interrupts(vdev);

    if (vdev->intx.mmap_timer) {

        timer_free(vdev->intx.mmap_timer);

    }

    vfio_teardown_msi(vdev);

    vfio_unmap_bars(vdev);

}


static uint64_t vgafb_read(void *opaque, target_phys_addr_t addr,

                           unsigned size)

{

    MilkymistVgafbState *s = opaque;

    uint32_t r = 0;

    addr >>= 2;

    switch (addr) {

    case R_CTRL:

    case R_HRES:

    case R_HSYNC_START:

    case R_HSYNC_END:

    case R_HSCAN:

    case R_VRES:

    case R_VSYNC_START:

    case R_VSYNC_END:

    case R_VSCAN:

    case R_BASEADDRESS:

    case R_BURST_COUNT:

    case R_DDC:

    case R_SOURCE_CLOCK:

        r = s->regs[addr];

    break;

    case R_BASEADDRESS_ACT:

        r = s->regs[R_BASEADDRESS];

    break;

    default:

        error_report("milkymist_vgafb: read access to unknown register 0x"

                TARGET_FMT_plx, addr << 2);

        break;

    }

    trace_milkymist_vgafb_memory_read(addr << 2, r);

    return r;

}


static int local_open2(FsContext *fs_ctx, V9fsPath *dir_path, const char *name,

                       int flags, FsCred *credp, V9fsFidOpenState *fs)

{

    char *path;

    int fd = -1;

    int err = -1;

    int serrno = 0;

    V9fsString fullname;

    char buffer[PATH_MAX];

    /*

     * Mark all the open to not follow symlinks

     */

    flags |= O_NOFOLLOW;

    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) {

        fd = open(rpath(fs_ctx, path, buffer), flags, SM_LOCAL_MODE_BITS);

        if (fd == -1) {

            err = fd;

            goto out;

        }

        credp->fc_mode = credp->fc_mode|S_IFREG;

        /* Set cleint credentials in xattr */

        err = local_set_xattr(rpath(fs_ctx, path, buffer), credp);

        if (err == -1) {

            serrno = errno;

            goto err_end;

        }

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

        fd = open(rpath(fs_ctx, path, buffer), flags, SM_LOCAL_MODE_BITS);

        if (fd == -1) {

            err = fd;

            goto out;

        }

        credp->fc_mode = credp->fc_mode|S_IFREG;

        /* Set client credentials in .virtfs_metadata directory files */

        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)) {

        fd = open(rpath(fs_ctx, path, buffer), flags, credp->fc_mode);

        if (fd == -1) {

            err = fd;

            goto out;

        }

        err = local_post_create_passthrough(fs_ctx, path, credp);

        if (err == -1) {

            serrno = errno;

            goto err_end;

        }

    }

    err = fd;

    fs->fd = fd;

    goto out;

err_end:

    close(fd);

    remove(rpath(fs_ctx, path, buffer));

    errno = serrno;

out:

    v9fs_string_free(&fullname);

    return err;

}


static int realloc_refcount_array(BDRVQcow2State *s, void **array,

                                  int64_t *size, int64_t new_size)

{

    size_t old_byte_size, new_byte_size;

    void *new_ptr;

    /* Round to clusters so the array can be directly written to disk */

    old_byte_size = size_to_clusters(s, refcount_array_byte_size(s, *size))

                    * s->cluster_size;

    new_byte_size = size_to_clusters(s, refcount_array_byte_size(s, new_size))

                    * s->cluster_size;

    if (new_byte_size == old_byte_size) {

        *size = new_size;

        return 0;

    }

    assert(new_byte_size > 0);

    new_ptr = g_try_realloc(*array, new_byte_size);

    if (!new_ptr) {

        return -ENOMEM;

    }

    if (new_byte_size > old_byte_size) {

        memset((void *)((uintptr_t)new_ptr + old_byte_size), 0,

               new_byte_size - old_byte_size);

    }

    *array = new_ptr;

    *size  = new_size;

    return 0;

}


Coroutine *qemu_coroutine_new(void)

{

    CoroutineThreadState *s = coroutine_get_thread_state();

    Coroutine *co;

    co = QLIST_FIRST(&s->pool);

    if (co) {

        QLIST_REMOVE(co, pool_next);

        s->pool_size--;

    } else {

        co = coroutine_new();

    }

    return co;

}


static uint64_t qemu_next_deadline_dyntick(void)

{

    int64_t delta;

    int64_t rtdelta;

    if (use_icount)

        delta = INT32_MAX;

    else

        delta = (qemu_next_deadline() + 999) / 1000;

    if (active_timers[QEMU_TIMER_REALTIME]) {

        rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -

                 qemu_get_clock(rt_clock))*1000;

        if (rtdelta < delta)

            delta = rtdelta;

    }

    if (delta < MIN_TIMER_REARM_US)

        delta = MIN_TIMER_REARM_US;

    return delta;

}


int ff_aac_ac3_parse(AVCodecParserContext *s1,

                     AVCodecContext *avctx,

                     const uint8_t **poutbuf, int *poutbuf_size,

                     const uint8_t *buf, int buf_size)

{

    AACAC3ParseContext *s = s1->priv_data;

    const uint8_t *buf_ptr;

    int len, sample_rate, bit_rate, channels, samples;

    *poutbuf = NULL;

    *poutbuf_size = 0;

    buf_ptr = buf;

    while (buf_size > 0) {

        int size_needed= s->frame_size ? s->frame_size : s->header_size;

        len = s->inbuf_ptr - s->inbuf;

        if(len<size_needed){

            len = FFMIN(size_needed - len, buf_size);

            memcpy(s->inbuf_ptr, buf_ptr, len);

            buf_ptr      += len;

            s->inbuf_ptr += len;

            buf_size     -= len;

        }

        if (s->frame_size == 0) {

            if ((s->inbuf_ptr - s->inbuf) == s->header_size) {

                len = s->sync(s->inbuf, &channels, &sample_rate, &bit_rate,

                              &samples);

                if (len == 0) {

                    /* no sync found : move by one byte (inefficient, but simple!) */

                    memmove(s->inbuf, s->inbuf + 1, s->header_size - 1);

                    s->inbuf_ptr--;

                } else {

                    s->frame_size = len;

                    /* update codec info */

                    avctx->sample_rate = sample_rate;

                    avctx->channels = channels;

                    /* allow downmixing to mono or stereo for AC3 */

                    if(avctx->request_channels > 0 &&

                            avctx->request_channels < channels &&

                            avctx->request_channels <= 2 &&

                            avctx->codec_id == CODEC_ID_AC3) {

                        avctx->channels = avctx->request_channels;

                    }

                    avctx->bit_rate = bit_rate;

                    avctx->frame_size = samples;

                }

            }

        } else {

            if(s->inbuf_ptr - s->inbuf == s->frame_size){

                *poutbuf = s->inbuf;

                *poutbuf_size = s->frame_size;

                s->inbuf_ptr = s->inbuf;

                s->frame_size = 0;

                break;

            }

        }

    }

    return buf_ptr - buf;

}


static uint32_t virtio_net_get_features(VirtIODevice *vdev)

{

    uint32_t features = (1 << VIRTIO_NET_F_MAC);

    return features;

}


static void s390_init(ram_addr_t ram_size,

                      const char *boot_device,

                      const char *kernel_filename,

                      const char *kernel_cmdline,

                      const char *initrd_filename,

                      const char *cpu_model)

{

    CPUState *env = NULL;

    ram_addr_t ram_addr;

    ram_addr_t kernel_size = 0;

    ram_addr_t initrd_offset;

    ram_addr_t initrd_size = 0;

    int i;

    /* XXX we only work on KVM for now */

    if (!kvm_enabled()) {

        fprintf(stderr, "The S390 target only works with KVM enabled\n");

        exit(1);

    }

    /* get a BUS */

    s390_bus = s390_virtio_bus_init(&ram_size);

    /* allocate RAM */

    ram_addr = qemu_ram_alloc(ram_size);

    cpu_register_physical_memory(0, ram_size, ram_addr);

    /* init CPUs */

    if (cpu_model == NULL) {

        cpu_model = "host";

    }

    ipi_states = qemu_malloc(sizeof(CPUState *) * smp_cpus);

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

        CPUState *tmp_env;

        tmp_env = cpu_init(cpu_model);

        if (!env) {

            env = tmp_env;

        }

        ipi_states[i] = tmp_env;

        tmp_env->halted = 1;

        tmp_env->exception_index = EXCP_HLT;

    }

    env->halted = 0;

    env->exception_index = 0;

    if (kernel_filename) {

        kernel_size = load_image(kernel_filename, qemu_get_ram_ptr(0));

        if (lduw_phys(KERN_IMAGE_START) != 0x0dd0) {

            fprintf(stderr, "Specified image is not an s390 boot image\n");

            exit(1);

        }

        env->psw.addr = KERN_IMAGE_START;

        env->psw.mask = 0x0000000180000000ULL;

    } else {

        ram_addr_t bios_size = 0;

        char *bios_filename;

        /* Load zipl bootloader */

        if (bios_name == NULL) {

            bios_name = ZIPL_FILENAME;

        }

        bios_filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);

        bios_size = load_image(bios_filename, qemu_get_ram_ptr(ZIPL_LOAD_ADDR));

        if ((long)bios_size < 0) {

            hw_error("could not load bootloader '%s'\n", bios_name);

        }

        if (bios_size > 4096) {

            hw_error("stage1 bootloader is > 4k\n");

        }

        env->psw.addr = ZIPL_START;

        env->psw.mask = 0x0000000180000000ULL;

    }

    if (initrd_filename) {

        initrd_offset = INITRD_START;

        while (kernel_size + 0x100000 > initrd_offset) {

            initrd_offset += 0x100000;

        }

        initrd_size = load_image(initrd_filename, qemu_get_ram_ptr(initrd_offset));

        stq_phys(INITRD_PARM_START, initrd_offset);

        stq_phys(INITRD_PARM_SIZE, initrd_size);

    }

    if (kernel_cmdline) {

        cpu_physical_memory_rw(KERN_PARM_AREA, (uint8_t *)kernel_cmdline,

                               strlen(kernel_cmdline), 1);

    }

    /* Create VirtIO network adapters */

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

        NICInfo *nd = &nd_table[i];

        DeviceState *dev;

        if (!nd->model) {

            nd->model = qemu_strdup("virtio");

        }

        if (strcmp(nd->model, "virtio")) {

            fprintf(stderr, "S390 only supports VirtIO nics\n");

            exit(1);

        }

        dev = qdev_create((BusState *)s390_bus, "virtio-net-s390");

        qdev_set_nic_properties(dev, nd);

        qdev_init_nofail(dev);

    }

    /* Create VirtIO disk drives */

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

        DriveInfo *dinfo;

        DeviceState *dev;

        dinfo = drive_get(IF_IDE, 0, i);

        if (!dinfo) {

            continue;

        }

        dev = qdev_create((BusState *)s390_bus, "virtio-blk-s390");

        qdev_prop_set_drive(dev, "drive", dinfo);

        qdev_init_nofail(dev);

    }

}


static void decode_opc(CPUMIPSState *env, DisasContext *ctx)

{

    int32_t offset;

    int rs, rt, rd, sa;

    uint32_t op, op1;

    int16_t imm;

    /* make sure instructions are on a word boundary */

    if (ctx->pc & 0x3) {

        env->CP0_BadVAddr = ctx->pc;

        generate_exception_err(ctx, EXCP_AdEL, EXCP_INST_NOTAVAIL);

        return;

    }

    /* Handle blikely not taken case */

    if ((ctx->hflags & MIPS_HFLAG_BMASK_BASE) == MIPS_HFLAG_BL) {

        TCGLabel *l1 = gen_new_label();

        tcg_gen_brcondi_tl(TCG_COND_NE, bcond, 0, l1);

        tcg_gen_movi_i32(hflags, ctx->hflags & ~MIPS_HFLAG_BMASK);

        gen_goto_tb(ctx, 1, ctx->pc + 4);

        gen_set_label(l1);

    }

    op = MASK_OP_MAJOR(ctx->opcode);

    rs = (ctx->opcode >> 21) & 0x1f;

    rt = (ctx->opcode >> 16) & 0x1f;

    rd = (ctx->opcode >> 11) & 0x1f;

    sa = (ctx->opcode >> 6) & 0x1f;

    imm = (int16_t)ctx->opcode;

    switch (op) {

    case OPC_SPECIAL:

        decode_opc_special(env, ctx);

        break;

    case OPC_SPECIAL2:

        decode_opc_special2_legacy(env, ctx);

        break;

    case OPC_SPECIAL3:

        decode_opc_special3(env, ctx);

        break;

    case OPC_REGIMM:

        op1 = MASK_REGIMM(ctx->opcode);

        switch (op1) {

        case OPC_BLTZL: /* REGIMM branches */

        case OPC_BGEZL:

        case OPC_BLTZALL:

        case OPC_BGEZALL:

            check_insn(ctx, ISA_MIPS2);

            check_insn_opc_removed(ctx, ISA_MIPS32R6);

            /* Fallthrough */

        case OPC_BLTZ:

        case OPC_BGEZ:

            gen_compute_branch(ctx, op1, 4, rs, -1, imm << 2, 4);

            break;

        case OPC_BLTZAL:

        case OPC_BGEZAL:

            if (ctx->insn_flags & ISA_MIPS32R6) {

                if (rs == 0) {

                    /* OPC_NAL, OPC_BAL */

                    gen_compute_branch(ctx, op1, 4, 0, -1, imm << 2, 4);

                } else {

                    generate_exception_end(ctx, EXCP_RI);

                }

            } else {

                gen_compute_branch(ctx, op1, 4, rs, -1, imm << 2, 4);

            }

            break;

        case OPC_TGEI ... OPC_TEQI: /* REGIMM traps */

        case OPC_TNEI:

            check_insn(ctx, ISA_MIPS2);

            check_insn_opc_removed(ctx, ISA_MIPS32R6);

            gen_trap(ctx, op1, rs, -1, imm);

            break;

        case OPC_SIGRIE:

            check_insn(ctx, ISA_MIPS32R6);

            generate_exception_end(ctx, EXCP_RI);

            break;

        case OPC_SYNCI:

            check_insn(ctx, ISA_MIPS32R2);

            /* Break the TB to be able to sync copied instructions

               immediately */

            ctx->bstate = BS_STOP;

            break;

        case OPC_BPOSGE32:    /* MIPS DSP branch */

#if defined(TARGET_MIPS64)

        case OPC_BPOSGE64:

#endif

            check_dsp(ctx);

            gen_compute_branch(ctx, op1, 4, -1, -2, (int32_t)imm << 2, 4);

            break;

#if defined(TARGET_MIPS64)

        case OPC_DAHI:

            check_insn(ctx, ISA_MIPS32R6);

            check_mips_64(ctx);

            if (rs != 0) {

                tcg_gen_addi_tl(cpu_gpr[rs], cpu_gpr[rs], (int64_t)imm << 32);

            }

            break;

        case OPC_DATI:

            check_insn(ctx, ISA_MIPS32R6);

            check_mips_64(ctx);

            if (rs != 0) {

                tcg_gen_addi_tl(cpu_gpr[rs], cpu_gpr[rs], (int64_t)imm << 48);

            }

            break;

#endif

        default:            /* Invalid */

            MIPS_INVAL("regimm");

            generate_exception_end(ctx, EXCP_RI);

            break;

        }

        break;

    case OPC_CP0:

        check_cp0_enabled(ctx);

        op1 = MASK_CP0(ctx->opcode);

        switch (op1) {

        case OPC_MFC0:

        case OPC_MTC0:

        case OPC_MFTR:

        case OPC_MTTR:

        case OPC_MFHC0:

        case OPC_MTHC0:

#if defined(TARGET_MIPS64)

        case OPC_DMFC0:

        case OPC_DMTC0:

#endif

#ifndef CONFIG_USER_ONLY

            gen_cp0(env, ctx, op1, rt, rd);

#endif /* !CONFIG_USER_ONLY */

            break;

        case OPC_C0_FIRST ... OPC_C0_LAST:

#ifndef CONFIG_USER_ONLY

            gen_cp0(env, ctx, MASK_C0(ctx->opcode), rt, rd);

#endif /* !CONFIG_USER_ONLY */

            break;

        case OPC_MFMC0:

#ifndef CONFIG_USER_ONLY

            {

                uint32_t op2;

                TCGv t0 = tcg_temp_new();

                op2 = MASK_MFMC0(ctx->opcode);

                switch (op2) {

                case OPC_DMT:

                    check_insn(ctx, ASE_MT);

                    gen_helper_dmt(t0);

                    gen_store_gpr(t0, rt);

                    break;

                case OPC_EMT:

                    check_insn(ctx, ASE_MT);

                    gen_helper_emt(t0);

                    gen_store_gpr(t0, rt);

                    break;

                case OPC_DVPE:

                    check_insn(ctx, ASE_MT);

                    gen_helper_dvpe(t0, cpu_env);

                    gen_store_gpr(t0, rt);

                    break;

                case OPC_EVPE:

                    check_insn(ctx, ASE_MT);

                    gen_helper_evpe(t0, cpu_env);

                    gen_store_gpr(t0, rt);

                    break;

                case OPC_DVP:

                    check_insn(ctx, ISA_MIPS32R6);

                    if (ctx->vp) {

                        gen_helper_dvp(t0, cpu_env);

                        gen_store_gpr(t0, rt);

                    }

                    break;

                case OPC_EVP:

                    check_insn(ctx, ISA_MIPS32R6);

                    if (ctx->vp) {

                        gen_helper_evp(t0, cpu_env);

                        gen_store_gpr(t0, rt);

                    }

                    break;

                case OPC_DI:

                    check_insn(ctx, ISA_MIPS32R2);

                    save_cpu_state(ctx, 1);

                    gen_helper_di(t0, cpu_env);

                    gen_store_gpr(t0, rt);

                    /* Stop translation as we may have switched

                       the execution mode.  */

                    ctx->bstate = BS_STOP;

                    break;

                case OPC_EI:

                    check_insn(ctx, ISA_MIPS32R2);

                    save_cpu_state(ctx, 1);

                    gen_helper_ei(t0, cpu_env);

                    gen_store_gpr(t0, rt);

                    /* Stop translation as we may have switched

                       the execution mode.  */

                    ctx->bstate = BS_STOP;

                    break;

                default:            /* Invalid */

                    MIPS_INVAL("mfmc0");

                    generate_exception_end(ctx, EXCP_RI);

                    break;

                }

                tcg_temp_free(t0);

            }

#endif /* !CONFIG_USER_ONLY */

            break;

        case OPC_RDPGPR:

            check_insn(ctx, ISA_MIPS32R2);

            gen_load_srsgpr(rt, rd);

            break;

        case OPC_WRPGPR:

            check_insn(ctx, ISA_MIPS32R2);

            gen_store_srsgpr(rt, rd);

            break;

        default:

            MIPS_INVAL("cp0");

            generate_exception_end(ctx, EXCP_RI);

            break;

        }

        break;

    case OPC_BOVC: /* OPC_BEQZALC, OPC_BEQC, OPC_ADDI */

        if (ctx->insn_flags & ISA_MIPS32R6) {

            /* OPC_BOVC, OPC_BEQZALC, OPC_BEQC */

            gen_compute_compact_branch(ctx, op, rs, rt, imm << 2);

        } else {

            /* OPC_ADDI */

            /* Arithmetic with immediate opcode */

            gen_arith_imm(ctx, op, rt, rs, imm);

        }

        break;

    case OPC_ADDIU:

         gen_arith_imm(ctx, op, rt, rs, imm);

         break;

    case OPC_SLTI: /* Set on less than with immediate opcode */

    case OPC_SLTIU:

         gen_slt_imm(ctx, op, rt, rs, imm);

         break;

    case OPC_ANDI: /* Arithmetic with immediate opcode */

    case OPC_LUI: /* OPC_AUI */

    case OPC_ORI:

    case OPC_XORI:

         gen_logic_imm(ctx, op, rt, rs, imm);

         break;

    case OPC_J ... OPC_JAL: /* Jump */

         offset = (int32_t)(ctx->opcode & 0x3FFFFFF) << 2;

         gen_compute_branch(ctx, op, 4, rs, rt, offset, 4);

         break;

    /* Branch */

    case OPC_BLEZC: /* OPC_BGEZC, OPC_BGEC, OPC_BLEZL */

        if (ctx->insn_flags & ISA_MIPS32R6) {

            if (rt == 0) {

                generate_exception_end(ctx, EXCP_RI);

                break;

            }

            /* OPC_BLEZC, OPC_BGEZC, OPC_BGEC */

            gen_compute_compact_branch(ctx, op, rs, rt, imm << 2);

        } else {

            /* OPC_BLEZL */

            gen_compute_branch(ctx, op, 4, rs, rt, imm << 2, 4);

        }

        break;

    case OPC_BGTZC: /* OPC_BLTZC, OPC_BLTC, OPC_BGTZL */

        if (ctx->insn_flags & ISA_MIPS32R6) {

            if (rt == 0) {

                generate_exception_end(ctx, EXCP_RI);

                break;

            }

            /* OPC_BGTZC, OPC_BLTZC, OPC_BLTC */

            gen_compute_compact_branch(ctx, op, rs, rt, imm << 2);

        } else {

            /* OPC_BGTZL */

            gen_compute_branch(ctx, op, 4, rs, rt, imm << 2, 4);

        }

        break;

    case OPC_BLEZALC: /* OPC_BGEZALC, OPC_BGEUC, OPC_BLEZ */

        if (rt == 0) {

            /* OPC_BLEZ */

            gen_compute_branch(ctx, op, 4, rs, rt, imm << 2, 4);

        } else {

            check_insn(ctx, ISA_MIPS32R6);

            /* OPC_BLEZALC, OPC_BGEZALC, OPC_BGEUC */

            gen_compute_compact_branch(ctx, op, rs, rt, imm << 2);

        }

        break;

    case OPC_BGTZALC: /* OPC_BLTZALC, OPC_BLTUC, OPC_BGTZ */

        if (rt == 0) {

            /* OPC_BGTZ */

            gen_compute_branch(ctx, op, 4, rs, rt, imm << 2, 4);

        } else {

            check_insn(ctx, ISA_MIPS32R6);

            /* OPC_BGTZALC, OPC_BLTZALC, OPC_BLTUC */

            gen_compute_compact_branch(ctx, op, rs, rt, imm << 2);

        }

        break;

    case OPC_BEQL:

    case OPC_BNEL:

        check_insn(ctx, ISA_MIPS2);

         check_insn_opc_removed(ctx, ISA_MIPS32R6);

        /* Fallthrough */

    case OPC_BEQ:

    case OPC_BNE:

         gen_compute_branch(ctx, op, 4, rs, rt, imm << 2, 4);

         break;

    case OPC_LL: /* Load and stores */

        check_insn(ctx, ISA_MIPS2);

        /* Fallthrough */

    case OPC_LWL:

    case OPC_LWR:

        check_insn_opc_removed(ctx, ISA_MIPS32R6);

         /* Fallthrough */

    case OPC_LB ... OPC_LH:

    case OPC_LW ... OPC_LHU:

         gen_ld(ctx, op, rt, rs, imm);

         break;

    case OPC_SWL:

    case OPC_SWR:

        check_insn_opc_removed(ctx, ISA_MIPS32R6);

        /* fall through */

    case OPC_SB ... OPC_SH:

    case OPC_SW:

         gen_st(ctx, op, rt, rs, imm);

         break;

    case OPC_SC:

        check_insn(ctx, ISA_MIPS2);

         check_insn_opc_removed(ctx, ISA_MIPS32R6);

         gen_st_cond(ctx, op, rt, rs, imm);

         break;

    case OPC_CACHE:

        check_insn_opc_removed(ctx, ISA_MIPS32R6);

        check_cp0_enabled(ctx);

        check_insn(ctx, ISA_MIPS3 | ISA_MIPS32);

        if (ctx->hflags & MIPS_HFLAG_ITC_CACHE) {

            gen_cache_operation(ctx, rt, rs, imm);

        }

        /* Treat as NOP. */

        break;

    case OPC_PREF:

        check_insn_opc_removed(ctx, ISA_MIPS32R6);

        check_insn(ctx, ISA_MIPS4 | ISA_MIPS32);

        /* Treat as NOP. */

        break;

    /* Floating point (COP1). */

    case OPC_LWC1:

    case OPC_LDC1:

    case OPC_SWC1:

    case OPC_SDC1:

        gen_cop1_ldst(ctx, op, rt, rs, imm);

        break;

    case OPC_CP1:

        op1 = MASK_CP1(ctx->opcode);

        switch (op1) {

        case OPC_MFHC1:

        case OPC_MTHC1:

            check_cp1_enabled(ctx);

            check_insn(ctx, ISA_MIPS32R2);

        case OPC_MFC1:

        case OPC_CFC1:

        case OPC_MTC1:

        case OPC_CTC1:

            check_cp1_enabled(ctx);

            gen_cp1(ctx, op1, rt, rd);

            break;

#if defined(TARGET_MIPS64)

        case OPC_DMFC1:

        case OPC_DMTC1:

            check_cp1_enabled(ctx);

            check_insn(ctx, ISA_MIPS3);

            check_mips_64(ctx);

            gen_cp1(ctx, op1, rt, rd);

            break;

#endif

        case OPC_BC1EQZ: /* OPC_BC1ANY2 */

            check_cp1_enabled(ctx);

            if (ctx->insn_flags & ISA_MIPS32R6) {

                /* OPC_BC1EQZ */

                gen_compute_branch1_r6(ctx, MASK_CP1(ctx->opcode),

                                       rt, imm << 2, 4);

            } else {

                /* OPC_BC1ANY2 */

                check_cop1x(ctx);

                check_insn(ctx, ASE_MIPS3D);

                gen_compute_branch1(ctx, MASK_BC1(ctx->opcode),

                                    (rt >> 2) & 0x7, imm << 2);

            }

            break;

        case OPC_BC1NEZ:

            check_cp1_enabled(ctx);

            check_insn(ctx, ISA_MIPS32R6);

            gen_compute_branch1_r6(ctx, MASK_CP1(ctx->opcode),

                                   rt, imm << 2, 4);

            break;

        case OPC_BC1ANY4:

            check_cp1_enabled(ctx);

            check_insn_opc_removed(ctx, ISA_MIPS32R6);

            check_cop1x(ctx);

            check_insn(ctx, ASE_MIPS3D);

            /* fall through */

        case OPC_BC1:

            check_cp1_enabled(ctx);

            check_insn_opc_removed(ctx, ISA_MIPS32R6);

            gen_compute_branch1(ctx, MASK_BC1(ctx->opcode),

                                (rt >> 2) & 0x7, imm << 2);

            break;

        case OPC_PS_FMT:

            check_ps(ctx);

            /* fall through */

        case OPC_S_FMT:

        case OPC_D_FMT:

            check_cp1_enabled(ctx);

            gen_farith(ctx, ctx->opcode & FOP(0x3f, 0x1f), rt, rd, sa,

                       (imm >> 8) & 0x7);

            break;

        case OPC_W_FMT:

        case OPC_L_FMT:

        {

            int r6_op = ctx->opcode & FOP(0x3f, 0x1f);

            check_cp1_enabled(ctx);

            if (ctx->insn_flags & ISA_MIPS32R6) {

                switch (r6_op) {

                case R6_OPC_CMP_AF_S:

                case R6_OPC_CMP_UN_S:

                case R6_OPC_CMP_EQ_S:

                case R6_OPC_CMP_UEQ_S:

                case R6_OPC_CMP_LT_S:

                case R6_OPC_CMP_ULT_S:

                case R6_OPC_CMP_LE_S:

                case R6_OPC_CMP_ULE_S:

                case R6_OPC_CMP_SAF_S:

                case R6_OPC_CMP_SUN_S:

                case R6_OPC_CMP_SEQ_S:

                case R6_OPC_CMP_SEUQ_S:

                case R6_OPC_CMP_SLT_S:

                case R6_OPC_CMP_SULT_S:

                case R6_OPC_CMP_SLE_S:

                case R6_OPC_CMP_SULE_S:

                case R6_OPC_CMP_OR_S:

                case R6_OPC_CMP_UNE_S:

                case R6_OPC_CMP_NE_S:

                case R6_OPC_CMP_SOR_S:

                case R6_OPC_CMP_SUNE_S:

                case R6_OPC_CMP_SNE_S:

                    gen_r6_cmp_s(ctx, ctx->opcode & 0x1f, rt, rd, sa);

                    break;

                case R6_OPC_CMP_AF_D:

                case R6_OPC_CMP_UN_D:

                case R6_OPC_CMP_EQ_D:

                case R6_OPC_CMP_UEQ_D:

                case R6_OPC_CMP_LT_D:

                case R6_OPC_CMP_ULT_D:

                case R6_OPC_CMP_LE_D:

                case R6_OPC_CMP_ULE_D:

                case R6_OPC_CMP_SAF_D:

                case R6_OPC_CMP_SUN_D:

                case R6_OPC_CMP_SEQ_D:

                case R6_OPC_CMP_SEUQ_D:

                case R6_OPC_CMP_SLT_D:

                case R6_OPC_CMP_SULT_D:

                case R6_OPC_CMP_SLE_D:

                case R6_OPC_CMP_SULE_D:

                case R6_OPC_CMP_OR_D:

                case R6_OPC_CMP_UNE_D:

                case R6_OPC_CMP_NE_D:

                case R6_OPC_CMP_SOR_D:

                case R6_OPC_CMP_SUNE_D:

                case R6_OPC_CMP_SNE_D:

                    gen_r6_cmp_d(ctx, ctx->opcode & 0x1f, rt, rd, sa);

                    break;

                default:

                    gen_farith(ctx, ctx->opcode & FOP(0x3f, 0x1f),

                               rt, rd, sa, (imm >> 8) & 0x7);

                    break;

                }

            } else {

                gen_farith(ctx, ctx->opcode & FOP(0x3f, 0x1f), rt, rd, sa,

                           (imm >> 8) & 0x7);

            }

            break;

        }

        case OPC_BZ_V:

        case OPC_BNZ_V:

        case OPC_BZ_B:

        case OPC_BZ_H:

        case OPC_BZ_W:

        case OPC_BZ_D:

        case OPC_BNZ_B:

        case OPC_BNZ_H:

        case OPC_BNZ_W:

        case OPC_BNZ_D:

            check_insn(ctx, ASE_MSA);

            gen_msa_branch(env, ctx, op1);

            break;

        default:

            MIPS_INVAL("cp1");

            generate_exception_end(ctx, EXCP_RI);

            break;

        }

        break;

    /* Compact branches [R6] and COP2 [non-R6] */

    case OPC_BC: /* OPC_LWC2 */

    case OPC_BALC: /* OPC_SWC2 */

        if (ctx->insn_flags & ISA_MIPS32R6) {

            /* OPC_BC, OPC_BALC */

            gen_compute_compact_branch(ctx, op, 0, 0,

                                       sextract32(ctx->opcode << 2, 0, 28));

        } else {

            /* OPC_LWC2, OPC_SWC2 */

            /* COP2: Not implemented. */

            generate_exception_err(ctx, EXCP_CpU, 2);

        }

        break;

    case OPC_BEQZC: /* OPC_JIC, OPC_LDC2 */

    case OPC_BNEZC: /* OPC_JIALC, OPC_SDC2 */

        if (ctx->insn_flags & ISA_MIPS32R6) {

            if (rs != 0) {

                /* OPC_BEQZC, OPC_BNEZC */

                gen_compute_compact_branch(ctx, op, rs, 0,

                                           sextract32(ctx->opcode << 2, 0, 23));

            } else {

                /* OPC_JIC, OPC_JIALC */

                gen_compute_compact_branch(ctx, op, 0, rt, imm);

            }

        } else {

            /* OPC_LWC2, OPC_SWC2 */

            /* COP2: Not implemented. */

            generate_exception_err(ctx, EXCP_CpU, 2);

        }

        break;

    case OPC_CP2:

        check_insn(ctx, INSN_LOONGSON2F);

        /* Note that these instructions use different fields.  */

        gen_loongson_multimedia(ctx, sa, rd, rt);

        break;

    case OPC_CP3:

        check_insn_opc_removed(ctx, ISA_MIPS32R6);

        if (ctx->CP0_Config1 & (1 << CP0C1_FP)) {

            check_cp1_enabled(ctx);

            op1 = MASK_CP3(ctx->opcode);

            switch (op1) {

            case OPC_LUXC1:

            case OPC_SUXC1:

                check_insn(ctx, ISA_MIPS5 | ISA_MIPS32R2);

                /* Fallthrough */

            case OPC_LWXC1:

            case OPC_LDXC1:

            case OPC_SWXC1:

            case OPC_SDXC1:

                check_insn(ctx, ISA_MIPS4 | ISA_MIPS32R2);

                gen_flt3_ldst(ctx, op1, sa, rd, rs, rt);

                break;

            case OPC_PREFX:

                check_insn(ctx, ISA_MIPS4 | ISA_MIPS32R2);

                /* Treat as NOP. */

                break;

            case OPC_ALNV_PS:

                check_insn(ctx, ISA_MIPS5 | ISA_MIPS32R2);

                /* Fallthrough */

            case OPC_MADD_S:

            case OPC_MADD_D:

            case OPC_MADD_PS:

            case OPC_MSUB_S:

            case OPC_MSUB_D:

            case OPC_MSUB_PS:

            case OPC_NMADD_S:

            case OPC_NMADD_D:

            case OPC_NMADD_PS:

            case OPC_NMSUB_S:

            case OPC_NMSUB_D:

            case OPC_NMSUB_PS:

                check_insn(ctx, ISA_MIPS4 | ISA_MIPS32R2);

                gen_flt3_arith(ctx, op1, sa, rs, rd, rt);

                break;

            default:

                MIPS_INVAL("cp3");

                generate_exception_end(ctx, EXCP_RI);

                break;

            }

        } else {

            generate_exception_err(ctx, EXCP_CpU, 1);

        }

        break;

#if defined(TARGET_MIPS64)

    /* MIPS64 opcodes */

    case OPC_LDL ... OPC_LDR:

    case OPC_LLD:

        check_insn_opc_removed(ctx, ISA_MIPS32R6);

        /* fall through */

    case OPC_LWU:

    case OPC_LD:

        check_insn(ctx, ISA_MIPS3);

        check_mips_64(ctx);

        gen_ld(ctx, op, rt, rs, imm);

        break;

    case OPC_SDL ... OPC_SDR:

        check_insn_opc_removed(ctx, ISA_MIPS32R6);

        /* fall through */

    case OPC_SD:

        check_insn(ctx, ISA_MIPS3);

        check_mips_64(ctx);

        gen_st(ctx, op, rt, rs, imm);

        break;

    case OPC_SCD:

        check_insn_opc_removed(ctx, ISA_MIPS32R6);

        check_insn(ctx, ISA_MIPS3);

        check_mips_64(ctx);

        gen_st_cond(ctx, op, rt, rs, imm);

        break;

    case OPC_BNVC: /* OPC_BNEZALC, OPC_BNEC, OPC_DADDI */

        if (ctx->insn_flags & ISA_MIPS32R6) {

            /* OPC_BNVC, OPC_BNEZALC, OPC_BNEC */

            gen_compute_compact_branch(ctx, op, rs, rt, imm << 2);

        } else {

            /* OPC_DADDI */

            check_insn(ctx, ISA_MIPS3);

            check_mips_64(ctx);

            gen_arith_imm(ctx, op, rt, rs, imm);

        }

        break;

    case OPC_DADDIU:

        check_insn(ctx, ISA_MIPS3);

        check_mips_64(ctx);

        gen_arith_imm(ctx, op, rt, rs, imm);

        break;

#else

    case OPC_BNVC: /* OPC_BNEZALC, OPC_BNEC */

        if (ctx->insn_flags & ISA_MIPS32R6) {

            gen_compute_compact_branch(ctx, op, rs, rt, imm << 2);

        } else {

            MIPS_INVAL("major opcode");

            generate_exception_end(ctx, EXCP_RI);

        }

        break;

#endif

    case OPC_DAUI: /* OPC_JALX */

        if (ctx->insn_flags & ISA_MIPS32R6) {

#if defined(TARGET_MIPS64)

            /* OPC_DAUI */

            check_mips_64(ctx);

            if (rs == 0) {

                generate_exception(ctx, EXCP_RI);

            } else if (rt != 0) {

                TCGv t0 = tcg_temp_new();

                gen_load_gpr(t0, rs);

                tcg_gen_addi_tl(cpu_gpr[rt], t0, imm << 16);

                tcg_temp_free(t0);

            }

#else

            generate_exception_end(ctx, EXCP_RI);

            MIPS_INVAL("major opcode");

#endif

        } else {

            /* OPC_JALX */

            check_insn(ctx, ASE_MIPS16 | ASE_MICROMIPS);

            offset = (int32_t)(ctx->opcode & 0x3FFFFFF) << 2;

            gen_compute_branch(ctx, op, 4, rs, rt, offset, 4);

        }

        break;

    case OPC_MSA: /* OPC_MDMX */

        /* MDMX: Not implemented. */

        gen_msa(env, ctx);

        break;

    case OPC_PCREL:

        check_insn(ctx, ISA_MIPS32R6);

        gen_pcrel(ctx, ctx->opcode, ctx->pc, rs);

        break;

    default:            /* Invalid */

        MIPS_INVAL("major opcode");

        generate_exception_end(ctx, EXCP_RI);

        break;

    }

}


static int mpegts_read_header(AVFormatContext *s,

                              AVFormatParameters *ap)

{

    MpegTSContext *ts = s->priv_data;

    AVIOContext *pb = s->pb;

    uint8_t buf[5*1024];

    int len;

    int64_t pos;

#if FF_API_FORMAT_PARAMETERS

    if (ap) {

        if (ap->mpeg2ts_compute_pcr)

            ts->mpeg2ts_compute_pcr = ap->mpeg2ts_compute_pcr;

        if(ap->mpeg2ts_raw){

            av_log(s, AV_LOG_ERROR, "use mpegtsraw_demuxer!\n");

            return -1;

        }

    }

#endif

    /* read the first 1024 bytes to get packet size */

    pos = avio_tell(pb);

    len = avio_read(pb, buf, sizeof(buf));

    if (len != sizeof(buf))

        goto fail;

    ts->raw_packet_size = get_packet_size(buf, sizeof(buf));

    if (ts->raw_packet_size <= 0)

        goto fail;

    ts->stream = s;

    ts->auto_guess = 0;

    if (s->iformat == &ff_mpegts_demuxer) {

        /* normal demux */

        /* first do a scaning to get all the services */

        if (avio_seek(pb, pos, SEEK_SET) < 0)

            av_log(s, AV_LOG_ERROR, "Unable to seek back to the start\n");

        mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1);

        mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1);

        handle_packets(ts, s->probesize / ts->raw_packet_size);

        /* if could not find service, enable auto_guess */

        ts->auto_guess = 1;

        av_dlog(ts->stream, "tuning done\n");

        s->ctx_flags |= AVFMTCTX_NOHEADER;

    } else {

        AVStream *st;

        int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l;

        int64_t pcrs[2], pcr_h;

        int packet_count[2];

        uint8_t packet[TS_PACKET_SIZE];

        /* only read packets */

        st = av_new_stream(s, 0);

        if (!st)

            goto fail;

        av_set_pts_info(st, 60, 1, 27000000);

        st->codec->codec_type = AVMEDIA_TYPE_DATA;

        st->codec->codec_id = CODEC_ID_MPEG2TS;

        /* we iterate until we find two PCRs to estimate the bitrate */

        pcr_pid = -1;

        nb_pcrs = 0;

        nb_packets = 0;

        for(;;) {

            ret = read_packet(s, packet, ts->raw_packet_size);

            if (ret < 0)

                return -1;

            pid = AV_RB16(packet + 1) & 0x1fff;

            if ((pcr_pid == -1 || pcr_pid == pid) &&

                parse_pcr(&pcr_h, &pcr_l, packet) == 0) {

                pcr_pid = pid;

                packet_count[nb_pcrs] = nb_packets;

                pcrs[nb_pcrs] = pcr_h * 300 + pcr_l;

                nb_pcrs++;

                if (nb_pcrs >= 2)

                    break;

            }

            nb_packets++;

        }

        /* NOTE1: the bitrate is computed without the FEC */

        /* NOTE2: it is only the bitrate of the start of the stream */

        ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]);

        ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0];

        s->bit_rate = (TS_PACKET_SIZE * 8) * 27e6 / ts->pcr_incr;

        st->codec->bit_rate = s->bit_rate;

        st->start_time = ts->cur_pcr;

        av_dlog(ts->stream, "start=%0.3f pcr=%0.3f incr=%d\n",

                st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr);

    }

    avio_seek(pb, pos, SEEK_SET);

    return 0;

 fail:

    return -1;

}


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

{

    DeviceClass *dc = DEVICE_CLASS(oc);

    dc->no_user = 1;

    dc->vmsd = &vmstate_pl080;

}


static void guest_panicked(void)

{

    QObject *data;

    data = qobject_from_jsonf("{ 'action': %s }", "pause");

    monitor_protocol_event(QEVENT_GUEST_PANICKED, data);

    qobject_decref(data);

    vm_stop(RUN_STATE_GUEST_PANICKED);

}


void vnc_init_state(VncState *vs)

{

    vs->initialized = true;

    VncDisplay *vd = vs->vd;

    vs->last_x = -1;

    vs->last_y = -1;

    vs->as.freq = 44100;

    vs->as.nchannels = 2;

    vs->as.fmt = AUD_FMT_S16;

    vs->as.endianness = 0;

    qemu_mutex_init(&vs->output_mutex);

    vs->bh = qemu_bh_new(vnc_jobs_bh, vs);

    QTAILQ_INSERT_HEAD(&vd->clients, vs, next);

    graphic_hw_update(vd->dcl.con);

    vnc_write(vs, "RFB 003.008\n", 12);

    vnc_flush(vs);

    vnc_read_when(vs, protocol_version, 12);

    reset_keys(vs);

    if (vs->vd->lock_key_sync)

        vs->led = qemu_add_led_event_handler(kbd_leds, vs);

    vs->mouse_mode_notifier.notify = check_pointer_type_change;

    qemu_add_mouse_mode_change_notifier(&vs->mouse_mode_notifier);

    /* vs might be free()ed here */

}


static void puv3_load_kernel(const char *kernel_filename)

{

    int size;

    if (kernel_filename == NULL && qtest_enabled()) {

        return;

    }

    assert(kernel_filename != NULL);

    /* only zImage format supported */

    size = load_image_targphys(kernel_filename, KERNEL_LOAD_ADDR,

            KERNEL_MAX_SIZE);

    if (size < 0) {

        error_report("Load kernel error: '%s'", kernel_filename);

        exit(1);

    }

    /* cheat curses that we have a graphic console, only under ocd console */

    graphic_console_init(NULL, 0, &no_ops, NULL);

}


static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom)

{

    AVStream *st;

    MOVStreamContext *sc;

    int entries, i, j;

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

        return 0;

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

    sc = st->priv_data;

    avio_rb32(pb); // version + flags

    entries = avio_rb32(pb);

    if (entries >  (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 ||

        entries >= UINT_MAX / sizeof(*sc->drefs))

        return AVERROR_INVALIDDATA;

    av_free(sc->drefs);

    sc->drefs_count = 0;

    sc->drefs = av_mallocz(entries * sizeof(*sc->drefs));

    if (!sc->drefs)

        return AVERROR(ENOMEM);

    sc->drefs_count = entries;

    for (i = 0; i < sc->drefs_count; i++) {

        MOVDref *dref = &sc->drefs[i];

        uint32_t size = avio_rb32(pb);

        int64_t next = avio_tell(pb) + size - 4;

        if (size < 12)

            return AVERROR_INVALIDDATA;

        dref->type = avio_rl32(pb);

        avio_rb32(pb); // version + flags

        av_dlog(c->fc, "type %.4s size %d\n", (char*)&dref->type, size);

        if (dref->type == MKTAG('a','l','i','s') && size > 150) {

            /* macintosh alias record */

            uint16_t volume_len, len;

            int16_t type;

            avio_skip(pb, 10);

            volume_len = avio_r8(pb);

            volume_len = FFMIN(volume_len, 27);

            avio_read(pb, dref->volume, 27);

            dref->volume[volume_len] = 0;

            av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len);

            avio_skip(pb, 12);

            len = avio_r8(pb);

            len = FFMIN(len, 63);

            avio_read(pb, dref->filename, 63);

            dref->filename[len] = 0;

            av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len);

            avio_skip(pb, 16);

            /* read next level up_from_alias/down_to_target */

            dref->nlvl_from = avio_rb16(pb);

            dref->nlvl_to   = avio_rb16(pb);

            av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n",

                   dref->nlvl_from, dref->nlvl_to);

            avio_skip(pb, 16);

            for (type = 0; type != -1 && avio_tell(pb) < next; ) {

                if(url_feof(pb))

                    return AVERROR_EOF;

                type = avio_rb16(pb);

                len = avio_rb16(pb);

                av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len);

                if (len&1)

                    len += 1;

                if (type == 2) { // absolute path

                    av_free(dref->path);

                    dref->path = av_mallocz(len+1);

                    if (!dref->path)

                        return AVERROR(ENOMEM);

                    avio_read(pb, dref->path, len);

                    if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) {

                        len -= volume_len;

                        memmove(dref->path, dref->path+volume_len, len);

                        dref->path[len] = 0;

                    }

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

                        if (dref->path[j] == ':')

                            dref->path[j] = '/';

                    av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path);

                } else if (type == 0) { // directory name

                    av_free(dref->dir);

                    dref->dir = av_malloc(len+1);

                    if (!dref->dir)

                        return AVERROR(ENOMEM);

                    avio_read(pb, dref->dir, len);

                    dref->dir[len] = 0;

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

                        if (dref->dir[j] == ':')

                            dref->dir[j] = '/';

                    av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir);

                } else

                    avio_skip(pb, len);

            }

        }

        avio_seek(pb, next, SEEK_SET);

    }

    return 0;

}


static void init_blk_migration(QEMUFile *f)

{

    BlockDriverState *bs;

    BlkMigDevState *bmds;

    int64_t sectors;

    block_mig_state.submitted = 0;

    block_mig_state.read_done = 0;

    block_mig_state.transferred = 0;

    block_mig_state.total_sector_sum = 0;

    block_mig_state.prev_progress = -1;

    block_mig_state.bulk_completed = 0;

    block_mig_state.zero_blocks = migrate_zero_blocks();

    for (bs = bdrv_next(NULL); bs; bs = bdrv_next(bs)) {

        if (bdrv_is_read_only(bs)) {

            continue;

        }

        sectors = bdrv_nb_sectors(bs);

        if (sectors <= 0) {

            return;

        }

        bmds = g_new0(BlkMigDevState, 1);

        bmds->bs = bs;

        bmds->bulk_completed = 0;

        bmds->total_sectors = sectors;

        bmds->completed_sectors = 0;

        bmds->shared_base = block_mig_state.shared_base;

        alloc_aio_bitmap(bmds);

        error_setg(&bmds->blocker, "block device is in use by migration");

        bdrv_op_block_all(bs, bmds->blocker);

        bdrv_ref(bs);

        block_mig_state.total_sector_sum += sectors;

        if (bmds->shared_base) {

            DPRINTF("Start migration for %s with shared base image\n",

                    bdrv_get_device_name(bs));

        } else {

            DPRINTF("Start full migration for %s\n", bdrv_get_device_name(bs));

        }

        QSIMPLEQ_INSERT_TAIL(&block_mig_state.bmds_list, bmds, entry);

    }

}


int ff_pulse_audio_get_devices(AVDeviceInfoList *devices, const char *server, int output)

{

    pa_mainloop *pa_ml = NULL;

    pa_mainloop_api *pa_mlapi = NULL;

    pa_operation *pa_op = NULL;

    pa_context *pa_ctx = NULL;

    enum pa_operation_state op_state;

    enum PulseAudioContextState loop_state = PULSE_CONTEXT_INITIALIZING;

    PulseAudioDeviceList dev_list = { 0 };

    int i;

    dev_list.output = output;

    dev_list.devices = devices;

    if (!devices)

        return AVERROR(EINVAL);

    devices->nb_devices = 0;

    devices->devices = NULL;

    if (!(pa_ml = pa_mainloop_new()))

        return AVERROR(ENOMEM);

    if (!(pa_mlapi = pa_mainloop_get_api(pa_ml))) {

        dev_list.error_code = AVERROR_EXTERNAL;

        goto fail;

    }

    if (!(pa_ctx = pa_context_new(pa_mlapi, "Query devices"))) {

        dev_list.error_code = AVERROR(ENOMEM);

        goto fail;

    }

    pa_context_set_state_callback(pa_ctx, pa_state_cb, &loop_state);

    if (pa_context_connect(pa_ctx, server, 0, NULL) < 0) {

        dev_list.error_code = AVERROR_EXTERNAL;

        goto fail;

    }

    while (loop_state == PULSE_CONTEXT_INITIALIZING)

        pa_mainloop_iterate(pa_ml, 1, NULL);

    if (loop_state == PULSE_CONTEXT_FINISHED) {

        dev_list.error_code = AVERROR_EXTERNAL;

        goto fail;

    }

    if (output)

        pa_op = pa_context_get_sink_info_list(pa_ctx, pulse_audio_sink_device_cb, &dev_list);

    else

        pa_op = pa_context_get_source_info_list(pa_ctx, pulse_audio_source_device_cb, &dev_list);

    while ((op_state = pa_operation_get_state(pa_op)) == PA_OPERATION_RUNNING)

        pa_mainloop_iterate(pa_ml, 1, NULL);

    if (op_state != PA_OPERATION_DONE)

        dev_list.error_code = AVERROR_EXTERNAL;

    pa_operation_unref(pa_op);

    if (dev_list.error_code < 0)

        goto fail;

    pa_op = pa_context_get_server_info(pa_ctx, pulse_server_info_cb, &dev_list);

    while ((op_state = pa_operation_get_state(pa_op)) == PA_OPERATION_RUNNING)

        pa_mainloop_iterate(pa_ml, 1, NULL);

    if (op_state != PA_OPERATION_DONE)

        dev_list.error_code = AVERROR_EXTERNAL;

    pa_operation_unref(pa_op);

    if (dev_list.error_code < 0)

        goto fail;

    devices->default_device = -1;

    for (i = 0; i < devices->nb_devices; i++) {

        if (!strcmp(devices->devices[i]->device_name, dev_list.default_device)) {

            devices->default_device = i;

            break;

        }

    }

  fail:

    av_free(dev_list.default_device);

    if(pa_ctx)

        pa_context_disconnect(pa_ctx);

    if (pa_ctx)

        pa_context_unref(pa_ctx);

    if (pa_ml)

        pa_mainloop_free(pa_ml);

    return dev_list.error_code;

}


void virtio_scsi_dataplane_stop(VirtIOSCSI *s)

{

    BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(s)));

    VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);

    VirtIODevice *vdev = VIRTIO_DEVICE(s);

    VirtIOSCSICommon *vs = VIRTIO_SCSI_COMMON(s);

    int i;

    if (!s->dataplane_started || s->dataplane_stopping) {

        return;

    }

    error_free(s->blocker);

    s->blocker = NULL;

    s->dataplane_stopping = true;

    assert(s->ctx == iothread_get_aio_context(vs->conf.iothread));

    aio_context_acquire(s->ctx);

    aio_set_event_notifier(s->ctx, &s->ctrl_vring->host_notifier, NULL);

    aio_set_event_notifier(s->ctx, &s->event_vring->host_notifier, NULL);

    for (i = 0; i < vs->conf.num_queues; i++) {

        aio_set_event_notifier(s->ctx, &s->cmd_vrings[i]->host_notifier, NULL);

    }

    blk_drain_all(); /* ensure there are no in-flight requests */

    aio_context_release(s->ctx);

    /* Sync vring state back to virtqueue so that non-dataplane request

     * processing can continue when we disable the host notifier below.

     */

    vring_teardown(&s->ctrl_vring->vring, vdev, 0);

    vring_teardown(&s->event_vring->vring, vdev, 1);

    for (i = 0; i < vs->conf.num_queues; i++) {

        vring_teardown(&s->cmd_vrings[i]->vring, vdev, 2 + i);

    }

    for (i = 0; i < vs->conf.num_queues + 2; i++) {

        k->set_host_notifier(qbus->parent, i, false);

    }

    /* Clean up guest notifier (irq) */

    k->set_guest_notifiers(qbus->parent, vs->conf.num_queues + 2, false);

    s->dataplane_stopping = false;

    s->dataplane_started = false;

}


static void fw_cfg_boot_set(void *opaque, const char *boot_device,

                            Error **errp)

{

    fw_cfg_add_i16(opaque, FW_CFG_BOOT_DEVICE, boot_device[0]);

}


static int vhost_sync_dirty_bitmap(struct vhost_dev *dev,

                                   MemoryRegionSection *section,

                                   hwaddr start_addr,

                                   hwaddr end_addr)

{

    int i;

    if (!dev->log_enabled || !dev->started) {

        return 0;

    }

    for (i = 0; i < dev->mem->nregions; ++i) {

        struct vhost_memory_region *reg = dev->mem->regions + i;

        vhost_dev_sync_region(dev, section, start_addr, end_addr,

                              reg->guest_phys_addr,

                              range_get_last(reg->guest_phys_addr,

                                             reg->memory_size));

    }

    for (i = 0; i < dev->nvqs; ++i) {

        struct vhost_virtqueue *vq = dev->vqs + i;

        vhost_dev_sync_region(dev, section, start_addr, end_addr, vq->used_phys,

                              range_get_last(vq->used_phys, vq->used_size));

    }

    return 0;

}


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

{

    DeviceClass *dc = DEVICE_CLASS(oc);

    CPUClass *cc = CPU_CLASS(oc);

    CRISCPUClass *ccc = CRIS_CPU_CLASS(oc);

    ccc->parent_realize = dc->realize;

    dc->realize = cris_cpu_realizefn;

    ccc->parent_reset = cc->reset;

    cc->reset = cris_cpu_reset;

    cc->class_by_name = cris_cpu_class_by_name;

    cc->has_work = cris_cpu_has_work;

    cc->do_interrupt = cris_cpu_do_interrupt;

    cc->cpu_exec_interrupt = cris_cpu_exec_interrupt;

    cc->dump_state = cris_cpu_dump_state;

    cc->set_pc = cris_cpu_set_pc;

    cc->gdb_read_register = cris_cpu_gdb_read_register;

    cc->gdb_write_register = cris_cpu_gdb_write_register;

#ifdef CONFIG_USER_ONLY

    cc->handle_mmu_fault = cris_cpu_handle_mmu_fault;

#else

    cc->get_phys_page_debug = cris_cpu_get_phys_page_debug;

    dc->vmsd = &vmstate_cris_cpu;

#endif

    cc->gdb_num_core_regs = 49;

    cc->gdb_stop_before_watchpoint = true;

    cc->disas_set_info = cris_disas_set_info;

    /*

     * Reason: cris_cpu_initfn() calls cpu_exec_init(), which saves

     * the object in cpus -> dangling pointer after final

     * object_unref().

     */

    dc->cannot_destroy_with_object_finalize_yet = true;

}


static void blk_mig_lock(void)

{

    qemu_mutex_lock(&block_mig_state.lock);

}


bool kvmppc_is_mem_backend_page_size_ok(const char *obj_path)

{

    Object *mem_obj = object_resolve_path(obj_path, NULL);

    char *mempath = object_property_get_str(mem_obj, "mem-path", NULL);

    long pagesize;

    if (mempath) {

        pagesize = qemu_mempath_getpagesize(mempath);

    } else {

        pagesize = getpagesize();

    }

    return pagesize >= max_cpu_page_size;

}


void helper_ldqf(CPUSPARCState *env, target_ulong addr, int mem_idx)

{

    /* XXX add 128 bit load */

    CPU_QuadU u;

    helper_check_align(env, addr, 7);

#if !defined(CONFIG_USER_ONLY)

    switch (mem_idx) {

    case MMU_USER_IDX:

        u.ll.upper = cpu_ldq_user(env, addr);

        u.ll.lower = cpu_ldq_user(env, addr + 8);

        QT0 = u.q;

        break;

    case MMU_KERNEL_IDX:

        u.ll.upper = cpu_ldq_kernel(env, addr);

        u.ll.lower = cpu_ldq_kernel(env, addr + 8);

        QT0 = u.q;

        break;

#ifdef TARGET_SPARC64

    case MMU_HYPV_IDX:

        u.ll.upper = cpu_ldq_hypv(env, addr);

        u.ll.lower = cpu_ldq_hypv(env, addr + 8);

        QT0 = u.q;

        break;

#endif

    default:

        DPRINTF_MMU("helper_ldqf: need to check MMU idx %d\n", mem_idx);

        break;

    }

#else

    u.ll.upper = ldq_raw(address_mask(env, addr));

    u.ll.lower = ldq_raw(address_mask(env, addr + 8));

    QT0 = u.q;

#endif

}


static void allocate_buffers(ALACContext *alac)

{

    int chan;

    for (chan = 0; chan < alac->numchannels; chan++) {

        alac->predicterror_buffer[chan] =

            av_malloc(alac->setinfo_max_samples_per_frame * 4);

        alac->outputsamples_buffer[chan] =

            av_malloc(alac->setinfo_max_samples_per_frame * 4);

        alac->wasted_bits_buffer[chan] = av_malloc(alac->setinfo_max_samples_per_frame * 4);

    }

}