x11grab_read_header(AVFormatContext *s1, AVFormatParameters *ap)

{

    struct x11_grab *x11grab = s1->priv_data;

    Display *dpy;

    AVStream *st = NULL;

    enum PixelFormat input_pixfmt;

    XImage *image;

    int x_off = 0;

    int y_off = 0;

    int use_shm;

    char *param, *offset;

    int ret = 0;

    AVRational framerate;

    param = av_strdup(s1->filename);

    offset = strchr(param, '+');

    if (offset) {

        sscanf(offset, "%d,%d", &x_off, &y_off);

        x11grab->nomouse= strstr(offset, "nomouse");

        *offset= 0;

    }

    if ((ret = av_parse_video_size(&x11grab->width, &x11grab->height, x11grab->video_size)) < 0) {

        av_log(s1, AV_LOG_ERROR, "Couldn't parse video size.\n");

        goto out;

    }

    if ((ret = av_parse_video_rate(&framerate, x11grab->framerate)) < 0) {

        av_log(s1, AV_LOG_ERROR, "Could not parse framerate: %s.\n", x11grab->framerate);

        goto out;

    }

#if FF_API_FORMAT_PARAMETERS

    if (ap->width > 0)

        x11grab->width = ap->width;

    if (ap->height > 0)

        x11grab->height = ap->height;

    if (ap->time_base.num)

        framerate = (AVRational){ap->time_base.den, ap->time_base.num};

#endif

    av_log(s1, AV_LOG_INFO, "device: %s -> display: %s x: %d y: %d width: %d height: %d\n",

           s1->filename, param, x_off, y_off, x11grab->width, x11grab->height);

    dpy = XOpenDisplay(param);

    if(!dpy) {

        av_log(s1, AV_LOG_ERROR, "Could not open X display.\n");

        ret = AVERROR(EIO);

        goto out;

    }

    st = av_new_stream(s1, 0);

    if (!st) {

        ret = AVERROR(ENOMEM);

        goto out;

    }

    av_set_pts_info(st, 64, 1, 1000000); /* 64 bits pts in us */

    use_shm = XShmQueryExtension(dpy);

    av_log(s1, AV_LOG_INFO, "shared memory extension %s found\n", use_shm ? "" : "not");

    if(use_shm) {

        int scr = XDefaultScreen(dpy);

        image = XShmCreateImage(dpy,

                                DefaultVisual(dpy, scr),

                                DefaultDepth(dpy, scr),

                                ZPixmap,

                                NULL,

                                &x11grab->shminfo,

                                x11grab->width, x11grab->height);

        x11grab->shminfo.shmid = shmget(IPC_PRIVATE,

                                        image->bytes_per_line * image->height,

                                        IPC_CREAT|0777);

        if (x11grab->shminfo.shmid == -1) {

            av_log(s1, AV_LOG_ERROR, "Fatal: Can't get shared memory!\n");

            ret = AVERROR(ENOMEM);

            goto out;

        }

        x11grab->shminfo.shmaddr = image->data = shmat(x11grab->shminfo.shmid, 0, 0);

        x11grab->shminfo.readOnly = False;

        if (!XShmAttach(dpy, &x11grab->shminfo)) {

            av_log(s1, AV_LOG_ERROR, "Fatal: Failed to attach shared memory!\n");

            /* needs some better error subroutine :) */

            ret = AVERROR(EIO);

            goto out;

        }

    } else {

        image = XGetImage(dpy, RootWindow(dpy, DefaultScreen(dpy)),

                          x_off,y_off,

                          x11grab->width, x11grab->height,

                          AllPlanes, ZPixmap);

    }

    switch (image->bits_per_pixel) {

    case 8:

        av_log (s1, AV_LOG_DEBUG, "8 bit palette\n");

        input_pixfmt = PIX_FMT_PAL8;

        break;

    case 16:

        if (       image->red_mask   == 0xf800 &&

                   image->green_mask == 0x07e0 &&

                   image->blue_mask  == 0x001f ) {

            av_log (s1, AV_LOG_DEBUG, "16 bit RGB565\n");

            input_pixfmt = PIX_FMT_RGB565;

        } else if (image->red_mask   == 0x7c00 &&

                   image->green_mask == 0x03e0 &&

                   image->blue_mask  == 0x001f ) {

            av_log(s1, AV_LOG_DEBUG, "16 bit RGB555\n");

            input_pixfmt = PIX_FMT_RGB555;

        } else {

            av_log(s1, AV_LOG_ERROR, "RGB ordering at image depth %i not supported ... aborting\n", image->bits_per_pixel);

            av_log(s1, AV_LOG_ERROR, "color masks: r 0x%.6lx g 0x%.6lx b 0x%.6lx\n", image->red_mask, image->green_mask, image->blue_mask);

            ret = AVERROR(EIO);

            goto out;

        }

        break;

    case 24:

        if (        image->red_mask   == 0xff0000 &&

                    image->green_mask == 0x00ff00 &&

                    image->blue_mask  == 0x0000ff ) {

            input_pixfmt = PIX_FMT_BGR24;

        } else if ( image->red_mask   == 0x0000ff &&

                    image->green_mask == 0x00ff00 &&

                    image->blue_mask  == 0xff0000 ) {

            input_pixfmt = PIX_FMT_RGB24;

        } else {

            av_log(s1, AV_LOG_ERROR,"rgb ordering at image depth %i not supported ... aborting\n", image->bits_per_pixel);

            av_log(s1, AV_LOG_ERROR, "color masks: r 0x%.6lx g 0x%.6lx b 0x%.6lx\n", image->red_mask, image->green_mask, image->blue_mask);

            ret = AVERROR(EIO);

            goto out;

        }

        break;

    case 32:

        input_pixfmt = PIX_FMT_RGB32;

        break;

    default:

        av_log(s1, AV_LOG_ERROR, "image depth %i not supported ... aborting\n", image->bits_per_pixel);

        ret = AVERROR(EINVAL);

        goto out;

    }

    x11grab->frame_size = x11grab->width * x11grab->height * image->bits_per_pixel/8;

    x11grab->dpy = dpy;

    x11grab->time_base  = (AVRational){framerate.den, framerate.num};

    x11grab->time_frame = av_gettime() / av_q2d(x11grab->time_base);

    x11grab->x_off = x_off;

    x11grab->y_off = y_off;

    x11grab->image = image;

    x11grab->use_shm = use_shm;

    st->codec->codec_type = AVMEDIA_TYPE_VIDEO;

    st->codec->codec_id = CODEC_ID_RAWVIDEO;

    st->codec->width  = x11grab->width;

    st->codec->height = x11grab->height;

    st->codec->pix_fmt = input_pixfmt;

    st->codec->time_base = x11grab->time_base;

    st->codec->bit_rate = x11grab->frame_size * 1/av_q2d(x11grab->time_base) * 8;

out:

    return ret;

}


static void simple_list(void)

{

    int i;

    struct {

        const char *encoded;

        LiteralQObject decoded;

    } test_cases[] = {

        {

            .encoded = "[43,42]",

            .decoded = QLIT_QLIST(((LiteralQObject[]){

                        QLIT_QINT(43),

                        QLIT_QINT(42),

                        { }

                    })),

        },

        {

            .encoded = "[43]",

            .decoded = QLIT_QLIST(((LiteralQObject[]){

                        QLIT_QINT(43),

                        { }

                    })),

        },

        {

            .encoded = "[]",

            .decoded = QLIT_QLIST(((LiteralQObject[]){

                        { }

                    })),

        },

        {

            .encoded = "[{}]",

            .decoded = QLIT_QLIST(((LiteralQObject[]){

                        QLIT_QDICT(((LiteralQDictEntry[]){

                                    {},

                                        })),

                        {},

                            })),

        },

        { }

    };

    for (i = 0; test_cases[i].encoded; i++) {

        QObject *obj;

        QString *str;

        obj = qobject_from_json(test_cases[i].encoded, NULL);

        g_assert(compare_litqobj_to_qobj(&test_cases[i].decoded, obj) == 1);

        str = qobject_to_json(obj);

        qobject_decref(obj);

        obj = qobject_from_json(qstring_get_str(str), NULL);

        g_assert(compare_litqobj_to_qobj(&test_cases[i].decoded, obj) == 1);

        qobject_decref(obj);

        QDECREF(str);

    }

}


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

                                         const uint16_t *ubuf0, const uint16_t *ubuf1,

                                         const uint16_t *vbuf0, const uint16_t *vbuf1,

                                         const uint16_t *abuf0, uint8_t *dest,

                                         int dstW, int uvalpha, enum PixelFormat dstFormat,

                                         int flags, int y)

{

    x86_reg uv_off = c->uv_off << 1;

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

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

        __asm__ volatile(

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

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

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

            YSCALEYUV2PACKED1(%%REGBP, %5, %6)

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

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

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

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

               "a" (&c->redDither), "m"(uv_off)

        );

    } else {

        __asm__ volatile(

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

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

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

            YSCALEYUV2PACKED1b(%%REGBP, %5, %6)

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

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

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

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

               "a" (&c->redDither), "m"(uv_off)

        );

    }

}


static void tcp_wait_for_connect(void *opaque)

{

    MigrationState *s = opaque;

    int val, ret;

    socklen_t valsize = sizeof(val);

    DPRINTF("connect completed\n");

    do {

        ret = getsockopt(s->fd, SOL_SOCKET, SO_ERROR, (void *) &val, &valsize);

    } while (ret == -1 && (socket_error()) == EINTR);

    if (ret < 0) {

        migrate_fd_error(s);

        return;

    }

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

    if (val == 0)

        migrate_fd_connect(s);

    else {

        DPRINTF("error connecting %d\n", val);

        migrate_fd_error(s);

    }

}


static int ipvideo_decode_block_opcode_0x4(IpvideoContext *s)

{

    int x, y;

    unsigned char B, BL, BH;

    /* copy a block from the previous frame; need 1 more byte */

    CHECK_STREAM_PTR(1);

    B = *s->stream_ptr++;

    BL = B & 0x0F;

    BH = (B >> 4) & 0x0F;

    x = -8 + BL;

    y = -8 + BH;

    debug_interplay ("    motion byte = %d, (x, y) = (%d, %d)\n", B, x, y);

    return copy_from(s, &s->last_frame, x, y);

}


static int open_input_stream(HTTPContext *c, const char *info)

{

    char buf[128];

    char input_filename[1024];

    AVFormatContext *s;

    int buf_size, i, ret;

    int64_t stream_pos;

    /* find file name */

    if (c->stream->feed) {

        strcpy(input_filename, c->stream->feed->feed_filename);

        buf_size = FFM_PACKET_SIZE;

        /* compute position (absolute time) */

        if (find_info_tag(buf, sizeof(buf), "date", info)) {

            stream_pos = parse_date(buf, 0);

            if (stream_pos == INT64_MIN)

                return -1;

        } else if (find_info_tag(buf, sizeof(buf), "buffer", info)) {

            int prebuffer = strtol(buf, 0, 10);

            stream_pos = av_gettime() - prebuffer * (int64_t)1000000;

        } else

            stream_pos = av_gettime() - c->stream->prebuffer * (int64_t)1000;

    } else {

        strcpy(input_filename, c->stream->feed_filename);

        buf_size = 0;

        /* compute position (relative time) */

        if (find_info_tag(buf, sizeof(buf), "date", info)) {

            stream_pos = parse_date(buf, 1);

            if (stream_pos == INT64_MIN)

                return -1;

        } else

            stream_pos = 0;

    }

    if (input_filename[0] == '\0')

        return -1;

#if 0

    { time_t when = stream_pos / 1000000;

    http_log("Stream pos = %"PRId64", time=%s", stream_pos, ctime(&when));

    }

#endif

    /* open stream */

    if ((ret = av_open_input_file(&s, input_filename, c->stream->ifmt,

                                  buf_size, c->stream->ap_in)) < 0) {

        http_log("could not open %s: %d\n", input_filename, ret);

        return -1;

    }

    s->flags |= AVFMT_FLAG_GENPTS;

    c->fmt_in = s;

    av_find_stream_info(c->fmt_in);

    /* open each parser */

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

        open_parser(s, i);

    /* choose stream as clock source (we favorize video stream if

       present) for packet sending */

    c->pts_stream_index = 0;

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

        if (c->pts_stream_index == 0 &&

            c->stream->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO) {

            c->pts_stream_index = i;

        }

    }

#if 1

    if (c->fmt_in->iformat->read_seek)

        av_seek_frame(c->fmt_in, -1, stream_pos, 0);

#endif

    /* set the start time (needed for maxtime and RTP packet timing) */

    c->start_time = cur_time;

    c->first_pts = AV_NOPTS_VALUE;

    return 0;

}


static int rtcp_parse_packet(RTPDemuxContext *s, const unsigned char *buf,

                             int len)

{

    int payload_len;

    while (len >= 4) {

        payload_len = FFMIN(len, (AV_RB16(buf + 2) + 1) * 4);

        switch (buf[1]) {

        case RTCP_SR:

            if (payload_len < 20) {

                av_log(NULL, AV_LOG_ERROR,

                       "Invalid length for RTCP SR packet\n");

                return AVERROR_INVALIDDATA;

            }

            s->last_rtcp_reception_time = av_gettime_relative();

            s->last_rtcp_ntp_time  = AV_RB64(buf + 8);

            s->last_rtcp_timestamp = AV_RB32(buf + 16);

            if (s->first_rtcp_ntp_time == AV_NOPTS_VALUE) {

                s->first_rtcp_ntp_time = s->last_rtcp_ntp_time;

                if (!s->base_timestamp)

                    s->base_timestamp = s->last_rtcp_timestamp;

                s->rtcp_ts_offset = s->last_rtcp_timestamp - s->base_timestamp;

            }

            break;

        case RTCP_BYE:

            return -RTCP_BYE;

        }

        buf += payload_len;

        len -= payload_len;

    }

    return -1;

}


