static int ffm_write_header(AVFormatContext *s)

{

    FFMContext *ffm = s->priv_data;

    AVStream *st;

    ByteIOContext *pb = s->pb;

    AVCodecContext *codec;

    int bit_rate, i;

    ffm->packet_size = FFM_PACKET_SIZE;

    /* header */

    put_le32(pb, MKTAG('F', 'F', 'M', '1'));

    put_be32(pb, ffm->packet_size);

    /* XXX: store write position in other file ? */

    put_be64(pb, ffm->packet_size); /* current write position */

    put_be32(pb, s->nb_streams);

    bit_rate = 0;

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

        st = s->streams[i];

        bit_rate += st->codec->bit_rate;

    }

    put_be32(pb, bit_rate);

    /* list of streams */

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

        st = s->streams[i];

        av_set_pts_info(st, 64, 1, 1000000);

        codec = st->codec;

        /* generic info */

        put_be32(pb, codec->codec_id);

        put_byte(pb, codec->codec_type);

        put_be32(pb, codec->bit_rate);

        put_be32(pb, st->quality);

        put_be32(pb, codec->flags);

        put_be32(pb, codec->flags2);

        put_be32(pb, codec->debug);

        /* specific info */

        switch(codec->codec_type) {

        case CODEC_TYPE_VIDEO:

            put_be32(pb, codec->time_base.num);

            put_be32(pb, codec->time_base.den);

            put_be16(pb, codec->width);

            put_be16(pb, codec->height);

            put_be16(pb, codec->gop_size);

            put_be32(pb, codec->pix_fmt);

            put_byte(pb, codec->qmin);

            put_byte(pb, codec->qmax);

            put_byte(pb, codec->max_qdiff);

            put_be16(pb, (int) (codec->qcompress * 10000.0));

            put_be16(pb, (int) (codec->qblur * 10000.0));

            put_be32(pb, codec->bit_rate_tolerance);

            put_strz(pb, codec->rc_eq);

            put_be32(pb, codec->rc_max_rate);

            put_be32(pb, codec->rc_min_rate);

            put_be32(pb, codec->rc_buffer_size);

            put_be64(pb, av_dbl2int(codec->i_quant_factor));

            put_be64(pb, av_dbl2int(codec->b_quant_factor));

            put_be64(pb, av_dbl2int(codec->i_quant_offset));

            put_be64(pb, av_dbl2int(codec->b_quant_offset));

            put_be32(pb, codec->dct_algo);

            put_be32(pb, codec->strict_std_compliance);

            put_be32(pb, codec->max_b_frames);

            put_be32(pb, codec->luma_elim_threshold);

            put_be32(pb, codec->chroma_elim_threshold);

            put_be32(pb, codec->mpeg_quant);

            put_be32(pb, codec->intra_dc_precision);

            put_be32(pb, codec->me_method);

            put_be32(pb, codec->mb_decision);

            put_be32(pb, codec->nsse_weight);

            put_be32(pb, codec->frame_skip_cmp);

            put_be64(pb, av_dbl2int(codec->rc_buffer_aggressivity));

            put_be32(pb, codec->codec_tag);

            break;

        case CODEC_TYPE_AUDIO:

            put_be32(pb, codec->sample_rate);

            put_le16(pb, codec->channels);

            put_le16(pb, codec->frame_size);

            break;

        default:

            return -1;

        }

    }

    /* hack to have real time */

    if (ffm_nopts)

        ffm->start_time = 0;

    else

        ffm->start_time = av_gettime();

    /* flush until end of block reached */

    while ((url_ftell(pb) % ffm->packet_size) != 0)

        put_byte(pb, 0);

    put_flush_packet(pb);

    /* init packet mux */

    ffm->packet_ptr = ffm->packet;

    ffm->packet_end = ffm->packet + ffm->packet_size - FFM_HEADER_SIZE;

    assert(ffm->packet_end >= ffm->packet);

    ffm->frame_offset = 0;

    ffm->pts = 0;

    ffm->first_packet = 1;

    return 0;

}


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

{

    int ret = USB_RET_NAK;

    if (s->in_ptr > s->in_len) {

        s->in_ptr = s->in_len = 0;

        ret = USB_RET_NAK;

        return ret;

    }

    if (!s->in_len) {

        ret = USB_RET_NAK;

        return ret;

    }

    ret = s->in_len - s->in_ptr;

    if (ret > p->iov.size) {

        ret = p->iov.size;

    }

    usb_packet_copy(p, &s->in_buf[s->in_ptr], ret);

    s->in_ptr += ret;

    if (s->in_ptr >= s->in_len &&

                    (is_rndis(s) || (s->in_len & (64 - 1)) || !ret)) {

        /* no short packet necessary */

        s->in_ptr = s->in_len = 0;

    }

#ifdef TRAFFIC_DEBUG

    fprintf(stderr, "usbnet: data in len %zu return %d", p->iov.size, ret);

    iov_hexdump(p->iov.iov, p->iov.niov, stderr, "usbnet", ret);

#endif

    return ret;

}


static void usb_msd_realize_storage(USBDevice *dev, Error **errp)

{

    MSDState *s = USB_STORAGE_DEV(dev);

    BlockBackend *blk = s->conf.blk;

    SCSIDevice *scsi_dev;

    Error *err = NULL;

    if (!blk) {

        error_setg(errp, "drive property not set");

        return;

    }

    bdrv_add_key(blk_bs(blk), NULL, &err);

    if (err) {

        if (monitor_cur_is_qmp()) {

            error_propagate(errp, err);

            return;

        }

        error_free(err);

        err = NULL;

        if (cur_mon) {

            monitor_read_bdrv_key_start(cur_mon, blk_bs(blk),

                                        usb_msd_password_cb, s);

            s->dev.auto_attach = 0;

        } else {

            autostart = 0;

        }

    }

    blkconf_serial(&s->conf, &dev->serial);

    blkconf_blocksizes(&s->conf);

    /*

     * Hack alert: this pretends to be a block device, but it's really

     * a SCSI bus that can serve only a single device, which it

     * creates automatically.  But first it needs to detach from its

     * blockdev, or else scsi_bus_legacy_add_drive() dies when it

     * attaches again.

     *

     * The hack is probably a bad idea.

     */

    blk_detach_dev(blk, &s->dev.qdev);

    s->conf.blk = NULL;

    usb_desc_create_serial(dev);

    usb_desc_init(dev);

    scsi_bus_new(&s->bus, sizeof(s->bus), DEVICE(dev),

                 &usb_msd_scsi_info_storage, NULL);

    scsi_dev = scsi_bus_legacy_add_drive(&s->bus, blk, 0, !!s->removable,

                                         s->conf.bootindex, dev->serial,

                                         &err);

    if (!scsi_dev) {

        error_propagate(errp, err);

        return;

    }

    usb_msd_handle_reset(dev);

    s->scsi_dev = scsi_dev;

}


static int usb_xhci_initfn(struct PCIDevice *dev)

{

    int i, ret;

    XHCIState *xhci = DO_UPCAST(XHCIState, pci_dev, dev);

    xhci->pci_dev.config[PCI_CLASS_PROG] = 0x30;    /* xHCI */

    xhci->pci_dev.config[PCI_INTERRUPT_PIN] = 0x01; /* interrupt pin 1 */

    xhci->pci_dev.config[PCI_CACHE_LINE_SIZE] = 0x10;

    xhci->pci_dev.config[0x60] = 0x30; /* release number */

    usb_xhci_init(xhci, &dev->qdev);

    if (xhci->numintrs > MAXINTRS) {

        xhci->numintrs = MAXINTRS;

    }

    if (xhci->numintrs < 1) {

        xhci->numintrs = 1;

    }

    if (xhci->numslots > MAXSLOTS) {

        xhci->numslots = MAXSLOTS;

    }

    if (xhci->numslots < 1) {

        xhci->numslots = 1;

    }

    xhci->mfwrap_timer = qemu_new_timer_ns(vm_clock, xhci_mfwrap_timer, xhci);

    xhci->irq = xhci->pci_dev.irq[0];

    memory_region_init(&xhci->mem, "xhci", LEN_REGS);

    memory_region_init_io(&xhci->mem_cap, &xhci_cap_ops, xhci,

                          "capabilities", LEN_CAP);

    memory_region_init_io(&xhci->mem_oper, &xhci_oper_ops, xhci,

                          "operational", 0x400);

    memory_region_init_io(&xhci->mem_runtime, &xhci_runtime_ops, xhci,

                          "runtime", LEN_RUNTIME);

    memory_region_init_io(&xhci->mem_doorbell, &xhci_doorbell_ops, xhci,

                          "doorbell", LEN_DOORBELL);

    memory_region_add_subregion(&xhci->mem, 0,            &xhci->mem_cap);

    memory_region_add_subregion(&xhci->mem, OFF_OPER,     &xhci->mem_oper);

    memory_region_add_subregion(&xhci->mem, OFF_RUNTIME,  &xhci->mem_runtime);

    memory_region_add_subregion(&xhci->mem, OFF_DOORBELL, &xhci->mem_doorbell);

    for (i = 0; i < xhci->numports; i++) {

        XHCIPort *port = &xhci->ports[i];

        uint32_t offset = OFF_OPER + 0x400 + 0x10 * i;

        port->xhci = xhci;

        memory_region_init_io(&port->mem, &xhci_port_ops, port,

                              port->name, 0x10);

        memory_region_add_subregion(&xhci->mem, offset, &port->mem);

    }

    pci_register_bar(&xhci->pci_dev, 0,

                     PCI_BASE_ADDRESS_SPACE_MEMORY|PCI_BASE_ADDRESS_MEM_TYPE_64,

                     &xhci->mem);

    ret = pcie_cap_init(&xhci->pci_dev, 0xa0, PCI_EXP_TYPE_ENDPOINT, 0);

    assert(ret >= 0);

    if (xhci->flags & (1 << XHCI_FLAG_USE_MSI)) {

        msi_init(&xhci->pci_dev, 0x70, xhci->numintrs, true, false);

    }

    if (xhci->flags & (1 << XHCI_FLAG_USE_MSI_X)) {

        msix_init(&xhci->pci_dev, xhci->numintrs,

                  &xhci->mem, 0, OFF_MSIX_TABLE,

                  &xhci->mem, 0, OFF_MSIX_PBA,

                  0x90);

    }

    return 0;

}


void memory_region_iommu_replay(MemoryRegion *mr, IOMMUNotifier *n,

                                bool is_write)

{

    hwaddr addr, granularity;

    IOMMUTLBEntry iotlb;

    IOMMUAccessFlags flag = is_write ? IOMMU_WO : IOMMU_RO;

    /* If the IOMMU has its own replay callback, override */

    if (mr->iommu_ops->replay) {

        mr->iommu_ops->replay(mr, n);

        return;

    }

    granularity = memory_region_iommu_get_min_page_size(mr);

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

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

        if (iotlb.perm != IOMMU_NONE) {

            n->notify(n, &iotlb);

        }

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

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

        if ((addr + granularity) < addr) {

            break;

        }

    }

}


static void qmp_output_end_list(Visitor *v)

{

    QmpOutputVisitor *qov = to_qov(v);

    qmp_output_pop(qov);

}


static av_cold int mpeg_mc_decode_init(AVCodecContext *avctx){

    if( avctx->thread_count > 1)

        return -1;

    if( !(avctx->slice_flags & SLICE_FLAG_CODED_ORDER) )

        return -1;

    if( !(avctx->slice_flags & SLICE_FLAG_ALLOW_FIELD) ){

        av_dlog(avctx, "mpeg12.c: XvMC decoder will work better if SLICE_FLAG_ALLOW_FIELD is set\n");

    }

    mpeg_decode_init(avctx);

    avctx->pix_fmt = PIX_FMT_XVMC_MPEG2_IDCT;

    avctx->xvmc_acceleration = 2;//2 - the blocks are packed!

    return 0;

}


static int avs_read_packet(AVFormatContext * s, AVPacket * pkt)

{

    AvsFormat *avs = s->priv_data;

    int sub_type = 0, size = 0;

    AvsBlockType type = AVS_NONE;

    int palette_size = 0;

    uint8_t palette[4 + 3 * 256];

    int ret;

    if (avs->remaining_audio_size > 0)

        if (avs_read_audio_packet(s, pkt) > 0)

            return 0;

    while (1) {

        if (avs->remaining_frame_size <= 0) {

            if (!avio_rl16(s->pb))    /* found EOF */

                return AVERROR(EIO);

            avs->remaining_frame_size = avio_rl16(s->pb) - 4;

        }

        while (avs->remaining_frame_size > 0) {

            sub_type = avio_r8(s->pb);

            type = avio_r8(s->pb);

            size = avio_rl16(s->pb);

            if (size < 4)

                return AVERROR_INVALIDDATA;

            avs->remaining_frame_size -= size;

            switch (type) {

            case AVS_PALETTE:

                if (size - 4 > sizeof(palette))

                    return AVERROR_INVALIDDATA;

                ret = avio_read(s->pb, palette, size - 4);

                if (ret < size - 4)

                    return AVERROR(EIO);

                palette_size = size;

                break;

            case AVS_VIDEO:

                if (!avs->st_video) {

                    avs->st_video = avformat_new_stream(s, NULL);

                    if (avs->st_video == NULL)

                        return AVERROR(ENOMEM);

                    avs->st_video->codec->codec_type = AVMEDIA_TYPE_VIDEO;

                    avs->st_video->codec->codec_id = AV_CODEC_ID_AVS;

                    avs->st_video->codec->width = avs->width;

                    avs->st_video->codec->height = avs->height;

                    avs->st_video->codec->bits_per_coded_sample=avs->bits_per_sample;

                    avs->st_video->nb_frames = avs->nb_frames;

                    avs->st_video->avg_frame_rate = (AVRational){avs->fps, 1};

                }

                return avs_read_video_packet(s, pkt, type, sub_type, size,

                                             palette, palette_size);

            case AVS_AUDIO:

                if (!avs->st_audio) {

                    avs->st_audio = avformat_new_stream(s, NULL);

                    if (avs->st_audio == NULL)

                        return AVERROR(ENOMEM);

                    avs->st_audio->codec->codec_type = AVMEDIA_TYPE_AUDIO;

                }

                avs->remaining_audio_size = size - 4;

                size = avs_read_audio_packet(s, pkt);

                if (size != 0)

                    return size;

                break;

            default:

                avio_skip(s->pb, size - 4);

            }

        }

    }

}


