static void vmsvga_fifo_run(struct vmsvga_state_s *s)

{

    uint32_t cmd, colour;

    int args, len;

    int x, y, dx, dy, width, height;

    struct vmsvga_cursor_definition_s cursor;

    uint32_t cmd_start;

    len = vmsvga_fifo_length(s);

    while (len > 0) {

        /* May need to go back to the start of the command if incomplete */

        cmd_start = s->cmd->stop;

        switch (cmd = vmsvga_fifo_read(s)) {

        case SVGA_CMD_UPDATE:

        case SVGA_CMD_UPDATE_VERBOSE:

            len -= 5;

            if (len < 0) {

                goto rewind;

            }

            x = vmsvga_fifo_read(s);

            y = vmsvga_fifo_read(s);

            width = vmsvga_fifo_read(s);

            height = vmsvga_fifo_read(s);

            vmsvga_update_rect_delayed(s, x, y, width, height);

            break;

        case SVGA_CMD_RECT_FILL:

            len -= 6;

            if (len < 0) {

                goto rewind;

            }

            colour = vmsvga_fifo_read(s);

            x = vmsvga_fifo_read(s);

            y = vmsvga_fifo_read(s);

            width = vmsvga_fifo_read(s);

            height = vmsvga_fifo_read(s);

#ifdef HW_FILL_ACCEL

            vmsvga_fill_rect(s, colour, x, y, width, height);

            break;

#else

            args = 0;

            goto badcmd;

#endif

        case SVGA_CMD_RECT_COPY:

            len -= 7;

            if (len < 0) {

                goto rewind;

            }

            x = vmsvga_fifo_read(s);

            y = vmsvga_fifo_read(s);

            dx = vmsvga_fifo_read(s);

            dy = vmsvga_fifo_read(s);

            width = vmsvga_fifo_read(s);

            height = vmsvga_fifo_read(s);

#ifdef HW_RECT_ACCEL

            if (vmsvga_copy_rect(s, x, y, dx, dy, width, height) == 0) {

                break;

            }

#endif

            args = 0;

            goto badcmd;

        case SVGA_CMD_DEFINE_CURSOR:

            len -= 8;

            if (len < 0) {

                goto rewind;

            }

            cursor.id = vmsvga_fifo_read(s);

            cursor.hot_x = vmsvga_fifo_read(s);

            cursor.hot_y = vmsvga_fifo_read(s);

            cursor.width = x = vmsvga_fifo_read(s);

            cursor.height = y = vmsvga_fifo_read(s);

            vmsvga_fifo_read(s);

            cursor.bpp = vmsvga_fifo_read(s);

            args = SVGA_BITMAP_SIZE(x, y) + SVGA_PIXMAP_SIZE(x, y, cursor.bpp);

            if (SVGA_BITMAP_SIZE(x, y) > sizeof cursor.mask ||

                SVGA_PIXMAP_SIZE(x, y, cursor.bpp) > sizeof cursor.image) {

                    goto badcmd;

            }

            len -= args;

            if (len < 0) {

                goto rewind;

            }

            for (args = 0; args < SVGA_BITMAP_SIZE(x, y); args++) {

                cursor.mask[args] = vmsvga_fifo_read_raw(s);

            }

            for (args = 0; args < SVGA_PIXMAP_SIZE(x, y, cursor.bpp); args++) {

                cursor.image[args] = vmsvga_fifo_read_raw(s);

            }

#ifdef HW_MOUSE_ACCEL

            vmsvga_cursor_define(s, &cursor);

            break;

#else

            args = 0;

            goto badcmd;

#endif

        /*

         * Other commands that we at least know the number of arguments

         * for so we can avoid FIFO desync if driver uses them illegally.

         */

        case SVGA_CMD_DEFINE_ALPHA_CURSOR:

            len -= 6;

            if (len < 0) {

                goto rewind;

            }

            vmsvga_fifo_read(s);

            vmsvga_fifo_read(s);

            vmsvga_fifo_read(s);

            x = vmsvga_fifo_read(s);

            y = vmsvga_fifo_read(s);

            args = x * y;

            goto badcmd;

        case SVGA_CMD_RECT_ROP_FILL:

            args = 6;

            goto badcmd;

        case SVGA_CMD_RECT_ROP_COPY:

            args = 7;

            goto badcmd;

        case SVGA_CMD_DRAW_GLYPH_CLIPPED:

            len -= 4;

            if (len < 0) {

                goto rewind;

            }

            vmsvga_fifo_read(s);

            vmsvga_fifo_read(s);

            args = 7 + (vmsvga_fifo_read(s) >> 2);

            goto badcmd;

        case SVGA_CMD_SURFACE_ALPHA_BLEND:

            args = 12;

            goto badcmd;

        /*

         * Other commands that are not listed as depending on any

         * CAPABILITIES bits, but are not described in the README either.

         */

        case SVGA_CMD_SURFACE_FILL:

        case SVGA_CMD_SURFACE_COPY:

        case SVGA_CMD_FRONT_ROP_FILL:

        case SVGA_CMD_FENCE:

        case SVGA_CMD_INVALID_CMD:

            break; /* Nop */

        default:

            args = 0;

        badcmd:

            len -= args;

            if (len < 0) {

                goto rewind;

            }

            while (args--) {

                vmsvga_fifo_read(s);

            }

            printf("%s: Unknown command 0x%02x in SVGA command FIFO\n",

                   __func__, cmd);

            break;

        rewind:

            s->cmd->stop = cmd_start;

            break;

        }

    }

    s->syncing = 0;

}


static void aw_a10_class_init(ObjectClass *oc, void *data)
{
    DeviceClass *dc = DEVICE_CLASS(oc);
    dc->realize = aw_a10_realize;
}


static void flash_sync_page(Flash *s, int page)

{

    QEMUIOVector *iov = g_new(QEMUIOVector, 1);

    if (!s->blk || blk_is_read_only(s->blk)) {

        return;

    }

    qemu_iovec_init(iov, 1);

    qemu_iovec_add(iov, s->storage + page * s->pi->page_size,

                   s->pi->page_size);

    blk_aio_pwritev(s->blk, page * s->pi->page_size, iov, 0,

                    blk_sync_complete, iov);

}


static int dca_find_frame_end(DCAParseContext * pc1, const uint8_t * buf,

                              int buf_size)

{

    int start_found, i;

    uint32_t state;

    ParseContext *pc = &pc1->pc;

    start_found = pc->frame_start_found;

    state = pc->state;

    i = 0;

    if (!start_found) {

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

            state = (state << 8) | buf[i];

            if (IS_MARKER(state, i, buf, buf_size)) {

                if (!pc1->lastmarker || state == pc1->lastmarker || pc1->lastmarker == DCA_HD_MARKER) {

                    start_found = 1;

                    pc1->lastmarker = state;

                    break;

                }

            }

        }

    }

    if (start_found) {

        for (; i < buf_size; i++) {

            pc1->size++;

            state = (state << 8) | buf[i];

            if (state == DCA_HD_MARKER && !pc1->hd_pos)

                pc1->hd_pos = pc1->size;

            if (IS_MARKER(state, i, buf, buf_size) && (state == pc1->lastmarker || pc1->lastmarker == DCA_HD_MARKER)) {

                if(pc1->framesize > pc1->size)

                    continue;

                if(!pc1->framesize){

                    pc1->framesize = pc1->hd_pos ? pc1->hd_pos : pc1->size;

                }

                pc->frame_start_found = 0;

                pc->state = -1;

                pc1->size = 0;

                return i - 3;

            }

        }

    }

    pc->frame_start_found = start_found;

    pc->state = state;

    return END_NOT_FOUND;

}


static int mpeg1_decode_picture(AVCodecContext *avctx, const uint8_t *buf,

                                int buf_size)

{

    Mpeg1Context *s1  = avctx->priv_data;

    MpegEncContext *s = &s1->mpeg_enc_ctx;

    int ref, f_code, vbv_delay;

    init_get_bits(&s->gb, buf, buf_size * 8);

    ref = get_bits(&s->gb, 10); /* temporal ref */

    s->pict_type = get_bits(&s->gb, 3);

    if (s->pict_type == 0 || s->pict_type > 3)

        return -1;

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

    if (s->pict_type == AV_PICTURE_TYPE_P ||

        s->pict_type == AV_PICTURE_TYPE_B) {

        s->full_pel[0] = get_bits1(&s->gb);

        f_code = get_bits(&s->gb, 3);

        if (f_code == 0 && (avctx->err_recognition & AV_EF_BITSTREAM))

            return -1;

        s->mpeg_f_code[0][0] = f_code;

        s->mpeg_f_code[0][1] = f_code;

    }

    if (s->pict_type == AV_PICTURE_TYPE_B) {

        s->full_pel[1] = get_bits1(&s->gb);

        f_code = get_bits(&s->gb, 3);

        if (f_code == 0 && (avctx->err_recognition & AV_EF_BITSTREAM))

            return -1;

        s->mpeg_f_code[1][0] = f_code;

        s->mpeg_f_code[1][1] = f_code;

    }

    s->current_picture.f.pict_type = s->pict_type;

    s->current_picture.f.key_frame = s->pict_type == AV_PICTURE_TYPE_I;

    if (avctx->debug & FF_DEBUG_PICT_INFO)

        av_log(avctx, AV_LOG_DEBUG,

               "vbv_delay %d, ref %d type:%d\n", vbv_delay, ref, s->pict_type);

    s->y_dc_scale = 8;

    s->c_dc_scale = 8;

    return 0;

}


static int read_quant_tables(RangeCoder *c,

                             int16_t quant_table[MAX_CONTEXT_INPUTS][256])

{

    int i;

    int context_count = 1;

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

        context_count *= read_quant_table(c, quant_table[i], context_count);

        if (context_count > 32768U) {

            return AVERROR_INVALIDDATA;

        }

    }

    return (context_count + 1) / 2;

}


int av_copy_packet_side_data(AVPacket *pkt, AVPacket *src)

{

    if (src->side_data_elems) {

        int i;

        DUP_DATA(pkt->side_data, src->side_data,

                src->side_data_elems * sizeof(*src->side_data), 0, ALLOC_MALLOC);

        memset(pkt->side_data, 0,

                src->side_data_elems * sizeof(*src->side_data));

        for (i = 0; i < src->side_data_elems; i++) {

            DUP_DATA(pkt->side_data[i].data, src->side_data[i].data,

                    src->side_data[i].size, 1, ALLOC_MALLOC);

            pkt->side_data[i].size = src->side_data[i].size;

            pkt->side_data[i].type = src->side_data[i].type;

        }

    }

    return 0;

failed_alloc:

    av_destruct_packet(pkt);

    return AVERROR(ENOMEM);

}


static inline void RENAME(rgb32tobgr32)(const uint8_t *src, uint8_t *dst, long src_size)

{

#ifdef HAVE_MMX

/* TODO: unroll this loop */

	asm volatile (

		"xor %%"REG_a", %%"REG_a"	\n\t"

		ASMALIGN16

		"1:				\n\t"

		PREFETCH" 32(%0, %%"REG_a")	\n\t"

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

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

		"movq %%mm0, %%mm2		\n\t"

		"pslld $16, %%mm0		\n\t"

		"psrld $16, %%mm1		\n\t"

		"pand "MANGLE(mask32r)", %%mm0	\n\t"

		"pand "MANGLE(mask32g)", %%mm2	\n\t"

		"pand "MANGLE(mask32b)", %%mm1	\n\t"

		"por %%mm0, %%mm2		\n\t"

		"por %%mm1, %%mm2		\n\t"

		MOVNTQ" %%mm2, (%1, %%"REG_a")	\n\t"

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

		"cmp %2, %%"REG_a"		\n\t"

		" jb 1b				\n\t"

		:: "r" (src), "r"(dst), "r" (src_size-7)

		: "%"REG_a

	);

	__asm __volatile(SFENCE:::"memory");

	__asm __volatile(EMMS:::"memory");

#else

	unsigned i;

	unsigned num_pixels = src_size >> 2;

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

	{

#ifdef WORDS_BIGENDIAN

	  dst[4*i + 1] = src[4*i + 3];

	  dst[4*i + 2] = src[4*i + 2];

	  dst[4*i + 3] = src[4*i + 1];

#else

	  dst[4*i + 0] = src[4*i + 2];

	  dst[4*i + 1] = src[4*i + 1];

	  dst[4*i + 2] = src[4*i + 0];

#endif

	}

#endif

}


static int read_block(ALSDecContext *ctx, ALSBlockData *bd)

{

    GetBitContext *gb        = &ctx->gb;

    *bd->shift_lsbs = 0;

    // read block type flag and read the samples accordingly

    if (get_bits1(gb)) {

        if (read_var_block_data(ctx, bd))

            return -1;

    } else {

        read_const_block_data(ctx, bd);

    }

    return 0;

}


static int init_input(AVFormatContext *s, const char *filename,

                      AVDictionary **options)