void idct_add_altivec(uint8_t* dest, int stride, vector_s16_t* block)

{

POWERPC_TBL_DECLARE(altivec_idct_add_num, 1);

#ifdef ALTIVEC_USE_REFERENCE_C_CODE

POWERPC_TBL_START_COUNT(altivec_idct_add_num, 1);

    void simple_idct_add(uint8_t *dest, int line_size, int16_t *block);

    simple_idct_add(dest, stride, (int16_t*)block);

POWERPC_TBL_STOP_COUNT(altivec_idct_add_num, 1);

#else /* ALTIVEC_USE_REFERENCE_C_CODE */

    vector_u8_t tmp;

    vector_s16_t tmp2, tmp3;

    vector_u8_t perm0;

    vector_u8_t perm1;

    vector_u8_t p0, p1, p;

POWERPC_TBL_START_COUNT(altivec_idct_add_num, 1);

    IDCT

    p0 = vec_lvsl (0, dest);

    p1 = vec_lvsl (stride, dest);

    p = vec_splat_u8 (-1);

    perm0 = vec_mergeh (p, p0);

    perm1 = vec_mergeh (p, p1);

#define ADD(dest,src,perm)						\

    /* *(uint64_t *)&tmp = *(uint64_t *)dest; */			\

    tmp = vec_ld (0, dest);						\

    tmp2 = (vector_s16_t)vec_perm (tmp, (vector_u8_t)zero, perm);	\

    tmp3 = vec_adds (tmp2, src);					\

    tmp = vec_packsu (tmp3, tmp3);					\

    vec_ste ((vector_u32_t)tmp, 0, (unsigned int *)dest);		\

    vec_ste ((vector_u32_t)tmp, 4, (unsigned int *)dest);

    ADD (dest, vx0, perm0)	dest += stride;

    ADD (dest, vx1, perm1)	dest += stride;

    ADD (dest, vx2, perm0)	dest += stride;

    ADD (dest, vx3, perm1)	dest += stride;

    ADD (dest, vx4, perm0)	dest += stride;

    ADD (dest, vx5, perm1)	dest += stride;

    ADD (dest, vx6, perm0)	dest += stride;

    ADD (dest, vx7, perm1)

POWERPC_TBL_STOP_COUNT(altivec_idct_add_num, 1);

#endif /* ALTIVEC_USE_REFERENCE_C_CODE */

}


AVBufferRef *av_buffer_alloc(int size)

{

    AVBufferRef *ret = NULL;

    uint8_t    *data = NULL;

    data = av_malloc(size);

    if (!data)

        return NULL;

    if(CONFIG_MEMORY_POISONING)

        memset(data, 0x2a, size);

    ret = av_buffer_create(data, size, av_buffer_default_free, NULL, 0);

    if (!ret)

        av_freep(&data);

    return ret;

}


void msix_notify(PCIDevice *dev, unsigned vector)

{

    MSIMessage msg;

    if (vector >= dev->msix_entries_nr || !dev->msix_entry_used[vector])

        return;

    if (msix_is_masked(dev, vector)) {

        msix_set_pending(dev, vector);

        return;

    }

    msg = msix_get_message(dev, vector);

    stl_le_phys(&address_space_memory, msg.address, msg.data);

}


void msi_write_config(PCIDevice *dev, uint32_t addr, uint32_t val, int len)

{

    uint16_t flags = pci_get_word(dev->config + msi_flags_off(dev));

    bool msi64bit = flags & PCI_MSI_FLAGS_64BIT;

    bool msi_per_vector_mask = flags & PCI_MSI_FLAGS_MASKBIT;

    unsigned int nr_vectors;

    uint8_t log_num_vecs;

    uint8_t log_max_vecs;

    unsigned int vector;

    uint32_t pending;

    if (!ranges_overlap(addr, len, dev->msi_cap, msi_cap_sizeof(flags))) {

        return;

    }

#ifdef MSI_DEBUG

    MSI_DEV_PRINTF(dev, "addr 0x%"PRIx32" val 0x%"PRIx32" len %d\n",

                   addr, val, len);

    MSI_DEV_PRINTF(dev, "ctrl: 0x%"PRIx16" address: 0x%"PRIx32,

                   flags,

                   pci_get_long(dev->config + msi_address_lo_off(dev)));

    if (msi64bit) {

        fprintf(stderr, " address-hi: 0x%"PRIx32,

                pci_get_long(dev->config + msi_address_hi_off(dev)));

    }

    fprintf(stderr, " data: 0x%"PRIx16,

            pci_get_word(dev->config + msi_data_off(dev, msi64bit)));

    if (flags & PCI_MSI_FLAGS_MASKBIT) {

        fprintf(stderr, " mask 0x%"PRIx32" pending 0x%"PRIx32,

                pci_get_long(dev->config + msi_mask_off(dev, msi64bit)),

                pci_get_long(dev->config + msi_pending_off(dev, msi64bit)));

    }

    fprintf(stderr, "\n");

#endif

    if (!(flags & PCI_MSI_FLAGS_ENABLE)) {

        return;

    }

    /*

     * Now MSI is enabled, clear INTx# interrupts.

     * the driver is prohibited from writing enable bit to mask

     * a service request. But the guest OS could do this.

     * So we just discard the interrupts as moderate fallback.

     *

     * 6.8.3.3. Enabling Operation

     *   While enabled for MSI or MSI-X operation, a function is prohibited

     *   from using its INTx# pin (if implemented) to request

     *   service (MSI, MSI-X, and INTx# are mutually exclusive).

     */

    pci_device_deassert_intx(dev);

    /*

     * nr_vectors might be set bigger than capable. So clamp it.

     * This is not legal by spec, so we can do anything we like,

     * just don't crash the host

     */

    log_num_vecs =

        (flags & PCI_MSI_FLAGS_QSIZE) >> (ffs(PCI_MSI_FLAGS_QSIZE) - 1);

    log_max_vecs =

        (flags & PCI_MSI_FLAGS_QMASK) >> (ffs(PCI_MSI_FLAGS_QMASK) - 1);

    if (log_num_vecs > log_max_vecs) {

        flags &= ~PCI_MSI_FLAGS_QSIZE;

        flags |= log_max_vecs << (ffs(PCI_MSI_FLAGS_QSIZE) - 1);

        pci_set_word(dev->config + msi_flags_off(dev), flags);

    }

    if (!msi_per_vector_mask) {

        /* if per vector masking isn't supported,

           there is no pending interrupt. */

        return;

    }

    nr_vectors = msi_nr_vectors(flags);

    /* This will discard pending interrupts, if any. */

    pending = pci_get_long(dev->config + msi_pending_off(dev, msi64bit));

    pending &= 0xffffffff >> (PCI_MSI_VECTORS_MAX - nr_vectors);

    pci_set_long(dev->config + msi_pending_off(dev, msi64bit), pending);

    /* deliver pending interrupts which are unmasked */

    for (vector = 0; vector < nr_vectors; ++vector) {

        if (msi_is_masked(dev, vector) || !(pending & (1U << vector))) {

            continue;

        }

        pci_long_test_and_clear_mask(

            dev->config + msi_pending_off(dev, msi64bit), 1U << vector);

        msi_notify(dev, vector);

    }

}


static bool acpi_has_nvdimm(void)

{

    PCMachineState *pcms = PC_MACHINE(qdev_get_machine());

    return pcms->nvdimm;

}


void ide_flush_cache(IDEState *s)

{

    if (s->bs == NULL) {

        ide_flush_cb(s, 0);

        return;

    }

    s->status |= BUSY_STAT;

    block_acct_start(bdrv_get_stats(s->bs), &s->acct, 0, BLOCK_ACCT_FLUSH);

    s->pio_aiocb = bdrv_aio_flush(s->bs, ide_flush_cb, s);

}


have_autoneg(E1000State *s)

{

    return (s->compat_flags & E1000_FLAG_AUTONEG) &&

           (s->phy_reg[PHY_CTRL] & MII_CR_AUTO_NEG_EN);

}


qemu_irq *mpic_init (MemoryRegion *address_space, hwaddr base,

                     int nb_cpus, qemu_irq **irqs, qemu_irq irq_out)

{

    OpenPICState    *mpp;

    int           i;

    struct {

        const char             *name;

        MemoryRegionOps const  *ops;

        hwaddr      start_addr;

        ram_addr_t              size;

    } const list[] = {

        {"glb", &openpic_glb_ops_be, MPIC_GLB_REG_START, MPIC_GLB_REG_SIZE},

        {"tmr", &openpic_tmr_ops_be, MPIC_TMR_REG_START, MPIC_TMR_REG_SIZE},

        {"src", &openpic_src_ops_be, MPIC_SRC_REG_START, MPIC_SRC_REG_SIZE},

        {"cpu", &openpic_cpu_ops_be, MPIC_CPU_REG_START, MPIC_CPU_REG_SIZE},

    };

    mpp = g_malloc0(sizeof(OpenPICState));

    memory_region_init(&mpp->mem, "mpic", 0x40000);

    memory_region_add_subregion(address_space, base, &mpp->mem);

    for (i = 0; i < sizeof(list)/sizeof(list[0]); i++) {

        memory_region_init_io(&mpp->sub_io_mem[i], list[i].ops, mpp,

                              list[i].name, list[i].size);

        memory_region_add_subregion(&mpp->mem, list[i].start_addr,

                                    &mpp->sub_io_mem[i]);

    }

    mpp->nb_cpus = nb_cpus;

    /* 12 external sources, 48 internal sources , 4 timer sources,

       4 IPI sources, 4 messaging sources, and 8 Shared MSI sources */

    mpp->nb_irqs = 80;

    mpp->vid = VID_REVISION_1_2;

    mpp->veni = VENI_GENERIC;

    mpp->spve_mask = 0xFFFF;

    mpp->tifr_reset = 0x00000000;

    mpp->ipvp_reset = 0x80000000;

    mpp->ide_reset = 0x00000001;

    mpp->max_irq = MPIC_MAX_IRQ;

    mpp->irq_ipi0 = MPIC_IPI_IRQ;

    mpp->irq_tim0 = MPIC_TMR_IRQ;

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

        mpp->dst[i].irqs = irqs[i];

    mpp->irq_out = irq_out;

    /* Enable critical interrupt support */

    mpp->flags |= OPENPIC_FLAG_IDE_CRIT;

    register_savevm(NULL, "mpic", 0, 2, openpic_save, openpic_load, mpp);

    qemu_register_reset(openpic_reset, mpp);

    return qemu_allocate_irqs(openpic_set_irq, mpp, mpp->max_irq);

}


static void qmp_output_end_list(Visitor *v, void **obj)

{

    QmpOutputVisitor *qov = to_qov(v);

    QObject *value = qmp_output_pop(qov, obj);

    assert(qobject_type(value) == QTYPE_QLIST);

}


void blkconf_geometry(BlockConf *conf, int *ptrans,

                      unsigned cyls_max, unsigned heads_max, unsigned secs_max,

                      Error **errp)

{

    DriveInfo *dinfo;

    if (!conf->cyls && !conf->heads && !conf->secs) {

        /* try to fall back to value set with legacy -drive cyls=... */

        dinfo = drive_get_by_blockdev(conf->bs);

        conf->cyls  = dinfo->cyls;

        conf->heads = dinfo->heads;

        conf->secs  = dinfo->secs;

        if (ptrans) {

            *ptrans = dinfo->trans;

        }

    }

    if (!conf->cyls && !conf->heads && !conf->secs) {

        hd_geometry_guess(conf->bs,

                          &conf->cyls, &conf->heads, &conf->secs,

                          ptrans);

    } else if (ptrans && *ptrans == BIOS_ATA_TRANSLATION_AUTO) {

        *ptrans = hd_bios_chs_auto_trans(conf->cyls, conf->heads, conf->secs);

    }

    if (conf->cyls || conf->heads || conf->secs) {

        if (conf->cyls < 1 || conf->cyls > cyls_max) {

            error_setg(errp, "cyls must be between 1 and %u", cyls_max);

            return;

        }

        if (conf->heads < 1 || conf->heads > heads_max) {

            error_setg(errp, "heads must be between 1 and %u", heads_max);

            return;

        }

        if (conf->secs < 1 || conf->secs > secs_max) {

            error_setg(errp, "secs must be between 1 and %u", secs_max);

            return;

        }

    }

}


static void strongarm_ppc_handler_update(StrongARMPPCInfo *s)

{

    uint32_t level, diff;

    int bit;

    level = s->olevel & s->dir;

    for (diff = s->prev_level ^ level; diff; diff ^= 1 << bit) {

        bit = ffs(diff) - 1;

        qemu_set_irq(s->handler[bit], (level >> bit) & 1);

    }

    s->prev_level = level;

}


sPAPRTCETable *spapr_tce_new_table(DeviceState *owner, uint32_t liobn, size_t window_size)