static void *file_ram_alloc(RAMBlock *block,

                            ram_addr_t memory,

                            const char *path)

{

    char *filename;

    char *sanitized_name;

    char *c;

    void *area;

    int fd;

    unsigned long hpagesize;

    hpagesize = gethugepagesize(path);

    if (!hpagesize) {

        return NULL;

    }

    if (memory < hpagesize) {

        return NULL;

    }

    if (kvm_enabled() && !kvm_has_sync_mmu()) {

        fprintf(stderr, "host lacks kvm mmu notifiers, -mem-path unsupported\n");

        return NULL;

    }

    /* Make name safe to use with mkstemp by replacing '/' with '_'. */

    sanitized_name = g_strdup(block->mr->name);

    for (c = sanitized_name; *c != '\0'; c++) {

        if (*c == '/')

            *c = '_';

    }

    filename = g_strdup_printf("%s/qemu_back_mem.%s.XXXXXX", path,

                               sanitized_name);

    g_free(sanitized_name);

    fd = mkstemp(filename);

    if (fd < 0) {

        perror("unable to create backing store for hugepages");

        g_free(filename);

        return NULL;

    }

    unlink(filename);

    g_free(filename);

    memory = (memory+hpagesize-1) & ~(hpagesize-1);

    /*

     * ftruncate is not supported by hugetlbfs in older

     * hosts, so don't bother bailing out on errors.

     * If anything goes wrong with it under other filesystems,

     * mmap will fail.

     */

    if (ftruncate(fd, memory))

        perror("ftruncate");

    area = mmap(0, memory, PROT_READ | PROT_WRITE, MAP_PRIVATE, fd, 0);

    if (area == MAP_FAILED) {

        perror("file_ram_alloc: can't mmap RAM pages");

        close(fd);

        return (NULL);

    }

    if (mem_prealloc) {

        int ret, i;

        struct sigaction act, oldact;

        sigset_t set, oldset;

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

        act.sa_handler = &sigbus_handler;

        act.sa_flags = 0;

        ret = sigaction(SIGBUS, &act, &oldact);

        if (ret) {

            perror("file_ram_alloc: failed to install signal handler");

            exit(1);

        }

        /* unblock SIGBUS */

        sigemptyset(&set);

        sigaddset(&set, SIGBUS);

        pthread_sigmask(SIG_UNBLOCK, &set, &oldset);

        if (sigsetjmp(sigjump, 1)) {

            fprintf(stderr, "file_ram_alloc: failed to preallocate pages\n");

            exit(1);

        }

        /* MAP_POPULATE silently ignores failures */

        for (i = 0; i < (memory/hpagesize)-1; i++) {

            memset(area + (hpagesize*i), 0, 1);

        }

        ret = sigaction(SIGBUS, &oldact, NULL);

        if (ret) {

            perror("file_ram_alloc: failed to reinstall signal handler");

            exit(1);

        }

        pthread_sigmask(SIG_SETMASK, &oldset, NULL);

    }

    block->fd = fd;

    return area;

}


static void boston_register_types(void)

{

    type_register_static(&boston_device);

}


static gboolean nbd_accept(QIOChannel *ioc, GIOCondition condition,

                           gpointer opaque)

{

    QIOChannelSocket *cioc;

    if (!nbd_server) {

        return FALSE;

    }

    cioc = qio_channel_socket_accept(QIO_CHANNEL_SOCKET(ioc),

                                     NULL);

    if (!cioc) {

        return TRUE;

    }

    qio_channel_set_name(QIO_CHANNEL(cioc), "nbd-server");

    nbd_client_new(NULL, cioc,

                   nbd_server->tlscreds, NULL,

                   nbd_client_put);

    object_unref(OBJECT(cioc));

    return TRUE;

}


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

                            int *data_size, const uint8_t * buf,

                            int buf_size)

{

    BFIContext *bfi = avctx->priv_data;

    uint8_t *dst = bfi->dst;

    uint8_t *src, *dst_offset, colour1, colour2;

    uint8_t *frame_end = bfi->dst + avctx->width * avctx->height;

    uint32_t *pal;

    int i, j, height = avctx->height;

    if (bfi->frame.data[0])

        avctx->release_buffer(avctx, &bfi->frame);

    bfi->frame.reference = 1;

    if (avctx->get_buffer(avctx, &bfi->frame) < 0) {

        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");

        return -1;

    }

    /* Set frame parameters and palette, if necessary */

    if (!avctx->frame_number) {

        bfi->frame.pict_type = FF_I_TYPE;

        bfi->frame.key_frame = 1;

        /* Setting the palette */

        if(avctx->extradata_size>768) {

            av_log(NULL, AV_LOG_ERROR, "Palette is too large.\n");

            return -1;

        }

        pal = (uint32_t *) bfi->frame.data[1];

        for (i = 0; i < avctx->extradata_size / 3; i++) {

            int shift = 16;

            *pal = 0;

            for (j = 0; j < 3; j++, shift -= 8)

                *pal +=

                    ((avctx->extradata[i * 3 + j] << 2) |

                    (avctx->extradata[i * 3 + j] >> 4)) << shift;

            pal++;

        }

        bfi->frame.palette_has_changed = 1;

    } else {

        bfi->frame.pict_type = FF_P_TYPE;

        bfi->frame.key_frame = 0;

    }

    buf += 4; //Unpacked size, not required.

    while (dst != frame_end) {

        static const uint8_t lentab[4]={0,2,0,1};

        unsigned int byte = *buf++, offset;

        unsigned int code = byte >> 6;

        unsigned int length = byte & ~0xC0;

        /* Get length and offset(if required) */

        if (length == 0) {

            if (code == 1) {

                length = bytestream_get_byte(&buf);

                offset = bytestream_get_le16(&buf);

            } else {

                length = bytestream_get_le16(&buf);

                if (code == 2 && length == 0)

                    break;

            }

        } else {

            if (code == 1)

                offset = bytestream_get_byte(&buf);

        }

        /* Do boundary check */

        if (dst + (length<<lentab[code]) > frame_end)

            break;

        switch (code) {

        case 0:                //Normal Chain

            bytestream_get_buffer(&buf, dst, length);

            dst += length;

            break;

        case 1:                //Back Chain

            dst_offset = dst - offset;

            length *= 4;        //Convert dwords to bytes.

            if (dst_offset < bfi->dst)

                break;

            while (length--)

                *dst++ = *dst_offset++;

            break;

        case 2:                //Skip Chain

            dst += length;

            break;

        case 3:                //Fill Chain

            colour1 = bytestream_get_byte(&buf);

            colour2 = bytestream_get_byte(&buf);

            while (length--) {

                *dst++ = colour1;

                *dst++ = colour2;

            }

            break;

        }

    }

    src = bfi->dst;

    dst = bfi->frame.data[0];

    while (height--) {

        memcpy(dst, src, avctx->width);

        src += avctx->width;

        dst += bfi->frame.linesize[0];

    }

    *data_size = sizeof(AVFrame);

    *(AVFrame *) data = bfi->frame;

    return buf_size;

}


bool block_job_user_paused(BlockJob *job)

{

    return job ? job->user_paused : 0;

}


static void booke_decr_cb(void *opaque)

{

    PowerPCCPU *cpu = opaque;

    CPUPPCState *env = &cpu->env;

    env->spr[SPR_BOOKE_TSR] |= TSR_DIS;

    booke_update_irq(cpu);

    if (env->spr[SPR_BOOKE_TCR] & TCR_ARE) {

        /* Auto Reload */

        cpu_ppc_store_decr(env, env->spr[SPR_BOOKE_DECAR]);

    }

}


static char *read_splashfile(char *filename, size_t *file_sizep,

                             int *file_typep)

{

    GError *err = NULL;

    gboolean res;

    gchar *content;

    int file_type = -1;

    unsigned int filehead = 0;

    int bmp_bpp;

    res = g_file_get_contents(filename, &content, file_sizep, &err);

    if (res == FALSE) {

        error_report("failed to read splash file '%s'", filename);

        g_error_free(err);

        return NULL;

    }

    /* check file size */

    if (*file_sizep < 30) {

        goto error;

    }

    /* check magic ID */

    filehead = ((content[0] & 0xff) + (content[1] << 8)) & 0xffff;

    if (filehead == 0xd8ff) {

        file_type = JPG_FILE;

    } else if (filehead == 0x4d42) {

        file_type = BMP_FILE;

    } else {

        goto error;

    }

    /* check BMP bpp */

    if (file_type == BMP_FILE) {

        bmp_bpp = (content[28] + (content[29] << 8)) & 0xffff;

        if (bmp_bpp != 24) {

            goto error;

        }

    }

    /* return values */

    *file_typep = file_type;

    return content;

error:

    error_report("splash file '%s' format not recognized; must be JPEG "

                 "or 24 bit BMP", filename);

    g_free(content);

    return NULL;

}


static void qemu_event_read(void *opaque)

{

    int fd = (intptr_t)opaque;

    ssize_t len;

    char buffer[512];

    /* Drain the notify pipe.  For eventfd, only 8 bytes will be read.  */

    do {

        len = read(fd, buffer, sizeof(buffer));

    } while ((len == -1 && errno == EINTR) || len == sizeof(buffer));

}


static int coreaudio_init_out (HWVoiceOut *hw, audsettings_t *as)

{

    OSStatus status;

    coreaudioVoiceOut *core = (coreaudioVoiceOut *) hw;

    UInt32 propertySize;

    int err;

    const char *typ = "playback";

    AudioValueRange frameRange;

    /* create mutex */

    err = pthread_mutex_init(&core->mutex, NULL);

    if (err) {

        dolog("Could not create mutex\nReason: %s\n", strerror (err));

        return -1;

    }

    audio_pcm_init_info (&hw->info, as);

    /* open default output device */

    propertySize = sizeof(core->outputDeviceID);

    status = AudioHardwareGetProperty(

        kAudioHardwarePropertyDefaultOutputDevice,

        &propertySize,

        &core->outputDeviceID);

    if (status != kAudioHardwareNoError) {

        coreaudio_logerr2 (status, typ,

                           "Could not get default output Device\n");

        return -1;

    }

    if (core->outputDeviceID == kAudioDeviceUnknown) {

        dolog ("Could not initialize %s - Unknown Audiodevice\n", typ);

        return -1;

    }

    /* get minimum and maximum buffer frame sizes */

    propertySize = sizeof(frameRange);

    status = AudioDeviceGetProperty(

        core->outputDeviceID,

        0,

        0,

        kAudioDevicePropertyBufferFrameSizeRange,

        &propertySize,

        &frameRange);

    if (status != kAudioHardwareNoError) {

        coreaudio_logerr2 (status, typ,

                           "Could not get device buffer frame range\n");

        return -1;

    }

    if (frameRange.mMinimum > conf.buffer_frames) {

        core->audioDevicePropertyBufferFrameSize = (UInt32) frameRange.mMinimum;

        dolog ("warning: Upsizing Buffer Frames to %f\n", frameRange.mMinimum);

    }

    else if (frameRange.mMaximum < conf.buffer_frames) {

        core->audioDevicePropertyBufferFrameSize = (UInt32) frameRange.mMaximum;

        dolog ("warning: Downsizing Buffer Frames to %f\n", frameRange.mMaximum);

    }

    else {

        core->audioDevicePropertyBufferFrameSize = conf.buffer_frames;

    }

    /* set Buffer Frame Size */

    propertySize = sizeof(core->audioDevicePropertyBufferFrameSize);

    status = AudioDeviceSetProperty(

        core->outputDeviceID,

        NULL,

        0,

        false,

        kAudioDevicePropertyBufferFrameSize,

        propertySize,

        &core->audioDevicePropertyBufferFrameSize);

    if (status != kAudioHardwareNoError) {

        coreaudio_logerr2 (status, typ,

                           "Could not set device buffer frame size %ld\n",

                           core->audioDevicePropertyBufferFrameSize);

        return -1;

    }

    /* get Buffer Frame Size */

    propertySize = sizeof(core->audioDevicePropertyBufferFrameSize);

    status = AudioDeviceGetProperty(

        core->outputDeviceID,

        0,

        false,

        kAudioDevicePropertyBufferFrameSize,

        &propertySize,

        &core->audioDevicePropertyBufferFrameSize);

    if (status != kAudioHardwareNoError) {

        coreaudio_logerr2 (status, typ,

                           "Could not get device buffer frame size\n");

        return -1;

    }

    hw->samples = conf.nbuffers * core->audioDevicePropertyBufferFrameSize;

    /* get StreamFormat */

    propertySize = sizeof(core->outputStreamBasicDescription);

    status = AudioDeviceGetProperty(

        core->outputDeviceID,

        0,

        false,

        kAudioDevicePropertyStreamFormat,

        &propertySize,

        &core->outputStreamBasicDescription);

    if (status != kAudioHardwareNoError) {

        coreaudio_logerr2 (status, typ,

                           "Could not get Device Stream properties\n");

        core->outputDeviceID = kAudioDeviceUnknown;

        return -1;

    }

    /* set Samplerate */

    core->outputStreamBasicDescription.mSampleRate = (Float64) as->freq;

    propertySize = sizeof(core->outputStreamBasicDescription);

    status = AudioDeviceSetProperty(

        core->outputDeviceID,

        0,

        0,

        0,

        kAudioDevicePropertyStreamFormat,

        propertySize,

        &core->outputStreamBasicDescription);

    if (status != kAudioHardwareNoError) {

        coreaudio_logerr2 (status, typ, "Could not set samplerate %d\n",

                           as->freq);

        core->outputDeviceID = kAudioDeviceUnknown;

        return -1;

    }

    /* set Callback */

    status = AudioDeviceAddIOProc(core->outputDeviceID, audioDeviceIOProc, hw);

    if (status != kAudioHardwareNoError) {

        coreaudio_logerr2 (status, typ, "Could not set IOProc\n");

        core->outputDeviceID = kAudioDeviceUnknown;

        return -1;

    }

    /* start Playback */

    if (!isPlaying(core->outputDeviceID)) {

        status = AudioDeviceStart(core->outputDeviceID, audioDeviceIOProc);

        if (status != kAudioHardwareNoError) {

            coreaudio_logerr2 (status, typ, "Could not start playback\n");

            AudioDeviceRemoveIOProc(core->outputDeviceID, audioDeviceIOProc);

            core->outputDeviceID = kAudioDeviceUnknown;

            return -1;

        }

    }

    return 0;

}