{

    int ret;

    AVProbeData pd = { filename, NULL, 0 };

    int score = AVPROBE_SCORE_RETRY;

    if (s->pb) {

        s->flags |= AVFMT_FLAG_CUSTOM_IO;

        if (!s->iformat)

            return av_probe_input_buffer2(s->pb, &s->iformat, filename,

                                         s, 0, s->format_probesize);

        else if (s->iformat->flags & AVFMT_NOFILE)

            av_log(s, AV_LOG_WARNING, "Custom AVIOContext makes no sense and "

                                      "will be ignored with AVFMT_NOFILE format.\n");

        return 0;

    }

    if ((s->iformat && s->iformat->flags & AVFMT_NOFILE) ||

        (!s->iformat && (s->iformat = av_probe_input_format2(&pd, 0, &score))))

        return score;

    if ((ret = avio_open2(&s->pb, filename, AVIO_FLAG_READ | s->avio_flags,

                          &s->interrupt_callback, options)) < 0)

        return ret;

    if (s->iformat)

        return 0;

    return av_probe_input_buffer2(s->pb, &s->iformat, filename,

                                 s, 0, s->format_probesize);

}


static int inet_aton(const char *str, struct in_addr *add)

{

    return inet_aton(str, add);

}


MAKE_ACCESSORS(AVVDPAUContext, vdpau_hwaccel, AVVDPAU_Render2, render2)

int ff_vdpau_common_init(AVCodecContext *avctx, VdpDecoderProfile profile,

                         int level)

{

    VDPAUHWContext *hwctx = avctx->hwaccel_context;

    VDPAUContext *vdctx = avctx->internal->hwaccel_priv_data;

    VdpVideoSurfaceQueryCapabilities *surface_query_caps;

    VdpDecoderQueryCapabilities *decoder_query_caps;

    VdpDecoderCreate *create;

    void *func;

    VdpStatus status;

    VdpBool supported;

    uint32_t max_level, max_mb, max_width, max_height;

    /* See vdpau/vdpau.h for alignment constraints. */

    uint32_t width  = (avctx->coded_width + 1) & ~1;

    uint32_t height = (avctx->coded_height + 3) & ~3;

    vdctx->width            = UINT32_MAX;

    vdctx->height           = UINT32_MAX;

    hwctx->reset            = 0;

    if (!hwctx) {

        vdctx->device  = VDP_INVALID_HANDLE;

        av_log(avctx, AV_LOG_WARNING, "hwaccel_context has not been setup by the user application, cannot initialize\n");

        return 0;

    }

    if (hwctx->context.decoder != VDP_INVALID_HANDLE) {

        vdctx->decoder = hwctx->context.decoder;

        vdctx->render  = hwctx->context.render;

        vdctx->device  = VDP_INVALID_HANDLE;

        return 0; /* Decoder created by user */

    }

    vdctx->device           = hwctx->device;

    vdctx->get_proc_address = hwctx->get_proc_address;

    if (level < 0)

        return AVERROR(ENOTSUP);

    status = vdctx->get_proc_address(vdctx->device,

                                     VDP_FUNC_ID_VIDEO_SURFACE_QUERY_CAPABILITIES,

                                     &func);

    if (status != VDP_STATUS_OK)

        return vdpau_error(status);

    else

        surface_query_caps = func;

    status = surface_query_caps(vdctx->device, VDP_CHROMA_TYPE_420, &supported,

                                &max_width, &max_height);

    if (status != VDP_STATUS_OK)

        return vdpau_error(status);

    if (supported != VDP_TRUE ||

        max_width < width || max_height < height)

        return AVERROR(ENOTSUP);

    status = vdctx->get_proc_address(vdctx->device,

                                     VDP_FUNC_ID_DECODER_QUERY_CAPABILITIES,

                                     &func);

    if (status != VDP_STATUS_OK)

        return vdpau_error(status);

    else

        decoder_query_caps = func;

    status = decoder_query_caps(vdctx->device, profile, &supported, &max_level,

                                &max_mb, &max_width, &max_height);

    if (status != VDP_STATUS_OK)

        return vdpau_error(status);

    if (supported != VDP_TRUE || max_level < level ||

        max_width < width || max_height < height)

        return AVERROR(ENOTSUP);

    status = vdctx->get_proc_address(vdctx->device, VDP_FUNC_ID_DECODER_CREATE,

                                     &func);

    if (status != VDP_STATUS_OK)

        return vdpau_error(status);

    else

        create = func;

    status = vdctx->get_proc_address(vdctx->device, VDP_FUNC_ID_DECODER_RENDER,

                                     &func);

    if (status != VDP_STATUS_OK)

        return vdpau_error(status);

    else

        vdctx->render = func;

    status = create(vdctx->device, profile, width, height, avctx->refs,

                    &vdctx->decoder);

    if (status == VDP_STATUS_OK) {

        vdctx->width  = avctx->coded_width;

        vdctx->height = avctx->coded_height;

    }

    return vdpau_error(status);

}


static qemu_irq *vpb_sic_init(uint32_t base, qemu_irq *parent, int irq)

{

    vpb_sic_state *s;

    qemu_irq *qi;

    int iomemtype;

    s = (vpb_sic_state *)qemu_mallocz(sizeof(vpb_sic_state));

    if (!s)

        return NULL;

    qi = qemu_allocate_irqs(vpb_sic_set_irq, s, 32);

    s->base = base;

    s->parent = parent;

    s->irq = irq;

    iomemtype = cpu_register_io_memory(0, vpb_sic_readfn,

                                       vpb_sic_writefn, s);

    cpu_register_physical_memory(base, 0x00000fff, iomemtype);

    /* ??? Save/restore.  */

    return qi;

}


static bool use_exit_tb(DisasContext *s)

{

    return (s->singlestep_enabled ||

            (s->tb->cflags & CF_LAST_IO) ||

            (s->tb->flags & FLAG_MASK_PER));

}


static int opt_show_format_entry(void *optctx, const char *opt, const char *arg)
{
    char *buf = av_asprintf("format=%s", arg);
    int ret;
    av_log(NULL, AV_LOG_WARNING,
           "Option '%s' is deprecated, use '-show_entries format=%s' instead\n",
           opt, arg);
    ret = opt_show_entries(optctx, opt, buf);
    av_free(buf);
    return ret;
}


int qcow2_get_cluster_offset(BlockDriverState *bs, uint64_t offset,

    int *num, uint64_t *cluster_offset)

{

    BDRVQcowState *s = bs->opaque;

    unsigned int l2_index;

    uint64_t l1_index, l2_offset, *l2_table;

    int l1_bits, c;

    unsigned int index_in_cluster, nb_clusters;

    uint64_t nb_available, nb_needed;

    int ret;

    index_in_cluster = (offset >> 9) & (s->cluster_sectors - 1);

    nb_needed = *num + index_in_cluster;

    l1_bits = s->l2_bits + s->cluster_bits;

    /* compute how many bytes there are between the offset and

     * the end of the l1 entry

     */

    nb_available = (1ULL << l1_bits) - (offset & ((1ULL << l1_bits) - 1));

    /* compute the number of available sectors */

    nb_available = (nb_available >> 9) + index_in_cluster;

    if (nb_needed > nb_available) {

        nb_needed = nb_available;

    }

    *cluster_offset = 0;

    /* seek the the l2 offset in the l1 table */

    l1_index = offset >> l1_bits;

    if (l1_index >= s->l1_size) {

        ret = QCOW2_CLUSTER_UNALLOCATED;

        goto out;

    }

    l2_offset = s->l1_table[l1_index] & L1E_OFFSET_MASK;

    if (!l2_offset) {

        ret = QCOW2_CLUSTER_UNALLOCATED;

        goto out;

    }

    /* load the l2 table in memory */

    ret = l2_load(bs, l2_offset, &l2_table);

    if (ret < 0) {

        return ret;

    }

    /* find the cluster offset for the given disk offset */

    l2_index = (offset >> s->cluster_bits) & (s->l2_size - 1);

    *cluster_offset = be64_to_cpu(l2_table[l2_index]);

    nb_clusters = size_to_clusters(s, nb_needed << 9);

    ret = qcow2_get_cluster_type(*cluster_offset);

    switch (ret) {

    case QCOW2_CLUSTER_COMPRESSED:

        /* Compressed clusters can only be processed one by one */

        c = 1;

        *cluster_offset &= L2E_COMPRESSED_OFFSET_SIZE_MASK;

        break;

    case QCOW2_CLUSTER_ZERO:

        if (s->qcow_version < 3) {

            return -EIO;

        }

        c = count_contiguous_clusters(nb_clusters, s->cluster_size,

                &l2_table[l2_index], QCOW_OFLAG_ZERO);

        *cluster_offset = 0;

        break;

    case QCOW2_CLUSTER_UNALLOCATED:

        /* how many empty clusters ? */

        c = count_contiguous_free_clusters(nb_clusters, &l2_table[l2_index]);

        *cluster_offset = 0;

        break;

    case QCOW2_CLUSTER_NORMAL:

        /* how many allocated clusters ? */

        c = count_contiguous_clusters(nb_clusters, s->cluster_size,

                &l2_table[l2_index], QCOW_OFLAG_ZERO);

        *cluster_offset &= L2E_OFFSET_MASK;

        break;

    default:

        abort();

    }

    nb_available = (c * s->cluster_sectors);

out:

    if (nb_available > nb_needed)

        nb_available = nb_needed;

    *num = nb_available - index_in_cluster;

    return ret;

}


static AVFilterContext *create_filter_with_args(const char *filt, void *opaque)
{
    AVFilterContext *ret;
    char *filter = av_strdup(filt); /* copy - don't mangle the input string */
    char *name, *args;
    name = filter;
    if((args = strchr(filter, '='))) {
        /* ensure we at least have a name */
        if(args == filter)
            goto fail;
        *args ++ = 0;
    }
    av_log(NULL, AV_LOG_INFO, "creating filter \"%s\" with args \"%s\"\n",
           name, args ? args : "(none)");
    if((ret = avfilter_create_by_name(name, NULL))) {
        if(avfilter_init_filter(ret, args, opaque)) {
            av_log(NULL, AV_LOG_ERROR, "error initializing filter!\n");
            avfilter_destroy(ret);
            goto fail;
        }
    } else av_log(NULL, AV_LOG_ERROR, "error creating filter!\n");
    return ret;
fail:
    return NULL;
}


static int set_string_binary(void *obj, const AVOption *o, const char *val, uint8_t **dst)

{

    int *lendst = (int *)(dst + 1);

    uint8_t *bin, *ptr;

    int len = strlen(val);

    av_freep(dst);

    *lendst = 0;

    if (len & 1)

        return AVERROR(EINVAL);

    len /= 2;

    ptr = bin = av_malloc(len);

    while (*val) {

        int a = hexchar2int(*val++);

        int b = hexchar2int(*val++);

        if (a < 0 || b < 0) {

            av_free(bin);

            return AVERROR(EINVAL);

        }

        *ptr++ = (a << 4) | b;

    }

    *dst = bin;

    *lendst = len;

    return 0;

}


static int xen_host_pci_get_resource(XenHostPCIDevice *d)

{

    int i, rc, fd;

    char path[PATH_MAX];

    char buf[XEN_HOST_PCI_RESOURCE_BUFFER_SIZE];

    unsigned long long start, end, flags, size;

    char *endptr, *s;

    uint8_t type;

    rc = xen_host_pci_sysfs_path(d, "resource", path, sizeof (path));

    if (rc) {

        return rc;

    }

    fd = open(path, O_RDONLY);

    if (fd == -1) {

        XEN_HOST_PCI_LOG("Error: Can't open %s: %s\n", path, strerror(errno));

        return -errno;

    }

    do {

        rc = read(fd, &buf, sizeof (buf) - 1);

        if (rc < 0 && errno != EINTR) {

            rc = -errno;

            goto out;

        }

    } while (rc < 0);

    buf[rc] = 0;

    rc = 0;

    s = buf;

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

        type = 0;

        start = strtoll(s, &endptr, 16);

        if (*endptr != ' ' || s == endptr) {

            break;

        }

        s = endptr + 1;

        end = strtoll(s, &endptr, 16);

        if (*endptr != ' ' || s == endptr) {

            break;

        }

        s = endptr + 1;

        flags = strtoll(s, &endptr, 16);

        if (*endptr != '\n' || s == endptr) {

            break;

        }

        s = endptr + 1;

        if (start) {

            size = end - start + 1;

        } else {

            size = 0;

        }

        if (flags & IORESOURCE_IO) {

            type |= XEN_HOST_PCI_REGION_TYPE_IO;

        }

        if (flags & IORESOURCE_MEM) {

            type |= XEN_HOST_PCI_REGION_TYPE_MEM;

        }

        if (flags & IORESOURCE_PREFETCH) {

            type |= XEN_HOST_PCI_REGION_TYPE_PREFETCH;

        }

        if (flags & IORESOURCE_MEM_64) {

            type |= XEN_HOST_PCI_REGION_TYPE_MEM_64;

        }

        if (i < PCI_ROM_SLOT) {

            d->io_regions[i].base_addr = start;

            d->io_regions[i].size = size;

            d->io_regions[i].type = type;

            d->io_regions[i].bus_flags = flags & IORESOURCE_BITS;

        } else {

            d->rom.base_addr = start;

            d->rom.size = size;

            d->rom.type = type;

            d->rom.bus_flags = flags & IORESOURCE_BITS;

        }

    }

    if (i != PCI_NUM_REGIONS) {

        /* Invalid format or input to short */

        rc = -ENODEV;

    }