{

    sPAPRTCETable *tcet;

    if (spapr_tce_find_by_liobn(liobn)) {

        fprintf(stderr, "Attempted to create TCE table with duplicate"

                " LIOBN 0x%x\n", liobn);

        return NULL;

    }

    if (!window_size) {

        return NULL;

    }

    tcet = g_malloc0(sizeof(*tcet));

    tcet->liobn = liobn;

    tcet->window_size = window_size;

    if (kvm_enabled()) {

        tcet->table = kvmppc_create_spapr_tce(liobn,

                                              window_size,

                                              &tcet->fd);

    }

    if (!tcet->table) {

        size_t table_size = (window_size >> SPAPR_TCE_PAGE_SHIFT)

            * sizeof(sPAPRTCE);

        tcet->table = g_malloc0(table_size);

    }

#ifdef DEBUG_TCE

    fprintf(stderr, "spapr_iommu: New TCE table @ %p, liobn=0x%x, "

            "table @ %p, fd=%d\n", tcet, liobn, tcet->table, tcet->fd);

#endif

    memory_region_init_iommu(&tcet->iommu, OBJECT(owner), &spapr_iommu_ops,

                             "iommu-spapr", UINT64_MAX);

    QLIST_INSERT_HEAD(&spapr_tce_tables, tcet, list);

    return tcet;

}


static void vhost_set_memory(MemoryListener *listener,

                             MemoryRegionSection *section,

                             bool add)

{

    struct vhost_dev *dev = container_of(listener, struct vhost_dev,

                                         memory_listener);

    hwaddr start_addr = section->offset_within_address_space;

    ram_addr_t size = int128_get64(section->size);

    bool log_dirty = memory_region_is_logging(section->mr);

    int s = offsetof(struct vhost_memory, regions) +

        (dev->mem->nregions + 1) * sizeof dev->mem->regions[0];

    void *ram;

    dev->mem = g_realloc(dev->mem, s);

    if (log_dirty) {

        add = false;

    }

    assert(size);

    /* Optimize no-change case. At least cirrus_vga does this a lot at this time. */

    ram = memory_region_get_ram_ptr(section->mr) + section->offset_within_region;

    if (add) {

        if (!vhost_dev_cmp_memory(dev, start_addr, size, (uintptr_t)ram)) {

            /* Region exists with same address. Nothing to do. */

            return;

        }

    } else {

        if (!vhost_dev_find_reg(dev, start_addr, size)) {

            /* Removing region that we don't access. Nothing to do. */

            return;

        }

    }

    vhost_dev_unassign_memory(dev, start_addr, size);

    if (add) {

        /* Add given mapping, merging adjacent regions if any */

        vhost_dev_assign_memory(dev, start_addr, size, (uintptr_t)ram);

    } else {

        /* Remove old mapping for this memory, if any. */

        vhost_dev_unassign_memory(dev, start_addr, size);

    }

    dev->mem_changed_start_addr = MIN(dev->mem_changed_start_addr, start_addr);

    dev->mem_changed_end_addr = MAX(dev->mem_changed_end_addr, start_addr + size - 1);

    dev->memory_changed = true;

}


static void setup_rt_frame(int sig, struct target_sigaction *ka,

                           target_siginfo_t *info,

                           target_sigset_t *set, CPUS390XState *env)

{

    int i;

    rt_sigframe *frame;

    abi_ulong frame_addr;

    frame_addr = get_sigframe(ka, env, sizeof *frame);

    qemu_log("%s: frame_addr 0x%llx\n", __FUNCTION__,

             (unsigned long long)frame_addr);

    if (!lock_user_struct(VERIFY_WRITE, frame, frame_addr, 0)) {

        goto give_sigsegv;

    }

    qemu_log("%s: 1\n", __FUNCTION__);

    if (copy_siginfo_to_user(&frame->info, info)) {

        goto give_sigsegv;

    }

    /* Create the ucontext.  */

    __put_user(0, &frame->uc.tuc_flags);

    __put_user((abi_ulong)0, (abi_ulong *)&frame->uc.tuc_link);

    __put_user(target_sigaltstack_used.ss_sp, &frame->uc.tuc_stack.ss_sp);

    __put_user(sas_ss_flags(get_sp_from_cpustate(env)),

                      &frame->uc.tuc_stack.ss_flags);

    __put_user(target_sigaltstack_used.ss_size, &frame->uc.tuc_stack.ss_size);

    save_sigregs(env, &frame->uc.tuc_mcontext);

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

        __put_user((abi_ulong)set->sig[i],

        (abi_ulong *)&frame->uc.tuc_sigmask.sig[i]);

    }

    /* Set up to return from userspace.  If provided, use a stub

       already in userspace.  */

    if (ka->sa_flags & TARGET_SA_RESTORER) {

        env->regs[14] = (unsigned long) ka->sa_restorer | PSW_ADDR_AMODE;

    } else {

        env->regs[14] = (unsigned long) frame->retcode | PSW_ADDR_AMODE;

        if (__put_user(S390_SYSCALL_OPCODE | TARGET_NR_rt_sigreturn,

                       (uint16_t *)(frame->retcode))) {

            goto give_sigsegv;

        }

    }

    /* Set up backchain. */

    if (__put_user(env->regs[15], (abi_ulong *) frame)) {

        goto give_sigsegv;

    }

    /* Set up registers for signal handler */

    env->regs[15] = frame_addr;

    env->psw.addr = (target_ulong) ka->_sa_handler | PSW_ADDR_AMODE;

    env->regs[2] = sig; //map_signal(sig);

    env->regs[3] = frame_addr + offsetof(typeof(*frame), info);

    env->regs[4] = frame_addr + offsetof(typeof(*frame), uc);

    return;

give_sigsegv:

    qemu_log("%s: give_sigsegv\n", __FUNCTION__);

    unlock_user_struct(frame, frame_addr, 1);

    force_sig(TARGET_SIGSEGV);

}


static int64_t alloc_clusters_noref(BlockDriverState *bs, int64_t size)

{

    BDRVQcowState *s = bs->opaque;

    int i, nb_clusters;

    nb_clusters = size_to_clusters(s, size);

retry:

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

        int64_t i = s->free_cluster_index++;

        if (get_refcount(bs, i) != 0)

            goto retry;

    }

#ifdef DEBUG_ALLOC2

    printf("alloc_clusters: size=%" PRId64 " -> %" PRId64 "\n",

            size,

            (s->free_cluster_index - nb_clusters) << s->cluster_bits);

#endif

    return (s->free_cluster_index - nb_clusters) << s->cluster_bits;

}


static inline int get_dwords(uint32_t addr, uint32_t *buf, int num)

{

    int i;

    for(i = 0; i < num; i++, buf++, addr += sizeof(*buf)) {

        cpu_physical_memory_rw(addr,(uint8_t *)buf, sizeof(*buf), 0);

        *buf = le32_to_cpu(*buf);

    }

    return 1;

}


static long kvm_hypercall(unsigned long nr, unsigned long param1,

                          unsigned long param2)

{

	register ulong r_nr asm("1") = nr;

	register ulong r_param1 asm("2") = param1;

	register ulong r_param2 asm("3") = param2;

	register long retval asm("2");

	asm volatile ("diag 2,4,0x500"

		      : "=d" (retval)

		      : "d" (r_nr), "0" (r_param1), "r"(r_param2)

		      : "memory", "cc");

	return retval;

}


static void io_mem_init(void)

{

    int i;

    cpu_register_io_memory_fixed(IO_MEM_ROM, error_mem_read, unassigned_mem_write, NULL);

    cpu_register_io_memory_fixed(IO_MEM_UNASSIGNED, unassigned_mem_read, unassigned_mem_write, NULL);

    cpu_register_io_memory_fixed(IO_MEM_NOTDIRTY, error_mem_read, notdirty_mem_write, NULL);

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

        io_mem_used[i] = 1;

    io_mem_watch = cpu_register_io_memory(watch_mem_read,

                                          watch_mem_write, NULL);

#ifdef CONFIG_KQEMU

    if (kqemu_phys_ram_base) {

        /* alloc dirty bits array */

        phys_ram_dirty = qemu_vmalloc(kqemu_phys_ram_size >> TARGET_PAGE_BITS);

        memset(phys_ram_dirty, 0xff, kqemu_phys_ram_size >> TARGET_PAGE_BITS);

    }

#endif

}


static size_t qemu_rdma_save_page(QEMUFile *f, void *opaque,

                                  ram_addr_t block_offset, ram_addr_t offset,

                                  size_t size, int *bytes_sent)

{

    QEMUFileRDMA *rfile = opaque;

    RDMAContext *rdma = rfile->rdma;

    int ret;

    CHECK_ERROR_STATE();

    qemu_fflush(f);

    if (size > 0) {

        /*

         * Add this page to the current 'chunk'. If the chunk

         * is full, or the page doen't belong to the current chunk,

         * an actual RDMA write will occur and a new chunk will be formed.

         */

        ret = qemu_rdma_write(f, rdma, block_offset, offset, size);

        if (ret < 0) {

            fprintf(stderr, "rdma migration: write error! %d\n", ret);

            goto err;

        }

        /*

         * We always return 1 bytes because the RDMA

         * protocol is completely asynchronous. We do not yet know

         * whether an  identified chunk is zero or not because we're

         * waiting for other pages to potentially be merged with

         * the current chunk. So, we have to call qemu_update_position()

         * later on when the actual write occurs.

         */

        if (bytes_sent) {

            *bytes_sent = 1;

        }

    } else {

        uint64_t index, chunk;

        /* TODO: Change QEMUFileOps prototype to be signed: size_t => long

        if (size < 0) {

            ret = qemu_rdma_drain_cq(f, rdma);

            if (ret < 0) {

                fprintf(stderr, "rdma: failed to synchronously drain"

                                " completion queue before unregistration.\n");

                goto err;

            }

        }

        */

        ret = qemu_rdma_search_ram_block(rdma, block_offset,

                                         offset, size, &index, &chunk);

        if (ret) {

            fprintf(stderr, "ram block search failed\n");

            goto err;

        }

        qemu_rdma_signal_unregister(rdma, index, chunk, 0);

        /*

         * TODO: Synchronous, guaranteed unregistration (should not occur during

         * fast-path). Otherwise, unregisters will process on the next call to

         * qemu_rdma_drain_cq()

        if (size < 0) {

            qemu_rdma_unregister_waiting(rdma);

        }

        */

    }

    /*

     * Drain the Completion Queue if possible, but do not block,

     * just poll.

     *

     * If nothing to poll, the end of the iteration will do this

     * again to make sure we don't overflow the request queue.

     */

    while (1) {

        uint64_t wr_id, wr_id_in;

        int ret = qemu_rdma_poll(rdma, &wr_id_in);

        if (ret < 0) {

            fprintf(stderr, "rdma migration: polling error! %d\n", ret);

            goto err;

        }

        wr_id = wr_id_in & RDMA_WRID_TYPE_MASK;

        if (wr_id == RDMA_WRID_NONE) {

            break;

        }

    }

    return RAM_SAVE_CONTROL_DELAYED;

err:

    rdma->error_state = ret;

    return ret;

}


static unsigned tget(const uint8_t **p, int type, int le)

{

    switch (type) {

    case TIFF_BYTE : return *(*p)++;

    case TIFF_SHORT: return tget_short(p, le);

    case TIFF_LONG : return tget_long(p, le);

    default        : return UINT_MAX;

    }

}


static void tcg_temp_free_internal(int idx)

{

    TCGContext *s = &tcg_ctx;

    TCGTemp *ts;

    int k;

#if defined(CONFIG_DEBUG_TCG)

    s->temps_in_use--;

    if (s->temps_in_use < 0) {

        fprintf(stderr, "More temporaries freed than allocated!\n");

    }

#endif

    assert(idx >= s->nb_globals && idx < s->nb_temps);

    ts = &s->temps[idx];

    assert(ts->temp_allocated != 0);

    ts->temp_allocated = 0;

    k = ts->base_type + (ts->temp_local ? TCG_TYPE_COUNT : 0);

    set_bit(idx, s->free_temps[k].l);

}


static bool pte64_match(target_ulong pte0, target_ulong pte1,

                        bool secondary, target_ulong ptem)

{

    return (pte0 & HPTE64_V_VALID)

        && (secondary == !!(pte0 & HPTE64_V_SECONDARY))

        && HPTE64_V_COMPARE(pte0, ptem);

}


PCIBus *ppc4xx_pci_init(CPUState *env, qemu_irq pci_irqs[4],

                        target_phys_addr_t config_space,

                        target_phys_addr_t int_ack,

                        target_phys_addr_t special_cycle,

                        target_phys_addr_t registers)