void tcg_region_init(void)

{

    void *buf = tcg_init_ctx.code_gen_buffer;

    void *aligned;

    size_t size = tcg_init_ctx.code_gen_buffer_size;

    size_t page_size = qemu_real_host_page_size;

    size_t region_size;

    size_t n_regions;

    size_t i;

    /* We do not yet support multiple TCG contexts, so use one region for now */

    n_regions = 1;

    /* The first region will be 'aligned - buf' bytes larger than the others */

    aligned = QEMU_ALIGN_PTR_UP(buf, page_size);

    g_assert(aligned < tcg_init_ctx.code_gen_buffer + size);

    /*

     * Make region_size a multiple of page_size, using aligned as the start.

     * As a result of this we might end up with a few extra pages at the end of

     * the buffer; we will assign those to the last region.

     */

    region_size = (size - (aligned - buf)) / n_regions;

    region_size = QEMU_ALIGN_DOWN(region_size, page_size);

    /* A region must have at least 2 pages; one code, one guard */

    g_assert(region_size >= 2 * page_size);

    /* init the region struct */

    qemu_mutex_init(&region.lock);

    region.n = n_regions;

    region.size = region_size - page_size;

    region.stride = region_size;

    region.start = buf;

    region.start_aligned = aligned;

    /* page-align the end, since its last page will be a guard page */

    region.end = QEMU_ALIGN_PTR_DOWN(buf + size, page_size);

    /* account for that last guard page */

    region.end -= page_size;

    /* set guard pages */

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

        void *start, *end;

        int rc;

        tcg_region_bounds(i, &start, &end);

        rc = qemu_mprotect_none(end, page_size);

        g_assert(!rc);

    }

    /* We do not yet support multiple TCG contexts so allocate the region now */

    {

        bool err = tcg_region_initial_alloc__locked(tcg_ctx);

        g_assert(!err);

    }

}


static int vt82c686b_ac97_initfn(PCIDevice *dev)

{

    VT686AC97State *s = DO_UPCAST(VT686AC97State, dev, dev);

    uint8_t *pci_conf = s->dev.config;

    pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_VIA);

    pci_config_set_device_id(pci_conf, PCI_DEVICE_ID_VIA_AC97);

    pci_config_set_class(pci_conf, PCI_CLASS_MULTIMEDIA_AUDIO);

    pci_config_set_revision(pci_conf, 0x50);

    pci_set_word(pci_conf + PCI_COMMAND, PCI_COMMAND_INVALIDATE |

                 PCI_COMMAND_PARITY);

    pci_set_word(pci_conf + PCI_STATUS, PCI_STATUS_CAP_LIST |

                 PCI_STATUS_DEVSEL_MEDIUM);

    pci_set_long(pci_conf + PCI_INTERRUPT_PIN, 0x03);

    return 0;

}


void sysbus_dev_print(Monitor *mon, DeviceState *dev, int indent)

{

    SysBusDevice *s = sysbus_from_qdev(dev);

    int i;

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

        monitor_printf(mon, "%*smmio " TARGET_FMT_plx "/" TARGET_FMT_plx "\n",

                       indent, "", s->mmio[i].addr, s->mmio[i].size);

    }

}


static void handle_arg_reserved_va(const char *arg)

{

    char *p;

    int shift = 0;

    reserved_va = strtoul(arg, &p, 0);

    switch (*p) {

    case 'k':

    case 'K':

        shift = 10;

        break;

    case 'M':

        shift = 20;

        break;

    case 'G':

        shift = 30;

        break;

    }

    if (shift) {

        unsigned long unshifted = reserved_va;

        p++;

        reserved_va <<= shift;

        if (((reserved_va >> shift) != unshifted)

#if HOST_LONG_BITS > TARGET_VIRT_ADDR_SPACE_BITS

            || (reserved_va > (1ul << TARGET_VIRT_ADDR_SPACE_BITS))

#endif

            ) {

            fprintf(stderr, "Reserved virtual address too big\n");

            exit(EXIT_FAILURE);

        }

    }

    if (*p) {

        fprintf(stderr, "Unrecognised -R size suffix '%s'\n", p);

        exit(EXIT_FAILURE);

    }

}


void spapr_events_init(sPAPRMachineState *spapr)

{

    QTAILQ_INIT(&spapr->pending_events);

    spapr->check_exception_irq = xics_spapr_alloc(spapr->xics, 0, false,

                                            &error_fatal);

    spapr->epow_notifier.notify = spapr_powerdown_req;

    qemu_register_powerdown_notifier(&spapr->epow_notifier);

    spapr_rtas_register(RTAS_CHECK_EXCEPTION, "check-exception",

                        check_exception);

    spapr_rtas_register(RTAS_EVENT_SCAN, "event-scan", event_scan);

}


static void bdrv_co_maybe_schedule_bh(BlockAIOCBCoroutine *acb)

{

    acb->need_bh = false;

    if (acb->req.error != -EINPROGRESS) {

        BlockDriverState *bs = acb->common.bs;

        acb->bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_co_em_bh, acb);

        qemu_bh_schedule(acb->bh);

    }

}


static void xlnx_zynqmp_init(Object *obj)

{

    XlnxZynqMPState *s = XLNX_ZYNQMP(obj);

    int i;

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

        object_initialize(&s->apu_cpu[i], sizeof(s->apu_cpu[i]),

                          "cortex-a53-" TYPE_ARM_CPU);

        object_property_add_child(obj, "apu-cpu[*]", OBJECT(&s->apu_cpu[i]),

                                  &error_abort);

    }

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

        object_initialize(&s->rpu_cpu[i], sizeof(s->rpu_cpu[i]),

                          "cortex-r5-" TYPE_ARM_CPU);

        object_property_add_child(obj, "rpu-cpu[*]", OBJECT(&s->rpu_cpu[i]),

                                  &error_abort);

    }

    object_property_add_link(obj, "ddr-ram", TYPE_MEMORY_REGION,

                             (Object **)&s->ddr_ram,

                             qdev_prop_allow_set_link_before_realize,

                             OBJ_PROP_LINK_UNREF_ON_RELEASE, &error_abort);

    object_initialize(&s->gic, sizeof(s->gic), TYPE_ARM_GIC);

    qdev_set_parent_bus(DEVICE(&s->gic), sysbus_get_default());

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

        object_initialize(&s->gem[i], sizeof(s->gem[i]), TYPE_CADENCE_GEM);

        qdev_set_parent_bus(DEVICE(&s->gem[i]), sysbus_get_default());

    }

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

        object_initialize(&s->uart[i], sizeof(s->uart[i]), TYPE_CADENCE_UART);

        qdev_set_parent_bus(DEVICE(&s->uart[i]), sysbus_get_default());

    }

    object_initialize(&s->sata, sizeof(s->sata), TYPE_SYSBUS_AHCI);

    qdev_set_parent_bus(DEVICE(&s->sata), sysbus_get_default());

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

        object_initialize(&s->sdhci[i], sizeof(s->sdhci[i]),

                          TYPE_SYSBUS_SDHCI);

        qdev_set_parent_bus(DEVICE(&s->sdhci[i]),

                            sysbus_get_default());

    }

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

        object_initialize(&s->spi[i], sizeof(s->spi[i]),

                          TYPE_XILINX_SPIPS);

        qdev_set_parent_bus(DEVICE(&s->spi[i]), sysbus_get_default());

    }

}


static int thread_execute(AVCodecContext *avctx, action_func* func, void *arg, int *ret, int job_count, int job_size)

{

    SliceThreadContext *c = avctx->internal->thread_ctx;

    int dummy_ret;

    if (!(avctx->active_thread_type&FF_THREAD_SLICE) || avctx->thread_count <= 1)

        return avcodec_default_execute(avctx, func, arg, ret, job_count, job_size);

    if (job_count <= 0)

        return 0;

    pthread_mutex_lock(&c->current_job_lock);

    c->current_job = avctx->thread_count;

    c->job_count = job_count;

    c->job_size = job_size;

    c->args = arg;

    c->func = func;

    if (ret) {

        c->rets = ret;

        c->rets_count = job_count;

    } else {

        c->rets = &dummy_ret;

        c->rets_count = 1;

    }

    c->current_execute++;

    pthread_cond_broadcast(&c->current_job_cond);

    thread_park_workers(c, avctx->thread_count);

    return 0;

}


static int xen_pt_config_reg_init(XenPCIPassthroughState *s,

                                  XenPTRegGroup *reg_grp, XenPTRegInfo *reg)

{

    XenPTReg *reg_entry;

    uint32_t data = 0;

    int rc = 0;

    reg_entry = g_new0(XenPTReg, 1);

    reg_entry->reg = reg;

    if (reg->init) {

        uint32_t host_mask, size_mask;

        unsigned int offset;

        uint32_t val;

        /* initialize emulate register */

        rc = reg->init(s, reg_entry->reg,

                       reg_grp->base_offset + reg->offset, &data);

        if (rc < 0) {

            g_free(reg_entry);

            return rc;

        }

        if (data == XEN_PT_INVALID_REG) {

            /* free unused BAR register entry */

            g_free(reg_entry);

            return 0;

        }

        /* Sync up the data to dev.config */

        offset = reg_grp->base_offset + reg->offset;

        size_mask = 0xFFFFFFFF >> ((4 - reg->size) << 3);

        switch (reg->size) {

        case 1: rc = xen_host_pci_get_byte(&s->real_device, offset, (uint8_t *)&val);

                break;

        case 2: rc = xen_host_pci_get_word(&s->real_device, offset, (uint16_t *)&val);

                break;

        case 4: rc = xen_host_pci_get_long(&s->real_device, offset, &val);

                break;

        default: assert(1);

        }

        if (rc) {

            /* Serious issues when we cannot read the host values! */

            g_free(reg_entry);

            return rc;

        }

        /* Set bits in emu_mask are the ones we emulate. The dev.config shall

         * contain the emulated view of the guest - therefore we flip the mask

         * to mask out the host values (which dev.config initially has) . */

        host_mask = size_mask & ~reg->emu_mask;

        if ((data & host_mask) != (val & host_mask)) {

            uint32_t new_val;

            /* Mask out host (including past size). */

            new_val = val & host_mask;

            /* Merge emulated ones (excluding the non-emulated ones). */

            new_val |= data & host_mask;

            /* Leave intact host and emulated values past the size - even though

             * we do not care as we write per reg->size granularity, but for the

             * logging below lets have the proper value. */

            new_val |= ((val | data)) & ~size_mask;

            XEN_PT_LOG(&s->dev,"Offset 0x%04x mismatch! Emulated=0x%04x, host=0x%04x, syncing to 0x%04x.\n",

                       offset, data, val, new_val);

            val = new_val;

        } else

            val = data;

        /* This could be just pci_set_long as we don't modify the bits

         * past reg->size, but in case this routine is run in parallel

         * we do not want to over-write other registers. */

        switch (reg->size) {

        case 1: pci_set_byte(s->dev.config + offset, (uint8_t)val);

                break;

        case 2: pci_set_word(s->dev.config + offset, (uint16_t)val);

                break;

        case 4: pci_set_long(s->dev.config + offset, val);

                break;

        default: assert(1);

        }

        /* set register value */

        reg_entry->data = val;

    }

    /* list add register entry */

    QLIST_INSERT_HEAD(&reg_grp->reg_tbl_list, reg_entry, entries);

    return 0;

}


static void chs_assemble_msbs_lsbs(DCAXllDecoder *s, DCAXllChSet *c, int band)