out:

    close(fd);

    return rc;

}


static int decode_nal_units(H264Context *h, uint8_t *buf, int buf_size){

    MpegEncContext * const s = &h->s;

    AVCodecContext * const avctx= s->avctx;

    int buf_index=0;

#if 0

    int i;

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

        av_log(NULL, AV_LOG_ERROR,"%02X ", buf[i]);

    }

#endif

    h->slice_num = 0;

    s->current_picture_ptr= NULL;

    for(;;){

        int consumed;

        int dst_length;

        int bit_length;

        uint8_t *ptr;

        int i, nalsize = 0;

      if(h->is_avc) {

        if(buf_index >= buf_size) break;

        nalsize = 0;

        for(i = 0; i < h->nal_length_size; i++)

            nalsize = (nalsize << 8) | buf[buf_index++];

        if(nalsize <= 1){

            if(nalsize == 1){

                buf_index++;

                continue;

            }else{

                av_log(h->s.avctx, AV_LOG_ERROR, "AVC: nal size %d\n", nalsize);

                break;

            }

        }

      } else {

        // start code prefix search

        for(; buf_index + 3 < buf_size; buf_index++){

            // this should allways succeed in the first iteration

            if(buf[buf_index] == 0 && buf[buf_index+1] == 0 && buf[buf_index+2] == 1)

                break;

        }

        if(buf_index+3 >= buf_size) break;

        buf_index+=3;

      }

        ptr= decode_nal(h, buf + buf_index, &dst_length, &consumed, h->is_avc ? nalsize : buf_size - buf_index);

        while(ptr[dst_length - 1] == 0 && dst_length > 1)

            dst_length--;

        bit_length= 8*dst_length - decode_rbsp_trailing(ptr + dst_length - 1);

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

            av_log(h->s.avctx, AV_LOG_DEBUG, "NAL %d at %d/%d length %d\n", h->nal_unit_type, buf_index, buf_size, dst_length);

        }

        if (h->is_avc && (nalsize != consumed))

            av_log(h->s.avctx, AV_LOG_ERROR, "AVC: Consumed only %d bytes instead of %d\n", consumed, nalsize);

        buf_index += consumed;

        if(  (s->hurry_up == 1 && h->nal_ref_idc  == 0) //FIXME dont discard SEI id

           ||(avctx->skip_frame >= AVDISCARD_NONREF && h->nal_ref_idc  == 0))

            continue;

        switch(h->nal_unit_type){

        case NAL_IDR_SLICE:

            idr(h); //FIXME ensure we don't loose some frames if there is reordering

        case NAL_SLICE:

            init_get_bits(&s->gb, ptr, bit_length);

            h->intra_gb_ptr=

            h->inter_gb_ptr= &s->gb;

            s->data_partitioning = 0;

            if(decode_slice_header(h) < 0){

                av_log(h->s.avctx, AV_LOG_ERROR, "decode_slice_header error\n");

                break;

            }

            s->current_picture_ptr->key_frame= (h->nal_unit_type == NAL_IDR_SLICE);

            if(h->redundant_pic_count==0 && s->hurry_up < 5

               && (avctx->skip_frame < AVDISCARD_NONREF || h->nal_ref_idc)

               && (avctx->skip_frame < AVDISCARD_BIDIR  || h->slice_type!=B_TYPE)

               && (avctx->skip_frame < AVDISCARD_NONKEY || h->slice_type==I_TYPE)

               && avctx->skip_frame < AVDISCARD_ALL)

                decode_slice(h);

            break;

        case NAL_DPA:

            init_get_bits(&s->gb, ptr, bit_length);

            h->intra_gb_ptr=

            h->inter_gb_ptr= NULL;

            s->data_partitioning = 1;

            if(decode_slice_header(h) < 0){

                av_log(h->s.avctx, AV_LOG_ERROR, "decode_slice_header error\n");

            }

            break;

        case NAL_DPB:

            init_get_bits(&h->intra_gb, ptr, bit_length);

            h->intra_gb_ptr= &h->intra_gb;

            break;

        case NAL_DPC:

            init_get_bits(&h->inter_gb, ptr, bit_length);

            h->inter_gb_ptr= &h->inter_gb;

            if(h->redundant_pic_count==0 && h->intra_gb_ptr && s->data_partitioning

               && s->context_initialized

               && s->hurry_up < 5

               && (avctx->skip_frame < AVDISCARD_NONREF || h->nal_ref_idc)

               && (avctx->skip_frame < AVDISCARD_BIDIR  || h->slice_type!=B_TYPE)

               && (avctx->skip_frame < AVDISCARD_NONKEY || h->slice_type==I_TYPE)

               && avctx->skip_frame < AVDISCARD_ALL)

                decode_slice(h);

            break;

        case NAL_SEI:

            init_get_bits(&s->gb, ptr, bit_length);

            decode_sei(h);

            break;

        case NAL_SPS:

            init_get_bits(&s->gb, ptr, bit_length);

            decode_seq_parameter_set(h);

            if(s->flags& CODEC_FLAG_LOW_DELAY)

                s->low_delay=1;

            if(avctx->has_b_frames < 2)

                avctx->has_b_frames= !s->low_delay;

            break;

        case NAL_PPS:

            init_get_bits(&s->gb, ptr, bit_length);

            decode_picture_parameter_set(h, bit_length);

            break;

        case NAL_AUD:

        case NAL_END_SEQUENCE:

        case NAL_END_STREAM:

        case NAL_FILLER_DATA:

        case NAL_SPS_EXT:

        case NAL_AUXILIARY_SLICE:

            break;

        default:

            av_log(avctx, AV_LOG_ERROR, "Unknown NAL code: %d\n", h->nal_unit_type);

        }

    }

    if(!s->current_picture_ptr) return buf_index; //no frame

    s->current_picture_ptr->qscale_type= FF_QSCALE_TYPE_H264;

    s->current_picture_ptr->pict_type= s->pict_type;

    h->prev_frame_num_offset= h->frame_num_offset;

    h->prev_frame_num= h->frame_num;

    if(s->current_picture_ptr->reference){

        h->prev_poc_msb= h->poc_msb;

        h->prev_poc_lsb= h->poc_lsb;

    }

    if(s->current_picture_ptr->reference)

        execute_ref_pic_marking(h, h->mmco, h->mmco_index);

    ff_er_frame_end(s);

    MPV_frame_end(s);

    return buf_index;

}


static target_ulong h_put_tce(PowerPCCPU *cpu, sPAPREnvironment *spapr,

                              target_ulong opcode, target_ulong *args)

{

    target_ulong liobn = args[0];

    target_ulong ioba = args[1];

    target_ulong tce = args[2];

    sPAPRTCETable *tcet = spapr_tce_find_by_liobn(liobn);

    if (liobn & 0xFFFFFFFF00000000ULL) {

        hcall_dprintf("spapr_vio_put_tce on out-of-boundsw LIOBN "

                      TARGET_FMT_lx "\n", liobn);

        return H_PARAMETER;

    }

    ioba &= ~(SPAPR_TCE_PAGE_SIZE - 1);

    if (tcet) {

        return put_tce_emu(tcet, ioba, tce);

    }

#ifdef DEBUG_TCE

    fprintf(stderr, "%s on liobn=" TARGET_FMT_lx /*%s*/

            "  ioba 0x" TARGET_FMT_lx "  TCE 0x" TARGET_FMT_lx "\n",

            __func__, liobn, /*dev->qdev.id, */ioba, tce);

#endif

    return H_PARAMETER;

}


static void ivi_process_empty_tile(AVCodecContext *avctx, IVIBandDesc *band,

                                   IVITile *tile, int32_t mv_scale)

{

    int             x, y, need_mc, mbn, blk, num_blocks, mv_x, mv_y, mc_type;

    int             offs, mb_offset, row_offset;

    IVIMbInfo       *mb, *ref_mb;

    const int16_t   *src;

    int16_t         *dst;

    void (*mc_no_delta_func)(int16_t *buf, const int16_t *ref_buf, uint32_t pitch,

                             int mc_type);

    offs       = tile->ypos * band->pitch + tile->xpos;

    mb         = tile->mbs;

    ref_mb     = tile->ref_mbs;

    row_offset = band->mb_size * band->pitch;

    need_mc    = 0; /* reset the mc tracking flag */

    for (y = tile->ypos; y < (tile->ypos + tile->height); y += band->mb_size) {

        mb_offset = offs;

        for (x = tile->xpos; x < (tile->xpos + tile->width); x += band->mb_size) {

            mb->xpos     = x;

            mb->ypos     = y;

            mb->buf_offs = mb_offset;

            mb->type = 1; /* set the macroblocks type = INTER */

            mb->cbp  = 0; /* all blocks are empty */

            if (!band->qdelta_present && !band->plane && !band->band_num) {

                mb->q_delta = band->glob_quant;

                mb->mv_x    = 0;

                mb->mv_y    = 0;

            }

            if (band->inherit_qdelta && ref_mb)

                mb->q_delta = ref_mb->q_delta;

            if (band->inherit_mv) {

                /* motion vector inheritance */

                if (mv_scale) {

                    mb->mv_x = ivi_scale_mv(ref_mb->mv_x, mv_scale);

                    mb->mv_y = ivi_scale_mv(ref_mb->mv_y, mv_scale);

                } else {

                    mb->mv_x = ref_mb->mv_x;

                    mb->mv_y = ref_mb->mv_y;

                }

                need_mc |= mb->mv_x || mb->mv_y; /* tracking non-zero motion vectors */

            }

            mb++;

            if (ref_mb)

                ref_mb++;

            mb_offset += band->mb_size;

        } // for x

        offs += row_offset;

    } // for y

    if (band->inherit_mv && need_mc) { /* apply motion compensation if there is at least one non-zero motion vector */

        num_blocks = (band->mb_size != band->blk_size) ? 4 : 1; /* number of blocks per mb */

        mc_no_delta_func = (band->blk_size == 8) ? ff_ivi_mc_8x8_no_delta

                                                 : ff_ivi_mc_4x4_no_delta;

        for (mbn = 0, mb = tile->mbs; mbn < tile->num_MBs; mb++, mbn++) {

            mv_x = mb->mv_x;

            mv_y = mb->mv_y;

            if (!band->is_halfpel) {

                mc_type = 0; /* we have only fullpel vectors */

            } else {

                mc_type = ((mv_y & 1) << 1) | (mv_x & 1);

                mv_x >>= 1;

                mv_y >>= 1; /* convert halfpel vectors into fullpel ones */

            }

            for (blk = 0; blk < num_blocks; blk++) {

                /* adjust block position in the buffer according with its number */

                offs = mb->buf_offs + band->blk_size * ((blk & 1) + !!(blk & 2) * band->pitch);

                mc_no_delta_func(band->buf + offs,

                                 band->ref_buf + offs + mv_y * band->pitch + mv_x,

                                 band->pitch, mc_type);

            }

        }

    } else {

        /* copy data from the reference tile into the current one */

        src = band->ref_buf + tile->ypos * band->pitch + tile->xpos;

        dst = band->buf     + tile->ypos * band->pitch + tile->xpos;

        for (y = 0; y < tile->height; y++) {

            memcpy(dst, src, tile->width*sizeof(band->buf[0]));

            src += band->pitch;

            dst += band->pitch;

        }

    }

}


static void handle_rev16(DisasContext *s, unsigned int sf,

                         unsigned int rn, unsigned int rd)

{

    TCGv_i64 tcg_rd = cpu_reg(s, rd);

    TCGv_i64 tcg_tmp = tcg_temp_new_i64();

    TCGv_i64 tcg_rn = read_cpu_reg(s, rn, sf);

    TCGv_i64 mask = tcg_const_i64(sf ? 0x00ff00ff00ff00ffull : 0x00ff00ff);

    tcg_gen_shri_i64(tcg_tmp, tcg_rn, 8);

    tcg_gen_and_i64(tcg_rd, tcg_rn, mask);

    tcg_gen_and_i64(tcg_tmp, tcg_tmp, mask);

    tcg_gen_shli_i64(tcg_rd, tcg_rd, 8);

    tcg_gen_or_i64(tcg_rd, tcg_rd, tcg_tmp);

    tcg_temp_free_i64(tcg_tmp);

}