{

    PPC4xxPCIState *controller;

    int index;

    static int ppc4xx_pci_id;

    uint8_t *pci_conf;

    controller = qemu_mallocz(sizeof(PPC4xxPCIState));

    controller->pci_state.bus = pci_register_bus(NULL, "pci",

                                                 ppc4xx_pci_set_irq,

                                                 ppc4xx_pci_map_irq,

                                                 pci_irqs, 0, 4);

    controller->pci_dev = pci_register_device(controller->pci_state.bus,

                                              "host bridge", sizeof(PCIDevice),

                                              0, NULL, NULL);

    pci_conf = controller->pci_dev->config;

    pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_IBM);

    pci_config_set_device_id(pci_conf, PCI_DEVICE_ID_IBM_440GX);

    pci_config_set_class(pci_conf, PCI_CLASS_BRIDGE_OTHER);

    /* CFGADDR */

    index = cpu_register_io_memory(pci4xx_cfgaddr_read,

                                   pci4xx_cfgaddr_write, controller);

    if (index < 0)

        goto free;

    cpu_register_physical_memory(config_space + PCIC0_CFGADDR, 4, index);

    /* CFGDATA */

    index = cpu_register_io_memory(pci4xx_cfgdata_read,

                                   pci4xx_cfgdata_write,

                                   &controller->pci_state);

    if (index < 0)

        goto free;

    cpu_register_physical_memory(config_space + PCIC0_CFGDATA, 4, index);

    /* Internal registers */

    index = cpu_register_io_memory(pci_reg_read, pci_reg_write, controller);

    if (index < 0)

        goto free;

    cpu_register_physical_memory(registers, PCI_REG_SIZE, index);

    qemu_register_reset(ppc4xx_pci_reset, controller);

    /* XXX load/save code not tested. */

    register_savevm("ppc4xx_pci", ppc4xx_pci_id++, 1,

                    ppc4xx_pci_save, ppc4xx_pci_load, controller);

    return controller->pci_state.bus;

free:

    printf("%s error\n", __func__);

    qemu_free(controller);

    return NULL;

}


static void watch_mem_write(void *opaque, target_phys_addr_t addr,

                            uint64_t val, unsigned size)

{

    check_watchpoint(addr & ~TARGET_PAGE_MASK, ~(size - 1), BP_MEM_WRITE);

    switch (size) {

    case 1:

        stb_phys(addr, val);

        break;

    case 2:

        stw_phys(addr, val);

        break;

    case 4:

        stl_phys(addr, val);

        break;

    default: abort();

    }

}


static int io_channel_send_full(QIOChannel *ioc,

                                const void *buf, size_t len,

                                int *fds, size_t nfds)

{

    size_t offset = 0;

    while (offset < len) {

        ssize_t ret = 0;

        struct iovec iov = { .iov_base = (char *)buf + offset,

                             .iov_len = len - offset };

        ret = qio_channel_writev_full(

            ioc, &iov, 1,

            fds, nfds, NULL);

        if (ret == QIO_CHANNEL_ERR_BLOCK) {

            errno = EAGAIN;

            return -1;

        } else if (ret < 0) {

            if (offset) {

                return offset;

            }

            errno = EINVAL;

            return -1;

        }

        offset += ret;

    }

    return offset;

}


qemu_inject_x86_mce(Monitor *mon, CPUState *cenv, int bank, uint64_t status,

                    uint64_t mcg_status, uint64_t addr, uint64_t misc,

                    int flags)

{

    uint64_t mcg_cap = cenv->mcg_cap;

    uint64_t *banks = cenv->mce_banks + 4 * bank;

    /*

     * If there is an MCE exception being processed, ignore this SRAO MCE

     * unless unconditional injection was requested.

     */

    if (!(flags & MCE_INJECT_UNCOND_AO) && !(status & MCI_STATUS_AR)

        && (cenv->mcg_status & MCG_STATUS_MCIP)) {

        return;

    }

    if (status & MCI_STATUS_UC) {

        /*

         * if MSR_MCG_CTL is not all 1s, the uncorrected error

         * reporting is disabled

         */

        if ((mcg_cap & MCG_CTL_P) && cenv->mcg_ctl != ~(uint64_t)0) {

            monitor_printf(mon,

                           "CPU %d: Uncorrected error reporting disabled\n",

                           cenv->cpu_index);

            return;

        }

        /*

         * if MSR_MCi_CTL is not all 1s, the uncorrected error

         * reporting is disabled for the bank

         */

        if (banks[0] != ~(uint64_t)0) {

            monitor_printf(mon, "CPU %d: Uncorrected error reporting disabled "

                           "for bank %d\n", cenv->cpu_index, bank);

            return;

        }

        if ((cenv->mcg_status & MCG_STATUS_MCIP) ||

            !(cenv->cr[4] & CR4_MCE_MASK)) {

            monitor_printf(mon, "CPU %d: Previous MCE still in progress, "

                                "raising triple fault\n", cenv->cpu_index);

            qemu_log_mask(CPU_LOG_RESET, "Triple fault\n");

            qemu_system_reset_request();

            return;

        }

        if (banks[1] & MCI_STATUS_VAL) {

            status |= MCI_STATUS_OVER;

        }

        banks[2] = addr;

        banks[3] = misc;

        cenv->mcg_status = mcg_status;

        banks[1] = status;

        cpu_interrupt(cenv, CPU_INTERRUPT_MCE);

    } else if (!(banks[1] & MCI_STATUS_VAL)

               || !(banks[1] & MCI_STATUS_UC)) {

        if (banks[1] & MCI_STATUS_VAL) {

            status |= MCI_STATUS_OVER;

        }

        banks[2] = addr;

        banks[3] = misc;

        banks[1] = status;

    } else {

        banks[1] |= MCI_STATUS_OVER;

    }

}


static void test_pxe_e1000(void)

{

    test_pxe_one("-device e1000,netdev=" NETNAME, false);

}


static int mpeg4_decode_partitioned_mb(MpegEncContext *s, DCTELEM block[6][64])

{

    int cbp, mb_type;

    const int xy= s->mb_x + s->mb_y*s->mb_width;

    mb_type= s->mb_type[xy];

    cbp = s->cbp_table[xy];

    if(s->current_picture.qscale_table[xy] != s->qscale){

        s->qscale= s->current_picture.qscale_table[xy];

        s->y_dc_scale= s->y_dc_scale_table[ s->qscale ];

        s->c_dc_scale= s->c_dc_scale_table[ s->qscale ];

    }

    if (s->pict_type == P_TYPE || s->pict_type==S_TYPE) {

        int i;

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

            s->mv[0][i][0] = s->motion_val[ s->block_index[i] ][0];

            s->mv[0][i][1] = s->motion_val[ s->block_index[i] ][1];

        }

        s->mb_intra = mb_type&MB_TYPE_INTRA;

        if (mb_type&MB_TYPE_SKIPED) {

            /* skip mb */

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

                s->block_last_index[i] = -1;

            s->mv_dir = MV_DIR_FORWARD;

            s->mv_type = MV_TYPE_16X16;

            if(s->pict_type==S_TYPE && s->vol_sprite_usage==GMC_SPRITE){

                s->mcsel=1;

                s->mb_skiped = 0;

            }else{

                s->mcsel=0;

                s->mb_skiped = 1;

            }

        }else if(s->mb_intra){

            s->ac_pred = s->pred_dir_table[xy]>>7;

            /* decode each block */

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

                if(mpeg4_decode_block(s, block[i], i, cbp&32, 1) < 0){

                    fprintf(stderr, "texture corrupted at %d %d\n", s->mb_x, s->mb_y);

                    return -1;

                }

                cbp+=cbp;

            }

        }else if(!s->mb_intra){

//            s->mcsel= 0; //FIXME do we need to init that

            s->mv_dir = MV_DIR_FORWARD;

            if (mb_type&MB_TYPE_INTER4V) {

                s->mv_type = MV_TYPE_8X8;

            } else {

                s->mv_type = MV_TYPE_16X16;

            }

            /* decode each block */

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

                if(mpeg4_decode_block(s, block[i], i, cbp&32, 0) < 0){

                    fprintf(stderr, "texture corrupted at %d %d (trying to continue with mc/dc only)\n", s->mb_x, s->mb_y);

                    return -1;

                }

                cbp+=cbp;

            }

        }

    } else { /* I-Frame */

        int i;

        s->mb_intra = 1;

        s->ac_pred = s->pred_dir_table[xy]>>7;

        /* decode each block */

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

            if(mpeg4_decode_block(s, block[i], i, cbp&32, 1) < 0){

                fprintf(stderr, "texture corrupted at %d %d (trying to continue with dc only)\n", s->mb_x, s->mb_y);

                return -1;

            }

            cbp+=cbp;

        }

    }

    s->error_status_table[xy]&= ~AC_ERROR;

    /* per-MB end of slice check */

    if(--s->mb_num_left <= 0){

//printf("%06X %d\n", show_bits(&s->gb, 24), s->gb.size*8 - get_bits_count(&s->gb));

        if(mpeg4_is_resync(s))

            return SLICE_END;

        else

            return SLICE_NOEND;

    }else{

        if(s->cbp_table[xy+1] && mpeg4_is_resync(s))

            return SLICE_END;

        else

            return SLICE_OK;

    }

}


void visit_type_uint8(Visitor *v, uint8_t *obj, const char *name, Error **errp)

{

    int64_t value;

    if (v->type_uint8) {

        v->type_uint8(v, obj, name, errp);

    } else {

        value = *obj;

        v->type_int64(v, &value, name, errp);

        if (value < 0 || value > UINT8_MAX) {

            /* FIXME questionable reuse of errp if callback changed

               value on error */

            error_setg(errp, QERR_INVALID_PARAMETER_VALUE,

                       name ? name : "null", "uint8_t");

            return;

        }

        *obj = value;

    }

}


void xen_cmos_set_s3_resume(void *opaque, int irq, int level)

{

    pc_cmos_set_s3_resume(opaque, irq, level);

    if (level) {

        xc_set_hvm_param(xen_xc, xen_domid, HVM_PARAM_ACPI_S_STATE, 3);

    }

}


size_t v9fs_marshal(struct iovec *in_sg, int in_num, size_t offset,

                    int bswap, const char *fmt, ...)

{

    int i;

    va_list ap;

    size_t old_offset = offset;

    va_start(ap, fmt);

    for (i = 0; fmt[i]; i++) {

        switch (fmt[i]) {

        case 'b': {

            uint8_t val = va_arg(ap, int);

            offset += v9fs_pack(in_sg, in_num, offset, &val, sizeof(val));

            break;

        }

        case 'w': {

            uint16_t val;

            if (bswap) {

                cpu_to_le16w(&val, va_arg(ap, int));

            } else {

                val =  va_arg(ap, int);

            }

            offset += v9fs_pack(in_sg, in_num, offset, &val, sizeof(val));

            break;

        }

        case 'd': {

            uint32_t val;

            if (bswap) {

                cpu_to_le32w(&val, va_arg(ap, uint32_t));

            } else {

                val =  va_arg(ap, uint32_t);

            }

            offset += v9fs_pack(in_sg, in_num, offset, &val, sizeof(val));

            break;

        }

        case 'q': {

            uint64_t val;

            if (bswap) {

                cpu_to_le64w(&val, va_arg(ap, uint64_t));

            } else {

                val =  va_arg(ap, uint64_t);

            }

            offset += v9fs_pack(in_sg, in_num, offset, &val, sizeof(val));

            break;

        }

        case 's': {

            V9fsString *str = va_arg(ap, V9fsString *);

            offset += v9fs_marshal(in_sg, in_num, offset, bswap,

                            "w", str->size);

            offset += v9fs_pack(in_sg, in_num, offset, str->data, str->size);

            break;

        }

        case 'Q': {

            V9fsQID *qidp = va_arg(ap, V9fsQID *);

            offset += v9fs_marshal(in_sg, in_num, offset, bswap, "bdq",

                                   qidp->type, qidp->version, qidp->path);

            break;

        }

        case 'S': {

            V9fsStat *statp = va_arg(ap, V9fsStat *);

            offset += v9fs_marshal(in_sg, in_num, offset, bswap,

                                   "wwdQdddqsssssddd",

                                   statp->size, statp->type, statp->dev,

                                   &statp->qid, statp->mode, statp->atime,

                                   statp->mtime, statp->length, &statp->name,

                                   &statp->uid, &statp->gid, &statp->muid,

                                   &statp->extension, statp->n_uid,

                                   statp->n_gid, statp->n_muid);

            break;

        }

        case 'A': {

            V9fsStatDotl *statp = va_arg(ap, V9fsStatDotl *);

            offset += v9fs_marshal(in_sg, in_num, offset, bswap,

                                   "qQdddqqqqqqqqqqqqqqq",

                                   statp->st_result_mask,

                                   &statp->qid, statp->st_mode,

                                   statp->st_uid, statp->st_gid,

                                   statp->st_nlink, statp->st_rdev,

                                   statp->st_size, statp->st_blksize,

                                   statp->st_blocks, statp->st_atime_sec,

                                   statp->st_atime_nsec, statp->st_mtime_sec,

                                   statp->st_mtime_nsec, statp->st_ctime_sec,

                                   statp->st_ctime_nsec, statp->st_btime_sec,

                                   statp->st_btime_nsec, statp->st_gen,

                                   statp->st_data_version);

            break;

        }

        default:

            break;

        }

    }

    va_end(ap);

    return offset - old_offset;

}


void memory_region_iommu_replay(MemoryRegion *mr, Notifier *n,

                                hwaddr granularity, bool is_write)

{

    hwaddr addr;

    IOMMUTLBEntry iotlb;

    for (addr = 0; addr < memory_region_size(mr); addr += granularity) {

        iotlb = mr->iommu_ops->translate(mr, addr, is_write);

        if (iotlb.perm != IOMMU_NONE) {

            n->notify(n, &iotlb);

        }

        /* if (2^64 - MR size) < granularity, it's possible to get an

         * infinite loop here.  This should catch such a wraparound */

        if ((addr + granularity) < addr) {

            break;

        }

    }

}


static void s390_init_cpus(MachineState *machine)

{

    MachineClass *mc = MACHINE_GET_CLASS(machine);

    int i;

    if (tcg_enabled() && max_cpus > 1) {

        error_report("Number of SMP CPUs requested (%d) exceeds max CPUs "

                     "supported by TCG (1) on s390x", max_cpus);

        exit(1);

    }

    /* initialize possible_cpus */

    mc->possible_cpu_arch_ids(machine);

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

        s390x_new_cpu(machine->cpu_type, i, &error_fatal);

    }

}