{

    DCAXllBand *b = &c->bands[band];

    int n, ch, nsamples = s->nframesamples;

    for (ch = 0; ch < c->nchannels; ch++) {

        int shift = chs_get_lsb_width(s, c, band, ch);

        if (shift) {

            int32_t *msb = b->msb_sample_buffer[ch];

            if (b->nscalablelsbs[ch]) {

                int32_t *lsb = b->lsb_sample_buffer[ch];

                int adj = b->bit_width_adjust[ch];

                for (n = 0; n < nsamples; n++)

                    msb[n] = msb[n] * (1 << shift) + (lsb[n] << adj);

            } else {

                for (n = 0; n < nsamples; n++)

                    msb[n] = msb[n] * (1 << shift);

            }

        }

    }

}


static void coroutine_fn send_pending_req(BDRVSheepdogState *s, uint64_t oid)

{

    AIOReq *aio_req;

    SheepdogAIOCB *acb;

    while ((aio_req = find_pending_req(s, oid)) != NULL) {

        acb = aio_req->aiocb;

        /* move aio_req from pending list to inflight one */

        QLIST_REMOVE(aio_req, aio_siblings);

        QLIST_INSERT_HEAD(&s->inflight_aio_head, aio_req, aio_siblings);

        add_aio_request(s, aio_req, acb->qiov->iov, acb->qiov->niov, false,

                        acb->aiocb_type);

    }

}


static av_cold int vqa_decode_init(AVCodecContext *avctx)

{

    VqaContext *s = avctx->priv_data;

    unsigned char *vqa_header;

    int i, j, codebook_index;

    s->avctx = avctx;

    avctx->pix_fmt = PIX_FMT_PAL8;

    /* make sure the extradata made it */

    if (s->avctx->extradata_size != VQA_HEADER_SIZE) {

        av_log(s->avctx, AV_LOG_ERROR, "  VQA video: expected extradata size of %d\n", VQA_HEADER_SIZE);

        return -1;

    }

    /* load up the VQA parameters from the header */

    vqa_header = (unsigned char *)s->avctx->extradata;

    s->vqa_version = vqa_header[0];

    s->width = AV_RL16(&vqa_header[6]);

    s->height = AV_RL16(&vqa_header[8]);

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

        s->width= s->height= 0;

        return -1;

    }

    s->vector_width = vqa_header[10];

    s->vector_height = vqa_header[11];

    s->partial_count = s->partial_countdown = vqa_header[13];

    /* the vector dimensions have to meet very stringent requirements */

    if ((s->vector_width != 4) ||

        ((s->vector_height != 2) && (s->vector_height != 4))) {

        /* return without further initialization */

        return -1;

    }

    /* allocate codebooks */

    s->codebook_size = MAX_CODEBOOK_SIZE;

    s->codebook = av_malloc(s->codebook_size);

    if (!s->codebook)

        goto fail;

    s->next_codebook_buffer = av_malloc(s->codebook_size);

    if (!s->next_codebook_buffer)

        goto fail;

    /* allocate decode buffer */

    s->decode_buffer_size = (s->width / s->vector_width) *

        (s->height / s->vector_height) * 2;

    s->decode_buffer = av_malloc(s->decode_buffer_size);

    if (!s->decode_buffer)

        goto fail;

    /* initialize the solid-color vectors */

    if (s->vector_height == 4) {

        codebook_index = 0xFF00 * 16;

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

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

                s->codebook[codebook_index++] = i;

    } else {

        codebook_index = 0xF00 * 8;

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

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

                s->codebook[codebook_index++] = i;

    }

    s->next_codebook_buffer_index = 0;

    s->frame.data[0] = NULL;

    return 0;

fail:

    av_freep(&s->codebook);

    av_freep(&s->next_codebook_buffer);

    av_freep(&s->decode_buffer);

    return AVERROR(ENOMEM);

}


static int t27(InterplayACMContext *s, unsigned ind, unsigned col)