static void guess_dc(MpegEncContext *s, int16_t *dc, int w,
                     int h, int stride, int is_luma)
{
    int b_x, b_y;
    int16_t  (*col )[4] = av_malloc(stride*h*sizeof( int16_t)*4);
    uint32_t (*dist)[4] = av_malloc(stride*h*sizeof(uint32_t)*4);
    if(!col || !dist) {
        av_log(s->avctx, AV_LOG_ERROR, "guess_dc() is out of memory\n");
        goto fail;
    }
    for(b_y=0; b_y<h; b_y++){
        int color= 1024;
        int distance= -1;
        for(b_x=0; b_x<w; b_x++){
            int mb_index_j= (b_x>>is_luma) + (b_y>>is_luma)*s->mb_stride;
            int error_j= s->error_status_table[mb_index_j];
            int intra_j = IS_INTRA(s->current_picture.f.mb_type[mb_index_j]);
            if(intra_j==0 || !(error_j&ER_DC_ERROR)){
                color= dc[b_x + b_y*stride];
                distance= b_x;
            }
            col [b_x + b_y*stride][1]= color;
            dist[b_x + b_y*stride][1]= distance >= 0 ? b_x-distance : 9999;
        }
        color= 1024;
        distance= -1;
        for(b_x=w-1; b_x>=0; b_x--){
            int mb_index_j= (b_x>>is_luma) + (b_y>>is_luma)*s->mb_stride;
            int error_j= s->error_status_table[mb_index_j];
            int intra_j = IS_INTRA(s->current_picture.f.mb_type[mb_index_j]);
            if(intra_j==0 || !(error_j&ER_DC_ERROR)){
                color= dc[b_x + b_y*stride];
                distance= b_x;
            }
            col [b_x + b_y*stride][0]= color;
            dist[b_x + b_y*stride][0]= distance >= 0 ? distance-b_x : 9999;
        }
    }
    for(b_x=0; b_x<w; b_x++){
        int color= 1024;
        int distance= -1;
        for(b_y=0; b_y<h; b_y++){
            int mb_index_j= (b_x>>is_luma) + (b_y>>is_luma)*s->mb_stride;
            int error_j= s->error_status_table[mb_index_j];
            int intra_j = IS_INTRA(s->current_picture.f.mb_type[mb_index_j]);
            if(intra_j==0 || !(error_j&ER_DC_ERROR)){
                color= dc[b_x + b_y*stride];
                distance= b_y;
            }
            col [b_x + b_y*stride][3]= color;
            dist[b_x + b_y*stride][3]= distance >= 0 ? b_y-distance : 9999;
        }
        color= 1024;
        distance= -1;
        for(b_y=h-1; b_y>=0; b_y--){
            int mb_index_j= (b_x>>is_luma) + (b_y>>is_luma)*s->mb_stride;
            int error_j= s->error_status_table[mb_index_j];
            int intra_j = IS_INTRA(s->current_picture.f.mb_type[mb_index_j]);
            if(intra_j==0 || !(error_j&ER_DC_ERROR)){
                color= dc[b_x + b_y*stride];
                distance= b_y;
            }
            col [b_x + b_y*stride][2]= color;
            dist[b_x + b_y*stride][2]= distance >= 0 ? distance-b_y : 9999;
        }
    }
    for (b_y = 0; b_y < h; b_y++) {
        for (b_x = 0; b_x < w; b_x++) {
            int mb_index, error, j;
            int64_t guess, weight_sum;
            mb_index = (b_x >> is_luma) + (b_y >> is_luma) * s->mb_stride;
            error    = s->error_status_table[mb_index];
            if (IS_INTER(s->current_picture.f.mb_type[mb_index]))
                continue; // inter
            if (!(error & ER_DC_ERROR))
                continue; // dc-ok
            weight_sum = 0;
            guess      = 0;
            for (j = 0; j < 4; j++) {
                int64_t weight  = 256 * 256 * 256 * 16 / FFMAX(dist[b_x + b_y*stride][j], 1);
                guess          += weight*(int64_t)col[b_x + b_y*stride][j];
                weight_sum     += weight;
            }
            guess = (guess + weight_sum / 2) / weight_sum;
            dc[b_x + b_y * stride] = guess;
        }
    }
    av_freep(&col);
    av_freep(&dist);
}


int ff_flac_parse_picture(AVFormatContext *s, uint8_t *buf, int buf_size)

{

    const CodecMime *mime = ff_id3v2_mime_tags;

    enum AVCodecID id = AV_CODEC_ID_NONE;

    AVBufferRef *data = NULL;

    uint8_t mimetype[64], *desc = NULL;

    AVIOContext *pb = NULL;

    AVStream *st;

    int type, width, height;

    int len, ret = 0;

    pb = avio_alloc_context(buf, buf_size, 0, NULL, NULL, NULL, NULL);

    if (!pb)

        return AVERROR(ENOMEM);

    /* read the picture type */

    type = avio_rb32(pb);

    if (type >= FF_ARRAY_ELEMS(ff_id3v2_picture_types) || type < 0) {

        av_log(s, AV_LOG_ERROR, "Invalid picture type: %d.\n", type);

        if (s->error_recognition & AV_EF_EXPLODE) {

            ret = AVERROR_INVALIDDATA;

            goto fail;

        }

        type = 0;

    }

    /* picture mimetype */

    len = avio_rb32(pb);

    if (len <= 0 ||

        avio_read(pb, mimetype, FFMIN(len, sizeof(mimetype) - 1)) != len) {

        av_log(s, AV_LOG_ERROR, "Could not read mimetype from an attached "

               "picture.\n");

        if (s->error_recognition & AV_EF_EXPLODE)

            ret = AVERROR_INVALIDDATA;

        goto fail;

    }

    mimetype[len] = 0;

    while (mime->id != AV_CODEC_ID_NONE) {

        if (!strncmp(mime->str, mimetype, sizeof(mimetype))) {

            id = mime->id;

            break;

        }

        mime++;

    }

    if (id == AV_CODEC_ID_NONE) {

        av_log(s, AV_LOG_ERROR, "Unknown attached picture mimetype: %s.\n",

               mimetype);

        if (s->error_recognition & AV_EF_EXPLODE)

            ret = AVERROR_INVALIDDATA;

        goto fail;

    }

    /* picture description */

    len = avio_rb32(pb);

    if (len > 0) {

        if (!(desc = av_malloc(len + 1))) {

            ret = AVERROR(ENOMEM);

            goto fail;

        }

        if (avio_read(pb, desc, len) != len) {

            av_log(s, AV_LOG_ERROR, "Error reading attached picture description.\n");

            if (s->error_recognition & AV_EF_EXPLODE)

                ret = AVERROR(EIO);

            goto fail;

        }

        desc[len] = 0;

    }

    /* picture metadata */

    width  = avio_rb32(pb);

    height = avio_rb32(pb);

    avio_skip(pb, 8);

    /* picture data */

    len = avio_rb32(pb);

    if (len <= 0) {

        av_log(s, AV_LOG_ERROR, "Invalid attached picture size: %d.\n", len);

        if (s->error_recognition & AV_EF_EXPLODE)

            ret = AVERROR_INVALIDDATA;

        goto fail;

    }

    if (!(data = av_buffer_alloc(len))) {

        ret = AVERROR(ENOMEM);

        goto fail;

    }

    if (avio_read(pb, data->data, len) != len) {

        av_log(s, AV_LOG_ERROR, "Error reading attached picture data.\n");

        if (s->error_recognition & AV_EF_EXPLODE)

            ret = AVERROR(EIO);

        goto fail;

    }

    st = avformat_new_stream(s, NULL);

    if (!st) {

        ret = AVERROR(ENOMEM);

        goto fail;

    }

    av_init_packet(&st->attached_pic);

    st->attached_pic.buf          = data;

    st->attached_pic.data         = data->data;

    st->attached_pic.size         = len;

    st->attached_pic.stream_index = st->index;

    st->attached_pic.flags       |= AV_PKT_FLAG_KEY;

    st->disposition      |= AV_DISPOSITION_ATTACHED_PIC;

    st->codec->codec_type = AVMEDIA_TYPE_VIDEO;

    st->codec->codec_id   = id;

    st->codec->width      = width;

    st->codec->height     = height;

    av_dict_set(&st->metadata, "comment", ff_id3v2_picture_types[type], 0);

    if (desc)

        av_dict_set(&st->metadata, "title", desc, AV_DICT_DONT_STRDUP_VAL);

    av_freep(&pb);

    return 0;

fail:

    av_buffer_unref(&data);

    av_freep(&desc);

    av_freep(&pb);

    return ret;

}


int avpriv_mpegaudio_decode_header(MPADecodeHeader *s, uint32_t header)

{

    int sample_rate, frame_size, mpeg25, padding;

    int sample_rate_index, bitrate_index;

    if (header & (1<<20)) {

        s->lsf = (header & (1<<19)) ? 0 : 1;

        mpeg25 = 0;

    } else {

        s->lsf = 1;

        mpeg25 = 1;

    }

    s->layer = 4 - ((header >> 17) & 3);

    /* extract frequency */

    sample_rate_index = (header >> 10) & 3;

    sample_rate = avpriv_mpa_freq_tab[sample_rate_index] >> (s->lsf + mpeg25);

    sample_rate_index += 3 * (s->lsf + mpeg25);

    s->sample_rate_index = sample_rate_index;

    s->error_protection = ((header >> 16) & 1) ^ 1;

    s->sample_rate = sample_rate;

    bitrate_index = (header >> 12) & 0xf;

    padding = (header >> 9) & 1;

    //extension = (header >> 8) & 1;

    s->mode = (header >> 6) & 3;

    s->mode_ext = (header >> 4) & 3;

    //copyright = (header >> 3) & 1;

    //original = (header >> 2) & 1;

    //emphasis = header & 3;

    if (s->mode == MPA_MONO)

        s->nb_channels = 1;

    else

        s->nb_channels = 2;

    if (bitrate_index != 0) {

        frame_size = avpriv_mpa_bitrate_tab[s->lsf][s->layer - 1][bitrate_index];

        s->bit_rate = frame_size * 1000;

        switch(s->layer) {

        case 1:

            frame_size = (frame_size * 12000) / sample_rate;

            frame_size = (frame_size + padding) * 4;

            break;

        case 2:

            frame_size = (frame_size * 144000) / sample_rate;

            frame_size += padding;

            break;

        default:

        case 3:

            frame_size = (frame_size * 144000) / (sample_rate << s->lsf);

            frame_size += padding;

            break;

        }

        s->frame_size = frame_size;

    } else {

        /* if no frame size computed, signal it */

        return 1;

    }

#if defined(DEBUG)

    av_dlog(NULL, "layer%d, %d Hz, %d kbits/s, ",

           s->layer, s->sample_rate, s->bit_rate);

    if (s->nb_channels == 2) {

        if (s->layer == 3) {

            if (s->mode_ext & MODE_EXT_MS_STEREO)

                av_dlog(NULL, "ms-");

            if (s->mode_ext & MODE_EXT_I_STEREO)

                av_dlog(NULL, "i-");

        }

        av_dlog(NULL, "stereo");

    } else {

        av_dlog(NULL, "mono");

    }

    av_dlog(NULL, "\n");

#endif

    return 0;

}


static int vhost_set_vring(struct vhost_dev *dev,

                           unsigned long int request,

                           struct vhost_vring_state *ring)

{

    VhostUserMsg msg = {

        .request = request,

        .flags = VHOST_USER_VERSION,

        .state = *ring,

        .size = sizeof(*ring),

    };

    vhost_user_write(dev, &msg, NULL, 0);

    return 0;

}