static int roq_decode_init(AVCodecContext *avctx)

{

    RoqContext *s = avctx->priv_data;

    s->avctx = avctx;

    s->width = avctx->width;

    s->height = avctx->height;

    s->last_frame    = &s->frames[0];

    s->current_frame = &s->frames[1];

    avctx->pix_fmt = PIX_FMT_YUV444P;

    dsputil_init(&s->dsp, avctx);

    return 0;

}


static inline void helper_ret_protected(CPUX86State *env, int shift,

                                        int is_iret, int addend)

{

    uint32_t new_cs, new_eflags, new_ss;

    uint32_t new_es, new_ds, new_fs, new_gs;

    uint32_t e1, e2, ss_e1, ss_e2;

    int cpl, dpl, rpl, eflags_mask, iopl;

    target_ulong ssp, sp, new_eip, new_esp, sp_mask;

#ifdef TARGET_X86_64

    if (shift == 2) {

        sp_mask = -1;

    } else

#endif

    {

        sp_mask = get_sp_mask(env->segs[R_SS].flags);

    }

    sp = env->regs[R_ESP];

    ssp = env->segs[R_SS].base;

    new_eflags = 0; /* avoid warning */

#ifdef TARGET_X86_64

    if (shift == 2) {

        POPQ(sp, new_eip);

        POPQ(sp, new_cs);

        new_cs &= 0xffff;

        if (is_iret) {

            POPQ(sp, new_eflags);

        }

    } else

#endif

    {

        if (shift == 1) {

            /* 32 bits */

            POPL(ssp, sp, sp_mask, new_eip);

            POPL(ssp, sp, sp_mask, new_cs);

            new_cs &= 0xffff;

            if (is_iret) {

                POPL(ssp, sp, sp_mask, new_eflags);

                if (new_eflags & VM_MASK) {

                    goto return_to_vm86;

                }

            }

        } else {

            /* 16 bits */

            POPW(ssp, sp, sp_mask, new_eip);

            POPW(ssp, sp, sp_mask, new_cs);

            if (is_iret) {

                POPW(ssp, sp, sp_mask, new_eflags);

            }

        }

    }

    LOG_PCALL("lret new %04x:" TARGET_FMT_lx " s=%d addend=0x%x\n",

              new_cs, new_eip, shift, addend);

    LOG_PCALL_STATE(CPU(x86_env_get_cpu(env)));

    if ((new_cs & 0xfffc) == 0) {

        raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);

    }

    if (load_segment(env, &e1, &e2, new_cs) != 0) {

        raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);

    }

    if (!(e2 & DESC_S_MASK) ||

        !(e2 & DESC_CS_MASK)) {

        raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);

    }

    cpl = env->hflags & HF_CPL_MASK;

    rpl = new_cs & 3;

    if (rpl < cpl) {

        raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);

    }

    dpl = (e2 >> DESC_DPL_SHIFT) & 3;

    if (e2 & DESC_C_MASK) {

        if (dpl > rpl) {

            raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);

        }

    } else {

        if (dpl != rpl) {

            raise_exception_err(env, EXCP0D_GPF, new_cs & 0xfffc);

        }

    }

    if (!(e2 & DESC_P_MASK)) {

        raise_exception_err(env, EXCP0B_NOSEG, new_cs & 0xfffc);

    }

    sp += addend;

    if (rpl == cpl && (!(env->hflags & HF_CS64_MASK) ||

                       ((env->hflags & HF_CS64_MASK) && !is_iret))) {

        /* return to same privilege level */

        cpu_x86_load_seg_cache(env, R_CS, new_cs,

                       get_seg_base(e1, e2),

                       get_seg_limit(e1, e2),

                       e2);

    } else {

        /* return to different privilege level */

#ifdef TARGET_X86_64

        if (shift == 2) {

            POPQ(sp, new_esp);

            POPQ(sp, new_ss);

            new_ss &= 0xffff;

        } else

#endif

        {

            if (shift == 1) {

                /* 32 bits */

                POPL(ssp, sp, sp_mask, new_esp);

                POPL(ssp, sp, sp_mask, new_ss);

                new_ss &= 0xffff;

            } else {

                /* 16 bits */

                POPW(ssp, sp, sp_mask, new_esp);

                POPW(ssp, sp, sp_mask, new_ss);

            }

        }

        LOG_PCALL("new ss:esp=%04x:" TARGET_FMT_lx "\n",

                  new_ss, new_esp);

        if ((new_ss & 0xfffc) == 0) {

#ifdef TARGET_X86_64

            /* NULL ss is allowed in long mode if cpl != 3 */

            /* XXX: test CS64? */

            if ((env->hflags & HF_LMA_MASK) && rpl != 3) {

                cpu_x86_load_seg_cache(env, R_SS, new_ss,

                                       0, 0xffffffff,

                                       DESC_G_MASK | DESC_B_MASK | DESC_P_MASK |

                                       DESC_S_MASK | (rpl << DESC_DPL_SHIFT) |

                                       DESC_W_MASK | DESC_A_MASK);

                ss_e2 = DESC_B_MASK; /* XXX: should not be needed? */

            } else

#endif

            {

                raise_exception_err(env, EXCP0D_GPF, 0);

            }

        } else {

            if ((new_ss & 3) != rpl) {

                raise_exception_err(env, EXCP0D_GPF, new_ss & 0xfffc);

            }

            if (load_segment(env, &ss_e1, &ss_e2, new_ss) != 0) {

                raise_exception_err(env, EXCP0D_GPF, new_ss & 0xfffc);

            }

            if (!(ss_e2 & DESC_S_MASK) ||

                (ss_e2 & DESC_CS_MASK) ||

                !(ss_e2 & DESC_W_MASK)) {

                raise_exception_err(env, EXCP0D_GPF, new_ss & 0xfffc);

            }

            dpl = (ss_e2 >> DESC_DPL_SHIFT) & 3;

            if (dpl != rpl) {

                raise_exception_err(env, EXCP0D_GPF, new_ss & 0xfffc);

            }

            if (!(ss_e2 & DESC_P_MASK)) {

                raise_exception_err(env, EXCP0B_NOSEG, new_ss & 0xfffc);

            }

            cpu_x86_load_seg_cache(env, R_SS, new_ss,

                                   get_seg_base(ss_e1, ss_e2),

                                   get_seg_limit(ss_e1, ss_e2),

                                   ss_e2);

        }

        cpu_x86_load_seg_cache(env, R_CS, new_cs,

                       get_seg_base(e1, e2),

                       get_seg_limit(e1, e2),

                       e2);

        cpu_x86_set_cpl(env, rpl);

        sp = new_esp;

#ifdef TARGET_X86_64

        if (env->hflags & HF_CS64_MASK) {

            sp_mask = -1;

        } else

#endif

        {

            sp_mask = get_sp_mask(ss_e2);

        }

        /* validate data segments */

        validate_seg(env, R_ES, rpl);

        validate_seg(env, R_DS, rpl);

        validate_seg(env, R_FS, rpl);

        validate_seg(env, R_GS, rpl);

        sp += addend;

    }

    SET_ESP(sp, sp_mask);

    env->eip = new_eip;

    if (is_iret) {

        /* NOTE: 'cpl' is the _old_ CPL */

        eflags_mask = TF_MASK | AC_MASK | ID_MASK | RF_MASK | NT_MASK;

        if (cpl == 0) {

            eflags_mask |= IOPL_MASK;

        }

        iopl = (env->eflags >> IOPL_SHIFT) & 3;

        if (cpl <= iopl) {

            eflags_mask |= IF_MASK;

        }

        if (shift == 0) {

            eflags_mask &= 0xffff;

        }

        cpu_load_eflags(env, new_eflags, eflags_mask);

    }

    return;

 return_to_vm86:

    POPL(ssp, sp, sp_mask, new_esp);

    POPL(ssp, sp, sp_mask, new_ss);

    POPL(ssp, sp, sp_mask, new_es);

    POPL(ssp, sp, sp_mask, new_ds);

    POPL(ssp, sp, sp_mask, new_fs);

    POPL(ssp, sp, sp_mask, new_gs);

    /* modify processor state */

    cpu_load_eflags(env, new_eflags, TF_MASK | AC_MASK | ID_MASK |

                    IF_MASK | IOPL_MASK | VM_MASK | NT_MASK | VIF_MASK |

                    VIP_MASK);

    load_seg_vm(env, R_CS, new_cs & 0xffff);

    cpu_x86_set_cpl(env, 3);

    load_seg_vm(env, R_SS, new_ss & 0xffff);

    load_seg_vm(env, R_ES, new_es & 0xffff);

    load_seg_vm(env, R_DS, new_ds & 0xffff);

    load_seg_vm(env, R_FS, new_fs & 0xffff);

    load_seg_vm(env, R_GS, new_gs & 0xffff);

    env->eip = new_eip & 0xffff;

    env->regs[R_ESP] = new_esp;

}


static int qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)

{

    int i;

    for (i = 0; i < qiov->niov; i++) {

        if ((uintptr_t) qiov->iov[i].iov_base % bs->buffer_alignment) {

            return 0;

        }

    }

    return 1;

}


void *qemu_anon_ram_alloc(size_t size)

{

    void *ptr;

    /* FIXME: this is not exactly optimal solution since VirtualAlloc

       has 64Kb granularity, but at least it guarantees us that the

       memory is page aligned. */

    ptr = VirtualAlloc(NULL, size, MEM_COMMIT, PAGE_READWRITE);

    trace_qemu_anon_ram_alloc(size, ptr);

    return ptr;

}


static bool coroutine_fn do_perform_cow_encrypt(BlockDriverState *bs,

                                                uint64_t src_cluster_offset,

                                                unsigned offset_in_cluster,

                                                uint8_t *buffer,

                                                unsigned bytes)

{

    if (bytes && bs->encrypted) {

        BDRVQcow2State *s = bs->opaque;

        int64_t sector = (src_cluster_offset + offset_in_cluster)

                         >> BDRV_SECTOR_BITS;

        assert(s->cipher);

        assert((offset_in_cluster & ~BDRV_SECTOR_MASK) == 0);

        assert((bytes & ~BDRV_SECTOR_MASK) == 0);

        if (qcow2_encrypt_sectors(s, sector, buffer,

                                  bytes >> BDRV_SECTOR_BITS, true, NULL) < 0) {

            return false;

        }

    }

    return true;

}


static uint32_t nam_readl (void *opaque, uint32_t addr)

{

    PCIAC97LinkState *d = opaque;

    AC97LinkState *s = &d->ac97;

    dolog ("U nam readl %#x\n", addr);

    s->cas = 0;

    return ~0U;

}


static int vpc_open(BlockDriverState *bs, int flags)

{

    BDRVVPCState *s = bs->opaque;

    int i;

    struct vhd_footer* footer;

    struct vhd_dyndisk_header* dyndisk_header;

    uint8_t buf[HEADER_SIZE];

    uint32_t checksum;

    int err = -1;

    int disk_type = VHD_DYNAMIC;

    if (bdrv_pread(bs->file, 0, s->footer_buf, HEADER_SIZE) != HEADER_SIZE)

        goto fail;

    footer = (struct vhd_footer*) s->footer_buf;

    if (strncmp(footer->creator, "conectix", 8)) {

        int64_t offset = bdrv_getlength(bs->file);

        if (offset < HEADER_SIZE) {

            goto fail;

        }

        /* If a fixed disk, the footer is found only at the end of the file */

        if (bdrv_pread(bs->file, offset-HEADER_SIZE, s->footer_buf, HEADER_SIZE)

                != HEADER_SIZE) {

            goto fail;

        }

        if (strncmp(footer->creator, "conectix", 8)) {

            goto fail;

        }

        disk_type = VHD_FIXED;

    }

    checksum = be32_to_cpu(footer->checksum);

    footer->checksum = 0;

    if (vpc_checksum(s->footer_buf, HEADER_SIZE) != checksum)

        fprintf(stderr, "block-vpc: The header checksum of '%s' is "

            "incorrect.\n", bs->filename);

    /* Write 'checksum' back to footer, or else will leave it with zero. */

    footer->checksum = be32_to_cpu(checksum);

    // The visible size of a image in Virtual PC depends on the geometry

    // rather than on the size stored in the footer (the size in the footer

    // is too large usually)

    bs->total_sectors = (int64_t)

        be16_to_cpu(footer->cyls) * footer->heads * footer->secs_per_cyl;

    if (bs->total_sectors >= 65535 * 16 * 255) {

        err = -EFBIG;

        goto fail;

    }

    if (disk_type == VHD_DYNAMIC) {

        if (bdrv_pread(bs->file, be64_to_cpu(footer->data_offset), buf,

                HEADER_SIZE) != HEADER_SIZE) {

            goto fail;

        }

        dyndisk_header = (struct vhd_dyndisk_header *) buf;

        if (strncmp(dyndisk_header->magic, "cxsparse", 8)) {

            goto fail;

        }

        s->block_size = be32_to_cpu(dyndisk_header->block_size);

        s->bitmap_size = ((s->block_size / (8 * 512)) + 511) & ~511;

        s->max_table_entries = be32_to_cpu(dyndisk_header->max_table_entries);

        s->pagetable = g_malloc(s->max_table_entries * 4);

        s->bat_offset = be64_to_cpu(dyndisk_header->table_offset);

        if (bdrv_pread(bs->file, s->bat_offset, s->pagetable,

                s->max_table_entries * 4) != s->max_table_entries * 4) {

            goto fail;

        }

        s->free_data_block_offset =

            (s->bat_offset + (s->max_table_entries * 4) + 511) & ~511;

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

            be32_to_cpus(&s->pagetable[i]);

            if (s->pagetable[i] != 0xFFFFFFFF) {

                int64_t next = (512 * (int64_t) s->pagetable[i]) +

                    s->bitmap_size + s->block_size;

                if (next > s->free_data_block_offset) {

                    s->free_data_block_offset = next;

                }

            }

        }

        s->last_bitmap_offset = (int64_t) -1;

#ifdef CACHE

        s->pageentry_u8 = g_malloc(512);

        s->pageentry_u32 = s->pageentry_u8;

        s->pageentry_u16 = s->pageentry_u8;

        s->last_pagetable = -1;

#endif

    }

    qemu_co_mutex_init(&s->lock);

    /* Disable migration when VHD images are used */

    error_set(&s->migration_blocker,

              QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,

              "vpc", bs->device_name, "live migration");

    migrate_add_blocker(s->migration_blocker);

    return 0;

 fail:

    return err;

}