{

    GetBitContext *gb = &s->gb;

    unsigned i, b;

    int n1, n2, n3;

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

        /* b = (x1) + (x2 * 5) + (x3 * 25) */

        b = get_bits(gb, 7);

        n1 =  (mul_3x5[b] & 0x0F) - 2;

        n2 = ((mul_3x5[b] >> 4) & 0x0F) - 2;

        n3 = ((mul_3x5[b] >> 8) & 0x0F) - 2;

        set_pos(s, i++, col, n1);

        if (i >= s->rows)

            break;

        set_pos(s, i++, col, n2);

        if (i >= s->rows)

            break;

        set_pos(s, i, col, n3);

    return 0;


static int decode_residual(H264Context *h, GetBitContext *gb, DCTELEM *block, int n, const uint8_t *scantable, const uint32_t *qmul, int max_coeff){

    MpegEncContext * const s = &h->s;

    static const int coeff_token_table_index[17]= {0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3};

    int level[16];

    int zeros_left, coeff_token, total_coeff, i, trailing_ones, run_before;

    //FIXME put trailing_onex into the context

    if(max_coeff <= 8){

        if (max_coeff == 4)

            coeff_token = get_vlc2(gb, chroma_dc_coeff_token_vlc.table, CHROMA_DC_COEFF_TOKEN_VLC_BITS, 1);

        else

            coeff_token = get_vlc2(gb, chroma422_dc_coeff_token_vlc.table, CHROMA422_DC_COEFF_TOKEN_VLC_BITS, 1);

        total_coeff= coeff_token>>2;

    }else{

        if(n >= LUMA_DC_BLOCK_INDEX){

            total_coeff= pred_non_zero_count(h, (n - LUMA_DC_BLOCK_INDEX)*16);

            coeff_token= get_vlc2(gb, coeff_token_vlc[ coeff_token_table_index[total_coeff] ].table, COEFF_TOKEN_VLC_BITS, 2);

            total_coeff= coeff_token>>2;

        }else{

            total_coeff= pred_non_zero_count(h, n);

            coeff_token= get_vlc2(gb, coeff_token_vlc[ coeff_token_table_index[total_coeff] ].table, COEFF_TOKEN_VLC_BITS, 2);

            total_coeff= coeff_token>>2;

        }

    }

    h->non_zero_count_cache[ scan8[n] ]= total_coeff;

    //FIXME set last_non_zero?

    if(total_coeff==0)

        return 0;

    if(total_coeff > (unsigned)max_coeff) {

        av_log(h->s.avctx, AV_LOG_ERROR, "corrupted macroblock %d %d (total_coeff=%d)\n", s->mb_x, s->mb_y, total_coeff);

        return -1;

    }

    trailing_ones= coeff_token&3;

    tprintf(h->s.avctx, "trailing:%d, total:%d\n", trailing_ones, total_coeff);

    assert(total_coeff<=16);

    i = show_bits(gb, 3);

    skip_bits(gb, trailing_ones);

    level[0] = 1-((i&4)>>1);

    level[1] = 1-((i&2)   );

    level[2] = 1-((i&1)<<1);

    if(trailing_ones<total_coeff) {

        int mask, prefix;

        int suffix_length = total_coeff > 10 & trailing_ones < 3;

        int bitsi= show_bits(gb, LEVEL_TAB_BITS);

        int level_code= cavlc_level_tab[suffix_length][bitsi][0];

        skip_bits(gb, cavlc_level_tab[suffix_length][bitsi][1]);

        if(level_code >= 100){

            prefix= level_code - 100;

            if(prefix == LEVEL_TAB_BITS)

                prefix += get_level_prefix(gb);

            //first coefficient has suffix_length equal to 0 or 1

            if(prefix<14){ //FIXME try to build a large unified VLC table for all this

                if(suffix_length)

                    level_code= (prefix<<1) + get_bits1(gb); //part

                else

                    level_code= prefix; //part

            }else if(prefix==14){

                if(suffix_length)

                    level_code= (prefix<<1) + get_bits1(gb); //part

                else

                    level_code= prefix + get_bits(gb, 4); //part

            }else{

                level_code= 30 + get_bits(gb, prefix-3); //part

                if(prefix>=16){

                    if(prefix > 25+3){

                        av_log(h->s.avctx, AV_LOG_ERROR, "Invalid level prefix\n");

                        return -1;

                    }

                    level_code += (1<<(prefix-3))-4096;

                }

            }

            if(trailing_ones < 3) level_code += 2;

            suffix_length = 2;

            mask= -(level_code&1);

            level[trailing_ones]= (((2+level_code)>>1) ^ mask) - mask;

        }else{

            level_code += ((level_code>>31)|1) & -(trailing_ones < 3);

            suffix_length = 1 + (level_code + 3U > 6U);

            level[trailing_ones]= level_code;

        }

        //remaining coefficients have suffix_length > 0

        for(i=trailing_ones+1;i<total_coeff;i++) {

            static const unsigned int suffix_limit[7] = {0,3,6,12,24,48,INT_MAX };

            int bitsi= show_bits(gb, LEVEL_TAB_BITS);

            level_code= cavlc_level_tab[suffix_length][bitsi][0];

            skip_bits(gb, cavlc_level_tab[suffix_length][bitsi][1]);

            if(level_code >= 100){

                prefix= level_code - 100;

                if(prefix == LEVEL_TAB_BITS){

                    prefix += get_level_prefix(gb);

                }

                if(prefix<15){

                    level_code = (prefix<<suffix_length) + get_bits(gb, suffix_length);

                }else{

                    level_code = (15<<suffix_length) + get_bits(gb, prefix-3);

                    if(prefix>=16)

                        level_code += (1<<(prefix-3))-4096;

                }

                mask= -(level_code&1);

                level_code= (((2+level_code)>>1) ^ mask) - mask;

            }

            level[i]= level_code;

            suffix_length+= suffix_limit[suffix_length] + level_code > 2U*suffix_limit[suffix_length];

        }

    }

    if(total_coeff == max_coeff)

        zeros_left=0;

    else{

        if (max_coeff <= 8) {

            if (max_coeff == 4)

                zeros_left = get_vlc2(gb, chroma_dc_total_zeros_vlc[total_coeff - 1].table,

                                      CHROMA_DC_TOTAL_ZEROS_VLC_BITS, 1);

            else

                zeros_left = get_vlc2(gb, chroma422_dc_total_zeros_vlc[total_coeff - 1].table,

                                      CHROMA422_DC_TOTAL_ZEROS_VLC_BITS, 1);

        } else {

            zeros_left= get_vlc2(gb, total_zeros_vlc[total_coeff - 1].table, TOTAL_ZEROS_VLC_BITS, 1);

        }

    }

#define STORE_BLOCK(type) \

    scantable += zeros_left + total_coeff - 1; \

    if(n >= LUMA_DC_BLOCK_INDEX){ \

        ((type*)block)[*scantable] = level[0]; \

        for(i=1;i<total_coeff && zeros_left > 0;i++) { \

            if(zeros_left < 7) \

                run_before= get_vlc2(gb, run_vlc[zeros_left - 1].table, RUN_VLC_BITS, 1); \

            else \

                run_before= get_vlc2(gb, run7_vlc.table, RUN7_VLC_BITS, 2); \

            zeros_left -= run_before; \

            scantable -= 1 + run_before; \

            ((type*)block)[*scantable]= level[i]; \

        } \

        for(;i<total_coeff;i++) { \

            scantable--; \

            ((type*)block)[*scantable]= level[i]; \

        } \

    }else{ \

        ((type*)block)[*scantable] = ((int)(level[0] * qmul[*scantable] + 32))>>6; \

        for(i=1;i<total_coeff && zeros_left > 0;i++) { \

            if(zeros_left < 7) \

                run_before= get_vlc2(gb, run_vlc[zeros_left - 1].table, RUN_VLC_BITS, 1); \

            else \

                run_before= get_vlc2(gb, run7_vlc.table, RUN7_VLC_BITS, 2); \

            zeros_left -= run_before; \

            scantable -= 1 + run_before; \

            ((type*)block)[*scantable]= ((int)(level[i] * qmul[*scantable] + 32))>>6; \

        } \

        for(;i<total_coeff;i++) { \

            scantable--; \

            ((type*)block)[*scantable]= ((int)(level[i] * qmul[*scantable] + 32))>>6; \

        } \

    }

    if (h->pixel_shift) {

        STORE_BLOCK(int32_t)

    } else {

        STORE_BLOCK(int16_t)

    }

    if(zeros_left<0){

        av_log(h->s.avctx, AV_LOG_ERROR, "negative number of zero coeffs at %d %d\n", s->mb_x, s->mb_y);

        return -1;

    }

    return 0;

}


static AVFrame *hwmap_get_buffer(AVFilterLink *inlink, int w, int h)

{

    AVFilterContext *avctx = inlink->dst;

    AVFilterLink  *outlink = avctx->outputs[0];

    HWMapContext      *ctx = avctx->priv;

    if (ctx->map_backwards) {

        AVFrame *src, *dst;

        int err;

        src = ff_get_video_buffer(outlink, w, h);

        if (!src) {

            av_log(avctx, AV_LOG_ERROR, "Failed to allocate source "

                   "frame for software mapping.\n");

            return NULL;

        }

        dst = av_frame_alloc();

        if (!dst) {

            av_frame_free(&src);

            return NULL;

        }

        err = av_hwframe_map(dst, src, ctx->mode);

        if (err) {

            av_log(avctx, AV_LOG_ERROR, "Failed to map frame to "

                   "software: %d.\n", err);

            av_frame_free(&src);

            av_frame_free(&dst);

            return NULL;

        }

        av_frame_free(&src);

        return dst;

    } else {

        return ff_default_get_video_buffer(inlink, w, h);

    }

}


static int decode_wdlt(uint8_t *frame, int width, int height,

                       const uint8_t *src, const uint8_t *src_end)

{

    const uint8_t *frame_end   = frame + width * height;

    uint8_t *line_ptr;

    int count, i, v, lines, segments;

    lines = bytestream_get_le16(&src);

    if (lines > height || src >= src_end)

        return -1;

    while (lines--) {

        segments = bytestream_get_le16(&src);

        while ((segments & 0xC000) == 0xC000) {

            unsigned delta = -((int16_t)segments * width);

            if (frame_end - frame <= delta)

                return -1;

            frame    += delta;

            segments = bytestream_get_le16(&src);

        }

        if (segments & 0x8000) {

            frame[width - 1] = segments & 0xFF;

            segments = bytestream_get_le16(&src);

        }

        line_ptr = frame;

        frame += width;

        while (segments--) {

            if (src_end - src < 2)

                return -1;

            if (frame - line_ptr <= *src)

                return -1;

            line_ptr += *src++;

            count = (int8_t)*src++;

            if (count >= 0) {

                if (frame - line_ptr < count*2 || src_end - src < count*2)

                    return -1;

                bytestream_get_buffer(&src, line_ptr, count*2);

                line_ptr += count * 2;

            } else {

                count = -count;

                if (frame - line_ptr < count*2 || src_end - src < 2)

                    return -1;

                v = bytestream_get_le16(&src);

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

                    bytestream_put_le16(&line_ptr, v);

            }

        }

    }

    return 0;

}


av_cold void ff_vp8dsp_init_x86(VP8DSPContext* c)

{

    mm_flags = mm_support();

#if HAVE_YASM

    if (mm_flags & FF_MM_MMX) {

        c->vp8_idct_dc_add                  = ff_vp8_idct_dc_add_mmx;

        c->vp8_idct_add                     = ff_vp8_idct_add_mmx;

        c->put_vp8_epel_pixels_tab[0][0][0]     =

        c->put_vp8_bilinear_pixels_tab[0][0][0] = ff_put_vp8_pixels16_mmx;

        c->put_vp8_epel_pixels_tab[1][0][0]     =

        c->put_vp8_bilinear_pixels_tab[1][0][0] = ff_put_vp8_pixels8_mmx;

        c->vp8_v_loop_filter_simple = ff_vp8_v_loop_filter_simple_mmx;

        c->vp8_h_loop_filter_simple = ff_vp8_h_loop_filter_simple_mmx;

        c->vp8_v_loop_filter16y_inner = ff_vp8_v_loop_filter16y_inner_mmx;

        c->vp8_h_loop_filter16y_inner = ff_vp8_h_loop_filter16y_inner_mmx;

        c->vp8_v_loop_filter8uv_inner = ff_vp8_v_loop_filter8uv_inner_mmx;

        c->vp8_h_loop_filter8uv_inner = ff_vp8_h_loop_filter8uv_inner_mmx;

    }

    /* note that 4-tap width=16 functions are missing because w=16

     * is only used for luma, and luma is always a copy or sixtap. */

    if (mm_flags & FF_MM_MMX2) {

        c->vp8_luma_dc_wht = ff_vp8_luma_dc_wht_mmxext;

        VP8_LUMA_MC_FUNC(0, 16, mmxext);

        VP8_MC_FUNC(1, 8, mmxext);

        VP8_MC_FUNC(2, 4, mmxext);

        VP8_BILINEAR_MC_FUNC(0, 16, mmxext);

        VP8_BILINEAR_MC_FUNC(1, 8, mmxext);

        VP8_BILINEAR_MC_FUNC(2, 4, mmxext);

        c->vp8_v_loop_filter_simple = ff_vp8_v_loop_filter_simple_mmxext;

        c->vp8_h_loop_filter_simple = ff_vp8_h_loop_filter_simple_mmxext;

        c->vp8_v_loop_filter16y_inner = ff_vp8_v_loop_filter16y_inner_mmxext;

        c->vp8_h_loop_filter16y_inner = ff_vp8_h_loop_filter16y_inner_mmxext;

        c->vp8_v_loop_filter8uv_inner = ff_vp8_v_loop_filter8uv_inner_mmxext;

        c->vp8_h_loop_filter8uv_inner = ff_vp8_h_loop_filter8uv_inner_mmxext;

    }

    if (mm_flags & FF_MM_SSE) {

        c->put_vp8_epel_pixels_tab[0][0][0]     =

        c->put_vp8_bilinear_pixels_tab[0][0][0] = ff_put_vp8_pixels16_sse;

    }

    if (mm_flags & FF_MM_SSE2) {

        VP8_LUMA_MC_FUNC(0, 16, sse2);

        VP8_MC_FUNC(1, 8, sse2);

        VP8_BILINEAR_MC_FUNC(0, 16, sse2);

        VP8_BILINEAR_MC_FUNC(1, 8, sse2);

        c->vp8_v_loop_filter_simple = ff_vp8_v_loop_filter_simple_sse2;

        c->vp8_h_loop_filter_simple = ff_vp8_h_loop_filter_simple_sse2;

        c->vp8_v_loop_filter16y_inner = ff_vp8_v_loop_filter16y_inner_sse2;

        c->vp8_h_loop_filter16y_inner = ff_vp8_h_loop_filter16y_inner_sse2;

        c->vp8_v_loop_filter8uv_inner = ff_vp8_v_loop_filter8uv_inner_sse2;

        c->vp8_h_loop_filter8uv_inner = ff_vp8_h_loop_filter8uv_inner_sse2;

    }

    if (mm_flags & FF_MM_SSSE3) {

        VP8_LUMA_MC_FUNC(0, 16, ssse3);

        VP8_MC_FUNC(1, 8, ssse3);

        VP8_MC_FUNC(2, 4, ssse3);

        VP8_BILINEAR_MC_FUNC(0, 16, ssse3);

        VP8_BILINEAR_MC_FUNC(1, 8, ssse3);

        VP8_BILINEAR_MC_FUNC(2, 4, ssse3);

    }

    if (mm_flags & FF_MM_SSE4) {

        c->vp8_idct_dc_add                  = ff_vp8_idct_dc_add_sse4;

    }

#endif

}


PIX_SAD(mmxext)

#endif /* HAVE_INLINE_ASM */

av_cold void ff_dsputil_init_pix_mmx(DSPContext *c, AVCodecContext *avctx)

{

#if HAVE_INLINE_ASM

    int cpu_flags = av_get_cpu_flags();

    if (INLINE_MMX(cpu_flags)) {

        c->pix_abs[0][0] = sad16_mmx;

        c->pix_abs[0][1] = sad16_x2_mmx;

        c->pix_abs[0][2] = sad16_y2_mmx;

        c->pix_abs[0][3] = sad16_xy2_mmx;

        c->pix_abs[1][0] = sad8_mmx;

        c->pix_abs[1][1] = sad8_x2_mmx;

        c->pix_abs[1][2] = sad8_y2_mmx;

        c->pix_abs[1][3] = sad8_xy2_mmx;

        c->sad[0] = sad16_mmx;

        c->sad[1] = sad8_mmx;

    }

    if (INLINE_MMXEXT(cpu_flags)) {

        c->pix_abs[0][0] = sad16_mmxext;

        c->pix_abs[1][0] = sad8_mmxext;

        c->sad[0] = sad16_mmxext;

        c->sad[1] = sad8_mmxext;

        if (!(avctx->flags & CODEC_FLAG_BITEXACT)) {

            c->pix_abs[0][1] = sad16_x2_mmxext;

            c->pix_abs[0][2] = sad16_y2_mmxext;

            c->pix_abs[0][3] = sad16_xy2_mmxext;

            c->pix_abs[1][1] = sad8_x2_mmxext;

            c->pix_abs[1][2] = sad8_y2_mmxext;

            c->pix_abs[1][3] = sad8_xy2_mmxext;

        }

    }

    if (INLINE_SSE2(cpu_flags) && !(cpu_flags & AV_CPU_FLAG_3DNOW) && avctx->codec_id != AV_CODEC_ID_SNOW) {

        c->sad[0] = sad16_sse2;

    }

#endif /* HAVE_INLINE_ASM */

}


void cpu_loop(CPUARMState *env)

{

    CPUState *cs = CPU(arm_env_get_cpu(env));

    int trapnr;

    unsigned int n, insn;

    target_siginfo_t info;

    uint32_t addr;

    for(;;) {

        cpu_exec_start(cs);

        trapnr = cpu_arm_exec(cs);

        cpu_exec_end(cs);

        switch(trapnr) {

        case EXCP_UDEF:

            {

                TaskState *ts = cs->opaque;

                uint32_t opcode;

                int rc;

                /* we handle the FPU emulation here, as Linux */

                /* we get the opcode */

                /* FIXME - what to do if get_user() fails? */

                get_user_code_u32(opcode, env->regs[15], env);

                rc = EmulateAll(opcode, &ts->fpa, env);

                if (rc == 0) { /* illegal instruction */

                    info.si_signo = TARGET_SIGILL;

                    info.si_errno = 0;

                    info.si_code = TARGET_ILL_ILLOPN;

                    info._sifields._sigfault._addr = env->regs[15];

                    queue_signal(env, info.si_signo, &info);

                } else if (rc < 0) { /* FP exception */

                    int arm_fpe=0;

                    /* translate softfloat flags to FPSR flags */

                    if (-rc & float_flag_invalid)

                      arm_fpe |= BIT_IOC;

                    if (-rc & float_flag_divbyzero)

                      arm_fpe |= BIT_DZC;

                    if (-rc & float_flag_overflow)

                      arm_fpe |= BIT_OFC;

                    if (-rc & float_flag_underflow)

                      arm_fpe |= BIT_UFC;

                    if (-rc & float_flag_inexact)

                      arm_fpe |= BIT_IXC;

                    FPSR fpsr = ts->fpa.fpsr;

                    //printf("fpsr 0x%x, arm_fpe 0x%x\n",fpsr,arm_fpe);

                    if (fpsr & (arm_fpe << 16)) { /* exception enabled? */

                      info.si_signo = TARGET_SIGFPE;

                      info.si_errno = 0;

                      /* ordered by priority, least first */

                      if (arm_fpe & BIT_IXC) info.si_code = TARGET_FPE_FLTRES;

                      if (arm_fpe & BIT_UFC) info.si_code = TARGET_FPE_FLTUND;

                      if (arm_fpe & BIT_OFC) info.si_code = TARGET_FPE_FLTOVF;

                      if (arm_fpe & BIT_DZC) info.si_code = TARGET_FPE_FLTDIV;

                      if (arm_fpe & BIT_IOC) info.si_code = TARGET_FPE_FLTINV;

                      info._sifields._sigfault._addr = env->regs[15];

                      queue_signal(env, info.si_signo, &info);

                    } else {

                      env->regs[15] += 4;

                    }

                    /* accumulate unenabled exceptions */

                    if ((!(fpsr & BIT_IXE)) && (arm_fpe & BIT_IXC))

                      fpsr |= BIT_IXC;

                    if ((!(fpsr & BIT_UFE)) && (arm_fpe & BIT_UFC))

                      fpsr |= BIT_UFC;

                    if ((!(fpsr & BIT_OFE)) && (arm_fpe & BIT_OFC))

                      fpsr |= BIT_OFC;

                    if ((!(fpsr & BIT_DZE)) && (arm_fpe & BIT_DZC))

                      fpsr |= BIT_DZC;

                    if ((!(fpsr & BIT_IOE)) && (arm_fpe & BIT_IOC))

                      fpsr |= BIT_IOC;

                    ts->fpa.fpsr=fpsr;

                } else { /* everything OK */

                    /* increment PC */

                    env->regs[15] += 4;

                }

            }

            break;

        case EXCP_SWI:

        case EXCP_BKPT:

            {

                env->eabi = 1;

                /* system call */

                if (trapnr == EXCP_BKPT) {

                    if (env->thumb) {

                        /* FIXME - what to do if get_user() fails? */

                        get_user_code_u16(insn, env->regs[15], env);

                        n = insn & 0xff;

                        env->regs[15] += 2;

                    } else {

                        /* FIXME - what to do if get_user() fails? */

                        get_user_code_u32(insn, env->regs[15], env);

                        n = (insn & 0xf) | ((insn >> 4) & 0xff0);

                        env->regs[15] += 4;

                    }

                } else {

                    if (env->thumb) {

                        /* FIXME - what to do if get_user() fails? */

                        get_user_code_u16(insn, env->regs[15] - 2, env);

                        n = insn & 0xff;

                    } else {

                        /* FIXME - what to do if get_user() fails? */

                        get_user_code_u32(insn, env->regs[15] - 4, env);

                        n = insn & 0xffffff;

                    }

                }

                if (n == ARM_NR_cacheflush) {

                    /* nop */

                } else if (n == ARM_NR_semihosting

                           || n == ARM_NR_thumb_semihosting) {

                    env->regs[0] = do_arm_semihosting (env);

                } else if (n == 0 || n >= ARM_SYSCALL_BASE || env->thumb) {

                    /* linux syscall */

                    if (env->thumb || n == 0) {

                        n = env->regs[7];

                    } else {

                        n -= ARM_SYSCALL_BASE;

                        env->eabi = 0;

                    }

                    if ( n > ARM_NR_BASE) {

                        switch (n) {

                        case ARM_NR_cacheflush:

                            /* nop */

                            break;

                        case ARM_NR_set_tls:

                            cpu_set_tls(env, env->regs[0]);

                            env->regs[0] = 0;

                            break;

                        case ARM_NR_breakpoint:

                            env->regs[15] -= env->thumb ? 2 : 4;

                            goto excp_debug;

                        default:

                            gemu_log("qemu: Unsupported ARM syscall: 0x%x\n",

                                     n);

                            env->regs[0] = -TARGET_ENOSYS;

                            break;

                        }

                    } else {

                        env->regs[0] = do_syscall(env,

                                                  n,

                                                  env->regs[0],

                                                  env->regs[1],

                                                  env->regs[2],

                                                  env->regs[3],

                                                  env->regs[4],

                                                  env->regs[5],

                                                  0, 0);

                    }

                } else {

                    goto error;

                }

            }

            break;

        case EXCP_INTERRUPT:

            /* just indicate that signals should be handled asap */

            break;

        case EXCP_STREX:

            if (!do_strex(env)) {

                break;

            }

            /* fall through for segv */

        case EXCP_PREFETCH_ABORT:

        case EXCP_DATA_ABORT:

            addr = env->exception.vaddress;

            {

                info.si_signo = TARGET_SIGSEGV;

                info.si_errno = 0;

                /* XXX: check env->error_code */

                info.si_code = TARGET_SEGV_MAPERR;

                info._sifields._sigfault._addr = addr;

                queue_signal(env, info.si_signo, &info);

            }

            break;

        case EXCP_DEBUG:

        excp_debug:

            {

                int sig;

                sig = gdb_handlesig(cs, TARGET_SIGTRAP);

                if (sig)

                  {

                    info.si_signo = sig;

                    info.si_errno = 0;

                    info.si_code = TARGET_TRAP_BRKPT;

                    queue_signal(env, info.si_signo, &info);

                  }

            }

            break;

        case EXCP_KERNEL_TRAP:

            if (do_kernel_trap(env))

              goto error;

            break;

        case EXCP_YIELD:

            /* nothing to do here for user-mode, just resume guest code */

            break;

        default:

        error:

            EXCP_DUMP(env, "qemu: unhandled CPU exception 0x%x - aborting\n", trapnr);

            abort();

        }

        process_pending_signals(env);

    }

}


static void sunkbd_event(void *opaque, int ch)

{

    ChannelState *s = opaque;

    int release = ch & 0x80;

    trace_escc_sunkbd_event_in(ch);

    switch (ch) {

    case 58: // Caps lock press

        s->caps_lock_mode ^= 1;

        if (s->caps_lock_mode == 2)

            return; // Drop second press

        break;

    case 69: // Num lock press

        s->num_lock_mode ^= 1;

        if (s->num_lock_mode == 2)

            return; // Drop second press

        break;

    case 186: // Caps lock release

        s->caps_lock_mode ^= 2;

        if (s->caps_lock_mode == 3)

            return; // Drop first release

        break;

    case 197: // Num lock release

        s->num_lock_mode ^= 2;

        if (s->num_lock_mode == 3)

            return; // Drop first release

        break;

    case 0xe0:

        s->e0_mode = 1;

        return;

    default:

        break;

    }

    if (s->e0_mode) {

        s->e0_mode = 0;

        ch = e0_keycodes[ch & 0x7f];

    } else {

        ch = keycodes[ch & 0x7f];

    }

    trace_escc_sunkbd_event_out(ch);

    put_queue(s, ch | release);

}


static void omap_pwl_update(struct omap_pwl_s *s)

{

    int output = (s->clk && s->enable) ? s->level : 0;

    if (output != s->output) {

        s->output = output;

        printf("%s: Backlight now at %i/256\n", __FUNCTION__, output);

    }

}


static void free_note_info(struct elf_note_info *info)

{

    struct elf_thread_status *ets;

    while (!TAILQ_EMPTY(&info->thread_list)) {

        ets = TAILQ_FIRST(&info->thread_list);

        TAILQ_REMOVE(&info->thread_list, ets, ets_link);

        qemu_free(ets);

    }

    qemu_free(info->prstatus);

    qemu_free(info->psinfo);

    qemu_free(info->notes);

}


void *get_mmap_addr(unsigned long size)

{

    return NULL;

}


uint32_t HELPER(neon_narrow_sat_s32)(CPUState *env, uint64_t x)

{

    if ((int64_t)x != (int32_t)x) {

        SET_QC();

        return (x >> 63) ^ 0x7fffffff;

    }

    return x;

}


static void amdvi_realize(DeviceState *dev, Error **err)

{

    int ret = 0;

    AMDVIState *s = AMD_IOMMU_DEVICE(dev);

    X86IOMMUState *x86_iommu = X86_IOMMU_DEVICE(dev);

    MachineState *ms = MACHINE(qdev_get_machine());

    MachineClass *mc = MACHINE_GET_CLASS(ms);

    PCMachineState *pcms =

        PC_MACHINE(object_dynamic_cast(OBJECT(ms), TYPE_PC_MACHINE));

    PCIBus *bus;

    if (!pcms) {

        error_setg(err, "Machine-type '%s' not supported by amd-iommu",

                   mc->name);

        return;

    }

    bus = pcms->bus;

    s->iotlb = g_hash_table_new_full(amdvi_uint64_hash,

                                     amdvi_uint64_equal, g_free, g_free);

    /* This device should take care of IOMMU PCI properties */

    x86_iommu->type = TYPE_AMD;

    qdev_set_parent_bus(DEVICE(&s->pci), &bus->qbus);

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

    ret = pci_add_capability(&s->pci.dev, AMDVI_CAPAB_ID_SEC, 0,

                                         AMDVI_CAPAB_SIZE, err);

    if (ret < 0) {

        return;

    }

    s->capab_offset = ret;

    ret = pci_add_capability(&s->pci.dev, PCI_CAP_ID_MSI, 0,

                             AMDVI_CAPAB_REG_SIZE, err);

    if (ret < 0) {

        return;

    }

    ret = pci_add_capability(&s->pci.dev, PCI_CAP_ID_HT, 0,

                             AMDVI_CAPAB_REG_SIZE, err);

    if (ret < 0) {

        return;

    }

    /* set up MMIO */

    memory_region_init_io(&s->mmio, OBJECT(s), &mmio_mem_ops, s, "amdvi-mmio",

                          AMDVI_MMIO_SIZE);

    sysbus_init_mmio(SYS_BUS_DEVICE(s), &s->mmio);

    sysbus_mmio_map(SYS_BUS_DEVICE(s), 0, AMDVI_BASE_ADDR);

    pci_setup_iommu(bus, amdvi_host_dma_iommu, s);

    s->devid = object_property_get_int(OBJECT(&s->pci), "addr", err);

    msi_init(&s->pci.dev, 0, 1, true, false, err);

    amdvi_init(s);

}


static int xan_decode_frame(AVCodecContext *avctx,

                            void *data, int *data_size,

                            uint8_t *buf, int buf_size)

{

    XanContext *s = avctx->priv_data;

    AVPaletteControl *palette_control = avctx->palctrl;

    int keyframe = 0;

    if (palette_control->palette_changed) {

        /* load the new palette and reset the palette control */

        xan_wc3_build_palette(s, palette_control->palette);

        /* If pal8 we clear flag when we copy palette */

        if (s->avctx->pix_fmt != PIX_FMT_PAL8)

            palette_control->palette_changed = 0;

        keyframe = 1;

    }

    if (avctx->get_buffer(avctx, &s->current_frame)) {

        av_log(s->avctx, AV_LOG_ERROR, "  Xan Video: get_buffer() failed\n");

        return -1;

    }

    s->current_frame.reference = 3;

    s->buf = buf;

    s->size = buf_size;

    if (avctx->codec->id == CODEC_ID_XAN_WC3)

        xan_wc3_decode_frame(s);

    else if (avctx->codec->id == CODEC_ID_XAN_WC4)

        xan_wc4_decode_frame(s);

    /* release the last frame if it is allocated */

    if (s->last_frame.data[0])

        avctx->release_buffer(avctx, &s->last_frame);

    /* shuffle frames */

    s->last_frame = s->current_frame;

    *data_size = sizeof(AVFrame);

    *(AVFrame*)data = s->current_frame;

    /* always report that the buffer was completely consumed */

    return buf_size;

}


void helper_rdmsr(void)

{

    uint64_t val;

    helper_svm_check_intercept_param(SVM_EXIT_MSR, 0);

    switch((uint32_t)ECX) {

    case MSR_IA32_SYSENTER_CS:

        val = env->sysenter_cs;

        break;

    case MSR_IA32_SYSENTER_ESP:

        val = env->sysenter_esp;

        break;

    case MSR_IA32_SYSENTER_EIP:

        val = env->sysenter_eip;

        break;

    case MSR_IA32_APICBASE:

        val = cpu_get_apic_base(env);

        break;

    case MSR_EFER:

        val = env->efer;

        break;

    case MSR_STAR:

        val = env->star;

        break;

    case MSR_PAT:

        val = env->pat;

        break;

    case MSR_VM_HSAVE_PA:

        val = env->vm_hsave;

        break;

    case MSR_IA32_PERF_STATUS:

        /* tsc_increment_by_tick */

        val = 1000ULL;

        /* CPU multiplier */

        val |= (((uint64_t)4ULL) << 40);

        break;

#ifdef TARGET_X86_64

    case MSR_LSTAR:

        val = env->lstar;

        break;

    case MSR_CSTAR:

        val = env->cstar;

        break;

    case MSR_FMASK:

        val = env->fmask;

        break;

    case MSR_FSBASE:

        val = env->segs[R_FS].base;

        break;

    case MSR_GSBASE:

        val = env->segs[R_GS].base;

        break;

    case MSR_KERNELGSBASE:

        val = env->kernelgsbase;

        break;

#endif

#ifdef CONFIG_KQEMU

    case MSR_QPI_COMMBASE:

        if (env->kqemu_enabled) {

            val = kqemu_comm_base;

        } else {

            val = 0;

        }

        break;

#endif

    case MSR_MTRRphysBase(0):

    case MSR_MTRRphysBase(1):

    case MSR_MTRRphysBase(2):

    case MSR_MTRRphysBase(3):

    case MSR_MTRRphysBase(4):

    case MSR_MTRRphysBase(5):

    case MSR_MTRRphysBase(6):

    case MSR_MTRRphysBase(7):

        val = env->mtrr_var[((uint32_t)ECX - MSR_MTRRphysBase(0)) / 2].base;

        break;

    case MSR_MTRRphysMask(0):

    case MSR_MTRRphysMask(1):

    case MSR_MTRRphysMask(2):

    case MSR_MTRRphysMask(3):

    case MSR_MTRRphysMask(4):

    case MSR_MTRRphysMask(5):

    case MSR_MTRRphysMask(6):

    case MSR_MTRRphysMask(7):

        val = env->mtrr_var[((uint32_t)ECX - MSR_MTRRphysMask(0)) / 2].mask;

        break;

    case MSR_MTRRfix64K_00000:

        val = env->mtrr_fixed[0];

        break;

    case MSR_MTRRfix16K_80000:

    case MSR_MTRRfix16K_A0000:

        val = env->mtrr_fixed[(uint32_t)ECX - MSR_MTRRfix16K_80000 + 1];

        break;

    case MSR_MTRRfix4K_C0000:

    case MSR_MTRRfix4K_C8000:

    case MSR_MTRRfix4K_D0000:

    case MSR_MTRRfix4K_D8000:

    case MSR_MTRRfix4K_E0000:

    case MSR_MTRRfix4K_E8000:

    case MSR_MTRRfix4K_F0000:

    case MSR_MTRRfix4K_F8000:

        val = env->mtrr_fixed[(uint32_t)ECX - MSR_MTRRfix4K_C0000 + 3];

        break;

    case MSR_MTRRdefType:

        val = env->mtrr_deftype;

        break;

    case MSR_MTRRcap:

        if (env->cpuid_features & CPUID_MTRR)

            val = MSR_MTRRcap_VCNT | MSR_MTRRcap_FIXRANGE_SUPPORT | MSR_MTRRcap_WC_SUPPORTED;

        else

            /* XXX: exception ? */

            val = 0;

        break;

    case MSR_MCG_CAP:

        val = env->mcg_cap;

        break;

    case MSR_MCG_CTL:

        if (env->mcg_cap & MCG_CTL_P)

            val = env->mcg_ctl;

        else

            val = 0;

        break;

    case MSR_MCG_STATUS:

        val = env->mcg_status;

        break;

    default:

        if ((uint32_t)ECX >= MSR_MC0_CTL

            && (uint32_t)ECX < MSR_MC0_CTL + (4 * env->mcg_cap & 0xff)) {

            uint32_t offset = (uint32_t)ECX - MSR_MC0_CTL;

            val = env->mce_banks[offset];

            break;

        }

        /* XXX: exception ? */

        val = 0;

        break;

    }

    EAX = (uint32_t)(val);

    EDX = (uint32_t)(val >> 32);

}


void AUD_del_capture (CaptureVoiceOut *cap, void *cb_opaque)

{

    struct capture_callback *cb;

    for (cb = cap->cb_head.lh_first; cb; cb = cb->entries.le_next) {

        if (cb->opaque == cb_opaque) {

            cb->ops.destroy (cb_opaque);

            LIST_REMOVE (cb, entries);

            qemu_free (cb);

            if (!cap->cb_head.lh_first) {

                SWVoiceOut *sw = cap->hw.sw_head.lh_first, *sw1;

                while (sw) {

                    SWVoiceCap *sc = (SWVoiceCap *) sw;

#ifdef DEBUG_CAPTURE

                    dolog ("freeing %s\n", sw->name);

#endif

                    sw1 = sw->entries.le_next;

                    if (sw->rate) {

                        st_rate_stop (sw->rate);

                        sw->rate = NULL;

                    }

                    LIST_REMOVE (sw, entries);

                    LIST_REMOVE (sc, entries);

                    qemu_free (sc);

                    sw = sw1;

                }

                LIST_REMOVE (cap, entries);

                qemu_free (cap);

            }

            return;

        }

    }

}


START_TEST(unterminated_dict)

{

    QObject *obj = qobject_from_json("{'abc':32");

    fail_unless(obj == NULL);

}


static void spapr_cpu_reset(void *opaque)

{

    sPAPRMachineState *spapr = SPAPR_MACHINE(qdev_get_machine());

    PowerPCCPU *cpu = opaque;

    CPUState *cs = CPU(cpu);

    CPUPPCState *env = &cpu->env;

    cpu_reset(cs);

    /* All CPUs start halted.  CPU0 is unhalted from the machine level

     * reset code and the rest are explicitly started up by the guest

     * using an RTAS call */

    cs->halted = 1;

    env->spr[SPR_HIOR] = 0;

    ppc_hash64_set_external_hpt(cpu, spapr->htab, spapr->htab_shift,

                                &error_fatal);

}


static int scsi_handle_rw_error(SCSIDiskReq *r, int error, int type)

{

    int is_read = (type == SCSI_REQ_STATUS_RETRY_READ);

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

    BlockErrorAction action = bdrv_get_on_error(s->bs, is_read);

    if (action == BLOCK_ERR_IGNORE) {

        bdrv_mon_event(s->bs, BDRV_ACTION_IGNORE, is_read);

        return 0;

    }

    if ((error == ENOSPC && action == BLOCK_ERR_STOP_ENOSPC)

            || action == BLOCK_ERR_STOP_ANY) {

        type &= SCSI_REQ_STATUS_RETRY_TYPE_MASK;

        r->status |= SCSI_REQ_STATUS_RETRY | type;

        bdrv_mon_event(s->bs, BDRV_ACTION_STOP, is_read);

        vm_stop(VMSTOP_DISKFULL);

    } else {

        if (type == SCSI_REQ_STATUS_RETRY_READ) {

            scsi_req_data(&r->req, 0);

        }

        if (error == ENOMEM) {

            scsi_command_complete(r, CHECK_CONDITION,

                                  SENSE_CODE(TARGET_FAILURE));

        } else {

            scsi_command_complete(r, CHECK_CONDITION,

                                  SENSE_CODE(IO_ERROR));

        }

        bdrv_mon_event(s->bs, BDRV_ACTION_REPORT, is_read);

    }

    return 1;

}


void xen_map_cache_init(phys_offset_to_gaddr_t f, void *opaque)

{

    unsigned long size;

    struct rlimit rlimit_as;

    mapcache = g_malloc0(sizeof (MapCache));

    mapcache->phys_offset_to_gaddr = f;

    mapcache->opaque = opaque;

    qemu_mutex_init(&mapcache->lock);

    QTAILQ_INIT(&mapcache->locked_entries);

    if (geteuid() == 0) {

        rlimit_as.rlim_cur = RLIM_INFINITY;

        rlimit_as.rlim_max = RLIM_INFINITY;

        mapcache->max_mcache_size = MCACHE_MAX_SIZE;

    } else {

        getrlimit(RLIMIT_AS, &rlimit_as);

        rlimit_as.rlim_cur = rlimit_as.rlim_max;

        if (rlimit_as.rlim_max != RLIM_INFINITY) {

            fprintf(stderr, "Warning: QEMU's maximum size of virtual"

                    " memory is not infinity.\n");

        }

        if (rlimit_as.rlim_max < MCACHE_MAX_SIZE + NON_MCACHE_MEMORY_SIZE) {

            mapcache->max_mcache_size = rlimit_as.rlim_max -

                NON_MCACHE_MEMORY_SIZE;

        } else {

            mapcache->max_mcache_size = MCACHE_MAX_SIZE;

        }

    }

    setrlimit(RLIMIT_AS, &rlimit_as);

    mapcache->nr_buckets =

        (((mapcache->max_mcache_size >> XC_PAGE_SHIFT) +

          (1UL << (MCACHE_BUCKET_SHIFT - XC_PAGE_SHIFT)) - 1) >>

         (MCACHE_BUCKET_SHIFT - XC_PAGE_SHIFT));

    size = mapcache->nr_buckets * sizeof (MapCacheEntry);

    size = (size + XC_PAGE_SIZE - 1) & ~(XC_PAGE_SIZE - 1);

    DPRINTF("%s, nr_buckets = %lx size %lu\n", __func__,

            mapcache->nr_buckets, size);

    mapcache->entry = g_malloc0(size);

}


static av_cold int libopenjpeg_encode_init(AVCodecContext *avctx)

{

    LibOpenJPEGContext *ctx = avctx->priv_data;

    int err = 0;

    opj_set_default_encoder_parameters(&ctx->enc_params);

#if HAVE_OPENJPEG_2_1_OPENJPEG_H

    switch (ctx->cinema_mode) {

    case OPJ_CINEMA2K_24:

        ctx->enc_params.rsiz = OPJ_PROFILE_CINEMA_2K;

        ctx->enc_params.max_cs_size = OPJ_CINEMA_24_CS;

        ctx->enc_params.max_comp_size = OPJ_CINEMA_24_COMP;

        break;

    case OPJ_CINEMA2K_48:

        ctx->enc_params.rsiz = OPJ_PROFILE_CINEMA_2K;

        ctx->enc_params.max_cs_size = OPJ_CINEMA_48_CS;

        ctx->enc_params.max_comp_size = OPJ_CINEMA_48_COMP;

        break;

    case OPJ_CINEMA4K_24:

        ctx->enc_params.rsiz = OPJ_PROFILE_CINEMA_4K;

        ctx->enc_params.max_cs_size = OPJ_CINEMA_24_CS;

        ctx->enc_params.max_comp_size = OPJ_CINEMA_24_COMP;

        break;

    }

    switch (ctx->profile) {

    case OPJ_CINEMA2K:

        if (ctx->enc_params.rsiz == OPJ_PROFILE_CINEMA_4K) {

            err = AVERROR(EINVAL);

            break;

        }

        ctx->enc_params.rsiz = OPJ_PROFILE_CINEMA_2K;

        break;

    case OPJ_CINEMA4K:

        if (ctx->enc_params.rsiz == OPJ_PROFILE_CINEMA_2K) {

            err = AVERROR(EINVAL);

            break;

        }

        ctx->enc_params.rsiz = OPJ_PROFILE_CINEMA_4K;

        break;

    }

    if (err) {

        av_log(avctx, AV_LOG_ERROR,

               "Invalid parameter pairing: cinema_mode and profile conflict.\n");

        goto fail;

    }

#else

    ctx->enc_params.cp_rsiz = ctx->profile;

    ctx->enc_params.cp_cinema = ctx->cinema_mode;

#endif

    if (!ctx->numresolution) {

        ctx->numresolution = 6;

        while (FFMIN(avctx->width, avctx->height) >> ctx->numresolution < 1)

            ctx->numresolution --;

    }

    ctx->enc_params.mode = !!avctx->global_quality;

    ctx->enc_params.prog_order = ctx->prog_order;

    ctx->enc_params.numresolution = ctx->numresolution;

    ctx->enc_params.cp_disto_alloc = ctx->disto_alloc;

    ctx->enc_params.cp_fixed_alloc = ctx->fixed_alloc;

    ctx->enc_params.cp_fixed_quality = ctx->fixed_quality;

    ctx->enc_params.tcp_numlayers = ctx->numlayers;

    ctx->enc_params.tcp_rates[0] = FFMAX(avctx->compression_level, 0) * 2;

    if (ctx->cinema_mode > 0) {

        cinema_parameters(&ctx->enc_params);

    }

#if OPENJPEG_MAJOR_VERSION == 1

    ctx->image = mj2_create_image(avctx, &ctx->enc_params);

    if (!ctx->image) {

        av_log(avctx, AV_LOG_ERROR, "Error creating the mj2 image\n");

        err = AVERROR(EINVAL);

        goto fail;

    }

#endif // OPENJPEG_MAJOR_VERSION == 1

    return 0;

fail:

#if OPENJPEG_MAJOR_VERSION == 1

    opj_image_destroy(ctx->image);

    ctx->image = NULL;

#endif // OPENJPEG_MAJOR_VERSION == 1

    return err;

}


static void init_filter_param(AVFilterContext *ctx, FilterParam *fp, const char *effect_type, int width)

{

    int z;

    const char *effect;

    effect = fp->amount == 0 ? "none" : fp->amount < 0 ? "blur" : "sharpen";

    av_log(ctx, AV_LOG_VERBOSE, "effect:%s type:%s msize_x:%d msize_y:%d amount:%0.2f\n",

           effect, effect_type, fp->msize_x, fp->msize_y, fp->amount / 65535.0);

    for (z = 0; z < 2 * fp->steps_y; z++)

        fp->sc[z] = av_malloc(sizeof(*(fp->sc[z])) * (width + 2 * fp->steps_x));

}


static inline void FUNC(idctRowCondDC_extrashift)(int16_t *row, int extra_shift)

#else

static inline void FUNC(idctRowCondDC)(int16_t *row, int extra_shift)

#endif

{

    int a0, a1, a2, a3, b0, b1, b2, b3;

#if HAVE_FAST_64BIT

#define ROW0_MASK (0xffffLL << 48 * HAVE_BIGENDIAN)

    if (((((uint64_t *)row)[0] & ~ROW0_MASK) | ((uint64_t *)row)[1]) == 0) {

        uint64_t temp;

        if (DC_SHIFT - extra_shift >= 0) {

            temp = (row[0] * (1 << (DC_SHIFT - extra_shift))) & 0xffff;

        } else {

            temp = ((row[0] + (1<<(extra_shift - DC_SHIFT-1))) >> (extra_shift - DC_SHIFT)) & 0xffff;

        }

        temp += temp * (1 << 16);

        temp += temp * ((uint64_t) 1 << 32);

        ((uint64_t *)row)[0] = temp;

        ((uint64_t *)row)[1] = temp;

        return;

    }

#else

    if (!(((uint32_t*)row)[1] |

          ((uint32_t*)row)[2] |

          ((uint32_t*)row)[3] |

          row[1])) {

        uint32_t temp;

        if (DC_SHIFT - extra_shift >= 0) {

            temp = (row[0] * (1 << (DC_SHIFT - extra_shift))) & 0xffff;

        } else {

            temp = ((row[0] + (1<<(extra_shift - DC_SHIFT-1))) >> (extra_shift - DC_SHIFT)) & 0xffff;

        }

        temp += temp * (1 << 16);

        ((uint32_t*)row)[0]=((uint32_t*)row)[1] =

            ((uint32_t*)row)[2]=((uint32_t*)row)[3] = temp;

        return;

    }

#endif

    a0 = (W4 * row[0]) + (1 << (ROW_SHIFT + extra_shift - 1));

    a1 = a0;

    a2 = a0;

    a3 = a0;

    a0 += W2 * row[2];

    a1 += W6 * row[2];

    a2 -= W6 * row[2];

    a3 -= W2 * row[2];

    b0 = MUL(W1, row[1]);

    MAC(b0, W3, row[3]);

    b1 = MUL(W3, row[1]);

    MAC(b1, -W7, row[3]);

    b2 = MUL(W5, row[1]);

    MAC(b2, -W1, row[3]);

    b3 = MUL(W7, row[1]);

    MAC(b3, -W5, row[3]);

    if (AV_RN64A(row + 4)) {

        a0 +=   W4*row[4] + W6*row[6];

        a1 += - W4*row[4] - W2*row[6];

        a2 += - W4*row[4] + W2*row[6];

        a3 +=   W4*row[4] - W6*row[6];

        MAC(b0,  W5, row[5]);

        MAC(b0,  W7, row[7]);

        MAC(b1, -W1, row[5]);

        MAC(b1, -W5, row[7]);

        MAC(b2,  W7, row[5]);

        MAC(b2,  W3, row[7]);

        MAC(b3,  W3, row[5]);

        MAC(b3, -W1, row[7]);

    }

    row[0] = (a0 + b0) >> (ROW_SHIFT + extra_shift);

    row[7] = (a0 - b0) >> (ROW_SHIFT + extra_shift);

    row[1] = (a1 + b1) >> (ROW_SHIFT + extra_shift);

    row[6] = (a1 - b1) >> (ROW_SHIFT + extra_shift);

    row[2] = (a2 + b2) >> (ROW_SHIFT + extra_shift);

    row[5] = (a2 - b2) >> (ROW_SHIFT + extra_shift);

    row[3] = (a3 + b3) >> (ROW_SHIFT + extra_shift);

    row[4] = (a3 - b3) >> (ROW_SHIFT + extra_shift);

}


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

{

    AVStream *st;

    MOVStreamContext *sc;

    unsigned int i, entries;

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

        return 0;

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

    sc = st->priv_data;

    avio_r8(pb); /* version */

    avio_rb24(pb); /* flags */

    entries = avio_rb32(pb);

    if (!entries)

        return 0;

    if (entries >= UINT_MAX/sizeof(int64_t))

        return AVERROR_INVALIDDATA;

    sc->chunk_offsets = av_malloc(entries * sizeof(int64_t));

    if (!sc->chunk_offsets)

        return AVERROR(ENOMEM);

    sc->chunk_count = entries;

    if      (atom.type == MKTAG('s','t','c','o'))

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

            sc->chunk_offsets[i] = avio_rb32(pb);

    else if (atom.type == MKTAG('c','o','6','4'))

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

            sc->chunk_offsets[i] = avio_rb64(pb);

    else

        return AVERROR_INVALIDDATA;

    return 0;

}


static inline void decode_subblock(DCTELEM *dst, int code, const int is_block2, GetBitContext *gb, VLC *vlc, int q)

{

    int coeffs[4];

    coeffs[0] = modulo_three_table[code][0];

    coeffs[1] = modulo_three_table[code][1];

    coeffs[2] = modulo_three_table[code][2];

    coeffs[3] = modulo_three_table[code][3];

    decode_coeff(dst  , coeffs[0], 3, gb, vlc, q);

    if(is_block2){

        decode_coeff(dst+8, coeffs[1], 2, gb, vlc, q);

        decode_coeff(dst+1, coeffs[2], 2, gb, vlc, q);

    }else{

        decode_coeff(dst+1, coeffs[1], 2, gb, vlc, q);

        decode_coeff(dst+8, coeffs[2], 2, gb, vlc, q);

    }

    decode_coeff(dst+9, coeffs[3], 2, gb, vlc, q);

}


static int coroutine_fn bdrv_aligned_pwritev(BlockDriverState *bs,

    BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,

    QEMUIOVector *qiov, int flags)

{

    BlockDriver *drv = bs->drv;

    bool waited;

    int ret;

    int64_t sector_num = offset >> BDRV_SECTOR_BITS;

    unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS;

    assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);

    assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);

    assert(!qiov || bytes == qiov->size);

    waited = wait_serialising_requests(req);

    assert(!waited || !req->serialising);

    assert(req->overlap_offset <= offset);

    assert(offset + bytes <= req->overlap_offset + req->overlap_bytes);

    ret = notifier_with_return_list_notify(&bs->before_write_notifiers, req);

    if (!ret && bs->detect_zeroes != BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF &&

        !(flags & BDRV_REQ_ZERO_WRITE) && drv->bdrv_co_write_zeroes &&

        qemu_iovec_is_zero(qiov)) {

        flags |= BDRV_REQ_ZERO_WRITE;

        if (bs->detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP) {

            flags |= BDRV_REQ_MAY_UNMAP;

        }

    }

    if (ret < 0) {

        /* Do nothing, write notifier decided to fail this request */

    } else if (flags & BDRV_REQ_ZERO_WRITE) {

        BLKDBG_EVENT(bs, BLKDBG_PWRITEV_ZERO);

        ret = bdrv_co_do_write_zeroes(bs, sector_num, nb_sectors, flags);

    } else {

        BLKDBG_EVENT(bs, BLKDBG_PWRITEV);

        ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);

    }

    BLKDBG_EVENT(bs, BLKDBG_PWRITEV_DONE);

    if (ret == 0 && !bs->enable_write_cache) {

        ret = bdrv_co_flush(bs);

    }

    bdrv_set_dirty(bs, sector_num, nb_sectors);

    if (bs->stats.wr_highest_sector < sector_num + nb_sectors - 1) {

        bs->stats.wr_highest_sector = sector_num + nb_sectors - 1;

    }

    if (bs->growable && ret >= 0) {

        bs->total_sectors = MAX(bs->total_sectors, sector_num + nb_sectors);

    }

    return ret;

}