static int encode_picture_lossless(AVCodecContext *avctx, AVPacket *pkt,
                                   const AVFrame *pict, int *got_packet)
{
    MpegEncContext * const s = avctx->priv_data;
    MJpegContext * const m = s->mjpeg_ctx;
    const int width= s->width;
    const int height= s->height;
    AVFrame * const p = &s->current_picture.f;
    const int predictor= avctx->prediction_method+1;
    const int mb_width  = (width  + s->mjpeg_hsample[0] - 1) / s->mjpeg_hsample[0];
    const int mb_height = (height + s->mjpeg_vsample[0] - 1) / s->mjpeg_vsample[0];
    int ret, max_pkt_size = FF_MIN_BUFFER_SIZE;
    if (avctx->pix_fmt == AV_PIX_FMT_BGRA)
        max_pkt_size += width * height * 3 * 4;
    else {
        max_pkt_size += mb_width * mb_height * 3 * 4
                        * s->mjpeg_hsample[0] * s->mjpeg_vsample[0];
    if ((ret = ff_alloc_packet2(avctx, pkt, max_pkt_size)) < 0)
    init_put_bits(&s->pb, pkt->data, pkt->size);
    *p = *pict;
    p->pict_type= AV_PICTURE_TYPE_I;
    p->key_frame= 1;
    ff_mjpeg_encode_picture_header(s);
    s->header_bits= put_bits_count(&s->pb);
    if(avctx->pix_fmt == AV_PIX_FMT_BGR0
        || avctx->pix_fmt == AV_PIX_FMT_BGRA
        || avctx->pix_fmt == AV_PIX_FMT_BGR24){
        int x, y, i;
        const int linesize= p->linesize[0];
        uint16_t (*buffer)[4]= (void *) s->rd_scratchpad;
        int left[3], top[3], topleft[3];
        for(i=0; i<3; i++){
            buffer[0][i]= 1 << (9 - 1);
        for(y = 0; y < height; y++) {
            const int modified_predictor= y ? predictor : 1;
            uint8_t *ptr = p->data[0] + (linesize * y);
            if(s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < width*3*4){
                av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
                return -1;
            for(i=0; i<3; i++){
                top[i]= left[i]= topleft[i]= buffer[0][i];
            for(x = 0; x < width; x++) {
                if(avctx->pix_fmt == AV_PIX_FMT_BGR24){
                    buffer[x][1] = ptr[3*x+0] - ptr[3*x+1] + 0x100;
                    buffer[x][2] = ptr[3*x+2] - ptr[3*x+1] + 0x100;
                    buffer[x][0] = (ptr[3*x+0] + 2*ptr[3*x+1] + ptr[3*x+2])>>2;
                }else{
                buffer[x][1] = ptr[4*x+0] - ptr[4*x+1] + 0x100;
                buffer[x][2] = ptr[4*x+2] - ptr[4*x+1] + 0x100;
                buffer[x][0] = (ptr[4*x+0] + 2*ptr[4*x+1] + ptr[4*x+2])>>2;
                for(i=0;i<3;i++) {
                    int pred, diff;
                    PREDICT(pred, topleft[i], top[i], left[i], modified_predictor);
                    topleft[i]= top[i];
                    top[i]= buffer[x+1][i];
                    left[i]= buffer[x][i];
                    diff= ((left[i] - pred + 0x100)&0x1FF) - 0x100;
                    if(i==0)
                        ff_mjpeg_encode_dc(s, diff, m->huff_size_dc_luminance, m->huff_code_dc_luminance); //FIXME ugly
                    else
                        ff_mjpeg_encode_dc(s, diff, m->huff_size_dc_chrominance, m->huff_code_dc_chrominance);
    }else{
        int mb_x, mb_y, i;
        for(mb_y = 0; mb_y < mb_height; mb_y++) {
            if(s->pb.buf_end - s->pb.buf - (put_bits_count(&s->pb)>>3) < mb_width * 4 * 3 * s->mjpeg_hsample[0] * s->mjpeg_vsample[0]){
                av_log(s->avctx, AV_LOG_ERROR, "encoded frame too large\n");
                return -1;
            for(mb_x = 0; mb_x < mb_width; mb_x++) {
                if(mb_x==0 || mb_y==0){
                    for(i=0;i<3;i++) {
                        uint8_t *ptr;
                        int x, y, h, v, linesize;
                        h = s->mjpeg_hsample[i];
                        v = s->mjpeg_vsample[i];
                        linesize= p->linesize[i];
                        for(y=0; y<v; y++){
                            for(x=0; x<h; x++){
                                int pred;
                                ptr = p->data[i] + (linesize * (v * mb_y + y)) + (h * mb_x + x); //FIXME optimize this crap
                                if(y==0 && mb_y==0){
                                    if(x==0 && mb_x==0){
                                        pred= 128;
                                    }else{
                                        pred= ptr[-1];
                                }else{
                                    if(x==0 && mb_x==0){
                                        pred= ptr[-linesize];
                                    }else{
                                        PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);
                                if(i==0)
                                    ff_mjpeg_encode_dc(s, *ptr - pred, m->huff_size_dc_luminance, m->huff_code_dc_luminance); //FIXME ugly
                                else
                                    ff_mjpeg_encode_dc(s, *ptr - pred, m->huff_size_dc_chrominance, m->huff_code_dc_chrominance);
                }else{
                    for(i=0;i<3;i++) {
                        uint8_t *ptr;
                        int x, y, h, v, linesize;
                        h = s->mjpeg_hsample[i];
                        v = s->mjpeg_vsample[i];
                        linesize= p->linesize[i];
                        for(y=0; y<v; y++){
                            for(x=0; x<h; x++){
                                int pred;
                                ptr = p->data[i] + (linesize * (v * mb_y + y)) + (h * mb_x + x); //FIXME optimize this crap
                                PREDICT(pred, ptr[-linesize-1], ptr[-linesize], ptr[-1], predictor);
                                if(i==0)
                                    ff_mjpeg_encode_dc(s, *ptr - pred, m->huff_size_dc_luminance, m->huff_code_dc_luminance); //FIXME ugly
                                else
                                    ff_mjpeg_encode_dc(s, *ptr - pred, m->huff_size_dc_chrominance, m->huff_code_dc_chrominance);
    emms_c();
    av_assert0(s->esc_pos == s->header_bits >> 3);
    ff_mjpeg_encode_stuffing(s);
    ff_mjpeg_encode_picture_trailer(s);
    s->picture_number++;
    flush_put_bits(&s->pb);
    pkt->size   = put_bits_ptr(&s->pb) - s->pb.buf;
    pkt->flags |= AV_PKT_FLAG_KEY;
    *got_packet = 1;
    return 0;
//    return (put_bits_count(&f->pb)+7)/8;


static void dump_regs(struct ucontext *uc)

{

}


static void do_wav_capture(Monitor *mon, const QDict *qdict)

{

    const char *path = qdict_get_str(qdict, "path");

    int has_freq = qdict_haskey(qdict, "freq");

    int freq = qdict_get_try_int(qdict, "freq", -1);

    int has_bits = qdict_haskey(qdict, "bits");

    int bits = qdict_get_try_int(qdict, "bits", -1);

    int has_channels = qdict_haskey(qdict, "nchannels");

    int nchannels = qdict_get_try_int(qdict, "nchannels", -1);

    CaptureState *s;

    s = qemu_mallocz (sizeof (*s));

    freq = has_freq ? freq : 44100;

    bits = has_bits ? bits : 16;

    nchannels = has_channels ? nchannels : 2;

    if (wav_start_capture (s, path, freq, bits, nchannels)) {

        monitor_printf(mon, "Faied to add wave capture\n");

        qemu_free (s);

    }

    LIST_INSERT_HEAD (&capture_head, s, entries);

}


static struct mm_struct *vma_init(void)

{

    struct mm_struct *mm;

    if ((mm = qemu_malloc(sizeof (*mm))) == NULL)

        return (NULL);

    mm->mm_count = 0;

    TAILQ_INIT(&mm->mm_mmap);

    return (mm);

}


CoroutineAction qemu_coroutine_switch(Coroutine *from_, Coroutine *to_,

                                      CoroutineAction action)

{

    CoroutineWin32 *from = DO_UPCAST(CoroutineWin32, base, from_);

    CoroutineWin32 *to = DO_UPCAST(CoroutineWin32, base, to_);

    current = to_;

    to->action = action;

    SwitchToFiber(to->fiber);

    return from->action;

}


av_cold void ff_rv34dsp_init_x86(RV34DSPContext* c, DSPContext *dsp)

{

#if HAVE_YASM

    int mm_flags = av_get_cpu_flags();

    if (mm_flags & AV_CPU_FLAG_MMX)

        c->rv34_idct_dc_add = ff_rv34_idct_dc_add_mmx;

    if (mm_flags & AV_CPU_FLAG_MMXEXT) {

        c->rv34_inv_transform_dc = ff_rv34_idct_dc_noround_mmx2;

        c->rv34_idct_add         = ff_rv34_idct_add_mmx2;

    }

    if (mm_flags & AV_CPU_FLAG_SSE4)

        c->rv34_idct_dc_add = ff_rv34_idct_dc_add_sse4;

#endif /* HAVE_YASM */

}


int64_t helper_fqtox(CPUSPARCState *env)

{

    int64_t ret;

    clear_float_exceptions(env);

    ret = float128_to_int64_round_to_zero(QT1, &env->fp_status);

    check_ieee_exceptions(env);

    return ret;

}


static void io_region_add(MemoryListener *listener,

                          MemoryRegionSection *section)

{

    MemoryRegionIORange *mrio = g_new(MemoryRegionIORange, 1);

    mrio->mr = section->mr;

    mrio->offset = section->offset_within_region;

    iorange_init(&mrio->iorange, &memory_region_iorange_ops,

                 section->offset_within_address_space,

                 int128_get64(section->size));

    ioport_register(&mrio->iorange);

}


build_mcfg_q35(GArray *table_data, GArray *linker, AcpiMcfgInfo *info)

{

    AcpiTableMcfg *mcfg;

    const char *sig;

    int len = sizeof(*mcfg) + 1 * sizeof(mcfg->allocation[0]);

    mcfg = acpi_data_push(table_data, len);

    mcfg->allocation[0].address = cpu_to_le64(info->mcfg_base);

    /* Only a single allocation so no need to play with segments */

    mcfg->allocation[0].pci_segment = cpu_to_le16(0);

    mcfg->allocation[0].start_bus_number = 0;

    mcfg->allocation[0].end_bus_number = PCIE_MMCFG_BUS(info->mcfg_size - 1);

    /* MCFG is used for ECAM which can be enabled or disabled by guest.

     * To avoid table size changes (which create migration issues),

     * always create the table even if there are no allocations,

     * but set the signature to a reserved value in this case.

     * ACPI spec requires OSPMs to ignore such tables.

     */

    if (info->mcfg_base == PCIE_BASE_ADDR_UNMAPPED) {

        /* Reserved signature: ignored by OSPM */

        sig = "QEMU";

    } else {

        sig = "MCFG";

    }

    build_header(linker, table_data, (void *)mcfg, sig, len, 1, NULL, NULL);

}


static void ide_resize_cb(void *opaque)

{

    IDEState *s = opaque;

    uint64_t nb_sectors;

    if (!s->identify_set) {

        return;

    }

    bdrv_get_geometry(s->bs, &nb_sectors);

    s->nb_sectors = nb_sectors;

    /* Update the identify data buffer. */

    if (s->drive_kind == IDE_CFATA) {

        ide_cfata_identify_size(s);

    } else {

        /* IDE_CD uses a different set of callbacks entirely. */

        assert(s->drive_kind != IDE_CD);

        ide_identify_size(s);

    }

}


static void reset_all_temps(int nb_temps)

{

    int i;

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

        temps[i].state = TCG_TEMP_UNDEF;

        temps[i].mask = -1;

    }

}


static inline void tcg_out_tlb_load(TCGContext *s, TCGReg addrlo, TCGReg addrhi,

                                    int mem_index, TCGMemOp opc,

                                    tcg_insn_unit **label_ptr, int which)

{

    const TCGReg r0 = TCG_REG_L0;

    const TCGReg r1 = TCG_REG_L1;

    TCGType ttype = TCG_TYPE_I32;

    TCGType tlbtype = TCG_TYPE_I32;

    int trexw = 0, hrexw = 0, tlbrexw = 0;

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

    bool aligned = (opc & MO_AMASK) == MO_ALIGN || s_mask == 0;

    if (TCG_TARGET_REG_BITS == 64) {

        if (TARGET_LONG_BITS == 64) {

            ttype = TCG_TYPE_I64;

            trexw = P_REXW;

        }

        if (TCG_TYPE_PTR == TCG_TYPE_I64) {

            hrexw = P_REXW;

            if (TARGET_PAGE_BITS + CPU_TLB_BITS > 32) {

                tlbtype = TCG_TYPE_I64;

                tlbrexw = P_REXW;

            }

        }

    }

    tcg_out_mov(s, tlbtype, r0, addrlo);

    if (aligned) {

        tcg_out_mov(s, ttype, r1, addrlo);

    } else {

        /* For unaligned access check that we don't cross pages using

           the page address of the last byte.  */

        tcg_out_modrm_offset(s, OPC_LEA + trexw, r1, addrlo, s_mask);

    }

    tcg_out_shifti(s, SHIFT_SHR + tlbrexw, r0,

                   TARGET_PAGE_BITS - CPU_TLB_ENTRY_BITS);

    tgen_arithi(s, ARITH_AND + trexw, r1,

                TARGET_PAGE_MASK | (aligned ? s_mask : 0), 0);

    tgen_arithi(s, ARITH_AND + tlbrexw, r0,

                (CPU_TLB_SIZE - 1) << CPU_TLB_ENTRY_BITS, 0);

    tcg_out_modrm_sib_offset(s, OPC_LEA + hrexw, r0, TCG_AREG0, r0, 0,

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

                             + which);

    /* cmp 0(r0), r1 */

    tcg_out_modrm_offset(s, OPC_CMP_GvEv + trexw, r1, r0, 0);

    /* Prepare for both the fast path add of the tlb addend, and the slow

       path function argument setup.  There are two cases worth note:

       For 32-bit guest and x86_64 host, MOVL zero-extends the guest address

       before the fastpath ADDQ below.  For 64-bit guest and x32 host, MOVQ

       copies the entire guest address for the slow path, while truncation

       for the 32-bit host happens with the fastpath ADDL below.  */

    tcg_out_mov(s, ttype, r1, addrlo);

    /* jne slow_path */

    tcg_out_opc(s, OPC_JCC_long + JCC_JNE, 0, 0, 0);

    label_ptr[0] = s->code_ptr;

    s->code_ptr += 4;

    if (TARGET_LONG_BITS > TCG_TARGET_REG_BITS) {

        /* cmp 4(r0), addrhi */

        tcg_out_modrm_offset(s, OPC_CMP_GvEv, addrhi, r0, 4);

        /* jne slow_path */

        tcg_out_opc(s, OPC_JCC_long + JCC_JNE, 0, 0, 0);

        label_ptr[1] = s->code_ptr;

        s->code_ptr += 4;

    }

    /* TLB Hit.  */

    /* add addend(r0), r1 */

    tcg_out_modrm_offset(s, OPC_ADD_GvEv + hrexw, r1, r0,

                         offsetof(CPUTLBEntry, addend) - which);

}


uint64_t helper_load_fpcr (void)

{

    uint64_t ret = 0;

#ifdef CONFIG_SOFTFLOAT

    ret |= env->fp_status.float_exception_flags << 52;

    if (env->fp_status.float_exception_flags)

        ret |= 1ULL << 63;

    env->ipr[IPR_EXC_SUM] &= ~0x3E:

    env->ipr[IPR_EXC_SUM] |= env->fp_status.float_exception_flags << 1;

#endif

    switch (env->fp_status.float_rounding_mode) {

    case float_round_nearest_even:

        ret |= 2ULL << 58;

        break;

    case float_round_down:

        ret |= 1ULL << 58;

        break;

    case float_round_up:

        ret |= 3ULL << 58;

        break;

    case float_round_to_zero:

        break;

    }

    return ret;

}


static void common_end(SnowContext *s){

    av_freep(&s->spatial_dwt_buffer);

    av_freep(&s->mb_band.buf);

    av_freep(&s->mv_band[0].buf);

    av_freep(&s->mv_band[1].buf);

    av_freep(&s->m.me.scratchpad);

    av_freep(&s->m.me.map);

    av_freep(&s->m.me.score_map);

    av_freep(&s->mb_type);

    av_freep(&s->mb_mean);

    av_freep(&s->dummy);

    av_freep(&s->motion_val8);

    av_freep(&s->motion_val16);

}


static void imx_ccm_write(void *opaque, target_phys_addr_t offset,

                          uint64_t value, unsigned size)

{

    IMXCCMState *s = (IMXCCMState *)opaque;

    DPRINTF("write(offset=%x, value = %x)\n",

            offset >> 2, (unsigned int)value);

    switch (offset >> 2) {

    case 0:

        s->ccmr = CCMR_FPMF | (value & 0x3b6fdfff);

        break;

    case 1:

        s->pdr0 = value & 0xff9f3fff;

        break;

    case 2:

        s->pdr1 = value;

        break;

    case 4:

        s->mpctl = value & 0xbfff3fff;

        break;

    case 6:

        s->spctl = value & 0xbfff3fff;

        break;

    case 8:

        s->cgr[0] = value;

        return;

    case 9:

        s->cgr[1] = value;

        return;

    case 10:

        s->cgr[2] = value;

        return;

    default:

        return;

    }

    update_clocks(s);

}


static void dump_regs(TCGContext *s)

{

    TCGTemp *ts;

    int i;

    char buf[64];

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

        ts = &s->temps[i];

        printf("  %10s: ", tcg_get_arg_str_idx(s, buf, sizeof(buf), i));

        switch(ts->val_type) {

        case TEMP_VAL_REG:

            printf("%s", tcg_target_reg_names[ts->reg]);

            break;

        case TEMP_VAL_MEM:

            printf("%d(%s)", (int)ts->mem_offset, tcg_target_reg_names[ts->mem_reg]);

            break;

        case TEMP_VAL_CONST:

            printf("$0x%" TCG_PRIlx, ts->val);

            break;

        case TEMP_VAL_DEAD:

            printf("D");

            break;

        default:

            printf("???");

            break;

        }

        printf("\n");

    }

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

        if (s->reg_to_temp[i] >= 0) {

            printf("%s: %s\n",

                   tcg_target_reg_names[i],

                   tcg_get_arg_str_idx(s, buf, sizeof(buf), s->reg_to_temp[i]));

        }

    }

}


static int pci_piix3_xen_ide_unplug(DeviceState *dev)

{

    PCIDevice *pci_dev;

    PCIIDEState *pci_ide;

    DriveInfo *di;

    int i = 0;

    pci_dev = DO_UPCAST(PCIDevice, qdev, dev);

    pci_ide = DO_UPCAST(PCIIDEState, dev, pci_dev);

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

        di = drive_get_by_index(IF_IDE, i);

        if (di != NULL && di->bdrv != NULL && !di->bdrv->removable) {

            DeviceState *ds = bdrv_get_attached(di->bdrv);

            if (ds) {

                bdrv_detach(di->bdrv, ds);

            }

            bdrv_close(di->bdrv);

            pci_ide->bus[di->bus].ifs[di->unit].bs = NULL;

            drive_put_ref(di);

        }

    }

    qdev_reset_all(&(pci_ide->dev.qdev));

    return 0;

}


int get_segment64(CPUPPCState *env, mmu_ctx_t *ctx,

                  target_ulong eaddr, int rw, int type)

{

    hwaddr hash;

    target_ulong vsid;

    int pr, target_page_bits;

    int ret, ret2;

    pr = msr_pr;

    ctx->eaddr = eaddr;

    ppc_slb_t *slb;

    target_ulong pageaddr;

    int segment_bits;

    LOG_MMU("Check SLBs\n");

    slb = slb_lookup(env, eaddr);

    if (!slb) {

        return -5;

    }

    if (slb->vsid & SLB_VSID_B) {

        vsid = (slb->vsid & SLB_VSID_VSID) >> SLB_VSID_SHIFT_1T;

        segment_bits = 40;

    } else {

        vsid = (slb->vsid & SLB_VSID_VSID) >> SLB_VSID_SHIFT;

        segment_bits = 28;

    }

    target_page_bits = (slb->vsid & SLB_VSID_L)

        ? TARGET_PAGE_BITS_16M : TARGET_PAGE_BITS;

    ctx->key = !!(pr ? (slb->vsid & SLB_VSID_KP)

                  : (slb->vsid & SLB_VSID_KS));

    ctx->nx = !!(slb->vsid & SLB_VSID_N);

    pageaddr = eaddr & ((1ULL << segment_bits)

                            - (1ULL << target_page_bits));

    if (slb->vsid & SLB_VSID_B) {

        hash = vsid ^ (vsid << 25) ^ (pageaddr >> target_page_bits);

    } else {

        hash = vsid ^ (pageaddr >> target_page_bits);

    }

    /* Only 5 bits of the page index are used in the AVPN */

    ctx->ptem = (slb->vsid & SLB_VSID_PTEM) |

        ((pageaddr >> 16) & ((1ULL << segment_bits) - 0x80));

    LOG_MMU("pte segment: key=%d nx %d vsid " TARGET_FMT_lx "\n",

            ctx->key, ctx->nx, vsid);

    ret = -1;

    /* Check if instruction fetch is allowed, if needed */

    if (type != ACCESS_CODE || ctx->nx == 0) {

        /* Page address translation */

        LOG_MMU("htab_base " TARGET_FMT_plx " htab_mask " TARGET_FMT_plx

                " hash " TARGET_FMT_plx "\n",

                env->htab_base, env->htab_mask, hash);

        ctx->hash[0] = hash;

        ctx->hash[1] = ~hash;

        /* Initialize real address with an invalid value */

        ctx->raddr = (hwaddr)-1ULL;

        LOG_MMU("0 htab=" TARGET_FMT_plx "/" TARGET_FMT_plx

                " vsid=" TARGET_FMT_lx " ptem=" TARGET_FMT_lx

                " hash=" TARGET_FMT_plx "\n",

                env->htab_base, env->htab_mask, vsid, ctx->ptem,

                ctx->hash[0]);

        /* Primary table lookup */

        ret = find_pte64(env, ctx, 0, rw, type, target_page_bits);

        if (ret < 0) {

            /* Secondary table lookup */

            LOG_MMU("1 htab=" TARGET_FMT_plx "/" TARGET_FMT_plx

                    " vsid=" TARGET_FMT_lx " api=" TARGET_FMT_lx

                    " hash=" TARGET_FMT_plx "\n", env->htab_base,

                    env->htab_mask, vsid, ctx->ptem, ctx->hash[1]);

            ret2 = find_pte64(env, ctx, 1, rw, type, target_page_bits);

            if (ret2 != -1) {

                ret = ret2;

            }

        }

    } else {

        LOG_MMU("No access allowed\n");

        ret = -3;

    }

    return ret;

}


static uint64_t cirrus_vga_mem_read(void *opaque,

                                    target_phys_addr_t addr,

                                    uint32_t size)

{

    CirrusVGAState *s = opaque;

    unsigned bank_index;

    unsigned bank_offset;

    uint32_t val;

    if ((s->vga.sr[0x07] & 0x01) == 0) {

        return vga_mem_readb(&s->vga, addr);

    }

    if (addr < 0x10000) {

	/* XXX handle bitblt */

	/* video memory */

	bank_index = addr >> 15;

	bank_offset = addr & 0x7fff;

	if (bank_offset < s->cirrus_bank_limit[bank_index]) {

	    bank_offset += s->cirrus_bank_base[bank_index];

	    if ((s->vga.gr[0x0B] & 0x14) == 0x14) {

		bank_offset <<= 4;

	    } else if (s->vga.gr[0x0B] & 0x02) {

		bank_offset <<= 3;

	    }

	    bank_offset &= s->cirrus_addr_mask;

	    val = *(s->vga.vram_ptr + bank_offset);

	} else

	    val = 0xff;

    } else if (addr >= 0x18000 && addr < 0x18100) {

	/* memory-mapped I/O */

	val = 0xff;

	if ((s->vga.sr[0x17] & 0x44) == 0x04) {

	    val = cirrus_mmio_blt_read(s, addr & 0xff);

	}

    } else {

	val = 0xff;

#ifdef DEBUG_CIRRUS

	printf("cirrus: mem_readb " TARGET_FMT_plx "\n", addr);

#endif

    }

    return val;

}


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

{

    XlnxZynqMPState *s = XLNX_ZYNQMP(dev);

    MemoryRegion *system_memory = get_system_memory();

    uint8_t i;

    uint64_t ram_size;

    const char *boot_cpu = s->boot_cpu ? s->boot_cpu : "apu-cpu[0]";

    ram_addr_t ddr_low_size, ddr_high_size;

    qemu_irq gic_spi[GIC_NUM_SPI_INTR];

    Error *err = NULL;

    ram_size = memory_region_size(s->ddr_ram);

    /* Create the DDR Memory Regions. User friendly checks should happen at

     * the board level

     */

    if (ram_size > XLNX_ZYNQMP_MAX_LOW_RAM_SIZE) {

        /* The RAM size is above the maximum available for the low DDR.

         * Create the high DDR memory region as well.

         */

        assert(ram_size <= XLNX_ZYNQMP_MAX_RAM_SIZE);

        ddr_low_size = XLNX_ZYNQMP_MAX_LOW_RAM_SIZE;

        ddr_high_size = ram_size - XLNX_ZYNQMP_MAX_LOW_RAM_SIZE;

        memory_region_init_alias(&s->ddr_ram_high, NULL,

                                 "ddr-ram-high", s->ddr_ram,

                                  ddr_low_size, ddr_high_size);

        memory_region_add_subregion(get_system_memory(),

                                    XLNX_ZYNQMP_HIGH_RAM_START,

                                    &s->ddr_ram_high);

    } else {

        /* RAM must be non-zero */

        assert(ram_size);

        ddr_low_size = ram_size;

    }

    memory_region_init_alias(&s->ddr_ram_low, NULL,

                             "ddr-ram-low", s->ddr_ram,

                              0, ddr_low_size);

    memory_region_add_subregion(get_system_memory(), 0, &s->ddr_ram_low);

    /* Create the four OCM banks */

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

        char *ocm_name = g_strdup_printf("zynqmp.ocm_ram_bank_%d", i);

        memory_region_init_ram(&s->ocm_ram[i], NULL, ocm_name,

                               XLNX_ZYNQMP_OCM_RAM_SIZE, &error_fatal);

        vmstate_register_ram_global(&s->ocm_ram[i]);

        memory_region_add_subregion(get_system_memory(),

                                    XLNX_ZYNQMP_OCM_RAM_0_ADDRESS +

                                        i * XLNX_ZYNQMP_OCM_RAM_SIZE,

                                    &s->ocm_ram[i]);

        g_free(ocm_name);

    }

    qdev_prop_set_uint32(DEVICE(&s->gic), "num-irq", GIC_NUM_SPI_INTR + 32);

    qdev_prop_set_uint32(DEVICE(&s->gic), "revision", 2);

    qdev_prop_set_uint32(DEVICE(&s->gic), "num-cpu", XLNX_ZYNQMP_NUM_APU_CPUS);

    object_property_set_bool(OBJECT(&s->gic), true, "realized", &err);

    if (err) {

        error_propagate(errp, err);

        return;

    }

    assert(ARRAY_SIZE(xlnx_zynqmp_gic_regions) == XLNX_ZYNQMP_GIC_REGIONS);

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

        SysBusDevice *gic = SYS_BUS_DEVICE(&s->gic);

        const XlnxZynqMPGICRegion *r = &xlnx_zynqmp_gic_regions[i];

        MemoryRegion *mr = sysbus_mmio_get_region(gic, r->region_index);

        uint32_t addr = r->address;

        int j;

        sysbus_mmio_map(gic, r->region_index, addr);

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

            MemoryRegion *alias = &s->gic_mr[i][j];

            addr += XLNX_ZYNQMP_GIC_REGION_SIZE;

            memory_region_init_alias(alias, OBJECT(s), "zynqmp-gic-alias", mr,

                                     0, XLNX_ZYNQMP_GIC_REGION_SIZE);

            memory_region_add_subregion(system_memory, addr, alias);

        }

    }

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

        qemu_irq irq;

        char *name;

        object_property_set_int(OBJECT(&s->apu_cpu[i]), QEMU_PSCI_CONDUIT_SMC,

                                "psci-conduit", &error_abort);

        name = object_get_canonical_path_component(OBJECT(&s->apu_cpu[i]));

        if (strcmp(name, boot_cpu)) {

            /* Secondary CPUs start in PSCI powered-down state */

            object_property_set_bool(OBJECT(&s->apu_cpu[i]), true,

                                     "start-powered-off", &error_abort);

        } else {

            s->boot_cpu_ptr = &s->apu_cpu[i];

        }

        g_free(name);

        object_property_set_bool(OBJECT(&s->apu_cpu[i]),

                                 s->secure, "has_el3", NULL);

        object_property_set_int(OBJECT(&s->apu_cpu[i]), GIC_BASE_ADDR,

                                "reset-cbar", &error_abort);

        object_property_set_bool(OBJECT(&s->apu_cpu[i]), true, "realized",

                                 &err);

        if (err) {

            error_propagate(errp, err);

            return;

        }

        sysbus_connect_irq(SYS_BUS_DEVICE(&s->gic), i,

                           qdev_get_gpio_in(DEVICE(&s->apu_cpu[i]),

                                            ARM_CPU_IRQ));

        irq = qdev_get_gpio_in(DEVICE(&s->gic),

                               arm_gic_ppi_index(i, ARM_PHYS_TIMER_PPI));

        qdev_connect_gpio_out(DEVICE(&s->apu_cpu[i]), 0, irq);

        irq = qdev_get_gpio_in(DEVICE(&s->gic),

                               arm_gic_ppi_index(i, ARM_VIRT_TIMER_PPI));

        qdev_connect_gpio_out(DEVICE(&s->apu_cpu[i]), 1, irq);

    }

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

        char *name;

        name = object_get_canonical_path_component(OBJECT(&s->rpu_cpu[i]));

        if (strcmp(name, boot_cpu)) {

            /* Secondary CPUs start in PSCI powered-down state */

            object_property_set_bool(OBJECT(&s->rpu_cpu[i]), true,

                                     "start-powered-off", &error_abort);

        } else {

            s->boot_cpu_ptr = &s->rpu_cpu[i];

        }

        g_free(name);

        object_property_set_bool(OBJECT(&s->rpu_cpu[i]), true, "reset-hivecs",

                                 &error_abort);

        object_property_set_bool(OBJECT(&s->rpu_cpu[i]), true, "realized",

                                 &err);

        if (err) {

            error_propagate(errp, err);

            return;

        }

    }

    if (!s->boot_cpu_ptr) {

        error_setg(errp, "ZynqMP Boot cpu %s not found", boot_cpu);

        return;

    }

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

        gic_spi[i] = qdev_get_gpio_in(DEVICE(&s->gic), i);

    }

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

        NICInfo *nd = &nd_table[i];

        if (nd->used) {

            qemu_check_nic_model(nd, TYPE_CADENCE_GEM);

            qdev_set_nic_properties(DEVICE(&s->gem[i]), nd);

        }

        object_property_set_bool(OBJECT(&s->gem[i]), true, "realized", &err);

        if (err) {

            error_propagate(errp, err);

            return;

        }

        sysbus_mmio_map(SYS_BUS_DEVICE(&s->gem[i]), 0, gem_addr[i]);

        sysbus_connect_irq(SYS_BUS_DEVICE(&s->gem[i]), 0,

                           gic_spi[gem_intr[i]]);

    }

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

        object_property_set_bool(OBJECT(&s->uart[i]), true, "realized", &err);

        if (err) {

            error_propagate(errp, err);

            return;

        }

        sysbus_mmio_map(SYS_BUS_DEVICE(&s->uart[i]), 0, uart_addr[i]);

        sysbus_connect_irq(SYS_BUS_DEVICE(&s->uart[i]), 0,

                           gic_spi[uart_intr[i]]);

    }

    object_property_set_int(OBJECT(&s->sata), SATA_NUM_PORTS, "num-ports",

                            &error_abort);

    object_property_set_bool(OBJECT(&s->sata), true, "realized", &err);

    if (err) {

        error_propagate(errp, err);

        return;

    }

    sysbus_mmio_map(SYS_BUS_DEVICE(&s->sata), 0, SATA_ADDR);

    sysbus_connect_irq(SYS_BUS_DEVICE(&s->sata), 0, gic_spi[SATA_INTR]);

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

        char *bus_name;

        object_property_set_bool(OBJECT(&s->sdhci[i]), true,

                                 "realized", &err);

        if (err) {

            error_propagate(errp, err);

            return;

        }

        sysbus_mmio_map(SYS_BUS_DEVICE(&s->sdhci[i]), 0,

                        sdhci_addr[i]);

        sysbus_connect_irq(SYS_BUS_DEVICE(&s->sdhci[i]), 0,

                           gic_spi[sdhci_intr[i]]);

        /* Alias controller SD bus to the SoC itself */

        bus_name = g_strdup_printf("sd-bus%d", i);

        object_property_add_alias(OBJECT(s), bus_name,

                                  OBJECT(&s->sdhci[i]), "sd-bus",

                                  &error_abort);

        g_free(bus_name);

    }

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

        gchar *bus_name;

        object_property_set_bool(OBJECT(&s->spi[i]), true, "realized", &err);

        sysbus_mmio_map(SYS_BUS_DEVICE(&s->spi[i]), 0, spi_addr[i]);

        sysbus_connect_irq(SYS_BUS_DEVICE(&s->spi[i]), 0,

                           gic_spi[spi_intr[i]]);

        /* Alias controller SPI bus to the SoC itself */

        bus_name = g_strdup_printf("spi%d", i);

        object_property_add_alias(OBJECT(s), bus_name,

                                  OBJECT(&s->spi[i]), "spi0",

                                  &error_abort);

	g_free(bus_name);

    }

}


static void virtio_pci_dc_realize(DeviceState *qdev, Error **errp)

{

    VirtioPCIClass *vpciklass = VIRTIO_PCI_GET_CLASS(qdev);

    VirtIOPCIProxy *proxy = VIRTIO_PCI(qdev);

    PCIDevice *pci_dev = &proxy->pci_dev;

    if (!(proxy->flags & VIRTIO_PCI_FLAG_DISABLE_PCIE) &&

        !(proxy->flags & VIRTIO_PCI_FLAG_DISABLE_MODERN)) {

        pci_dev->cap_present |= QEMU_PCI_CAP_EXPRESS;

    }

    vpciklass->parent_dc_realize(qdev, errp);

}


static void v9fs_symlink(void *opaque)

{

    V9fsPDU *pdu = opaque;

    V9fsString name;

    V9fsString symname;

    V9fsString fullname;

    V9fsFidState *dfidp;

    V9fsQID qid;

    struct stat stbuf;

    int32_t dfid;

    int err = 0;

    gid_t gid;

    size_t offset = 7;

    v9fs_string_init(&fullname);

    pdu_unmarshal(pdu, offset, "dssd", &dfid, &name, &symname, &gid);

    dfidp = get_fid(pdu->s, dfid);

    if (dfidp == NULL) {

        err = -EINVAL;

        goto out_nofid;

    }

    v9fs_string_sprintf(&fullname, "%s/%s", dfidp->path.data, name.data);

    err = v9fs_co_symlink(pdu->s, dfidp, symname.data, fullname.data, gid);

    if (err < 0) {

        goto out;

    }

    err = v9fs_co_lstat(pdu->s, &fullname, &stbuf);

    if (err < 0) {

        goto out;

    }

    stat_to_qid(&stbuf, &qid);

    offset += pdu_marshal(pdu, offset, "Q", &qid);

    err = offset;

out:

    put_fid(pdu->s, dfidp);

out_nofid:

    complete_pdu(pdu->s, pdu, err);

    v9fs_string_free(&name);

    v9fs_string_free(&symname);

    v9fs_string_free(&fullname);

}


static void s390_pci_generate_error_event(uint16_t pec, uint32_t fh,

                                          uint32_t fid, uint64_t faddr,

                                          uint32_t e)

{

    s390_pci_generate_event(1, pec, fh, fid, faddr, e);

}


int attribute_align_arg avcodec_decode_audio4(AVCodecContext *avctx,

                                              AVFrame *frame,

                                              int *got_frame_ptr,

                                              AVPacket *avpkt)

{

    AVCodecInternal *avci = avctx->internal;

    int planar, channels;

    int ret = 0;

    *got_frame_ptr = 0;

    avctx->pkt = avpkt;

    if (!avpkt->data && avpkt->size) {

        av_log(avctx, AV_LOG_ERROR, "invalid packet: NULL data, size != 0\n");

        return AVERROR(EINVAL);

    }

    apply_param_change(avctx, avpkt);

    avcodec_get_frame_defaults(frame);

    if (!avctx->refcounted_frames)

        av_frame_unref(&avci->to_free);

    if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size) {

        ret = avctx->codec->decode(avctx, frame, got_frame_ptr, avpkt);

        if (ret >= 0 && *got_frame_ptr) {

            avctx->frame_number++;

            frame->pkt_dts = avpkt->dts;

            if (frame->format == AV_SAMPLE_FMT_NONE)

                frame->format = avctx->sample_fmt;

            if (!avctx->refcounted_frames) {

                avci->to_free = *frame;

                avci->to_free.extended_data = avci->to_free.data;

                memset(frame->buf, 0, sizeof(frame->buf));

                frame->extended_buf    = NULL;

                frame->nb_extended_buf = 0;

            }

        } else if (frame->data[0])

            av_frame_unref(frame);

    }

    /* many decoders assign whole AVFrames, thus overwriting extended_data;

     * make sure it's set correctly; assume decoders that actually use

     * extended_data are doing it correctly */

    planar   = av_sample_fmt_is_planar(frame->format);

    channels = av_get_channel_layout_nb_channels(frame->channel_layout);

    if (!(planar && channels > AV_NUM_DATA_POINTERS))

        frame->extended_data = frame->data;

    return ret;

}


struct HCIInfo *hci_init(const char *str)

{

    char *endp;

    struct bt_scatternet_s *vlan = 0;

    if (!strcmp(str, "null"))

        /* null */

        return &null_hci;

    else if (!strncmp(str, "host", 4) && (str[4] == '\0' || str[4] == ':'))

        /* host[:hciN] */

        return bt_host_hci(str[4] ? str + 5 : "hci0");

    else if (!strncmp(str, "hci", 3)) {

        /* hci[,vlan=n] */

        if (str[3]) {

            if (!strncmp(str + 3, ",vlan=", 6)) {

                vlan = qemu_find_bt_vlan(strtol(str + 9, &endp, 0));

                if (*endp)

                    vlan = 0;

            }

        } else

            vlan = qemu_find_bt_vlan(0);

        if (vlan)

           return bt_new_hci(vlan);

    }

    fprintf(stderr, "qemu: Unknown bluetooth HCI `%s'.\n", str);

    return 0;

}


static int read_matrix_params(MLPDecodeContext *m, SubStream *s, GetBitContext *gbp)

{

    unsigned int mat, ch;

    s->num_primitive_matrices = get_bits(gbp, 4);

    m->matrix_changed++;

    for (mat = 0; mat < s->num_primitive_matrices; mat++) {

        int frac_bits, max_chan;

        s->matrix_out_ch[mat] = get_bits(gbp, 4);

        frac_bits             = get_bits(gbp, 4);

        s->lsb_bypass   [mat] = get_bits1(gbp);

        if (s->matrix_out_ch[mat] > s->max_matrix_channel) {

            av_log(m->avctx, AV_LOG_ERROR,

                    "Invalid channel %d specified as output from matrix.\n",

                    s->matrix_out_ch[mat]);

            return -1;

        }

        if (frac_bits > 14) {

            av_log(m->avctx, AV_LOG_ERROR,

                    "Too many fractional bits specified.\n");

            return -1;

        }

        max_chan = s->max_matrix_channel;

        if (!s->noise_type)

            max_chan+=2;

        for (ch = 0; ch <= max_chan; ch++) {

            int coeff_val = 0;

            if (get_bits1(gbp))

                coeff_val = get_sbits(gbp, frac_bits + 2);

            s->matrix_coeff[mat][ch] = coeff_val << (14 - frac_bits);

        }

        if (s->noise_type)

            s->matrix_noise_shift[mat] = get_bits(gbp, 4);

        else

            s->matrix_noise_shift[mat] = 0;

    }

    return 0;

}


static int libgsm_encode_frame(AVCodecContext *avctx, AVPacket *avpkt,

                               const AVFrame *frame, int *got_packet_ptr)

{

    int ret;

    gsm_signal *samples = (gsm_signal *)frame->data[0];

    struct gsm_state *state = avctx->priv_data;

    if ((ret = ff_alloc_packet2(avctx, avpkt, avctx->block_align)))

        return ret;

    switch(avctx->codec_id) {

    case AV_CODEC_ID_GSM:

        gsm_encode(state, samples, avpkt->data);

        break;

    case AV_CODEC_ID_GSM_MS:

        gsm_encode(state, samples,                  avpkt->data);

        gsm_encode(state, samples + GSM_FRAME_SIZE, avpkt->data + 32);

    }

    *got_packet_ptr = 1;

    return 0;

}


static void ff_h264_idct_dc_add_mmx2(uint8_t *dst, int16_t *block, int stride)

{

    int dc = (block[0] + 32) >> 6;

    __asm__ volatile(

        "movd          %0, %%mm0 \n\t"

        "pshufw $0, %%mm0, %%mm0 \n\t"

        "pxor       %%mm1, %%mm1 \n\t"

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

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

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

        ::"r"(dc)

    );

    __asm__ volatile(

        "movd          %0, %%mm2 \n\t"

        "movd          %1, %%mm3 \n\t"

        "movd          %2, %%mm4 \n\t"

        "movd          %3, %%mm5 \n\t"

        "paddusb    %%mm0, %%mm2 \n\t"

        "paddusb    %%mm0, %%mm3 \n\t"

        "paddusb    %%mm0, %%mm4 \n\t"

        "paddusb    %%mm0, %%mm5 \n\t"

        "psubusb    %%mm1, %%mm2 \n\t"

        "psubusb    %%mm1, %%mm3 \n\t"

        "psubusb    %%mm1, %%mm4 \n\t"

        "psubusb    %%mm1, %%mm5 \n\t"

        "movd       %%mm2, %0    \n\t"

        "movd       %%mm3, %1    \n\t"

        "movd       %%mm4, %2    \n\t"

        "movd       %%mm5, %3    \n\t"

        :"+m"(*(uint32_t*)(dst+0*stride)),

         "+m"(*(uint32_t*)(dst+1*stride)),

         "+m"(*(uint32_t*)(dst+2*stride)),

         "+m"(*(uint32_t*)(dst+3*stride))

    );

}


void ff_xvmc_field_end(MpegEncContext *s)

{

    struct xvmc_pix_fmt *render = (struct xvmc_pix_fmt*)s->current_picture.f->data[2];

    assert(render);

    if (render->filled_mv_blocks_num > 0)

        ff_mpeg_draw_horiz_band(s, 0, 0);

}


static int kempf_decode_tile(G2MContext *c, int tile_x, int tile_y,

                             const uint8_t *src, int src_size)

{

    int width, height;

    int hdr, zsize, npal, tidx = -1, ret;

    int i, j;

    const uint8_t *src_end = src + src_size;

    uint8_t pal[768], transp[3];

    uLongf dlen = (c->tile_width + 1) * c->tile_height;

    int sub_type;

    int nblocks, cblocks, bstride;

    int bits, bitbuf, coded;

    uint8_t *dst = c->framebuf + tile_x * c->tile_width * 3 +

                   tile_y * c->tile_height * c->framebuf_stride;

    if (src_size < 2)

        return AVERROR_INVALIDDATA;

    width  = FFMIN(c->width  - tile_x * c->tile_width,  c->tile_width);

    height = FFMIN(c->height - tile_y * c->tile_height, c->tile_height);

    hdr = *src++;

    sub_type = hdr >> 5;

    if (sub_type == 0) {

        int j;

        memcpy(transp, src, 3);

        src += 3;

        for (j = 0; j < height; j++, dst += c->framebuf_stride)

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

                memcpy(dst + i * 3, transp, 3);

        return 0;

    } else if (sub_type == 1) {

        return jpg_decode_data(&c->jc, width, height, src, src_end - src,

                               dst, c->framebuf_stride, NULL, 0, 0, 0);

    }

    if (sub_type != 2) {

        memcpy(transp, src, 3);

        src += 3;

    }

    npal = *src++ + 1;

    memcpy(pal, src, npal * 3); src += npal * 3;

    if (sub_type != 2) {

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

            if (!memcmp(pal + i * 3, transp, 3)) {

               tidx = i;

               break;

            }

        }

    }

    if (src_end - src < 2)

        return 0;

    zsize = (src[0] << 8) | src[1]; src += 2;

    if (src_end - src < zsize)

        return AVERROR_INVALIDDATA;

    ret = uncompress(c->kempf_buf, &dlen, src, zsize);

    if (ret)

        return AVERROR_INVALIDDATA;

    src += zsize;

    if (sub_type == 2) {

        kempf_restore_buf(c->kempf_buf, dlen, dst, c->framebuf_stride,

                          NULL, 0, width, height, pal, npal, tidx);

        return 0;

    }

    nblocks = *src++ + 1;

    cblocks = 0;

    bstride = FFALIGN(width, 16) >> 4;

    // blocks are coded LSB and we need normal bitreader for JPEG data

    bits = 0;

    for (i = 0; i < (FFALIGN(height, 16) >> 4); i++) {

        for (j = 0; j < (FFALIGN(width, 16) >> 4); j++) {

            if (!bits) {

                bitbuf = *src++;

                bits   = 8;

            }

            coded = bitbuf & 1;

            bits--;

            bitbuf >>= 1;

            cblocks += coded;

            if (cblocks > nblocks)

                return AVERROR_INVALIDDATA;

            c->kempf_flags[j + i * bstride] = coded;

        }

    }

    memset(c->jpeg_tile, 0, c->tile_stride * height);

    jpg_decode_data(&c->jc, width, height, src, src_end - src,

                    c->jpeg_tile, c->tile_stride,

                    c->kempf_flags, bstride, nblocks, 0);

    kempf_restore_buf(c->kempf_buf, dlen, dst, c->framebuf_stride,

                      c->jpeg_tile, c->tile_stride,

                      width, height, pal, npal, tidx);

    return 0;

}


static void vnc_dpy_update(DisplayChangeListener *dcl,

                           int x, int y, int w, int h)

{

    VncDisplay *vd = container_of(dcl, VncDisplay, dcl);

    struct VncSurface *s = &vd->guest;

    int width = surface_width(vd->ds);

    int height = surface_height(vd->ds);

    /* this is needed this to ensure we updated all affected

     * blocks if x % VNC_DIRTY_PIXELS_PER_BIT != 0 */

    w += (x % VNC_DIRTY_PIXELS_PER_BIT);

    x -= (x % VNC_DIRTY_PIXELS_PER_BIT);

    x = MIN(x, width);

    y = MIN(y, height);

    w = MIN(x + w, width) - x;

    h = MIN(y + h, height);

    for (; y < h; y++) {

        bitmap_set(s->dirty[y], x / VNC_DIRTY_PIXELS_PER_BIT,

                   DIV_ROUND_UP(w, VNC_DIRTY_PIXELS_PER_BIT));

    }

}


static int channelmap_config_input(AVFilterLink *inlink)

{

    AVFilterContext *ctx = inlink->dst;

    ChannelMapContext *s = ctx->priv;

    int i, err = 0;

    const char *channel_name;

    char layout_name[256];

    if (s->mode == MAP_PAIR_STR_INT || s->mode == MAP_PAIR_STR_STR) {

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

            s->map[i].in_channel_idx = av_get_channel_layout_channel_index(

                inlink->channel_layout, s->map[i].in_channel);

            if (s->map[i].in_channel_idx < 0) {

                channel_name = av_get_channel_name(s->map[i].in_channel);

                av_get_channel_layout_string(layout_name, sizeof(layout_name),

                                             0, inlink->channel_layout);

                av_log(ctx, AV_LOG_ERROR,

                       "input channel '%s' not available from input layout '%s'\n",

                       channel_name, layout_name);

                err = AVERROR(EINVAL);

            }

        }

    }

    return err;

}


static void decode_format80(const unsigned char *src, int src_size,

    unsigned char *dest, int dest_size, int check_size) {

    int src_index = 0;

    int dest_index = 0;

    int count;

    int src_pos;

    unsigned char color;

    int i;

    while (src_index < src_size) {

        av_dlog(NULL, "      opcode %02X: ", src[src_index]);

        /* 0x80 means that frame is finished */

        if (src[src_index] == 0x80)

        if (dest_index >= dest_size) {

            av_log(NULL, AV_LOG_ERROR, "  VQA video: decode_format80 problem: dest_index (%d) exceeded dest_size (%d)\n",

                dest_index, dest_size);

        }

        if (src[src_index] == 0xFF) {

            src_index++;

            count = AV_RL16(&src[src_index]);

            src_index += 2;

            src_pos = AV_RL16(&src[src_index]);

            src_index += 2;

            av_dlog(NULL, "(1) copy %X bytes from absolute pos %X\n", count, src_pos);

            CHECK_COUNT();

            if (src_pos + count > dest_size)

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

                dest[dest_index + i] = dest[src_pos + i];

            dest_index += count;

        } else if (src[src_index] == 0xFE) {

            src_index++;

            count = AV_RL16(&src[src_index]);

            src_index += 2;

            color = src[src_index++];

            av_dlog(NULL, "(2) set %X bytes to %02X\n", count, color);

            CHECK_COUNT();

            memset(&dest[dest_index], color, count);

            dest_index += count;

        } else if ((src[src_index] & 0xC0) == 0xC0) {

            count = (src[src_index++] & 0x3F) + 3;

            src_pos = AV_RL16(&src[src_index]);

            src_index += 2;

            av_dlog(NULL, "(3) copy %X bytes from absolute pos %X\n", count, src_pos);

            CHECK_COUNT();

            if (src_pos + count > dest_size)

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

                dest[dest_index + i] = dest[src_pos + i];

            dest_index += count;

        } else if (src[src_index] > 0x80) {

            count = src[src_index++] & 0x3F;

            av_dlog(NULL, "(4) copy %X bytes from source to dest\n", count);

            CHECK_COUNT();

            memcpy(&dest[dest_index], &src[src_index], count);

            src_index += count;

            dest_index += count;

        } else {

            count = ((src[src_index] & 0x70) >> 4) + 3;

            src_pos = AV_RB16(&src[src_index]) & 0x0FFF;

            src_index += 2;

            av_dlog(NULL, "(5) copy %X bytes from relpos %X\n", count, src_pos);

            CHECK_COUNT();

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

                dest[dest_index + i] = dest[dest_index - src_pos + i];

            dest_index += count;

        }

    }

    /* validate that the entire destination buffer was filled; this is

     * important for decoding frame maps since each vector needs to have a

     * codebook entry; it is not important for compressed codebooks because

     * not every entry needs to be filled */

    if (check_size)

        if (dest_index < dest_size)

            av_log(NULL, AV_LOG_ERROR, "  VQA video: decode_format80 problem: decode finished with dest_index (%d) < dest_size (%d)\n",

                dest_index, dest_size);

}


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

{

    Rom *rom;

    QTAILQ_FOREACH(rom, &roms, next) {

        if (!rom->fw_file) {

            monitor_printf(mon, "addr=" TARGET_FMT_plx

                           " size=0x%06zx mem=%s name=\"%s\"\n",

                           rom->addr, rom->romsize,

                           rom->isrom ? "rom" : "ram",

                           rom->name);

        } else {

            monitor_printf(mon, "fw=%s/%s"

                           " size=0x%06zx name=\"%s\"\n",

                           rom->fw_dir,

                           rom->fw_file,

                           rom->romsize,

                           rom->name);

        }

    }

}


static void migration_end(void)

{

    if (migration_bitmap) {

        memory_global_dirty_log_stop();

        g_free(migration_bitmap);

        migration_bitmap = NULL;

    }

    if (XBZRLE.cache) {

        cache_fini(XBZRLE.cache);

        g_free(XBZRLE.cache);

        g_free(XBZRLE.encoded_buf);

        g_free(XBZRLE.current_buf);

        g_free(XBZRLE.decoded_buf);

        XBZRLE.cache = NULL;

    }

}