static void test_identify(void)

{

    AHCIQState *ahci;

    ahci = ahci_boot_and_enable();

    ahci_test_identify(ahci);

    ahci_shutdown(ahci);

}


static void apic_send_msi(target_phys_addr_t addr, uint32_t data)

{

    uint8_t dest = (addr & MSI_ADDR_DEST_ID_MASK) >> MSI_ADDR_DEST_ID_SHIFT;

    uint8_t vector = (data & MSI_DATA_VECTOR_MASK) >> MSI_DATA_VECTOR_SHIFT;

    uint8_t dest_mode = (addr >> MSI_ADDR_DEST_MODE_SHIFT) & 0x1;

    uint8_t trigger_mode = (data >> MSI_DATA_TRIGGER_SHIFT) & 0x1;

    uint8_t delivery = (data >> MSI_DATA_DELIVERY_MODE_SHIFT) & 0x7;

    /* XXX: Ignore redirection hint. */

    apic_deliver_irq(dest, dest_mode, delivery, vector, trigger_mode);

}


PCIHostState *spapr_create_phb(sPAPREnvironment *spapr, int index,

                               const char *busname)

{

    DeviceState *dev;

    dev = qdev_create(NULL, TYPE_SPAPR_PCI_HOST_BRIDGE);

    qdev_prop_set_uint32(dev, "index", index);

    qdev_prop_set_string(dev, "busname", busname);

    qdev_init_nofail(dev);

    return PCI_HOST_BRIDGE(dev);

}


static void opt_format(const char *arg)

{

    /* compatibility stuff for pgmyuv */

    if (!strcmp(arg, "pgmyuv")) {

        opt_image_format(arg);

        arg = "image";

    }

    file_iformat = av_find_input_format(arg);

    file_oformat = guess_format(arg, NULL, NULL);

    if (!file_iformat && !file_oformat) {

        fprintf(stderr, "Unknown input or output format: %s\n", arg);

        exit(1);

    }

}