static int process_metadata(AVFormatContext *s, uint8_t *name, uint16_t name_len,

                            uint16_t val_len, uint16_t type, AVDictionary **met)

{

    int ret;

    ff_asf_guid guid;

    if (val_len) {

        switch (type) {

        case ASF_UNICODE:

            asf_read_value(s, name, name_len, val_len, type, met);

            break;

        case ASF_BYTE_ARRAY:

            if (!strcmp(name, "WM/Picture")) // handle cover art

                asf_read_picture(s, val_len);

            else if (!strcmp(name, "ID3")) // handle ID3 tag

                get_id3_tag(s, val_len);

            else

                asf_read_value(s, name, name_len, val_len, type, met);

            break;

        case ASF_GUID:

            ff_get_guid(s->pb, &guid);

            break;

        default:

            if ((ret = asf_read_generic_value(s, name, name_len, type, met)) < 0)

                return ret;

            break;

        }

    }

    av_freep(&name);

    return 0;

}


static V9fsSynthNode *v9fs_add_dir_node(V9fsSynthNode *parent, int mode,

                                        const char *name,

                                        V9fsSynthNodeAttr *attr, int inode)

{

    V9fsSynthNode *node;

    /* Add directory type and remove write bits */

    mode = ((mode & 0777) | S_IFDIR) & ~(S_IWUSR | S_IWGRP | S_IWOTH);

    node = g_malloc0(sizeof(V9fsSynthNode));

    if (attr) {

        /* We are adding .. or . entries */

        node->attr = attr;

        node->attr->nlink++;

    } else {

        node->attr = &node->actual_attr;

        node->attr->inode = inode;

        node->attr->nlink = 1;

        /* We don't allow write to directories */

        node->attr->mode   = mode;

        node->attr->write = NULL;

        node->attr->read  = NULL;

    }

    node->private = node;

    strncpy(node->name, name, sizeof(node->name));

    QLIST_INSERT_HEAD_RCU(&parent->child, node, sibling);

    return node;

}


static void add_bytes_l2_c(uint8_t *dst, uint8_t *src1, uint8_t *src2, int w)

{

    long i;

    for (i = 0; i <= w - sizeof(long); i += sizeof(long)) {

        long a = *(long *)(src1 + i);

        long b = *(long *)(src2 + i);

        *(long *)(dst + i) = ((a & pb_7f) + (b & pb_7f)) ^ ((a ^ b) & pb_80);

    }

    for (; i < w; i++)

        dst[i] = src1[i] + src2[i];

}


static int scsi_disk_emulate_command(SCSIDiskReq *r)

{

    SCSIRequest *req = &r->req;

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

    uint64_t nb_sectors;

    uint8_t *outbuf;

    int buflen = 0;

    if (!r->iov.iov_base) {

        /*

         * FIXME: we shouldn't return anything bigger than 4k, but the code

         * requires the buffer to be as big as req->cmd.xfer in several

         * places.  So, do not allow CDBs with a very large ALLOCATION

         * LENGTH.  The real fix would be to modify scsi_read_data and

         * dma_buf_read, so that they return data beyond the buflen

         * as all zeros.

         */

        if (req->cmd.xfer > 65536) {

            goto illegal_request;

        }

        r->buflen = MAX(4096, req->cmd.xfer);

        r->iov.iov_base = qemu_blockalign(s->qdev.conf.bs, r->buflen);

    }

    outbuf = r->iov.iov_base;

    switch (req->cmd.buf[0]) {

    case TEST_UNIT_READY:

        assert(!s->tray_open && bdrv_is_inserted(s->qdev.conf.bs));

        break;

    case INQUIRY:

        buflen = scsi_disk_emulate_inquiry(req, outbuf);

        if (buflen < 0) {

            goto illegal_request;

        }

        break;

    case MODE_SENSE:

    case MODE_SENSE_10:

        buflen = scsi_disk_emulate_mode_sense(r, outbuf);

        if (buflen < 0) {

            goto illegal_request;

        }

        break;

    case READ_TOC:

        buflen = scsi_disk_emulate_read_toc(req, outbuf);

        if (buflen < 0) {

            goto illegal_request;

        }

        break;

    case RESERVE:

        if (req->cmd.buf[1] & 1) {

            goto illegal_request;

        }

        break;

    case RESERVE_10:

        if (req->cmd.buf[1] & 3) {

            goto illegal_request;

        }

        break;

    case RELEASE:

        if (req->cmd.buf[1] & 1) {

            goto illegal_request;

        }

        break;

    case RELEASE_10:

        if (req->cmd.buf[1] & 3) {

            goto illegal_request;

        }

        break;

    case START_STOP:

        if (scsi_disk_emulate_start_stop(r) < 0) {

            return -1;

        }

        break;

    case ALLOW_MEDIUM_REMOVAL:

        s->tray_locked = req->cmd.buf[4] & 1;

        bdrv_lock_medium(s->qdev.conf.bs, req->cmd.buf[4] & 1);

        break;

    case READ_CAPACITY_10:

        /* The normal LEN field for this command is zero.  */

        memset(outbuf, 0, 8);

        bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors);

        if (!nb_sectors) {

            scsi_check_condition(r, SENSE_CODE(LUN_NOT_READY));

            return -1;

        }

        if ((req->cmd.buf[8] & 1) == 0 && req->cmd.lba) {

            goto illegal_request;

        }

        nb_sectors /= s->qdev.blocksize / 512;

        /* Returned value is the address of the last sector.  */

        nb_sectors--;

        /* Remember the new size for read/write sanity checking. */

        s->qdev.max_lba = nb_sectors;

        /* Clip to 2TB, instead of returning capacity modulo 2TB. */

        if (nb_sectors > UINT32_MAX) {

            nb_sectors = UINT32_MAX;

        }

        outbuf[0] = (nb_sectors >> 24) & 0xff;

        outbuf[1] = (nb_sectors >> 16) & 0xff;

        outbuf[2] = (nb_sectors >> 8) & 0xff;

        outbuf[3] = nb_sectors & 0xff;

        outbuf[4] = 0;

        outbuf[5] = 0;

        outbuf[6] = s->qdev.blocksize >> 8;

        outbuf[7] = 0;

        buflen = 8;

        break;

    case REQUEST_SENSE:

        /* Just return "NO SENSE".  */

        buflen = scsi_build_sense(NULL, 0, outbuf, r->buflen,

                                  (req->cmd.buf[1] & 1) == 0);

        break;

    case MECHANISM_STATUS:

        buflen = scsi_emulate_mechanism_status(s, outbuf);

        if (buflen < 0) {

            goto illegal_request;

        }

        break;

    case GET_CONFIGURATION:

        buflen = scsi_get_configuration(s, outbuf);

        if (buflen < 0) {

            goto illegal_request;

        }

        break;

    case GET_EVENT_STATUS_NOTIFICATION:

        buflen = scsi_get_event_status_notification(s, r, outbuf);

        if (buflen < 0) {

            goto illegal_request;

        }

        break;

    case READ_DVD_STRUCTURE:

        buflen = scsi_read_dvd_structure(s, r, outbuf);

        if (buflen < 0) {

            goto illegal_request;

        }

        break;

    case SERVICE_ACTION_IN_16:

        /* Service Action In subcommands. */

        if ((req->cmd.buf[1] & 31) == SAI_READ_CAPACITY_16) {

            DPRINTF("SAI READ CAPACITY(16)\n");

            memset(outbuf, 0, req->cmd.xfer);

            bdrv_get_geometry(s->qdev.conf.bs, &nb_sectors);

            if (!nb_sectors) {

                scsi_check_condition(r, SENSE_CODE(LUN_NOT_READY));

                return -1;

            }

            if ((req->cmd.buf[14] & 1) == 0 && req->cmd.lba) {

                goto illegal_request;

            }

            nb_sectors /= s->qdev.blocksize / 512;

            /* Returned value is the address of the last sector.  */

            nb_sectors--;

            /* Remember the new size for read/write sanity checking. */

            s->qdev.max_lba = nb_sectors;

            outbuf[0] = (nb_sectors >> 56) & 0xff;

            outbuf[1] = (nb_sectors >> 48) & 0xff;

            outbuf[2] = (nb_sectors >> 40) & 0xff;

            outbuf[3] = (nb_sectors >> 32) & 0xff;

            outbuf[4] = (nb_sectors >> 24) & 0xff;

            outbuf[5] = (nb_sectors >> 16) & 0xff;

            outbuf[6] = (nb_sectors >> 8) & 0xff;

            outbuf[7] = nb_sectors & 0xff;

            outbuf[8] = 0;

            outbuf[9] = 0;

            outbuf[10] = s->qdev.blocksize >> 8;

            outbuf[11] = 0;

            outbuf[12] = 0;

            outbuf[13] = get_physical_block_exp(&s->qdev.conf);

            /* set TPE bit if the format supports discard */

            if (s->qdev.conf.discard_granularity) {

                outbuf[14] = 0x80;

            }

            /* Protection, exponent and lowest lba field left blank. */

            buflen = req->cmd.xfer;

            break;

        }

        DPRINTF("Unsupported Service Action In\n");

        goto illegal_request;

    case VERIFY_10:

        break;

    default:

        scsi_check_condition(r, SENSE_CODE(INVALID_OPCODE));

        return -1;

    }

    buflen = MIN(buflen, req->cmd.xfer);

    return buflen;

illegal_request:

    if (r->req.status == -1) {

        scsi_check_condition(r, SENSE_CODE(INVALID_FIELD));

    }

    return -1;

}


static void bdrv_delete(BlockDriverState *bs)

{

    assert(!bs->dev);

    assert(!bs->job);

    assert(bdrv_op_blocker_is_empty(bs));

    assert(!bs->refcnt);

    assert(QLIST_EMPTY(&bs->dirty_bitmaps));

    bdrv_close(bs);

    /* remove from list, if necessary */

    bdrv_make_anon(bs);

    g_free(bs);

}