void memory_region_add_eventfd(MemoryRegion *mr,
                               hwaddr addr,
                               unsigned size,
                               bool match_data,
                               uint64_t data,
                               EventNotifier *e)
{
    MemoryRegionIoeventfd mrfd = {
        .addr.start = int128_make64(addr),
        .addr.size = int128_make64(size),
        .match_data = match_data,
        .data = data,
        .e = e,
    };
    unsigned i;
    if (size) {
        adjust_endianness(mr, &mrfd.data, size);
    memory_region_transaction_begin();
    for (i = 0; i < mr->ioeventfd_nb; ++i) {
        if (memory_region_ioeventfd_before(mrfd, mr->ioeventfds[i])) {
            break;
    ++mr->ioeventfd_nb;
    mr->ioeventfds = g_realloc(mr->ioeventfds,
                                  sizeof(*mr->ioeventfds) * mr->ioeventfd_nb);
    memmove(&mr->ioeventfds[i+1], &mr->ioeventfds[i],
            sizeof(*mr->ioeventfds) * (mr->ioeventfd_nb-1 - i));
    mr->ioeventfds[i] = mrfd;
    ioeventfd_update_pending |= mr->enabled;
    memory_region_transaction_commit();


static int pdu_copy_sg(V9fsPDU *pdu, size_t offset, int rx, struct iovec *sg)

{

    size_t pos = 0;

    int i, j;

    struct iovec *src_sg;

    unsigned int num;

    if (rx) {

        src_sg = pdu->elem.in_sg;

        num = pdu->elem.in_num;

    } else {

        src_sg = pdu->elem.out_sg;

        num = pdu->elem.out_num;

    }

    j = 0;

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

        if (offset <= pos) {

            sg[j].iov_base = src_sg[i].iov_base;

            sg[j].iov_len = src_sg[i].iov_len;

            j++;

        } else if (offset < (src_sg[i].iov_len + pos)) {

            sg[j].iov_base = src_sg[i].iov_base;

            sg[j].iov_len = src_sg[i].iov_len;

            sg[j].iov_base += (offset - pos);

            sg[j].iov_len -= (offset - pos);

            j++;

        }

        pos += src_sg[i].iov_len;

    }

    return j;

}


void init_vlc_rl(RLTable *rl)

{

    int i, q;

    init_vlc(&rl->vlc, 9, rl->n + 1,

             &rl->table_vlc[0][1], 4, 2,

             &rl->table_vlc[0][0], 4, 2);

    for(q=0; q<32; q++){

        int qmul= q*2;

        int qadd= (q-1)|1;

        if(q==0){

            qmul=1;

            qadd=0;

        }

        rl->rl_vlc[q]= av_malloc(rl->vlc.table_size*sizeof(RL_VLC_ELEM));

        for(i=0; i<rl->vlc.table_size; i++){

            int code= rl->vlc.table[i][0];

            int len = rl->vlc.table[i][1];

            int level, run;

            if(len==0){ // illegal code

                run= 66;

                level= MAX_LEVEL;

            }else if(len<0){ //more bits needed

                run= 0;

                level= code;

            }else{

                if(code==rl->n){ //esc

                    run= 66;

                    level= 0;

                }else{

                    run=   rl->table_run  [code] + 1;

                    level= rl->table_level[code] * qmul + qadd;

                    if(code >= rl->last) run+=192;

                }

            }

            rl->rl_vlc[q][i].len= len;

            rl->rl_vlc[q][i].level= level;

            rl->rl_vlc[q][i].run= run;

        }

    }

}


static void dec_sr(DisasContext *dc)

{

    if (dc->format == OP_FMT_RI) {

        LOG_DIS("sri r%d, r%d, %d\n", dc->r1, dc->r0, dc->imm5);

    } else {

        LOG_DIS("sr r%d, r%d, r%d\n", dc->r2, dc->r0, dc->r1);

    }

    if (!(dc->env->features & LM32_FEATURE_SHIFT)) {

        if (dc->format == OP_FMT_RI) {

            /* TODO: check r1 == 1 during runtime */

        } else {

            if (dc->imm5 != 1) {

                cpu_abort(dc->env, "hardware shifter is not available\n");

            }

        }

    }

    if (dc->format == OP_FMT_RI) {

        tcg_gen_sari_tl(cpu_R[dc->r1], cpu_R[dc->r0], dc->imm5);

    } else {

        TCGv t0 = tcg_temp_new();

        tcg_gen_andi_tl(t0, cpu_R[dc->r1], 0x1f);

        tcg_gen_sar_tl(cpu_R[dc->r2], cpu_R[dc->r0], t0);

        tcg_temp_free(t0);

    }

}


int kvm_arch_on_sigbus(int code, void *addr)

{

#ifdef KVM_CAP_MCE

    if ((first_cpu->mcg_cap & MCG_SER_P) && addr && code == BUS_MCEERR_AO) {

        ram_addr_t ram_addr;

        target_phys_addr_t paddr;

        /* Hope we are lucky for AO MCE */

        if (qemu_ram_addr_from_host(addr, &ram_addr) ||

            !kvm_physical_memory_addr_from_ram(first_cpu->kvm_state, ram_addr,

                                               &paddr)) {

            fprintf(stderr, "Hardware memory error for memory used by "

                    "QEMU itself instead of guest system!: %p\n", addr);

            return 0;

        }

        kvm_mce_inject(first_cpu, paddr, code);

    } else

#endif /* KVM_CAP_MCE */

    {

        if (code == BUS_MCEERR_AO) {

            return 0;

        } else if (code == BUS_MCEERR_AR) {

            hardware_memory_error();

        } else {

            return 1;

        }

    }

    return 0;

}


static int mxf_read_material_package(MXFPackage *package, ByteIOContext *pb, int tag)

{

    switch(tag) {

    case 0x4403:

        package->tracks_count = get_be32(pb);

        if (package->tracks_count >= UINT_MAX / sizeof(UID))

            return -1;

        package->tracks_refs = av_malloc(package->tracks_count * sizeof(UID));

        if (!package->tracks_refs)

            return -1;

        url_fskip(pb, 4); /* useless size of objects, always 16 according to specs */

        get_buffer(pb, (uint8_t *)package->tracks_refs, package->tracks_count * sizeof(UID));

        break;

    }

    return 0;

}


static void qemu_aio_complete(void *opaque, int ret)

{

    struct ioreq *ioreq = opaque;

    if (ret != 0) {

        xen_be_printf(&ioreq->blkdev->xendev, 0, "%s I/O error\n",

                      ioreq->req.operation == BLKIF_OP_READ ? "read" : "write");

        ioreq->aio_errors++;

    }

    ioreq->aio_inflight--;

    if (ioreq->presync) {

        ioreq->presync = 0;

        ioreq_runio_qemu_aio(ioreq);

        return;

    }

    if (ioreq->aio_inflight > 0) {

        return;

    }

    if (ioreq->postsync) {

        ioreq->postsync = 0;

        ioreq->aio_inflight++;

        bdrv_aio_flush(ioreq->blkdev->bs, qemu_aio_complete, ioreq);

        return;

    }

    ioreq->status = ioreq->aio_errors ? BLKIF_RSP_ERROR : BLKIF_RSP_OKAY;

    ioreq_unmap(ioreq);

    ioreq_finish(ioreq);

    switch (ioreq->req.operation) {

    case BLKIF_OP_WRITE:

    case BLKIF_OP_FLUSH_DISKCACHE:

        if (!ioreq->req.nr_segments) {

            break;

        }

    case BLKIF_OP_READ:

        block_acct_done(bdrv_get_stats(ioreq->blkdev->bs), &ioreq->acct);

        break;

    case BLKIF_OP_DISCARD:

    default:

        break;

    }

    qemu_bh_schedule(ioreq->blkdev->bh);

}


static int select_rc_mode(AVCodecContext *avctx, QSVEncContext *q)

{

    const char *rc_desc;

    mfxU16      rc_mode;

    int want_la     = q->la_depth >= 0;

    int want_qscale = !!(avctx->flags & AV_CODEC_FLAG_QSCALE);

    int want_vcm    = q->vcm;

    if (want_la && !QSV_HAVE_LA) {

        av_log(avctx, AV_LOG_ERROR,

               "Lookahead ratecontrol mode requested, but is not supported by this SDK version\n");

        return AVERROR(ENOSYS);

    }

    if (want_vcm && !QSV_HAVE_VCM) {

        av_log(avctx, AV_LOG_ERROR,

               "VCM ratecontrol mode requested, but is not supported by this SDK version\n");

        return AVERROR(ENOSYS);

    }

    if (want_la + want_qscale + want_vcm > 1) {

        av_log(avctx, AV_LOG_ERROR,

               "More than one of: { constant qscale, lookahead, VCM } requested, "

               "only one of them can be used at a time.\n");

        return AVERROR(EINVAL);

    }

    if (want_qscale) {

        rc_mode = MFX_RATECONTROL_CQP;

        rc_desc = "constant quantization parameter (CQP)";

    }

#if QSV_HAVE_VCM

    else if (want_vcm) {

        rc_mode = MFX_RATECONTROL_VCM;

        rc_desc = "video conferencing mode (VCM)";

    }

#endif

#if QSV_HAVE_LA

    else if (want_la) {

        rc_mode = MFX_RATECONTROL_LA;

        rc_desc = "VBR with lookahead (LA)";

#if QSV_HAVE_ICQ

        if (avctx->global_quality > 0) {

            rc_mode = MFX_RATECONTROL_LA_ICQ;

            rc_desc = "intelligent constant quality with lookahead (LA_ICQ)";

        }

#endif

    }

#endif

#if QSV_HAVE_ICQ

    else if (avctx->global_quality > 0) {

        rc_mode = MFX_RATECONTROL_ICQ;

        rc_desc = "intelligent constant quality (ICQ)";

    }

#endif

    else if (avctx->rc_max_rate == avctx->bit_rate) {

        rc_mode = MFX_RATECONTROL_CBR;

        rc_desc = "constant bitrate (CBR)";

    } else if (!avctx->rc_max_rate) {

        rc_mode = MFX_RATECONTROL_AVBR;

        rc_desc = "average variable bitrate (AVBR)";

    } else {

        rc_mode = MFX_RATECONTROL_VBR;

        rc_desc = "variable bitrate (VBR)";

    }

    q->param.mfx.RateControlMethod = rc_mode;

    av_log(avctx, AV_LOG_VERBOSE, "Using the %s ratecontrol method\n", rc_desc);

    return 0;

}


static BlockDriver *find_hdev_driver(const char *filename)

{

    int score_max = 0, score;

    BlockDriver *drv = NULL, *d;

    QLIST_FOREACH(d, &bdrv_drivers, list) {

        if (d->bdrv_probe_device) {

            score = d->bdrv_probe_device(filename);

            if (score > score_max) {

                score_max = score;

                drv = d;

            }

        }

    }

    return drv;

}


static void apb_pci_bridge_init(PCIBus *b)

{

    PCIDevice *dev = pci_bridge_get_device(b);

    /*

     * command register:

     * According to PCI bridge spec, after reset

     *   bus master bit is off

     *   memory space enable bit is off

     * According to manual (805-1251.pdf).

     *   the reset value should be zero unless the boot pin is tied high

     *   (which is true) and thus it should be PCI_COMMAND_MEMORY.

     */

    pci_set_word(dev->config + PCI_COMMAND,

                 PCI_COMMAND_MEMORY);

    pci_set_word(dev->config + PCI_STATUS,

                 PCI_STATUS_FAST_BACK | PCI_STATUS_66MHZ |

                 PCI_STATUS_DEVSEL_MEDIUM);

    pci_set_byte(dev->config + PCI_REVISION_ID, 0x11);

    pci_set_byte(dev->config + PCI_HEADER_TYPE,

                 pci_get_byte(dev->config + PCI_HEADER_TYPE) |

                 PCI_HEADER_TYPE_MULTI_FUNCTION);

}


static void tcg_out_setcond2(TCGContext *s, const TCGArg *args,

                             const int *const_args)

{

    TCGArg new_args[6];

    int label_true, label_over;

    memcpy(new_args, args+1, 5*sizeof(TCGArg));

    if (args[0] == args[1] || args[0] == args[2]

        || (!const_args[3] && args[0] == args[3])

        || (!const_args[4] && args[0] == args[4])) {

        /* When the destination overlaps with one of the argument

           registers, don't do anything tricky.  */

        label_true = label_arg(gen_new_label());

        label_over = label_arg(gen_new_label());

        new_args[5] = label_true;

        tcg_out_brcond2(s, new_args, const_args+1, 1);

        tcg_out_movi(s, TCG_TYPE_I32, args[0], 0);

        tcg_out_jxx(s, JCC_JMP, label_over, 1);

        tcg_out_label(s, label_true, s->code_ptr);

        tcg_out_movi(s, TCG_TYPE_I32, args[0], 1);

        tcg_out_label(s, label_over, s->code_ptr);

    } else {

        /* When the destination does not overlap one of the arguments,

           clear the destination first, jump if cond false, and emit an

           increment in the true case.  This results in smaller code.  */

        tcg_out_movi(s, TCG_TYPE_I32, args[0], 0);

        label_over = label_arg(gen_new_label());

        new_args[4] = tcg_invert_cond(new_args[4]);

        new_args[5] = label_over;

        tcg_out_brcond2(s, new_args, const_args+1, 1);

        tgen_arithi(s, ARITH_ADD, args[0], 1, 0);

        tcg_out_label(s, label_over, s->code_ptr);

    }

}


static int handle_dependencies(BlockDriverState *bs, uint64_t guest_offset,

    unsigned int *nb_clusters)

{

    BDRVQcowState *s = bs->opaque;

    QCowL2Meta *old_alloc;

    QLIST_FOREACH(old_alloc, &s->cluster_allocs, next_in_flight) {

        uint64_t start = guest_offset >> s->cluster_bits;

        uint64_t end = start + *nb_clusters;

        uint64_t old_start = old_alloc->offset >> s->cluster_bits;

        uint64_t old_end = old_start + old_alloc->nb_clusters;

        if (end < old_start || start > old_end) {

            /* No intersection */

        } else {

            if (start < old_start) {

                /* Stop at the start of a running allocation */

                *nb_clusters = old_start - start;

            } else {

                *nb_clusters = 0;

            }

            if (*nb_clusters == 0) {

                /* Wait for the dependency to complete. We need to recheck

                 * the free/allocated clusters when we continue. */

                qemu_co_mutex_unlock(&s->lock);

                qemu_co_queue_wait(&old_alloc->dependent_requests);

                qemu_co_mutex_lock(&s->lock);

                return -EAGAIN;

            }

        }

    }

    if (!*nb_clusters) {

        abort();

    }

    return 0;

}


char *g_strdup(const char *s)

{

    char *dup;

    size_t i;

    if (!s) {

        return NULL;

    }

    __coverity_string_null_sink__(s);

    __coverity_string_size_sink__(s);

    dup = __coverity_alloc_nosize__();

    __coverity_mark_as_afm_allocated__(dup, AFM_free);

    for (i = 0; (dup[i] = s[i]); i++) ;

    return dup;

}


void ff_avg_h264_qpel4_mc00_msa(uint8_t *dst, const uint8_t *src,

                                ptrdiff_t stride)

{

    avg_width4_msa(src, stride, dst, stride, 4);

}


static int net_vhost_user_init(NetClientState *peer, const char *device,

                               const char *name, CharDriverState *chr)

{

    NetClientState *nc;

    VhostUserState *s;

    nc = qemu_new_net_client(&net_vhost_user_info, peer, device, name);

    snprintf(nc->info_str, sizeof(nc->info_str), "vhost-user to %s",

             chr->label);

    s = DO_UPCAST(VhostUserState, nc, nc);

    /* We don't provide a receive callback */

    s->nc.receive_disabled = 1;

    s->chr = chr;

    qemu_chr_add_handlers(s->chr, NULL, NULL, net_vhost_user_event, s);

    return 0;

}


static int megasas_build_sense(MegasasCmd *cmd, uint8_t *sense_ptr,

    uint8_t sense_len)

{

    uint32_t pa_hi = 0, pa_lo;

    target_phys_addr_t pa;

    if (sense_len > cmd->frame->header.sense_len) {

        sense_len = cmd->frame->header.sense_len;

    }

    if (sense_len) {

        pa_lo = le32_to_cpu(cmd->frame->pass.sense_addr_lo);

        if (megasas_frame_is_sense64(cmd)) {

            pa_hi = le32_to_cpu(cmd->frame->pass.sense_addr_hi);

        }

        pa = ((uint64_t) pa_hi << 32) | pa_lo;

        cpu_physical_memory_write(pa, sense_ptr, sense_len);

        cmd->frame->header.sense_len = sense_len;

    }

    return sense_len;

}


MemoryRegion *rom_add_blob(const char *name, const void *blob, size_t len,

                   size_t max_len, hwaddr addr, const char *fw_file_name,

                   FWCfgReadCallback fw_callback, void *callback_opaque)

{

    MachineClass *mc = MACHINE_GET_CLASS(qdev_get_machine());

    Rom *rom;

    MemoryRegion *mr = NULL;

    rom           = g_malloc0(sizeof(*rom));

    rom->name     = g_strdup(name);

    rom->addr     = addr;

    rom->romsize  = max_len ? max_len : len;

    rom->datasize = len;

    rom->data     = g_malloc0(rom->datasize);

    memcpy(rom->data, blob, len);

    rom_insert(rom);

    if (fw_file_name && fw_cfg) {

        char devpath[100];

        void *data;

        snprintf(devpath, sizeof(devpath), "/rom@%s", fw_file_name);

        if (mc->rom_file_has_mr) {

            data = rom_set_mr(rom, OBJECT(fw_cfg), devpath);

            mr = rom->mr;

        } else {

            data = rom->data;

        }

        fw_cfg_add_file_callback(fw_cfg, fw_file_name,

                                 fw_callback, callback_opaque,

                                 data, rom->datasize);

    }

    return mr;

}


static uint64_t sysctl_read(void *opaque, target_phys_addr_t addr,

                            unsigned size)

{

    MilkymistSysctlState *s = opaque;

    uint32_t r = 0;

    addr >>= 2;

    switch (addr) {

    case R_TIMER0_COUNTER:

        r = (uint32_t)ptimer_get_count(s->ptimer0);

        /* milkymist timer counts up */

        r = s->regs[R_TIMER0_COMPARE] - r;

        break;

    case R_TIMER1_COUNTER:

        r = (uint32_t)ptimer_get_count(s->ptimer1);

        /* milkymist timer counts up */

        r = s->regs[R_TIMER1_COMPARE] - r;

        break;

    case R_GPIO_IN:

    case R_GPIO_OUT:

    case R_GPIO_INTEN:

    case R_TIMER0_CONTROL:

    case R_TIMER0_COMPARE:

    case R_TIMER1_CONTROL:

    case R_TIMER1_COMPARE:

    case R_ICAP:

    case R_DBG_SCRATCHPAD:

    case R_DBG_WRITE_LOCK:

    case R_CLK_FREQUENCY:

    case R_CAPABILITIES:

    case R_SYSTEM_ID:

        r = s->regs[addr];

        break;

    default:

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

                TARGET_FMT_plx, addr << 2);

        break;

    }

    trace_milkymist_sysctl_memory_read(addr << 2, r);

    return r;

}


static int vmdk_is_allocated(BlockDriverState *bs, int64_t sector_num,

                             int nb_sectors, int *pnum)

{

    BDRVVmdkState *s = bs->opaque;

    int64_t index_in_cluster, n, ret;

    uint64_t offset;

    VmdkExtent *extent;

    extent = find_extent(s, sector_num, NULL);

    if (!extent) {

        return 0;

    }

    ret = get_cluster_offset(bs, extent, NULL,

                            sector_num * 512, 0, &offset);

    /* get_cluster_offset returning 0 means success */

    ret = !ret;

    index_in_cluster = sector_num % extent->cluster_sectors;

    n = extent->cluster_sectors - index_in_cluster;

    if (n > nb_sectors) {

        n = nb_sectors;

    }

    *pnum = n;

    return ret;

}


void acpi_setup(PcGuestInfo *guest_info)

{

    AcpiBuildTables tables;

    AcpiBuildState *build_state;

    if (!guest_info->fw_cfg) {

        ACPI_BUILD_DPRINTF("No fw cfg. Bailing out.\n");

        return;

    }

    if (!guest_info->has_acpi_build) {

        ACPI_BUILD_DPRINTF("ACPI build disabled. Bailing out.\n");

        return;

    }

    if (!acpi_enabled) {

        ACPI_BUILD_DPRINTF("ACPI disabled. Bailing out.\n");

        return;

    }

    build_state = g_malloc0(sizeof *build_state);

    build_state->guest_info = guest_info;

    acpi_set_pci_info();

    acpi_build_tables_init(&tables);

    acpi_build(build_state->guest_info, &tables);

    /* Now expose it all to Guest */

    build_state->table_ram = acpi_add_rom_blob(build_state, tables.table_data,

                                               ACPI_BUILD_TABLE_FILE,

                                               ACPI_BUILD_TABLE_MAX_SIZE);

    assert(build_state->table_ram != RAM_ADDR_MAX);

    build_state->table_size = acpi_data_len(tables.table_data);

    build_state->linker_ram =

        acpi_add_rom_blob(build_state, tables.linker, "etc/table-loader", 0);

    build_state->linker_size = acpi_data_len(tables.linker);

    fw_cfg_add_file(guest_info->fw_cfg, ACPI_BUILD_TPMLOG_FILE,

                    tables.tcpalog->data, acpi_data_len(tables.tcpalog));

    if (guest_info->has_immutable_rsdp) {

        /*

         * Keep for compatibility with old machine types.

         * Though RSDP is small, its contents isn't immutable, so

         * update it along with the rest of tables on guest access.

         */

        fw_cfg_add_file_callback(guest_info->fw_cfg, ACPI_BUILD_RSDP_FILE,

                                 acpi_build_update, build_state,

                                 tables.rsdp->data, acpi_data_len(tables.rsdp));

        build_state->rsdp = tables.rsdp->data;

    } else {

        build_state->rsdp = qemu_get_ram_ptr(

            acpi_add_rom_blob(build_state, tables.rsdp, ACPI_BUILD_RSDP_FILE, 0)

        );

    }

    qemu_register_reset(acpi_build_reset, build_state);

    acpi_build_reset(build_state);

    vmstate_register(NULL, 0, &vmstate_acpi_build, build_state);

    /* Cleanup tables but don't free the memory: we track it

     * in build_state.

     */

    acpi_build_tables_cleanup(&tables, false);

}


static void pc_compat_2_0(MachineState *machine)

{

    pc_compat_2_1(machine);

    smbios_legacy_mode = true;

    has_reserved_memory = false;

    pc_set_legacy_acpi_data_size();

}


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

{

}


static int cdrom_read_toc_raw(IDEState *s, uint8_t *buf, int msf,

                              int session_num)

{

    uint8_t *q;

    int nb_sectors, len;

    q = buf + 2;

    *q++ = 1; /* first session */

    *q++ = 1; /* last session */

    *q++ = 1; /* session number */

    *q++ = 0x14; /* data track */

    *q++ = 0; /* track number */

    *q++ = 0xa0; /* lead-in */

    *q++ = 0; /* min */

    *q++ = 0; /* sec */

    *q++ = 0; /* frame */

    *q++ = 0;

    *q++ = 1; /* first track */

    *q++ = 0x00; /* disk type */

    *q++ = 0x00;

    *q++ = 1; /* session number */

    *q++ = 0x14; /* data track */

    *q++ = 0; /* track number */

    *q++ = 0xa1;

    *q++ = 0; /* min */

    *q++ = 0; /* sec */

    *q++ = 0; /* frame */

    *q++ = 0;

    *q++ = 1; /* last track */

    *q++ = 0x00;

    *q++ = 0x00;

    *q++ = 1; /* session number */

    *q++ = 0x14; /* data track */

    *q++ = 0; /* track number */

    *q++ = 0xa2; /* lead-out */

    *q++ = 0; /* min */

    *q++ = 0; /* sec */

    *q++ = 0; /* frame */

    nb_sectors = s->nb_sectors >> 2;

    if (msf) {

        *q++ = 0; /* reserved */

        lba_to_msf(q, nb_sectors);

        q += 3;

    } else {

        cpu_to_ube32(q, nb_sectors);

        q += 4;

    }

    *q++ = 1; /* session number */

    *q++ = 0x14; /* ADR, control */

    *q++ = 0;    /* track number */

    *q++ = 1;    /* point */

    *q++ = 0; /* min */

    *q++ = 0; /* sec */

    *q++ = 0; /* frame */

    *q++ = 0;

    *q++ = 0;

    *q++ = 0;

    *q++ = 0;

    len = q - buf;

    cpu_to_ube16(buf, len - 2);

    return len;

}


static void virtio_ccw_rng_instance_init(Object *obj)

{

    VirtIORNGCcw *dev = VIRTIO_RNG_CCW(obj);

    object_initialize(&dev->vdev, sizeof(dev->vdev), TYPE_VIRTIO_RNG);

    object_property_add_child(obj, "virtio-backend", OBJECT(&dev->vdev), NULL);

    object_property_add_link(obj, "rng", TYPE_RNG_BACKEND,

                             (Object **)&dev->vdev.conf.rng, NULL);

}


static int apic_init_common(SysBusDevice *dev)

{

    APICCommonState *s = APIC_COMMON(dev);

    APICCommonClass *info;

    static DeviceState *vapic;

    static int apic_no;

    if (apic_no >= MAX_APICS) {

        return -1;

    }

    s->idx = apic_no++;

    info = APIC_COMMON_GET_CLASS(s);

    info->init(s);

    sysbus_init_mmio(dev, &s->io_memory);

    if (!vapic && s->vapic_control & VAPIC_ENABLE_MASK) {

        vapic = sysbus_create_simple("kvmvapic", -1, NULL);

    }

    s->vapic = vapic;

    if (apic_report_tpr_access && info->enable_tpr_reporting) {

        info->enable_tpr_reporting(s, true);

    }

    return 0;

}


static int coroutine_fn bdrv_co_do_pwrite_zeroes(BlockDriverState *bs,
    int64_t offset, int bytes, BdrvRequestFlags flags)
{
    BlockDriver *drv = bs->drv;
    QEMUIOVector qiov;
    struct iovec iov = {0};
    int ret = 0;
    bool need_flush = false;
    int head = 0;
    int tail = 0;
    int max_write_zeroes = MIN_NON_ZERO(bs->bl.max_pwrite_zeroes, INT_MAX);
    int alignment = MAX(bs->bl.pwrite_zeroes_alignment,
                        bs->bl.request_alignment);
    int max_transfer = MIN_NON_ZERO(bs->bl.max_transfer, MAX_BOUNCE_BUFFER);
    assert(alignment % bs->bl.request_alignment == 0);
    head = offset % alignment;
    tail = (offset + bytes) % alignment;
    max_write_zeroes = QEMU_ALIGN_DOWN(max_write_zeroes, alignment);
    assert(max_write_zeroes >= bs->bl.request_alignment);
    while (bytes > 0 && !ret) {
        int num = bytes;
        /* Align request.  Block drivers can expect the "bulk" of the request
         * to be aligned, and that unaligned requests do not cross cluster
         * boundaries.
         */
        if (head) {
            /* Make a small request up to the first aligned sector. For
             * convenience, limit this request to max_transfer even if
             * we don't need to fall back to writes.  */
            num = MIN(MIN(bytes, max_transfer), alignment - head);
            head = (head + num) % alignment;
            assert(num < max_write_zeroes);
        } else if (tail && num > alignment) {
            /* Shorten the request to the last aligned sector.  */
            num -= tail;
        /* limit request size */
        if (num > max_write_zeroes) {
            num = max_write_zeroes;
        ret = -ENOTSUP;
        /* First try the efficient write zeroes operation */
        if (drv->bdrv_co_pwrite_zeroes) {
            ret = drv->bdrv_co_pwrite_zeroes(bs, offset, num,
                                             flags & bs->supported_zero_flags);
            if (ret != -ENOTSUP && (flags & BDRV_REQ_FUA) &&
                !(bs->supported_zero_flags & BDRV_REQ_FUA)) {
                need_flush = true;
        } else {
            assert(!bs->supported_zero_flags);
        if (ret == -ENOTSUP) {
            /* Fall back to bounce buffer if write zeroes is unsupported */
            BdrvRequestFlags write_flags = flags & ~BDRV_REQ_ZERO_WRITE;
            if ((flags & BDRV_REQ_FUA) &&
                !(bs->supported_write_flags & BDRV_REQ_FUA)) {
                /* No need for bdrv_driver_pwrite() to do a fallback
                 * flush on each chunk; use just one at the end */
                write_flags &= ~BDRV_REQ_FUA;
                need_flush = true;
            num = MIN(num, max_transfer);
            iov.iov_len = num;
            if (iov.iov_base == NULL) {
                iov.iov_base = qemu_try_blockalign(bs, num);
                if (iov.iov_base == NULL) {
                    ret = -ENOMEM;
                    goto fail;
                memset(iov.iov_base, 0, num);
            qemu_iovec_init_external(&qiov, &iov, 1);
            ret = bdrv_driver_pwritev(bs, offset, num, &qiov, write_flags);
            /* Keep bounce buffer around if it is big enough for all
             * all future requests.
             */
            if (num < max_transfer) {
                qemu_vfree(iov.iov_base);
                iov.iov_base = NULL;
        offset += num;
        bytes -= num;
fail:
    if (ret == 0 && need_flush) {
        ret = bdrv_co_flush(bs);
    qemu_vfree(iov.iov_base);
    return ret;


static av_cold int decode_close(AVCodecContext *avctx)
{
    IVI5DecContext *ctx = avctx->priv_data;
    ff_ivi_free_buffers(&ctx->planes[0]);
    if (ctx->frame.data[0])
        avctx->release_buffer(avctx, &ctx->frame);
    return 0;
}


static void ioreq_release(struct ioreq *ioreq, bool finish)

{

    struct XenBlkDev *blkdev = ioreq->blkdev;

    QLIST_REMOVE(ioreq, list);

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

    ioreq->blkdev = blkdev;

    QLIST_INSERT_HEAD(&blkdev->freelist, ioreq, list);

    if (finish) {

        blkdev->requests_finished--;

    } else {

        blkdev->requests_inflight--;

    }

}


int bdrv_open_backing_file(BlockDriverState *bs)

{

    char backing_filename[PATH_MAX];

    int back_flags, ret;

    BlockDriver *back_drv = NULL;

    if (bs->backing_hd != NULL) {

        return 0;

    }

    bs->open_flags &= ~BDRV_O_NO_BACKING;

    if (bs->backing_file[0] == '\0') {

        return 0;

    }

    bs->backing_hd = bdrv_new("");

    bdrv_get_full_backing_filename(bs, backing_filename,

                                   sizeof(backing_filename));

    if (bs->backing_format[0] != '\0') {

        back_drv = bdrv_find_format(bs->backing_format);

    }

    /* backing files always opened read-only */

    back_flags = bs->open_flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT);

    ret = bdrv_open(bs->backing_hd, backing_filename, NULL,

                    back_flags, back_drv);

    if (ret < 0) {

        bdrv_delete(bs->backing_hd);

        bs->backing_hd = NULL;

        bs->open_flags |= BDRV_O_NO_BACKING;

        return ret;

    }

    return 0;

}


static coroutine_fn int qcow_co_writev(BlockDriverState *bs, int64_t sector_num,

                          int nb_sectors, QEMUIOVector *qiov)

{

    BDRVQcowState *s = bs->opaque;

    int index_in_cluster;

    uint64_t cluster_offset;

    int ret = 0, n;

    struct iovec hd_iov;

    QEMUIOVector hd_qiov;

    uint8_t *buf;

    void *orig_buf;

    s->cluster_cache_offset = -1; /* disable compressed cache */

    /* We must always copy the iov when encrypting, so we

     * don't modify the original data buffer during encryption */

    if (bs->encrypted || qiov->niov > 1) {

        buf = orig_buf = qemu_try_blockalign(bs, qiov->size);

        if (buf == NULL) {

            return -ENOMEM;

        }

        qemu_iovec_to_buf(qiov, 0, buf, qiov->size);

    } else {

        orig_buf = NULL;

        buf = (uint8_t *)qiov->iov->iov_base;

    }

    qemu_co_mutex_lock(&s->lock);

    while (nb_sectors != 0) {

        index_in_cluster = sector_num & (s->cluster_sectors - 1);

        n = s->cluster_sectors - index_in_cluster;

        if (n > nb_sectors) {

            n = nb_sectors;

        }

        cluster_offset = get_cluster_offset(bs, sector_num << 9, 1, 0,

                                            index_in_cluster,

                                            index_in_cluster + n);

        if (!cluster_offset || (cluster_offset & 511) != 0) {

            ret = -EIO;

            break;

        }

        if (bs->encrypted) {

            assert(s->crypto);

            if (qcrypto_block_encrypt(s->crypto, sector_num, buf,

                                      n * BDRV_SECTOR_SIZE, NULL) < 0) {

                ret = -EIO;

                break;

            }

        }

        hd_iov.iov_base = (void *)buf;

        hd_iov.iov_len = n * 512;

        qemu_iovec_init_external(&hd_qiov, &hd_iov, 1);

        qemu_co_mutex_unlock(&s->lock);

        ret = bdrv_co_writev(bs->file,

                             (cluster_offset >> 9) + index_in_cluster,

                             n, &hd_qiov);

        qemu_co_mutex_lock(&s->lock);

        if (ret < 0) {

            break;

        }

        ret = 0;

        nb_sectors -= n;

        sector_num += n;

        buf += n * 512;

    }

    qemu_co_mutex_unlock(&s->lock);

    qemu_vfree(orig_buf);

    return ret;

}


static void monitor_qapi_event_emit(QAPIEvent event, QDict *qdict)

{

    Monitor *mon;

    trace_monitor_protocol_event_emit(event, qdict);

    QLIST_FOREACH(mon, &mon_list, entry) {

        if (monitor_is_qmp(mon) && mon->qmp.in_command_mode) {

            monitor_json_emitter(mon, QOBJECT(qdict));

        }

    }

}


static int input_get_buffer(AVCodecContext *codec, AVFrame *pic)

{

    AVFilterContext *ctx = codec->opaque;

    AVFilterBufferRef  *ref;

    int perms = AV_PERM_WRITE;

    int i, w, h, stride[4];

    unsigned edge;

    int pixel_size;

    av_assert0(codec->flags & CODEC_FLAG_EMU_EDGE);

    if (codec->codec->capabilities & CODEC_CAP_NEG_LINESIZES)

        perms |= AV_PERM_NEG_LINESIZES;

    if(pic->buffer_hints & FF_BUFFER_HINTS_VALID) {

        if(pic->buffer_hints & FF_BUFFER_HINTS_READABLE) perms |= AV_PERM_READ;

        if(pic->buffer_hints & FF_BUFFER_HINTS_PRESERVE) perms |= AV_PERM_PRESERVE;

        if(pic->buffer_hints & FF_BUFFER_HINTS_REUSABLE) perms |= AV_PERM_REUSE2;

    }

    if(pic->reference) perms |= AV_PERM_READ | AV_PERM_PRESERVE;

    w = codec->width;

    h = codec->height;

    if(av_image_check_size(w, h, 0, codec))

        return -1;

    avcodec_align_dimensions2(codec, &w, &h, stride);

    edge = codec->flags & CODEC_FLAG_EMU_EDGE ? 0 : avcodec_get_edge_width();

    w += edge << 1;

    h += edge << 1;

    if(!(ref = avfilter_get_video_buffer(ctx->outputs[0], perms, w, h)))

        return -1;

    pixel_size = av_pix_fmt_descriptors[ref->format].comp[0].step_minus1+1;

    ref->video->w = codec->width;

    ref->video->h = codec->height;

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

        unsigned hshift = (i == 1 || i == 2) ? av_pix_fmt_descriptors[ref->format].log2_chroma_w : 0;

        unsigned vshift = (i == 1 || i == 2) ? av_pix_fmt_descriptors[ref->format].log2_chroma_h : 0;

        if (ref->data[i]) {

            ref->data[i]    += ((edge * pixel_size) >> hshift) + ((edge * ref->linesize[i]) >> vshift);

        }

        pic->data[i]     = ref->data[i];

        pic->linesize[i] = ref->linesize[i];

    }

    pic->opaque = ref;

    pic->age    = INT_MAX;

    pic->type   = FF_BUFFER_TYPE_USER;

    pic->reordered_opaque = codec->reordered_opaque;

    if(codec->pkt) pic->pkt_pts = codec->pkt->pts;

    else           pic->pkt_pts = AV_NOPTS_VALUE;

    return 0;

}