static bool bdrv_exceed_io_limits(BlockDriverState *bs, int nb_sectors,

                           bool is_write, int64_t *wait)

{

    int64_t  now, max_wait;

    uint64_t bps_wait = 0, iops_wait = 0;

    double   elapsed_time;

    int      bps_ret, iops_ret;

    now = qemu_get_clock_ns(vm_clock);

    if ((bs->slice_start < now)

        && (bs->slice_end > now)) {

        bs->slice_end = now + BLOCK_IO_SLICE_TIME;

    } else {

        bs->slice_start = now;

        bs->slice_end   = now + BLOCK_IO_SLICE_TIME;

        memset(&bs->slice_submitted, 0, sizeof(bs->slice_submitted));

    }

    elapsed_time  = now - bs->slice_start;

    elapsed_time  /= (NANOSECONDS_PER_SECOND);

    bps_ret  = bdrv_exceed_bps_limits(bs, nb_sectors,

                                      is_write, elapsed_time, &bps_wait);

    iops_ret = bdrv_exceed_iops_limits(bs, is_write,

                                      elapsed_time, &iops_wait);

    if (bps_ret || iops_ret) {

        max_wait = bps_wait > iops_wait ? bps_wait : iops_wait;

        if (wait) {

            *wait = max_wait;

        }

        now = qemu_get_clock_ns(vm_clock);

        if (bs->slice_end < now + max_wait) {

            bs->slice_end = now + max_wait;

        }

        return true;

    }

    if (wait) {

        *wait = 0;

    }

    bs->slice_submitted.bytes[is_write] += (int64_t)nb_sectors *

                                           BDRV_SECTOR_SIZE;

    bs->slice_submitted.ios[is_write]++;

    return false;

}


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

{

    ISADevice *s = opaque;

    if (level) {

        rtc_set_memory(s, 0xF, 0xFE);

    }

}


static struct bt_device_s *bt_device_add(const char *opt)

{

    struct bt_scatternet_s *vlan;

    int vlan_id = 0;

    char *endp = strstr(opt, ",vlan=");

    int len = (endp ? endp - opt : strlen(opt)) + 1;

    char devname[10];

    pstrcpy(devname, MIN(sizeof(devname), len), opt);

    if (endp) {

        vlan_id = strtol(endp + 6, &endp, 0);

        if (*endp) {

            fprintf(stderr, "qemu: unrecognised bluetooth vlan Id\n");

            return 0;

        }

    }

    vlan = qemu_find_bt_vlan(vlan_id);

    if (!vlan->slave)

        fprintf(stderr, "qemu: warning: adding a slave device to "

                        "an empty scatternet %i\n", vlan_id);

    if (!strcmp(devname, "keyboard"))

        return bt_keyboard_init(vlan);

    fprintf(stderr, "qemu: unsupported bluetooth device `%s'\n", devname);

    return 0;

}


static void v9fs_fsync(void *opaque)

{

    int err;

    int32_t fid;

    int datasync;

    size_t offset = 7;

    V9fsFidState *fidp;

    V9fsPDU *pdu = opaque;

    V9fsState *s = pdu->s;

    pdu_unmarshal(pdu, offset, "dd", &fid, &datasync);

    trace_v9fs_fsync(pdu->tag, pdu->id, fid, datasync);

    fidp = get_fid(pdu, fid);

    if (fidp == NULL) {

        err = -ENOENT;

        goto out_nofid;

    }

    err = v9fs_co_fsync(pdu, fidp, datasync);

    if (!err) {

        err = offset;

    }

    put_fid(pdu, fidp);

out_nofid:

    complete_pdu(s, pdu, err);

}


matroska_read_packet (AVFormatContext *s,

                      AVPacket        *pkt)

{

    MatroskaDemuxContext *matroska = s->priv_data;

    int res = 0;

    uint32_t id;

    /* Read stream until we have a packet queued. */

    while (matroska_deliver_packet(matroska, pkt)) {

        /* Have we already reached the end? */

        if (matroska->done)

            return AVERROR_IO;

        while (res == 0) {

            if (!(id = ebml_peek_id(matroska, &matroska->level_up))) {

                return AVERROR_IO;

            } else if (matroska->level_up) {

                matroska->level_up--;

                break;

            }

            switch (id) {

                case MATROSKA_ID_CLUSTER:

                    if ((res = ebml_read_master(matroska, &id)) < 0)

                        break;

                    if ((res = matroska_parse_cluster(matroska)) == 0)

                        res = 1; /* Parsed one cluster, let's get out. */

                    break;

                default:

                case EBML_ID_VOID:

                    res = ebml_read_skip(matroska);

                    break;

            }

            if (matroska->level_up) {

                matroska->level_up--;

                break;

            }

        }

        if (res == -1)

            matroska->done = 1;

    }

    return 0;

}


static void pl061_write(void *opaque, hwaddr offset,

                        uint64_t value, unsigned size)

{

    PL061State *s = (PL061State *)opaque;

    uint8_t mask;

    if (offset < 0x400) {

        mask = (offset >> 2) & s->dir;

        s->data = (s->data & ~mask) | (value & mask);

        pl061_update(s);

        return;

    }

    switch (offset) {

    case 0x400: /* Direction */

        s->dir = value & 0xff;

        break;

    case 0x404: /* Interrupt sense */

        s->isense = value & 0xff;

        break;

    case 0x408: /* Interrupt both edges */

        s->ibe = value & 0xff;

        break;

    case 0x40c: /* Interrupt event */

        s->iev = value & 0xff;

        break;

    case 0x410: /* Interrupt mask */

        s->im = value & 0xff;

        break;

    case 0x41c: /* Interrupt clear */

        s->istate &= ~value;

        break;

    case 0x420: /* Alternate function select */

        mask = s->cr;

        s->afsel = (s->afsel & ~mask) | (value & mask);

        break;

    case 0x500: /* 2mA drive */

        s->dr2r = value & 0xff;

        break;

    case 0x504: /* 4mA drive */

        s->dr4r = value & 0xff;

        break;

    case 0x508: /* 8mA drive */

        s->dr8r = value & 0xff;

        break;

    case 0x50c: /* Open drain */

        s->odr = value & 0xff;

        break;

    case 0x510: /* Pull-up */

        s->pur = value & 0xff;

        break;

    case 0x514: /* Pull-down */

        s->pdr = value & 0xff;

        break;

    case 0x518: /* Slew rate control */

        s->slr = value & 0xff;

        break;

    case 0x51c: /* Digital enable */

        s->den = value & 0xff;

        break;

    case 0x520: /* Lock */

        s->locked = (value != 0xacce551);

        break;

    case 0x524: /* Commit */

        if (!s->locked)

            s->cr = value & 0xff;

        break;

    case 0x528:

        s->amsel = value & 0xff;

        break;

    default:

        qemu_log_mask(LOG_GUEST_ERROR,

                      "pl061_write: Bad offset %x\n", (int)offset);

    }

    pl061_update(s);

}


Aml *aml_or(Aml *arg1, Aml *arg2)

{

    Aml *var = aml_opcode(0x7D /* OrOp */);

    aml_append(var, arg1);

    aml_append(var, arg2);

    build_append_byte(var->buf, 0x00 /* NullNameOp */);

    return var;

}


static void pxa2xx_descriptor_load(PXA2xxLCDState *s)

{

    PXAFrameDescriptor desc;

    target_phys_addr_t descptr;

    int i;

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

        s->dma_ch[i].source = 0;

        if (!s->dma_ch[i].up)

            continue;

        if (s->dma_ch[i].branch & FBR_BRA) {

            descptr = s->dma_ch[i].branch & FBR_SRCADDR;

            if (s->dma_ch[i].branch & FBR_BINT)

                pxa2xx_dma_bs_set(s, i);

            s->dma_ch[i].branch &= ~FBR_BRA;

        } else

            descptr = s->dma_ch[i].descriptor;

        if (!(descptr >= PXA2XX_SDRAM_BASE && descptr +

                    sizeof(desc) <= PXA2XX_SDRAM_BASE + ram_size))

            continue;

        cpu_physical_memory_read(descptr, (void *)&desc, sizeof(desc));

        s->dma_ch[i].descriptor = tswap32(desc.fdaddr);

        s->dma_ch[i].source = tswap32(desc.fsaddr);

        s->dma_ch[i].id = tswap32(desc.fidr);

        s->dma_ch[i].command = tswap32(desc.ldcmd);

    }

}


static int ram_save_page(QEMUFile *f, PageSearchStatus *pss,

                         bool last_stage, uint64_t *bytes_transferred)

{

    int pages = -1;

    uint64_t bytes_xmit;

    ram_addr_t current_addr;

    uint8_t *p;

    int ret;

    bool send_async = true;

    RAMBlock *block = pss->block;

    ram_addr_t offset = pss->offset;

    p = block->host + offset;

    /* In doubt sent page as normal */

    bytes_xmit = 0;

    ret = ram_control_save_page(f, block->offset,

                           offset, TARGET_PAGE_SIZE, &bytes_xmit);

    if (bytes_xmit) {

        *bytes_transferred += bytes_xmit;

        pages = 1;

    }

    XBZRLE_cache_lock();

    current_addr = block->offset + offset;

    if (block == last_sent_block) {

        offset |= RAM_SAVE_FLAG_CONTINUE;

    }

    if (ret != RAM_SAVE_CONTROL_NOT_SUPP) {

        if (ret != RAM_SAVE_CONTROL_DELAYED) {

            if (bytes_xmit > 0) {

                acct_info.norm_pages++;

            } else if (bytes_xmit == 0) {

                acct_info.dup_pages++;

            }

        }

    } else {

        pages = save_zero_page(f, block, offset, p, bytes_transferred);

        if (pages > 0) {

            /* Must let xbzrle know, otherwise a previous (now 0'd) cached

             * page would be stale

             */

            xbzrle_cache_zero_page(current_addr);

        } else if (!ram_bulk_stage && migrate_use_xbzrle()) {

            pages = save_xbzrle_page(f, &p, current_addr, block,

                                     offset, last_stage, bytes_transferred);

            if (!last_stage) {

                /* Can't send this cached data async, since the cache page

                 * might get updated before it gets to the wire

                 */

                send_async = false;

            }

        }

    }

    /* XBZRLE overflow or normal page */

    if (pages == -1) {

        *bytes_transferred += save_page_header(f, block,

                                               offset | RAM_SAVE_FLAG_PAGE);

        if (send_async) {

            qemu_put_buffer_async(f, p, TARGET_PAGE_SIZE);

        } else {

            qemu_put_buffer(f, p, TARGET_PAGE_SIZE);

        }

        *bytes_transferred += TARGET_PAGE_SIZE;

        pages = 1;

        acct_info.norm_pages++;

    }

    XBZRLE_cache_unlock();

    return pages;

}


static int64_t coroutine_fn raw_co_get_block_status(BlockDriverState *bs,

                                                    int64_t sector_num,

                                                    int nb_sectors, int *pnum)

{

    off_t start, data = 0, hole = 0;

    int64_t total_size;

    int ret;

    ret = fd_open(bs);

    if (ret < 0) {

        return ret;

    }

    start = sector_num * BDRV_SECTOR_SIZE;

    total_size = bdrv_getlength(bs);

    if (total_size < 0) {

        return total_size;

    } else if (start >= total_size) {

        *pnum = 0;

        return 0;

    } else if (start + nb_sectors * BDRV_SECTOR_SIZE > total_size) {

        nb_sectors = DIV_ROUND_UP(total_size - start, BDRV_SECTOR_SIZE);

    }

    ret = find_allocation(bs, start, &data, &hole);

    if (ret == -ENXIO) {

        /* Trailing hole */

        *pnum = nb_sectors;

        ret = BDRV_BLOCK_ZERO;

    } else if (ret < 0) {

        /* No info available, so pretend there are no holes */

        *pnum = nb_sectors;

        ret = BDRV_BLOCK_DATA;

    } else if (data == start) {

        /* On a data extent, compute sectors to the end of the extent,

         * possibly including a partial sector at EOF. */

        *pnum = MIN(nb_sectors, DIV_ROUND_UP(hole - start, BDRV_SECTOR_SIZE));

        ret = BDRV_BLOCK_DATA;

    } else {

        /* On a hole, compute sectors to the beginning of the next extent.  */

        assert(hole == start);

        *pnum = MIN(nb_sectors, (data - start) / BDRV_SECTOR_SIZE);

        ret = BDRV_BLOCK_ZERO;

    }

    return ret | BDRV_BLOCK_OFFSET_VALID | start;

}


static int pte_check_hash32(struct mmu_ctx_hash32 *ctx, target_ulong pte0,

                            target_ulong pte1, int h, int rwx)

{

    target_ulong mmask;

    int access, ret, pp;

    ret = -1;

    /* Check validity and table match */

    if ((pte0 & HPTE32_V_VALID) && (h == !!(pte0 & HPTE32_V_SECONDARY))) {

        /* Check vsid & api */

        mmask = PTE_CHECK_MASK;

        pp = pte1 & HPTE32_R_PP;

        if (HPTE32_V_COMPARE(pte0, ctx->ptem)) {

            if (ctx->raddr != (hwaddr)-1ULL) {

                /* all matches should have equal RPN, WIMG & PP */

                if ((ctx->raddr & mmask) != (pte1 & mmask)) {

                    qemu_log("Bad RPN/WIMG/PP\n");

                    return -3;

                }

            }

            /* Compute access rights */

            access = ppc_hash32_pp_check(ctx->key, pp, ctx->nx);

            /* Keep the matching PTE informations */

            ctx->raddr = pte1;

            ctx->prot = access;

            ret = ppc_hash32_check_prot(ctx->prot, rwx);

            if (ret == 0) {

                /* Access granted */

                LOG_MMU("PTE access granted !\n");

            } else {

                /* Access right violation */

                LOG_MMU("PTE access rejected\n");

            }

        }

    }

    return ret;

}


static void vde_to_qemu(void *opaque)

{

    VDEState *s = opaque;

    uint8_t buf[4096];

    int size;

    size = vde_recv(s->vde, (char *)buf, sizeof(buf), 0);

    if (size > 0) {

        qemu_send_packet(&s->nc, buf, size);

    }

}


static inline void gen_op_movo(int d_offset, int s_offset)

{

    tcg_gen_ld_i64(cpu_tmp1_i64, cpu_env, s_offset);

    tcg_gen_st_i64(cpu_tmp1_i64, cpu_env, d_offset);

    tcg_gen_ld_i64(cpu_tmp1_i64, cpu_env, s_offset + 8);

    tcg_gen_st_i64(cpu_tmp1_i64, cpu_env, d_offset + 8);

}


static av_cold int libopenjpeg_encode_close(AVCodecContext *avctx)

{

    LibOpenJPEGContext *ctx = avctx->priv_data;

    opj_destroy_compress(ctx->compress);

    opj_image_destroy(ctx->image);

    av_freep(&avctx->coded_frame);

    return 0;

}


void ff_sws_init_swScale_altivec(SwsContext *c)

{

    enum PixelFormat dstFormat = c->dstFormat;

    if (!(av_get_cpu_flags() & AV_CPU_FLAG_ALTIVEC))

        return;

    c->hScale       = hScale_altivec_real;

    if (!is16BPS(dstFormat) && !is9_OR_10BPS(dstFormat)) {

        c->yuv2yuvX     = yuv2yuvX_altivec_real;

    }

    /* The following list of supported dstFormat values should

     * match what's found in the body of ff_yuv2packedX_altivec() */

    if (!(c->flags & (SWS_BITEXACT | SWS_FULL_CHR_H_INT)) && !c->alpPixBuf &&

        (c->dstFormat==PIX_FMT_ABGR  || c->dstFormat==PIX_FMT_BGRA  ||

         c->dstFormat==PIX_FMT_BGR24 || c->dstFormat==PIX_FMT_RGB24 ||

         c->dstFormat==PIX_FMT_RGBA  || c->dstFormat==PIX_FMT_ARGB)) {

            c->yuv2packedX  = ff_yuv2packedX_altivec;

        }

}


OP(zerof64)

{

    set_opf64(PARAM1, 0);

    FORCE_RET();

}


static void ide_sector_write_cb(void *opaque, int ret)

{

    IDEState *s = opaque;

    int n;

    if (ret == -ECANCELED) {

        return;

    }

    block_acct_done(bdrv_get_stats(s->bs), &s->acct);

    s->pio_aiocb = NULL;

    s->status &= ~BUSY_STAT;

    if (ret != 0) {

        if (ide_handle_rw_error(s, -ret, IDE_RETRY_PIO)) {

            return;

        }

    }

    n = s->nsector;

    if (n > s->req_nb_sectors) {

        n = s->req_nb_sectors;

    }

    s->nsector -= n;

    if (s->nsector == 0) {

        /* no more sectors to write */

        ide_transfer_stop(s);

    } else {

        int n1 = s->nsector;

        if (n1 > s->req_nb_sectors) {

            n1 = s->req_nb_sectors;

        }

        ide_transfer_start(s, s->io_buffer, n1 * BDRV_SECTOR_SIZE,

                           ide_sector_write);

    }

    ide_set_sector(s, ide_get_sector(s) + n);

    if (win2k_install_hack && ((++s->irq_count % 16) == 0)) {

        /* It seems there is a bug in the Windows 2000 installer HDD

           IDE driver which fills the disk with empty logs when the

           IDE write IRQ comes too early. This hack tries to correct

           that at the expense of slower write performances. Use this

           option _only_ to install Windows 2000. You must disable it

           for normal use. */

        timer_mod(s->sector_write_timer,

                       qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + (get_ticks_per_sec() / 1000));

    } else {

        ide_set_irq(s->bus);

    }

}


void nvdimm_build_acpi(GArray *table_offsets, GArray *table_data,

                       BIOSLinker *linker, AcpiNVDIMMState *state,

                       uint32_t ram_slots)

{

    nvdimm_build_nfit(state, table_offsets, table_data, linker);

    /*

     * NVDIMM device is allowed to be plugged only if there is available

     * slot.

     */

    if (ram_slots) {

        nvdimm_build_ssdt(table_offsets, table_data, linker, state->dsm_mem,

                          ram_slots);

    }

}


bdrv_co_rw_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos,

                   bool is_read)

{

    BlockDriver *drv = bs->drv;

    if (!drv) {

        return -ENOMEDIUM;

    } else if (drv->bdrv_load_vmstate) {

        return is_read ? drv->bdrv_load_vmstate(bs, qiov, pos)

                       : drv->bdrv_save_vmstate(bs, qiov, pos);

    } else if (bs->file) {

        return bdrv_co_rw_vmstate(bs->file->bs, qiov, pos, is_read);

    }

    return -ENOTSUP;

}


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

                            const char *name, int flags,

                            FsCred *credp, V9fsFidOpenState *fs)

{

    errno = ENOSYS;

    return -1;

}


static gboolean io_watch_poll_prepare(GSource *source, gint *timeout_)

{

    IOWatchPoll *iwp = io_watch_poll_from_source(source);

    bool now_active = iwp->fd_can_read(iwp->opaque) > 0;

    bool was_active = g_source_get_context(iwp->src) != NULL;

    if (was_active == now_active) {

        return FALSE;

    }

    if (now_active) {

        g_source_attach(iwp->src, NULL);

    } else {

        g_source_remove(g_source_get_id(iwp->src));

    }

    return FALSE;

}


static void uart_write(void *opaque, target_phys_addr_t addr, uint64_t value,

                       unsigned size)

{

    MilkymistUartState *s = opaque;

    unsigned char ch = value;

    trace_milkymist_uart_memory_write(addr, value);

    addr >>= 2;

    switch (addr) {

    case R_RXTX:

        if (s->chr) {

            qemu_chr_fe_write(s->chr, &ch, 1);

        }

        s->regs[R_STAT] |= STAT_TX_EVT;

        break;

    case R_DIV:

    case R_CTRL:

    case R_DBG:

        s->regs[addr] = value;

        break;

    case R_STAT:

        /* write one to clear bits */

        s->regs[addr] &= ~(value & (STAT_RX_EVT | STAT_TX_EVT));

        break;

    default:

        error_report("milkymist_uart: write access to unknown register 0x"

                TARGET_FMT_plx, addr << 2);

        break;

    }

    uart_update_irq(s);

}


static void test_visitor_in_null(TestInputVisitorData *data,

                                 const void *unused)

{

    Visitor *v;

    Error *err = NULL;

    char *tmp;

    /*

     * FIXME: Since QAPI doesn't know the 'null' type yet, we can't

     * test visit_type_null() by reading into a QAPI struct then

     * checking that it was populated correctly.  The best we can do

     * for now is ensure that we consumed null from the input, proven

     * by the fact that we can't re-read the key; and that we detect

     * when input is not null.

     */

    v = visitor_input_test_init(data, "{ 'a': null, 'b': '' }");

    visit_start_struct(v, NULL, NULL, 0, &error_abort);

    visit_type_null(v, "a", &error_abort);

    visit_type_str(v, "a", &tmp, &err);

    g_assert(!tmp);

    error_free_or_abort(&err);

    visit_type_null(v, "b", &err);

    error_free_or_abort(&err);

    visit_check_struct(v, &error_abort);

    visit_end_struct(v, NULL);

}


static int slirp_smb(SlirpState* s, const char *exported_dir,

                     struct in_addr vserver_addr)

{

    static int instance;

    char smb_conf[128];

    char smb_cmdline[128];

    FILE *f;

    snprintf(s->smb_dir, sizeof(s->smb_dir), "/tmp/qemu-smb.%ld-%d",

             (long)getpid(), instance++);

    if (mkdir(s->smb_dir, 0700) < 0) {

        error_report("could not create samba server dir '%s'", s->smb_dir);

        return -1;

    }

    snprintf(smb_conf, sizeof(smb_conf), "%s/%s", s->smb_dir, "smb.conf");

    f = fopen(smb_conf, "w");

    if (!f) {

        slirp_smb_cleanup(s);

        error_report("could not create samba server configuration file '%s'",

                     smb_conf);

        return -1;

    }

    fprintf(f,

            "[global]\n"

            "private dir=%s\n"

            "smb ports=0\n"

            "socket address=127.0.0.1\n"

            "pid directory=%s\n"

            "lock directory=%s\n"

            "log file=%s/log.smbd\n"

            "smb passwd file=%s/smbpasswd\n"

            "security = share\n"

            "[qemu]\n"

            "path=%s\n"

            "read only=no\n"

            "guest ok=yes\n",

            s->smb_dir,

            s->smb_dir,

            s->smb_dir,

            s->smb_dir,

            s->smb_dir,

            exported_dir

            );

    fclose(f);

    snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",

             SMBD_COMMAND, smb_conf);

    if (slirp_add_exec(s->slirp, 0, smb_cmdline, &vserver_addr, 139) < 0) {

        slirp_smb_cleanup(s);

        error_report("conflicting/invalid smbserver address");

        return -1;

    }

    return 0;

}


int kvm_irqchip_add_msi_route(KVMState *s, MSIMessage msg)

{

    struct kvm_irq_routing_entry kroute;

    int virq;

    if (!kvm_gsi_routing_enabled()) {

        return -ENOSYS;

    }

    virq = kvm_irqchip_get_virq(s);

    if (virq < 0) {

        return virq;

    }

    kroute.gsi = virq;

    kroute.type = KVM_IRQ_ROUTING_MSI;

    kroute.flags = 0;

    kroute.u.msi.address_lo = (uint32_t)msg.address;

    kroute.u.msi.address_hi = msg.address >> 32;

    kroute.u.msi.data = msg.data;

    kvm_add_routing_entry(s, &kroute);

    return virq;

}


static int32_t scsi_send_command(SCSIDevice *d, uint32_t tag,

                                 uint8_t *buf, int lun)

{

    SCSIDiskState *s = DO_UPCAST(SCSIDiskState, qdev, d);

    uint64_t nb_sectors;

    uint64_t lba;

    uint32_t len;

    int cmdlen;

    int is_write;

    uint8_t command;

    uint8_t *outbuf;

    SCSIRequest *r;

    command = buf[0];

    r = scsi_find_request(s, tag);

    if (r) {

        BADF("Tag 0x%x already in use\n", tag);

        scsi_cancel_io(d, tag);

    }

    /* ??? Tags are not unique for different luns.  We only implement a

       single lun, so this should not matter.  */

    r = scsi_new_request(d, tag);

    outbuf = (uint8_t *)r->iov.iov_base;

    is_write = 0;

    DPRINTF("Command: lun=%d tag=0x%x data=0x%02x", lun, tag, buf[0]);

    switch (command >> 5) {

    case 0:

        lba = (uint64_t) buf[3] | ((uint64_t) buf[2] << 8) |

              (((uint64_t) buf[1] & 0x1f) << 16);

        len = buf[4];

        cmdlen = 6;

        break;

    case 1:

    case 2:

        lba = (uint64_t) buf[5] | ((uint64_t) buf[4] << 8) |

              ((uint64_t) buf[3] << 16) | ((uint64_t) buf[2] << 24);

        len = buf[8] | (buf[7] << 8);

        cmdlen = 10;

        break;

    case 4:

        lba = (uint64_t) buf[9] | ((uint64_t) buf[8] << 8) |

              ((uint64_t) buf[7] << 16) | ((uint64_t) buf[6] << 24) |

              ((uint64_t) buf[5] << 32) | ((uint64_t) buf[4] << 40) |

              ((uint64_t) buf[3] << 48) | ((uint64_t) buf[2] << 56);

        len = buf[13] | (buf[12] << 8) | (buf[11] << 16) | (buf[10] << 24);

        cmdlen = 16;

        break;

    case 5:

        lba = (uint64_t) buf[5] | ((uint64_t) buf[4] << 8) |

              ((uint64_t) buf[3] << 16) | ((uint64_t) buf[2] << 24);

        len = buf[9] | (buf[8] << 8) | (buf[7] << 16) | (buf[6] << 24);

        cmdlen = 12;

        break;

    default:

        BADF("Unsupported command length, command %x\n", command);

        goto fail;

    }

#ifdef DEBUG_SCSI

    {

        int i;

        for (i = 1; i < cmdlen; i++) {

            printf(" 0x%02x", buf[i]);

        }

        printf("\n");

    }

#endif

    if (lun || buf[1] >> 5) {

        /* Only LUN 0 supported.  */

        DPRINTF("Unimplemented LUN %d\n", lun ? lun : buf[1] >> 5);

        if (command != 0x03 && command != 0x12) /* REQUEST SENSE and INQUIRY */

            goto fail;

    }

    switch (command) {

    case 0x0:

	DPRINTF("Test Unit Ready\n");

        if (!bdrv_is_inserted(s->dinfo->bdrv))

            goto notready;

	break;

    case 0x03:

        DPRINTF("Request Sense (len %d)\n", len);

        if (len < 4)

            goto fail;

        memset(outbuf, 0, 4);

        r->iov.iov_len = 4;

        if (s->sense == SENSE_NOT_READY && len >= 18) {

            memset(outbuf, 0, 18);

            r->iov.iov_len = 18;

            outbuf[7] = 10;

            /* asc 0x3a, ascq 0: Medium not present */

            outbuf[12] = 0x3a;

            outbuf[13] = 0;

        }

        outbuf[0] = 0xf0;

        outbuf[1] = 0;

        outbuf[2] = s->sense;

        break;

    case 0x12:

        DPRINTF("Inquiry (len %d)\n", len);

        if (buf[1] & 0x2) {

            /* Command support data - optional, not implemented */

            BADF("optional INQUIRY command support request not implemented\n");

            goto fail;

        }

        else if (buf[1] & 0x1) {

            /* Vital product data */

            uint8_t page_code = buf[2];

            if (len < 4) {

                BADF("Error: Inquiry (EVPD[%02X]) buffer size %d is "

                     "less than 4\n", page_code, len);

                goto fail;

            }

            switch (page_code) {

                case 0x00:

                    {

                        /* Supported page codes, mandatory */

                        DPRINTF("Inquiry EVPD[Supported pages] "

                                "buffer size %d\n", len);

                        r->iov.iov_len = 0;

                        if (bdrv_get_type_hint(s->dinfo->bdrv) == BDRV_TYPE_CDROM) {

                            outbuf[r->iov.iov_len++] = 5;

                        } else {

                            outbuf[r->iov.iov_len++] = 0;

                        }

                        outbuf[r->iov.iov_len++] = 0x00; // this page

                        outbuf[r->iov.iov_len++] = 0x00;

                        outbuf[r->iov.iov_len++] = 3;    // number of pages

                        outbuf[r->iov.iov_len++] = 0x00; // list of supported pages (this page)

                        outbuf[r->iov.iov_len++] = 0x80; // unit serial number

                        outbuf[r->iov.iov_len++] = 0x83; // device identification

                    }

                    break;

                case 0x80:

                    {

                        int l;

                        /* Device serial number, optional */

                        if (len < 4) {

                            BADF("Error: EVPD[Serial number] Inquiry buffer "

                                 "size %d too small, %d needed\n", len, 4);

                            goto fail;

                        }

                        DPRINTF("Inquiry EVPD[Serial number] buffer size %d\n", len);

                        l = MIN(len, strlen(s->drive_serial_str));

                        r->iov.iov_len = 0;

                        /* Supported page codes */

                        if (bdrv_get_type_hint(s->dinfo->bdrv) == BDRV_TYPE_CDROM) {

                            outbuf[r->iov.iov_len++] = 5;

                        } else {

                            outbuf[r->iov.iov_len++] = 0;

                        }

                        outbuf[r->iov.iov_len++] = 0x80; // this page

                        outbuf[r->iov.iov_len++] = 0x00;

                        outbuf[r->iov.iov_len++] = l;

                        memcpy(&outbuf[r->iov.iov_len], s->drive_serial_str, l);

                        r->iov.iov_len += l;

                    }

                    break;

                case 0x83:

                    {

                        /* Device identification page, mandatory */

                        int max_len = 255 - 8;

                        int id_len = strlen(bdrv_get_device_name(s->dinfo->bdrv));

                        if (id_len > max_len)

                            id_len = max_len;

                        DPRINTF("Inquiry EVPD[Device identification] "

                                "buffer size %d\n", len);

                        r->iov.iov_len = 0;

                        if (bdrv_get_type_hint(s->dinfo->bdrv) == BDRV_TYPE_CDROM) {

                            outbuf[r->iov.iov_len++] = 5;

                        } else {

                            outbuf[r->iov.iov_len++] = 0;

                        }

                        outbuf[r->iov.iov_len++] = 0x83; // this page

                        outbuf[r->iov.iov_len++] = 0x00;

                        outbuf[r->iov.iov_len++] = 3 + id_len;

                        outbuf[r->iov.iov_len++] = 0x2; // ASCII

                        outbuf[r->iov.iov_len++] = 0;   // not officially assigned

                        outbuf[r->iov.iov_len++] = 0;   // reserved

                        outbuf[r->iov.iov_len++] = id_len; // length of data following

                        memcpy(&outbuf[r->iov.iov_len],

                               bdrv_get_device_name(s->dinfo->bdrv), id_len);

                        r->iov.iov_len += id_len;

                    }

                    break;

                default:

                    BADF("Error: unsupported Inquiry (EVPD[%02X]) "

                         "buffer size %d\n", page_code, len);

                    goto fail;

            }

            /* done with EVPD */

            break;

        }

        else {

            /* Standard INQUIRY data */

            if (buf[2] != 0) {

                BADF("Error: Inquiry (STANDARD) page or code "

                     "is non-zero [%02X]\n", buf[2]);

                goto fail;

            }

            /* PAGE CODE == 0 */

            if (len < 5) {

                BADF("Error: Inquiry (STANDARD) buffer size %d "

                     "is less than 5\n", len);

                goto fail;

            }

            if (len < 36) {

                BADF("Error: Inquiry (STANDARD) buffer size %d "

                     "is less than 36 (TODO: only 5 required)\n", len);

            }

        }

        if(len > SCSI_MAX_INQUIRY_LEN)

            len = SCSI_MAX_INQUIRY_LEN;

        memset(outbuf, 0, len);

        if (lun || buf[1] >> 5) {

            outbuf[0] = 0x7f;	/* LUN not supported */

	} else if (bdrv_get_type_hint(s->dinfo->bdrv) == BDRV_TYPE_CDROM) {

	    outbuf[0] = 5;

            outbuf[1] = 0x80;

	    memcpy(&outbuf[16], "QEMU CD-ROM    ", 16);

	} else {

	    outbuf[0] = 0;

	    memcpy(&outbuf[16], "QEMU HARDDISK  ", 16);

	}

	memcpy(&outbuf[8], "QEMU   ", 8);

        memcpy(&outbuf[32], QEMU_VERSION, 4);

        /* Identify device as SCSI-3 rev 1.

           Some later commands are also implemented. */

	outbuf[2] = 3;

	outbuf[3] = 2; /* Format 2 */

	outbuf[4] = len - 5; /* Additional Length = (Len - 1) - 4 */

        /* Sync data transfer and TCQ.  */

        outbuf[7] = 0x10 | (r->bus->tcq ? 0x02 : 0);

	r->iov.iov_len = len;

	break;

    case 0x16:

        DPRINTF("Reserve(6)\n");

        if (buf[1] & 1)

            goto fail;

        break;

    case 0x17:

        DPRINTF("Release(6)\n");

        if (buf[1] & 1)

            goto fail;

        break;

    case 0x1a:

    case 0x5a:

        {

            uint8_t *p;

            int page;

            page = buf[2] & 0x3f;

            DPRINTF("Mode Sense (page %d, len %d)\n", page, len);

            p = outbuf;

            memset(p, 0, 4);

            outbuf[1] = 0; /* Default media type.  */

            outbuf[3] = 0; /* Block descriptor length.  */

            if (bdrv_get_type_hint(s->dinfo->bdrv) == BDRV_TYPE_CDROM) {

                outbuf[2] = 0x80; /* Readonly.  */

            }

            p += 4;

            if (page == 4) {

                int cylinders, heads, secs;

                /* Rigid disk device geometry page. */

                p[0] = 4;

                p[1] = 0x16;

                /* if a geometry hint is available, use it */

                bdrv_get_geometry_hint(s->dinfo->bdrv, &cylinders, &heads, &secs);

                p[2] = (cylinders >> 16) & 0xff;

                p[3] = (cylinders >> 8) & 0xff;

                p[4] = cylinders & 0xff;

                p[5] = heads & 0xff;

                /* Write precomp start cylinder, disabled */

                p[6] = (cylinders >> 16) & 0xff;

                p[7] = (cylinders >> 8) & 0xff;

                p[8] = cylinders & 0xff;

                /* Reduced current start cylinder, disabled */

                p[9] = (cylinders >> 16) & 0xff;

                p[10] = (cylinders >> 8) & 0xff;

                p[11] = cylinders & 0xff;

                /* Device step rate [ns], 200ns */

                p[12] = 0;

                p[13] = 200;

                /* Landing zone cylinder */

                p[14] = 0xff;

                p[15] =  0xff;

                p[16] = 0xff;

                /* Medium rotation rate [rpm], 5400 rpm */

                p[20] = (5400 >> 8) & 0xff;

                p[21] = 5400 & 0xff;

                p += 0x16;

            } else if (page == 5) {

                int cylinders, heads, secs;

                /* Flexible disk device geometry page. */

                p[0] = 5;

                p[1] = 0x1e;

                /* Transfer rate [kbit/s], 5Mbit/s */

                p[2] = 5000 >> 8;

                p[3] = 5000 & 0xff;

                /* if a geometry hint is available, use it */

                bdrv_get_geometry_hint(s->dinfo->bdrv, &cylinders, &heads, &secs);

                p[4] = heads & 0xff;

                p[5] = secs & 0xff;

                p[6] = s->cluster_size * 2;

                p[8] = (cylinders >> 8) & 0xff;

                p[9] = cylinders & 0xff;

                /* Write precomp start cylinder, disabled */

                p[10] = (cylinders >> 8) & 0xff;

                p[11] = cylinders & 0xff;

                /* Reduced current start cylinder, disabled */

                p[12] = (cylinders >> 8) & 0xff;

                p[13] = cylinders & 0xff;

                /* Device step rate [100us], 100us */

                p[14] = 0;

                p[15] = 1;

                /* Device step pulse width [us], 1us */

                p[16] = 1;

                /* Device head settle delay [100us], 100us */

                p[17] = 0;

                p[18] = 1;

                /* Motor on delay [0.1s], 0.1s */

                p[19] = 1;

                /* Motor off delay [0.1s], 0.1s */

                p[20] = 1;

                /* Medium rotation rate [rpm], 5400 rpm */

                p[28] = (5400 >> 8) & 0xff;

                p[29] = 5400 & 0xff;

                p += 0x1e;

            } else if ((page == 8 || page == 0x3f)) {

                /* Caching page.  */

                memset(p,0,20);

                p[0] = 8;

                p[1] = 0x12;

                if (bdrv_enable_write_cache(s->dinfo->bdrv)) {

                     p[2] = 4; /* WCE */

                }

                p += 20;

            }

            if ((page == 0x3f || page == 0x2a)

                    && (bdrv_get_type_hint(s->dinfo->bdrv) == BDRV_TYPE_CDROM)) {

                /* CD Capabilities and Mechanical Status page. */

                p[0] = 0x2a;

                p[1] = 0x14;

                p[2] = 3; // CD-R & CD-RW read

                p[3] = 0; // Writing not supported

                p[4] = 0x7f; /* Audio, composite, digital out,

                                         mode 2 form 1&2, multi session */

                p[5] = 0xff; /* CD DA, DA accurate, RW supported,

                                         RW corrected, C2 errors, ISRC,

                                         UPC, Bar code */

                p[6] = 0x2d | (bdrv_is_locked(s->dinfo->bdrv)? 2 : 0);

                /* Locking supported, jumper present, eject, tray */

                p[7] = 0; /* no volume & mute control, no

                                      changer */

                p[8] = (50 * 176) >> 8; // 50x read speed

                p[9] = (50 * 176) & 0xff;

                p[10] = 0 >> 8; // No volume

                p[11] = 0 & 0xff;

                p[12] = 2048 >> 8; // 2M buffer

                p[13] = 2048 & 0xff;

                p[14] = (16 * 176) >> 8; // 16x read speed current

                p[15] = (16 * 176) & 0xff;

                p[18] = (16 * 176) >> 8; // 16x write speed

                p[19] = (16 * 176) & 0xff;

                p[20] = (16 * 176) >> 8; // 16x write speed current

                p[21] = (16 * 176) & 0xff;

                p += 22;

            }

            r->iov.iov_len = p - outbuf;

            outbuf[0] = r->iov.iov_len - 4;

            if (r->iov.iov_len > len)

                r->iov.iov_len = len;

        }

        break;

    case 0x1b:

        DPRINTF("Start Stop Unit\n");

        if (bdrv_get_type_hint(s->dinfo->bdrv) == BDRV_TYPE_CDROM &&

            (buf[4] & 2))

            /* load/eject medium */

            bdrv_eject(s->dinfo->bdrv, !(buf[4] & 1));

	break;

    case 0x1e:

        DPRINTF("Prevent Allow Medium Removal (prevent = %d)\n", buf[4] & 3);

        bdrv_set_locked(s->dinfo->bdrv, buf[4] & 1);

	break;

    case 0x25:

	DPRINTF("Read Capacity\n");

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

	memset(outbuf, 0, 8);

	bdrv_get_geometry(s->dinfo->bdrv, &nb_sectors);

        nb_sectors /= s->cluster_size;

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

        if (nb_sectors) {

            nb_sectors--;

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

            s->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->cluster_size * 2;

            outbuf[7] = 0;

            r->iov.iov_len = 8;

        } else {

        notready:

            scsi_command_complete(r, STATUS_CHECK_CONDITION, SENSE_NOT_READY);

            return 0;

        }

	break;

    case 0x08:

    case 0x28:

    case 0x88:

        DPRINTF("Read (sector %" PRId64 ", count %d)\n", lba, len);

        if (lba > s->max_lba)

            goto illegal_lba;

        r->sector = lba * s->cluster_size;

        r->sector_count = len * s->cluster_size;

        break;

    case 0x0a:

    case 0x2a:

    case 0x8a:

        DPRINTF("Write (sector %" PRId64 ", count %d)\n", lba, len);

        if (lba > s->max_lba)

            goto illegal_lba;

        r->sector = lba * s->cluster_size;

        r->sector_count = len * s->cluster_size;

        is_write = 1;

        break;

    case 0x35:

        DPRINTF("Synchronise cache (sector %" PRId64 ", count %d)\n", lba, len);

        bdrv_flush(s->dinfo->bdrv);

        break;

    case 0x43:

        {

            int start_track, format, msf, toclen;

            msf = buf[1] & 2;

            format = buf[2] & 0xf;

            start_track = buf[6];

            bdrv_get_geometry(s->dinfo->bdrv, &nb_sectors);

            DPRINTF("Read TOC (track %d format %d msf %d)\n", start_track, format, msf >> 1);

            nb_sectors /= s->cluster_size;

            switch(format) {

            case 0:

                toclen = cdrom_read_toc(nb_sectors, outbuf, msf, start_track);

                break;

            case 1:

                /* multi session : only a single session defined */

                toclen = 12;

                memset(outbuf, 0, 12);

                outbuf[1] = 0x0a;

                outbuf[2] = 0x01;

                outbuf[3] = 0x01;

                break;

            case 2:

                toclen = cdrom_read_toc_raw(nb_sectors, outbuf, msf, start_track);

                break;

            default:

                goto error_cmd;

            }

            if (toclen > 0) {

                if (len > toclen)

                  len = toclen;

                r->iov.iov_len = len;

                break;

            }

        error_cmd:

            DPRINTF("Read TOC error\n");

            goto fail;

        }

    case 0x46:

        DPRINTF("Get Configuration (rt %d, maxlen %d)\n", buf[1] & 3, len);

        memset(outbuf, 0, 8);

        /* ??? This should probably return much more information.  For now

           just return the basic header indicating the CD-ROM profile.  */

        outbuf[7] = 8; // CD-ROM

        r->iov.iov_len = 8;

        break;

    case 0x56:

        DPRINTF("Reserve(10)\n");

        if (buf[1] & 3)

            goto fail;

        break;

    case 0x57:

        DPRINTF("Release(10)\n");

        if (buf[1] & 3)

            goto fail;

        break;

    case 0x9e:

        /* Service Action In subcommands. */

        if ((buf[1] & 31) == 0x10) {

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

            memset(outbuf, 0, len);

            bdrv_get_geometry(s->dinfo->bdrv, &nb_sectors);

            nb_sectors /= s->cluster_size;

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

            if (nb_sectors) {

                nb_sectors--;

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

                s->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->cluster_size * 2;

                outbuf[11] = 0;

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

                r->iov.iov_len = len;

            } else {

                scsi_command_complete(r, STATUS_CHECK_CONDITION, SENSE_NOT_READY);

                return 0;

            }

            break;

        }

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

        goto fail;

    case 0xa0:

        DPRINTF("Report LUNs (len %d)\n", len);

        if (len < 16)

            goto fail;

        memset(outbuf, 0, 16);

        outbuf[3] = 8;

        r->iov.iov_len = 16;

        break;

    case 0x2f:

        DPRINTF("Verify (sector %" PRId64 ", count %d)\n", lba, len);

        break;

    default:

	DPRINTF("Unknown SCSI command (%2.2x)\n", buf[0]);

    fail:

        scsi_command_complete(r, STATUS_CHECK_CONDITION, SENSE_ILLEGAL_REQUEST);

	return 0;

    illegal_lba:

        scsi_command_complete(r, STATUS_CHECK_CONDITION, SENSE_HARDWARE_ERROR);

        return 0;

    }

    if (r->sector_count == 0 && r->iov.iov_len == 0) {

        scsi_command_complete(r, STATUS_GOOD, SENSE_NO_SENSE);

    }

    len = r->sector_count * 512 + r->iov.iov_len;

    if (is_write) {

        return -len;

    } else {

        if (!r->sector_count)

            r->sector_count = -1;

        return len;

    }

}


MemTxResult gicv3_redist_write(void *opaque, hwaddr offset, uint64_t data,
                               unsigned size, MemTxAttrs attrs)
{
    GICv3State *s = opaque;
    GICv3CPUState *cs;
    MemTxResult r;
    int cpuidx;
    /* This region covers all the redistributor pages; there are
     * (for GICv3) two 64K pages per CPU. At the moment they are
     * all contiguous (ie in this one region), though we might later
     * want to allow splitting of redistributor pages into several
     * blocks so we can support more CPUs.
     */
    cpuidx = offset / 0x20000;
    offset %= 0x20000;
    assert(cpuidx < s->num_cpu);
    cs = &s->cpu[cpuidx];
    switch (size) {
    case 1:
        r = gicr_writeb(cs, offset, data, attrs);
        break;
    case 4:
        r = gicr_writel(cs, offset, data, attrs);
        break;
    case 8:
        r = gicr_writell(cs, offset, data, attrs);
        break;
    default:
        r = MEMTX_ERROR;
        break;
    }
    if (r == MEMTX_ERROR) {
        qemu_log_mask(LOG_GUEST_ERROR,
                      "%s: invalid guest write at offset " TARGET_FMT_plx
                      "size %u\n", __func__, offset, size);
        trace_gicv3_redist_badwrite(gicv3_redist_affid(cs), offset, data,
                                    size, attrs.secure);
    } else {
        trace_gicv3_redist_write(gicv3_redist_affid(cs), offset, data,
                                 size, attrs.secure);
    }
    return r;
}


uint8_t qpci_io_readb(QPCIDevice *dev, void *data)

{

    uintptr_t addr = (uintptr_t)data;

    if (addr < QPCI_PIO_LIMIT) {

        return dev->bus->pio_readb(dev->bus, addr);

    } else {

        uint8_t val;

        dev->bus->memread(dev->bus, addr, &val, sizeof(val));

        return val;

    }

}


static int xvid_strip_vol_header(AVCodecContext *avctx, AVPacket *pkt,

                                 unsigned int header_len,

                                 unsigned int frame_len)

{

    int vo_len = 0, i;

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

        if (pkt->data[i]     == 0x00 &&

            pkt->data[i + 1] == 0x00 &&

            pkt->data[i + 2] == 0x01 &&

            pkt->data[i + 3] == 0xB6) {

            vo_len = i;

            break;

        }

    }

    if (vo_len > 0) {

        /* We need to store the header, so extract it */

        if (!avctx->extradata) {

            avctx->extradata = av_malloc(vo_len);

            memcpy(avctx->extradata, pkt->data, vo_len);

            avctx->extradata_size = vo_len;

        }

        /* Less dangerous now, memmove properly copies the two

         * chunks of overlapping data */

        memmove(pkt->data, &pkt->data[vo_len], frame_len - vo_len);

        pkt->size = frame_len - vo_len;

    }

    return 0;

}


av_cold int ff_MPV_encode_init(AVCodecContext *avctx)

{

    MpegEncContext *s = avctx->priv_data;

    int i, ret;

    MPV_encode_defaults(s);

    switch (avctx->codec_id) {

    case AV_CODEC_ID_MPEG2VIDEO:

        if (avctx->pix_fmt != AV_PIX_FMT_YUV420P &&

            avctx->pix_fmt != AV_PIX_FMT_YUV422P) {

            av_log(avctx, AV_LOG_ERROR,

                   "only YUV420 and YUV422 are supported\n");

            return -1;

        }

        break;

    case AV_CODEC_ID_MJPEG:

        if (avctx->pix_fmt != AV_PIX_FMT_YUVJ420P &&

            avctx->pix_fmt != AV_PIX_FMT_YUVJ422P &&

            ((avctx->pix_fmt != AV_PIX_FMT_YUV420P &&

              avctx->pix_fmt != AV_PIX_FMT_YUV422P) ||

             avctx->strict_std_compliance > FF_COMPLIANCE_UNOFFICIAL)) {

            av_log(avctx, AV_LOG_ERROR, "colorspace not supported in jpeg\n");

            return -1;

        }

        break;

    default:

        if (avctx->pix_fmt != AV_PIX_FMT_YUV420P) {

            av_log(avctx, AV_LOG_ERROR, "only YUV420 is supported\n");

            return -1;

        }

    }

    switch (avctx->pix_fmt) {

    case AV_PIX_FMT_YUVJ422P:

    case AV_PIX_FMT_YUV422P:

        s->chroma_format = CHROMA_422;

        break;

    case AV_PIX_FMT_YUVJ420P:

    case AV_PIX_FMT_YUV420P:

    default:

        s->chroma_format = CHROMA_420;

        break;

    }

    s->bit_rate = avctx->bit_rate;

    s->width    = avctx->width;

    s->height   = avctx->height;

    if (avctx->gop_size > 600 &&

        avctx->strict_std_compliance > FF_COMPLIANCE_EXPERIMENTAL) {

        av_log(avctx, AV_LOG_ERROR,

               "Warning keyframe interval too large! reducing it ...\n");

        avctx->gop_size = 600;

    }

    s->gop_size     = avctx->gop_size;

    s->avctx        = avctx;

    s->flags        = avctx->flags;

    s->flags2       = avctx->flags2;

    if (avctx->max_b_frames > MAX_B_FRAMES) {

        av_log(avctx, AV_LOG_ERROR, "Too many B-frames requested, maximum "

               "is %d.\n", MAX_B_FRAMES);

    }

    s->max_b_frames = avctx->max_b_frames;

    s->codec_id     = avctx->codec->id;

    s->strict_std_compliance = avctx->strict_std_compliance;

    s->quarter_sample     = (avctx->flags & CODEC_FLAG_QPEL) != 0;

    s->mpeg_quant         = avctx->mpeg_quant;

    s->rtp_mode           = !!avctx->rtp_payload_size;

    s->intra_dc_precision = avctx->intra_dc_precision;

    s->user_specified_pts = AV_NOPTS_VALUE;

    if (s->gop_size <= 1) {

        s->intra_only = 1;

        s->gop_size   = 12;

    } else {

        s->intra_only = 0;

    }

    s->me_method = avctx->me_method;

    /* Fixed QSCALE */

    s->fixed_qscale = !!(avctx->flags & CODEC_FLAG_QSCALE);

    s->adaptive_quant = (s->avctx->lumi_masking ||

                         s->avctx->dark_masking ||

                         s->avctx->temporal_cplx_masking ||

                         s->avctx->spatial_cplx_masking  ||

                         s->avctx->p_masking      ||

                         s->avctx->border_masking ||

                         (s->mpv_flags & FF_MPV_FLAG_QP_RD)) &&

                        !s->fixed_qscale;

    s->loop_filter      = !!(s->flags & CODEC_FLAG_LOOP_FILTER);

    if (avctx->rc_max_rate && !avctx->rc_buffer_size) {

        av_log(avctx, AV_LOG_ERROR,

               "a vbv buffer size is needed, "

               "for encoding with a maximum bitrate\n");

        return -1;

    }

    if (avctx->rc_min_rate && avctx->rc_max_rate != avctx->rc_min_rate) {

        av_log(avctx, AV_LOG_INFO,

               "Warning min_rate > 0 but min_rate != max_rate isn't recommended!\n");

    }

    if (avctx->rc_min_rate && avctx->rc_min_rate > avctx->bit_rate) {

        av_log(avctx, AV_LOG_ERROR, "bitrate below min bitrate\n");

        return -1;

    }

    if (avctx->rc_max_rate && avctx->rc_max_rate < avctx->bit_rate) {

        av_log(avctx, AV_LOG_INFO, "bitrate above max bitrate\n");

        return -1;

    }

    if (avctx->rc_max_rate &&

        avctx->rc_max_rate == avctx->bit_rate &&

        avctx->rc_max_rate != avctx->rc_min_rate) {

        av_log(avctx, AV_LOG_INFO,

               "impossible bitrate constraints, this will fail\n");

    }

    if (avctx->rc_buffer_size &&

        avctx->bit_rate * (int64_t)avctx->time_base.num >

            avctx->rc_buffer_size * (int64_t)avctx->time_base.den) {

        av_log(avctx, AV_LOG_ERROR, "VBV buffer too small for bitrate\n");

        return -1;

    }

    if (!s->fixed_qscale &&

        avctx->bit_rate * av_q2d(avctx->time_base) >

            avctx->bit_rate_tolerance) {

        av_log(avctx, AV_LOG_ERROR,

               "bitrate tolerance too small for bitrate\n");

        return -1;

    }

    if (s->avctx->rc_max_rate &&

        s->avctx->rc_min_rate == s->avctx->rc_max_rate &&

        (s->codec_id == AV_CODEC_ID_MPEG1VIDEO ||

         s->codec_id == AV_CODEC_ID_MPEG2VIDEO) &&

        90000LL * (avctx->rc_buffer_size - 1) >

            s->avctx->rc_max_rate * 0xFFFFLL) {

        av_log(avctx, AV_LOG_INFO,

               "Warning vbv_delay will be set to 0xFFFF (=VBR) as the "

               "specified vbv buffer is too large for the given bitrate!\n");

    }

    if ((s->flags & CODEC_FLAG_4MV)  && s->codec_id != AV_CODEC_ID_MPEG4 &&

        s->codec_id != AV_CODEC_ID_H263 && s->codec_id != AV_CODEC_ID_H263P &&

        s->codec_id != AV_CODEC_ID_FLV1) {

        av_log(avctx, AV_LOG_ERROR, "4MV not supported by codec\n");

        return -1;

    }

    if (s->obmc && s->avctx->mb_decision != FF_MB_DECISION_SIMPLE) {

        av_log(avctx, AV_LOG_ERROR,

               "OBMC is only supported with simple mb decision\n");

        return -1;

    }

    if (s->quarter_sample && s->codec_id != AV_CODEC_ID_MPEG4) {

        av_log(avctx, AV_LOG_ERROR, "qpel not supported by codec\n");

        return -1;

    }

    if (s->max_b_frames                    &&

        s->codec_id != AV_CODEC_ID_MPEG4      &&

        s->codec_id != AV_CODEC_ID_MPEG1VIDEO &&

        s->codec_id != AV_CODEC_ID_MPEG2VIDEO) {

        av_log(avctx, AV_LOG_ERROR, "b frames not supported by codec\n");

        return -1;

    }

    if ((s->codec_id == AV_CODEC_ID_MPEG4 ||

         s->codec_id == AV_CODEC_ID_H263  ||

         s->codec_id == AV_CODEC_ID_H263P) &&

        (avctx->sample_aspect_ratio.num > 255 ||

         avctx->sample_aspect_ratio.den > 255)) {

        av_log(avctx, AV_LOG_ERROR,

               "Invalid pixel aspect ratio %i/%i, limit is 255/255\n",

               avctx->sample_aspect_ratio.num, avctx->sample_aspect_ratio.den);

        return -1;

    }

    if ((s->flags & (CODEC_FLAG_INTERLACED_DCT | CODEC_FLAG_INTERLACED_ME)) &&

        s->codec_id != AV_CODEC_ID_MPEG4 && s->codec_id != AV_CODEC_ID_MPEG2VIDEO) {

        av_log(avctx, AV_LOG_ERROR, "interlacing not supported by codec\n");

        return -1;

    }

    // FIXME mpeg2 uses that too

    if (s->mpeg_quant && s->codec_id != AV_CODEC_ID_MPEG4) {

        av_log(avctx, AV_LOG_ERROR,

               "mpeg2 style quantization not supported by codec\n");

        return -1;

    }

    if ((s->mpv_flags & FF_MPV_FLAG_CBP_RD) && !avctx->trellis) {

        av_log(avctx, AV_LOG_ERROR, "CBP RD needs trellis quant\n");

        return -1;

    }

    if ((s->mpv_flags & FF_MPV_FLAG_QP_RD) &&

        s->avctx->mb_decision != FF_MB_DECISION_RD) {

        av_log(avctx, AV_LOG_ERROR, "QP RD needs mbd=2\n");

        return -1;

    }

    if (s->avctx->scenechange_threshold < 1000000000 &&

        (s->flags & CODEC_FLAG_CLOSED_GOP)) {

        av_log(avctx, AV_LOG_ERROR,

               "closed gop with scene change detection are not supported yet, "

               "set threshold to 1000000000\n");

        return -1;

    }

    if (s->flags & CODEC_FLAG_LOW_DELAY) {

        if (s->codec_id != AV_CODEC_ID_MPEG2VIDEO) {

            av_log(avctx, AV_LOG_ERROR,

                  "low delay forcing is only available for mpeg2\n");

            return -1;

        }

        if (s->max_b_frames != 0) {

            av_log(avctx, AV_LOG_ERROR,

                   "b frames cannot be used with low delay\n");

            return -1;

        }

    }

    if (s->q_scale_type == 1) {

        if (avctx->qmax > 12) {

            av_log(avctx, AV_LOG_ERROR,

                   "non linear quant only supports qmax <= 12 currently\n");

            return -1;

        }

    }

    if (s->avctx->thread_count > 1         &&

        s->codec_id != AV_CODEC_ID_MPEG4      &&

        s->codec_id != AV_CODEC_ID_MPEG1VIDEO &&

        s->codec_id != AV_CODEC_ID_MPEG2VIDEO &&

        (s->codec_id != AV_CODEC_ID_H263P)) {

        av_log(avctx, AV_LOG_ERROR,

               "multi threaded encoding not supported by codec\n");

        return -1;

    }

    if (s->avctx->thread_count < 1) {

        av_log(avctx, AV_LOG_ERROR,

               "automatic thread number detection not supported by codec,"

               "patch welcome\n");

        return -1;

    }

    if (s->avctx->thread_count > 1)

        s->rtp_mode = 1;

    if (!avctx->time_base.den || !avctx->time_base.num) {

        av_log(avctx, AV_LOG_ERROR, "framerate not set\n");

        return -1;

    }

    i = (INT_MAX / 2 + 128) >> 8;

    if (avctx->mb_threshold >= i) {

        av_log(avctx, AV_LOG_ERROR, "mb_threshold too large, max is %d\n",

               i - 1);

        return -1;

    }

    if (avctx->b_frame_strategy && (avctx->flags & CODEC_FLAG_PASS2)) {

        av_log(avctx, AV_LOG_INFO,

               "notice: b_frame_strategy only affects the first pass\n");

        avctx->b_frame_strategy = 0;

    }

    i = av_gcd(avctx->time_base.den, avctx->time_base.num);

    if (i > 1) {

        av_log(avctx, AV_LOG_INFO, "removing common factors from framerate\n");

        avctx->time_base.den /= i;

        avctx->time_base.num /= i;

        //return -1;

    }

    if (s->mpeg_quant || s->codec_id == AV_CODEC_ID_MPEG1VIDEO ||

        s->codec_id == AV_CODEC_ID_MPEG2VIDEO || s->codec_id == AV_CODEC_ID_MJPEG) {

        // (a + x * 3 / 8) / x

        s->intra_quant_bias = 3 << (QUANT_BIAS_SHIFT - 3);

        s->inter_quant_bias = 0;

    } else {

        s->intra_quant_bias = 0;

        // (a - x / 4) / x

        s->inter_quant_bias = -(1 << (QUANT_BIAS_SHIFT - 2));

    }

    if (avctx->intra_quant_bias != FF_DEFAULT_QUANT_BIAS)

        s->intra_quant_bias = avctx->intra_quant_bias;

    if (avctx->inter_quant_bias != FF_DEFAULT_QUANT_BIAS)

        s->inter_quant_bias = avctx->inter_quant_bias;

    if (avctx->codec_id == AV_CODEC_ID_MPEG4 &&

        s->avctx->time_base.den > (1 << 16) - 1) {

        av_log(avctx, AV_LOG_ERROR,

               "timebase %d/%d not supported by MPEG 4 standard, "

               "the maximum admitted value for the timebase denominator "

               "is %d\n", s->avctx->time_base.num, s->avctx->time_base.den,

               (1 << 16) - 1);

        return -1;

    }

    s->time_increment_bits = av_log2(s->avctx->time_base.den - 1) + 1;

    switch (avctx->codec->id) {

    case AV_CODEC_ID_MPEG1VIDEO:

        s->out_format = FMT_MPEG1;

        s->low_delay  = !!(s->flags & CODEC_FLAG_LOW_DELAY);

        avctx->delay  = s->low_delay ? 0 : (s->max_b_frames + 1);

        break;

    case AV_CODEC_ID_MPEG2VIDEO:

        s->out_format = FMT_MPEG1;

        s->low_delay  = !!(s->flags & CODEC_FLAG_LOW_DELAY);

        avctx->delay  = s->low_delay ? 0 : (s->max_b_frames + 1);

        s->rtp_mode   = 1;

        break;

    case AV_CODEC_ID_MJPEG:

        s->out_format = FMT_MJPEG;

        s->intra_only = 1; /* force intra only for jpeg */

        if (!CONFIG_MJPEG_ENCODER ||

            ff_mjpeg_encode_init(s) < 0)

            return -1;

        avctx->delay = 0;

        s->low_delay = 1;

        break;

    case AV_CODEC_ID_H261:

        if (!CONFIG_H261_ENCODER)

            return -1;

        if (ff_h261_get_picture_format(s->width, s->height) < 0) {

            av_log(avctx, AV_LOG_ERROR,

                   "The specified picture size of %dx%d is not valid for the "

                   "H.261 codec.\nValid sizes are 176x144, 352x288\n",

                    s->width, s->height);

            return -1;

        }

        s->out_format = FMT_H261;

        avctx->delay  = 0;

        s->low_delay  = 1;

        break;

    case AV_CODEC_ID_H263:

        if (!CONFIG_H263_ENCODER)

        return -1;

        if (ff_match_2uint16(ff_h263_format, FF_ARRAY_ELEMS(ff_h263_format),

                             s->width, s->height) == 8) {

            av_log(avctx, AV_LOG_INFO,

                   "The specified picture size of %dx%d is not valid for "

                   "the H.263 codec.\nValid sizes are 128x96, 176x144, "

                   "352x288, 704x576, and 1408x1152."

                   "Try H.263+.\n", s->width, s->height);

            return -1;

        }

        s->out_format = FMT_H263;

        avctx->delay  = 0;

        s->low_delay  = 1;

        break;

    case AV_CODEC_ID_H263P:

        s->out_format = FMT_H263;

        s->h263_plus  = 1;

        /* Fx */

        s->h263_aic        = (avctx->flags & CODEC_FLAG_AC_PRED) ? 1 : 0;

        s->modified_quant  = s->h263_aic;

        s->loop_filter     = (avctx->flags & CODEC_FLAG_LOOP_FILTER) ? 1 : 0;

        s->unrestricted_mv = s->obmc || s->loop_filter || s->umvplus;

        /* /Fx */

        /* These are just to be sure */

        avctx->delay = 0;

        s->low_delay = 1;

        break;

    case AV_CODEC_ID_FLV1:

        s->out_format      = FMT_H263;

        s->h263_flv        = 2; /* format = 1; 11-bit codes */

        s->unrestricted_mv = 1;

        s->rtp_mode  = 0; /* don't allow GOB */

        avctx->delay = 0;

        s->low_delay = 1;

        break;

    case AV_CODEC_ID_RV10:

        s->out_format = FMT_H263;

        avctx->delay  = 0;

        s->low_delay  = 1;

        break;

    case AV_CODEC_ID_RV20:

        s->out_format      = FMT_H263;

        avctx->delay       = 0;

        s->low_delay       = 1;

        s->modified_quant  = 1;

        s->h263_aic        = 1;

        s->h263_plus       = 1;

        s->loop_filter     = 1;

        s->unrestricted_mv = 0;

        break;

    case AV_CODEC_ID_MPEG4:

        s->out_format      = FMT_H263;

        s->h263_pred       = 1;

        s->unrestricted_mv = 1;

        s->low_delay       = s->max_b_frames ? 0 : 1;

        avctx->delay       = s->low_delay ? 0 : (s->max_b_frames + 1);

        break;

    case AV_CODEC_ID_MSMPEG4V2:

        s->out_format      = FMT_H263;

        s->h263_pred       = 1;

        s->unrestricted_mv = 1;

        s->msmpeg4_version = 2;

        avctx->delay       = 0;

        s->low_delay       = 1;

        break;

    case AV_CODEC_ID_MSMPEG4V3:

        s->out_format        = FMT_H263;

        s->h263_pred         = 1;

        s->unrestricted_mv   = 1;

        s->msmpeg4_version   = 3;

        s->flipflop_rounding = 1;

        avctx->delay         = 0;

        s->low_delay         = 1;

        break;

    case AV_CODEC_ID_WMV1:

        s->out_format        = FMT_H263;

        s->h263_pred         = 1;

        s->unrestricted_mv   = 1;

        s->msmpeg4_version   = 4;

        s->flipflop_rounding = 1;

        avctx->delay         = 0;

        s->low_delay         = 1;

        break;

    case AV_CODEC_ID_WMV2:

        s->out_format        = FMT_H263;

        s->h263_pred         = 1;

        s->unrestricted_mv   = 1;

        s->msmpeg4_version   = 5;

        s->flipflop_rounding = 1;

        avctx->delay         = 0;

        s->low_delay         = 1;

        break;

    default:

        return -1;

    }

    avctx->has_b_frames = !s->low_delay;

    s->encoding = 1;

    s->progressive_frame    =

    s->progressive_sequence = !(avctx->flags & (CODEC_FLAG_INTERLACED_DCT |

                                                CODEC_FLAG_INTERLACED_ME) ||

                                s->alternate_scan);

    /* init */

    if (ff_MPV_common_init(s) < 0)

        return -1;

    if (ARCH_X86)

        ff_MPV_encode_init_x86(s);

    s->avctx->coded_frame = &s->current_picture.f;

    if (s->msmpeg4_version) {

        FF_ALLOCZ_OR_GOTO(s->avctx, s->ac_stats,

                          2 * 2 * (MAX_LEVEL + 1) *

                          (MAX_RUN + 1) * 2 * sizeof(int), fail);

    }

    FF_ALLOCZ_OR_GOTO(s->avctx, s->avctx->stats_out, 256, fail);

    FF_ALLOCZ_OR_GOTO(s->avctx, s->q_intra_matrix,   64 * 32 * sizeof(int), fail);

    FF_ALLOCZ_OR_GOTO(s->avctx, s->q_inter_matrix,   64 * 32 * sizeof(int), fail);

    FF_ALLOCZ_OR_GOTO(s->avctx, s->q_intra_matrix16, 64 * 32 * 2 * sizeof(uint16_t), fail);

    FF_ALLOCZ_OR_GOTO(s->avctx, s->q_inter_matrix16, 64 * 32 * 2 * sizeof(uint16_t), fail);

    FF_ALLOCZ_OR_GOTO(s->avctx, s->input_picture,

                      MAX_PICTURE_COUNT * sizeof(Picture *), fail);

    FF_ALLOCZ_OR_GOTO(s->avctx, s->reordered_input_picture,

                      MAX_PICTURE_COUNT * sizeof(Picture *), fail);

    if (s->avctx->noise_reduction) {

        FF_ALLOCZ_OR_GOTO(s->avctx, s->dct_offset,

                          2 * 64 * sizeof(uint16_t), fail);

    }

    if (CONFIG_H263_ENCODER)

        ff_h263dsp_init(&s->h263dsp);

    if (!s->dct_quantize)

        s->dct_quantize = ff_dct_quantize_c;

    if (!s->denoise_dct)

        s->denoise_dct  = denoise_dct_c;

    s->fast_dct_quantize = s->dct_quantize;

    if (avctx->trellis)

        s->dct_quantize  = dct_quantize_trellis_c;

    if ((CONFIG_H263P_ENCODER || CONFIG_RV20_ENCODER) && s->modified_quant)

        s->chroma_qscale_table = ff_h263_chroma_qscale_table;

    s->quant_precision = 5;

    ff_set_cmp(&s->dsp, s->dsp.ildct_cmp, s->avctx->ildct_cmp);

    ff_set_cmp(&s->dsp, s->dsp.frame_skip_cmp, s->avctx->frame_skip_cmp);

    if (CONFIG_H261_ENCODER && s->out_format == FMT_H261)

        ff_h261_encode_init(s);

    if (CONFIG_H263_ENCODER && s->out_format == FMT_H263)

        ff_h263_encode_init(s);

    if (CONFIG_MSMPEG4_ENCODER && s->msmpeg4_version)

        ff_msmpeg4_encode_init(s);

    if ((CONFIG_MPEG1VIDEO_ENCODER || CONFIG_MPEG2VIDEO_ENCODER)

        && s->out_format == FMT_MPEG1)

        ff_mpeg1_encode_init(s);

    /* init q matrix */

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

        int j = s->dsp.idct_permutation[i];

        if (CONFIG_MPEG4_ENCODER && s->codec_id == AV_CODEC_ID_MPEG4 &&

            s->mpeg_quant) {

            s->intra_matrix[j] = ff_mpeg4_default_intra_matrix[i];

            s->inter_matrix[j] = ff_mpeg4_default_non_intra_matrix[i];

        } else if (s->out_format == FMT_H263 || s->out_format == FMT_H261) {

            s->intra_matrix[j] =

            s->inter_matrix[j] = ff_mpeg1_default_non_intra_matrix[i];

        } else {

            /* mpeg1/2 */

            s->intra_matrix[j] = ff_mpeg1_default_intra_matrix[i];

            s->inter_matrix[j] = ff_mpeg1_default_non_intra_matrix[i];

        }

        if (s->avctx->intra_matrix)

            s->intra_matrix[j] = s->avctx->intra_matrix[i];

        if (s->avctx->inter_matrix)

            s->inter_matrix[j] = s->avctx->inter_matrix[i];

    }

    /* precompute matrix */

    /* for mjpeg, we do include qscale in the matrix */

    if (s->out_format != FMT_MJPEG) {

        ff_convert_matrix(&s->dsp, s->q_intra_matrix, s->q_intra_matrix16,

                          s->intra_matrix, s->intra_quant_bias, avctx->qmin,

                          31, 1);

        ff_convert_matrix(&s->dsp, s->q_inter_matrix, s->q_inter_matrix16,

                          s->inter_matrix, s->inter_quant_bias, avctx->qmin,

                          31, 0);

    }

    if (ff_rate_control_init(s) < 0)

        return -1;

#if FF_API_ERROR_RATE

    FF_DISABLE_DEPRECATION_WARNINGS

    if (avctx->error_rate)

        s->error_rate = avctx->error_rate;

    FF_ENABLE_DEPRECATION_WARNINGS;

#endif

    if (avctx->b_frame_strategy == 2) {

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

            s->tmp_frames[i] = av_frame_alloc();

            if (!s->tmp_frames[i])

                return AVERROR(ENOMEM);

            s->tmp_frames[i]->format = AV_PIX_FMT_YUV420P;

            s->tmp_frames[i]->width  = s->width  >> avctx->brd_scale;

            s->tmp_frames[i]->height = s->height >> avctx->brd_scale;

            ret = av_frame_get_buffer(s->tmp_frames[i], 32);

            if (ret < 0)

                return ret;

        }

    }

    return 0;

fail:

    ff_MPV_encode_end(avctx);

    return AVERROR_UNKNOWN;

}


static int remove_decoded_packets(AVFormatContext *ctx, int64_t scr){

//    MpegMuxContext *s = ctx->priv_data;

    int i;

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

        AVStream *st = ctx->streams[i];

        StreamInfo *stream = st->priv_data;

        PacketDesc *pkt_desc;

        while((pkt_desc= stream->predecode_packet)

              && scr > pkt_desc->dts){ //FIXME > vs >=

            if(stream->buffer_index < pkt_desc->size ||

               stream->predecode_packet == stream->premux_packet){

                av_log(ctx, AV_LOG_ERROR,

                       "buffer underflow i=%d bufi=%d size=%d\n",

                       i, stream->buffer_index, pkt_desc->size);

                break;

            }

            stream->buffer_index -= pkt_desc->size;

            stream->predecode_packet= pkt_desc->next;

            av_freep(&pkt_desc);

        }

    }

    return 0;

}


void gicv3_cpuif_update(GICv3CPUState *cs)
{
    /* Tell the CPU about its highest priority pending interrupt */
    int irqlevel = 0;
    int fiqlevel = 0;
    ARMCPU *cpu = ARM_CPU(cs->cpu);
    CPUARMState *env = &cpu->env;
    trace_gicv3_cpuif_update(gicv3_redist_affid(cs), cs->hppi.irq,
                             cs->hppi.grp, cs->hppi.prio);
    if (cs->hppi.grp == GICV3_G1 && !arm_feature(env, ARM_FEATURE_EL3)) {
        /* If a Security-enabled GIC sends a G1S interrupt to a
         * Security-disabled CPU, we must treat it as if it were G0.
         */
        cs->hppi.grp = GICV3_G0;
    }
    if (icc_hppi_can_preempt(cs)) {
        /* We have an interrupt: should we signal it as IRQ or FIQ?
         * This is described in the GICv3 spec section 4.6.2.
         */
        bool isfiq;
        switch (cs->hppi.grp) {
        case GICV3_G0:
            isfiq = true;
            break;
        case GICV3_G1:
            isfiq = (!arm_is_secure(env) ||
                     (arm_current_el(env) == 3 && arm_el_is_aa64(env, 3)));
            break;
        case GICV3_G1NS:
            isfiq = arm_is_secure(env);
            break;
        default:
            g_assert_not_reached();
        }
        if (isfiq) {
            fiqlevel = 1;
        } else {
            irqlevel = 1;
        }
    }
    trace_gicv3_cpuif_set_irqs(gicv3_redist_affid(cs), fiqlevel, irqlevel);
    qemu_set_irq(cs->parent_fiq, fiqlevel);
    qemu_set_irq(cs->parent_irq, irqlevel);
}


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

{

    VGAState *s = opaque;

    int is_vbe, i, ret;

    if (version_id > 2)

        return -EINVAL;

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

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

        if (ret < 0)

            return ret;

    }

    qemu_get_be32s(f, &s->latch);

    qemu_get_8s(f, &s->sr_index);

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

    qemu_get_8s(f, &s->gr_index);

    qemu_get_buffer(f, s->gr, 16);

    qemu_get_8s(f, &s->ar_index);

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

    s->ar_flip_flop=qemu_get_be32(f);

    qemu_get_8s(f, &s->cr_index);

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

    qemu_get_8s(f, &s->msr);

    qemu_get_8s(f, &s->fcr);

    qemu_get_8s(f, &s->st00);

    qemu_get_8s(f, &s->st01);

    qemu_get_8s(f, &s->dac_state);

    qemu_get_8s(f, &s->dac_sub_index);

    qemu_get_8s(f, &s->dac_read_index);

    qemu_get_8s(f, &s->dac_write_index);

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

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

    s->bank_offset=qemu_get_be32(f);

    is_vbe = qemu_get_byte(f);

#ifdef CONFIG_BOCHS_VBE

    if (!is_vbe)

        return -EINVAL;

    qemu_get_be16s(f, &s->vbe_index);

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

        qemu_get_be16s(f, &s->vbe_regs[i]);

    qemu_get_be32s(f, &s->vbe_start_addr);

    qemu_get_be32s(f, &s->vbe_line_offset);

    qemu_get_be32s(f, &s->vbe_bank_mask);

#else

    if (is_vbe)

        return -EINVAL;

#endif

    /* force refresh */

    s->graphic_mode = -1;

    return 0;

}


static uint64_t virtio_pci_common_read(void *opaque, hwaddr addr,

                                       unsigned size)

{

    VirtIOPCIProxy *proxy = opaque;

    VirtIODevice *vdev = virtio_bus_get_device(&proxy->bus);

    uint32_t val = 0;

    int i;

    switch (addr) {

    case VIRTIO_PCI_COMMON_DFSELECT:

        val = proxy->dfselect;

        break;

    case VIRTIO_PCI_COMMON_DF:

        if (proxy->dfselect <= 1) {

            val = vdev->host_features >> (32 * proxy->dfselect);

        }

        break;

    case VIRTIO_PCI_COMMON_GFSELECT:

        val = proxy->gfselect;

        break;

    case VIRTIO_PCI_COMMON_GF:

        if (proxy->gfselect <= ARRAY_SIZE(proxy->guest_features)) {

            val = proxy->guest_features[proxy->gfselect];

        }

        break;

    case VIRTIO_PCI_COMMON_MSIX:

        val = vdev->config_vector;

        break;

    case VIRTIO_PCI_COMMON_NUMQ:

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

            if (virtio_queue_get_num(vdev, i)) {

                val = i + 1;

            }

        }

        break;

    case VIRTIO_PCI_COMMON_STATUS:

        val = vdev->status;

        break;

    case VIRTIO_PCI_COMMON_CFGGENERATION:

        val = vdev->generation;

        break;

    case VIRTIO_PCI_COMMON_Q_SELECT:

        val = vdev->queue_sel;

        break;

    case VIRTIO_PCI_COMMON_Q_SIZE:

        val = virtio_queue_get_num(vdev, vdev->queue_sel);

        break;

    case VIRTIO_PCI_COMMON_Q_MSIX:

        val = virtio_queue_vector(vdev, vdev->queue_sel);

        break;

    case VIRTIO_PCI_COMMON_Q_ENABLE:

        val = proxy->vqs[vdev->queue_sel].enabled;

        break;

    case VIRTIO_PCI_COMMON_Q_NOFF:

        /* Simply map queues in order */

        val = vdev->queue_sel;

        break;

    case VIRTIO_PCI_COMMON_Q_DESCLO:

        val = proxy->vqs[vdev->queue_sel].desc[0];

        break;

    case VIRTIO_PCI_COMMON_Q_DESCHI:

        val = proxy->vqs[vdev->queue_sel].desc[1];

        break;

    case VIRTIO_PCI_COMMON_Q_AVAILLO:

        val = proxy->vqs[vdev->queue_sel].avail[0];

        break;

    case VIRTIO_PCI_COMMON_Q_AVAILHI:

        val = proxy->vqs[vdev->queue_sel].avail[1];

        break;

    case VIRTIO_PCI_COMMON_Q_USEDLO:

        val = proxy->vqs[vdev->queue_sel].used[0];

        break;

    case VIRTIO_PCI_COMMON_Q_USEDHI:

        val = proxy->vqs[vdev->queue_sel].used[1];

        break;

    default:

        val = 0;

    }

    return val;

}


void virtio_scsi_handle_cmd_req_submit(VirtIOSCSI *s, VirtIOSCSIReq *req)

{

    if (scsi_req_enqueue(req->sreq)) {

        scsi_req_continue(req->sreq);

    }

    bdrv_io_unplug(req->sreq->dev->conf.bs);

    scsi_req_unref(req->sreq);

}


static int init_poc(H264Context *h){

    MpegEncContext * const s = &h->s;

    const int max_frame_num= 1<<h->sps.log2_max_frame_num;

    int field_poc[2];

    if(h->nal_unit_type == NAL_IDR_SLICE){

        h->frame_num_offset= 0;

    }else{

        if(h->frame_num < h->prev_frame_num)

            h->frame_num_offset= h->prev_frame_num_offset + max_frame_num;

        else

            h->frame_num_offset= h->prev_frame_num_offset;

    }

    if(h->sps.poc_type==0){

        const int max_poc_lsb= 1<<h->sps.log2_max_poc_lsb;

        if(h->nal_unit_type == NAL_IDR_SLICE){

             h->prev_poc_msb=

             h->prev_poc_lsb= 0;

        }

        if     (h->poc_lsb < h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb >= max_poc_lsb/2)

            h->poc_msb = h->prev_poc_msb + max_poc_lsb;

        else if(h->poc_lsb > h->prev_poc_lsb && h->prev_poc_lsb - h->poc_lsb < -max_poc_lsb/2)

            h->poc_msb = h->prev_poc_msb - max_poc_lsb;

        else

            h->poc_msb = h->prev_poc_msb;

//printf("poc: %d %d\n", h->poc_msb, h->poc_lsb);

        field_poc[0] =

        field_poc[1] = h->poc_msb + h->poc_lsb;

        if(s->picture_structure == PICT_FRAME)

            field_poc[1] += h->delta_poc_bottom;

    }else if(h->sps.poc_type==1){

        int abs_frame_num, expected_delta_per_poc_cycle, expectedpoc;

        int i;

        if(h->sps.poc_cycle_length != 0)

            abs_frame_num = h->frame_num_offset + h->frame_num;

        else

            abs_frame_num = 0;

        if(h->nal_ref_idc==0 && abs_frame_num > 0)

            abs_frame_num--;

        expected_delta_per_poc_cycle = 0;

        for(i=0; i < h->sps.poc_cycle_length; i++)

            expected_delta_per_poc_cycle += h->sps.offset_for_ref_frame[ i ]; //FIXME integrate during sps parse

        if(abs_frame_num > 0){

            int poc_cycle_cnt          = (abs_frame_num - 1) / h->sps.poc_cycle_length;

            int frame_num_in_poc_cycle = (abs_frame_num - 1) % h->sps.poc_cycle_length;

            expectedpoc = poc_cycle_cnt * expected_delta_per_poc_cycle;

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

                expectedpoc = expectedpoc + h->sps.offset_for_ref_frame[ i ];

        } else

            expectedpoc = 0;

        if(h->nal_ref_idc == 0)

            expectedpoc = expectedpoc + h->sps.offset_for_non_ref_pic;

        field_poc[0] = expectedpoc + h->delta_poc[0];

        field_poc[1] = field_poc[0] + h->sps.offset_for_top_to_bottom_field;

        if(s->picture_structure == PICT_FRAME)

            field_poc[1] += h->delta_poc[1];

    }else{

        int poc;

        if(h->nal_unit_type == NAL_IDR_SLICE){

            poc= 0;

        }else{

            if(h->nal_ref_idc) poc= 2*(h->frame_num_offset + h->frame_num);

            else               poc= 2*(h->frame_num_offset + h->frame_num) - 1;

        }

        field_poc[0]= poc;

        field_poc[1]= poc;

    }

    if(s->picture_structure != PICT_BOTTOM_FIELD)

        s->current_picture_ptr->field_poc[0]= field_poc[0];

    if(s->picture_structure != PICT_TOP_FIELD)

        s->current_picture_ptr->field_poc[1]= field_poc[1];

    if(s->picture_structure == PICT_FRAME) // FIXME field pix?

        s->current_picture_ptr->poc= FFMIN(field_poc[0], field_poc[1]);

    return 0;

}


static void FUNCC(pred8x16_horizontal_add)(uint8_t *pix,

                                           const int *block_offset,

                                           const int16_t *block, ptrdiff_t stride)

{

    int i;

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

        FUNCC(pred4x4_horizontal_add)(pix + block_offset[i], block + i*16*sizeof(pixel), stride);

    for(i=4; i<8; i++)

        FUNCC(pred4x4_horizontal_add)(pix + block_offset[i+4], block + i*16*sizeof(pixel), stride);

}


static void seek_to_maindata(MPADecodeContext *s, long backstep)

{

    UINT8 *ptr;

    /* compute current position in stream */

    ptr = s->gb.buffer + (get_bits_count(&s->gb)>>3);

    /* copy old data before current one */

    ptr -= backstep;

    memcpy(ptr, s->inbuf1[s->inbuf_index ^ 1] +

           BACKSTEP_SIZE + s->old_frame_size - backstep, backstep);

    /* init get bits again */

    init_get_bits(&s->gb, ptr, s->frame_size + backstep);

    /* prepare next buffer */

    s->inbuf_index ^= 1;

    s->inbuf = &s->inbuf1[s->inbuf_index][BACKSTEP_SIZE];

    s->old_frame_size = s->frame_size;

}


static int codec_get_buffer(AVCodecContext *s, AVFrame *frame)

{

    InputStream *ist = s->opaque;

    FrameBuffer *buf;

    int ret, i;

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

        return -1;

    if (!ist->buffer_pool && (ret = alloc_buffer(s, ist, &ist->buffer_pool)) < 0)

        return ret;

    buf              = ist->buffer_pool;

    ist->buffer_pool = buf->next;

    buf->next        = NULL;

    if (buf->w != s->width || buf->h != s->height || buf->pix_fmt != s->pix_fmt) {

        av_freep(&buf->base[0]);

        av_free(buf);

        ist->dr1 = 0;

        if ((ret = alloc_buffer(s, ist, &buf)) < 0)

            return ret;

    }

    buf->refcount++;

    frame->opaque        = buf;

    frame->type          = FF_BUFFER_TYPE_USER;

    frame->extended_data = frame->data;

    frame->pkt_pts       = s->pkt ? s->pkt->pts : AV_NOPTS_VALUE;

    for (i = 0; i < FF_ARRAY_ELEMS(buf->data); i++) {

        frame->base[i]     = buf->base[i];  // XXX h264.c uses base though it shouldn't

        frame->data[i]     = buf->data[i];

        frame->linesize[i] = buf->linesize[i];

    }

    return 0;

}


static void json_print_int(WriterContext *wctx, const char *key, int value)

{

    char *key_esc = json_escape_str(key);

    if (wctx->nb_item) printf(",\n");

    printf(INDENT "\"%s\": %d", key_esc ? key_esc : "", value);

    av_free(key_esc);

}


int kvm_update_guest_debug(CPUState *env, unsigned long reinject_trap)

{

    struct kvm_set_guest_debug_data data;

    data.dbg.control = 0;

    if (env->singlestep_enabled)

        data.dbg.control = KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP;

    kvm_arch_update_guest_debug(env, &data.dbg);

    data.dbg.control |= reinject_trap;

    data.env = env;

    on_vcpu(env, kvm_invoke_set_guest_debug, &data);

    return data.err;

}


static bool qapi_dealloc_start_union(Visitor *v, bool data_present,

                                     Error **errp)

{

    return data_present;

}


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

{

    SPARCCPUClass *scc = SPARC_CPU_CLASS(oc);

    CPUClass *cc = CPU_CLASS(oc);

    DeviceClass *dc = DEVICE_CLASS(oc);

    scc->parent_realize = dc->realize;

    dc->realize = sparc_cpu_realizefn;

    scc->parent_reset = cc->reset;

    cc->reset = sparc_cpu_reset;

    cc->has_work = sparc_cpu_has_work;

    cc->do_interrupt = sparc_cpu_do_interrupt;

    cc->cpu_exec_interrupt = sparc_cpu_exec_interrupt;

    cc->dump_state = sparc_cpu_dump_state;

#if !defined(TARGET_SPARC64) && !defined(CONFIG_USER_ONLY)

    cc->memory_rw_debug = sparc_cpu_memory_rw_debug;

#endif

    cc->set_pc = sparc_cpu_set_pc;

    cc->synchronize_from_tb = sparc_cpu_synchronize_from_tb;

    cc->gdb_read_register = sparc_cpu_gdb_read_register;

    cc->gdb_write_register = sparc_cpu_gdb_write_register;

#ifdef CONFIG_USER_ONLY

    cc->handle_mmu_fault = sparc_cpu_handle_mmu_fault;

#else

    cc->do_unassigned_access = sparc_cpu_unassigned_access;

    cc->do_unaligned_access = sparc_cpu_do_unaligned_access;

    cc->get_phys_page_debug = sparc_cpu_get_phys_page_debug;

    cc->vmsd = &vmstate_sparc_cpu;

#endif

    cc->disas_set_info = cpu_sparc_disas_set_info;

#if defined(TARGET_SPARC64) && !defined(TARGET_ABI32)

    cc->gdb_num_core_regs = 86;

#else

    cc->gdb_num_core_regs = 72;

#endif

    /*

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

     * the object in cpus -> dangling pointer after final

     * object_unref().

     */

    dc->cannot_destroy_with_object_finalize_yet = true;

}


QList *qdict_get_qlist(const QDict *qdict, const char *key)

{

    return qobject_to_qlist(qdict_get_obj(qdict, key, QTYPE_QLIST));

}


static inline void RENAME(yuv2packed1)(SwsContext *c, uint16_t *buf0, uint16_t *uvbuf0, uint16_t *uvbuf1,

			    uint8_t *dest, int dstW, int uvalpha, int dstFormat, int flags, int y)

{

	const int yalpha1=0;

	int i;

	uint16_t *buf1= buf0; //FIXME needed for the rgb1/bgr1

	const int yalpha= 4096; //FIXME ...

	if(flags&SWS_FULL_CHR_H_INT)

	{

		RENAME(yuv2packed2)(c, buf0, buf0, uvbuf0, uvbuf1, dest, dstW, 0, uvalpha, y);

		return;

	}

#ifdef HAVE_MMX

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

	{

		switch(dstFormat)

		{

		case PIX_FMT_RGB32:

			asm volatile(

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

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

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

				YSCALEYUV2RGB1(%%REGBP, %5)

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

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

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

			:: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),

			"a" (&c->redDither)

			);

			return;

		case PIX_FMT_BGR24:

			asm volatile(

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

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

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

				YSCALEYUV2RGB1(%%REGBP, %5)

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

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

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

			:: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),

			"a" (&c->redDither)

			);

			return;

		case PIX_FMT_BGR555:

			asm volatile(

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

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

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

				YSCALEYUV2RGB1(%%REGBP, %5)

		/* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */

#ifdef DITHER1XBPP

				"paddusb "MANGLE(b5Dither)", %%mm2\n\t"

				"paddusb "MANGLE(g5Dither)", %%mm4\n\t"

				"paddusb "MANGLE(r5Dither)", %%mm5\n\t"

#endif

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

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

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

			:: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),

			"a" (&c->redDither)

			);

			return;

		case PIX_FMT_BGR565:

			asm volatile(

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

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

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

				YSCALEYUV2RGB1(%%REGBP, %5)

		/* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */

#ifdef DITHER1XBPP

				"paddusb "MANGLE(b5Dither)", %%mm2\n\t"

				"paddusb "MANGLE(g6Dither)", %%mm4\n\t"

				"paddusb "MANGLE(r5Dither)", %%mm5\n\t"

#endif

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

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

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

			:: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),

			"a" (&c->redDither)

			);

			return;

		case PIX_FMT_YUYV422:

			asm volatile(

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

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

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

				YSCALEYUV2PACKED1(%%REGBP, %5)

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

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

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

			:: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),

			"a" (&c->redDither)

			);

			return;

		}

	}

	else

	{

		switch(dstFormat)

		{

		case PIX_FMT_RGB32:

			asm volatile(

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

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

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

				YSCALEYUV2RGB1b(%%REGBP, %5)

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

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

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

			:: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),

			"a" (&c->redDither)

			);

			return;

		case PIX_FMT_BGR24:

			asm volatile(

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

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

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

				YSCALEYUV2RGB1b(%%REGBP, %5)

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

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

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

			:: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),

			"a" (&c->redDither)

			);

			return;

		case PIX_FMT_BGR555:

			asm volatile(

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

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

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

				YSCALEYUV2RGB1b(%%REGBP, %5)

		/* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */

#ifdef DITHER1XBPP

				"paddusb "MANGLE(b5Dither)", %%mm2\n\t"

				"paddusb "MANGLE(g5Dither)", %%mm4\n\t"

				"paddusb "MANGLE(r5Dither)", %%mm5\n\t"

#endif

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

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

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

			:: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),

			"a" (&c->redDither)

			);

			return;

		case PIX_FMT_BGR565:

			asm volatile(

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

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

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

				YSCALEYUV2RGB1b(%%REGBP, %5)

		/* mm2=B, %%mm4=G, %%mm5=R, %%mm7=0 */

#ifdef DITHER1XBPP

				"paddusb "MANGLE(b5Dither)", %%mm2\n\t"

				"paddusb "MANGLE(g6Dither)", %%mm4\n\t"

				"paddusb "MANGLE(r5Dither)", %%mm5\n\t"

#endif

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

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

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

			:: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),

			"a" (&c->redDither)

			);

			return;

		case PIX_FMT_YUYV422:

			asm volatile(

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

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

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

				YSCALEYUV2PACKED1b(%%REGBP, %5)

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

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

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

			:: "c" (buf0), "d" (buf1), "S" (uvbuf0), "D" (uvbuf1), "m" (dest),

			"a" (&c->redDither)

			);

			return;

		}

	}

#endif

	if( uvalpha < 2048 )

	{

		YSCALE_YUV_2_ANYRGB_C(YSCALE_YUV_2_RGB1_C, YSCALE_YUV_2_PACKED1_C)

	}else{

		YSCALE_YUV_2_ANYRGB_C(YSCALE_YUV_2_RGB1B_C, YSCALE_YUV_2_PACKED1B_C)

	}

}


static inline void RENAME(uyvyToUV)(uint8_t *dstU, uint8_t *dstV, const uint8_t *src1, const uint8_t *src2, long width, uint32_t *unused)

{

#if COMPILE_TEMPLATE_MMX

    __asm__ volatile(

        "movq "MANGLE(bm01010101)", %%mm4           \n\t"

        "mov                    %0, %%"REG_a"       \n\t"

        "1:                                         \n\t"

        "movq    (%1, %%"REG_a",4), %%mm0           \n\t"

        "movq   8(%1, %%"REG_a",4), %%mm1           \n\t"

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

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

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

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

        "psrlw                  $8, %%mm0           \n\t"

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

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

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

        "movd                %%mm0, (%3, %%"REG_a") \n\t"

        "movd                %%mm1, (%2, %%"REG_a") \n\t"

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

        " js                    1b                  \n\t"

        : : "g" ((x86_reg)-width), "r" (src1+width*4), "r" (dstU+width), "r" (dstV+width)

        : "%"REG_a

    );

#else

    int i;

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

        dstU[i]= src1[4*i + 0];

        dstV[i]= src1[4*i + 2];

    }

#endif

    assert(src1 == src2);

}


static int concat_read_packet(AVFormatContext *avf, AVPacket *pkt)

{

    ConcatContext *cat = avf->priv_data;

    int ret;

    int64_t delta;

    ConcatStream *cs;

    while (1) {

        ret = av_read_frame(cat->avf, pkt);

        if (ret == AVERROR_EOF) {

            if ((ret = open_next_file(avf)) < 0)

                return ret;

            continue;

        }

        if (ret < 0)

            return ret;

        if (cat->match_streams) {

            match_streams(avf);

            cs = &cat->cur_file->streams[pkt->stream_index];

            if (cs->out_stream_index < 0) {

                av_packet_unref(pkt);

                continue;

            }

            pkt->stream_index = cs->out_stream_index;

        }

        break;

    }

    delta = av_rescale_q(cat->cur_file->start_time - cat->avf->start_time,

                         AV_TIME_BASE_Q,

                         cat->avf->streams[pkt->stream_index]->time_base);

    if (pkt->pts != AV_NOPTS_VALUE)

        pkt->pts += delta;

    if (pkt->dts != AV_NOPTS_VALUE)

        pkt->dts += delta;

    return ret;

}


static int dxa_probe(AVProbeData *p)

{

    /* check file header */

    if (p->buf_size <= 4)

        return 0;

    if (p->buf[0] == 'D' && p->buf[1] == 'E' &&

        p->buf[2] == 'X' && p->buf[3] == 'A')

        return AVPROBE_SCORE_MAX;

    else

        return 0;

}


static PCIDevice *qemu_pci_hot_add_nic(Monitor *mon,

                                       const char *devaddr,

                                       const char *opts_str)

{

    Error *local_err = NULL;

    QemuOpts *opts;

    PCIBus *bus;

    int ret, devfn;

    bus = pci_get_bus_devfn(&devfn, devaddr);

    if (!bus) {

        monitor_printf(mon, "Invalid PCI device address %s\n", devaddr);

        return NULL;

    }

    if (!((BusState*)bus)->allow_hotplug) {

        monitor_printf(mon, "PCI bus doesn't support hotplug\n");

        return NULL;

    }

    opts = qemu_opts_parse(qemu_find_opts("net"), opts_str ? opts_str : "", 0);

    if (!opts) {

        return NULL;

    }

    qemu_opt_set(opts, "type", "nic");

    ret = net_client_init(opts, 0, &local_err);

    if (error_is_set(&local_err)) {

        qerror_report_err(local_err);

        error_free(local_err);

        return NULL;

    }

    if (nd_table[ret].devaddr) {

        monitor_printf(mon, "Parameter addr not supported\n");

        return NULL;

    }

    return pci_nic_init(&nd_table[ret], "rtl8139", devaddr);

}


static void glib_select_fill(int *max_fd, fd_set *rfds, fd_set *wfds,

                             fd_set *xfds, uint32_t *cur_timeout)

{

    GMainContext *context = g_main_context_default();

    int i;

    int timeout = 0;

    g_main_context_prepare(context, &max_priority);

    n_poll_fds = g_main_context_query(context, max_priority, &timeout,

                                      poll_fds, ARRAY_SIZE(poll_fds));

    g_assert(n_poll_fds <= ARRAY_SIZE(poll_fds));

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

        GPollFD *p = &poll_fds[i];

        if ((p->events & G_IO_IN)) {

            FD_SET(p->fd, rfds);

            *max_fd = MAX(*max_fd, p->fd);

        }

        if ((p->events & G_IO_OUT)) {

            FD_SET(p->fd, wfds);

            *max_fd = MAX(*max_fd, p->fd);

        }

        if ((p->events & G_IO_ERR)) {

            FD_SET(p->fd, xfds);

            *max_fd = MAX(*max_fd, p->fd);

        }

    }

    if (timeout >= 0 && timeout < *cur_timeout) {

        *cur_timeout = timeout;

    }

}


static void suspend_request(BlockDriverState *bs, BlkdebugRule *rule)

{

    BDRVBlkdebugState *s = bs->opaque;

    BlkdebugSuspendedReq r;

    r = (BlkdebugSuspendedReq) {

        .co         = qemu_coroutine_self(),

        .tag        = g_strdup(rule->options.suspend.tag),

    };

    remove_rule(rule);

    QLIST_INSERT_HEAD(&s->suspended_reqs, &r, next);

    printf("blkdebug: Suspended request '%s'\n", r.tag);

    qemu_coroutine_yield();

    printf("blkdebug: Resuming request '%s'\n", r.tag);

    QLIST_REMOVE(&r, next);

    g_free(r.tag);

}


int qmp_pc_dimm_device_list(Object *obj, void *opaque)

{

    MemoryDeviceInfoList ***prev = opaque;

    if (object_dynamic_cast(obj, TYPE_PC_DIMM)) {

        DeviceState *dev = DEVICE(obj);

        if (dev->realized) {

            MemoryDeviceInfoList *elem = g_new0(MemoryDeviceInfoList, 1);

            MemoryDeviceInfo *info = g_new0(MemoryDeviceInfo, 1);

            PCDIMMDeviceInfo *di = g_new0(PCDIMMDeviceInfo, 1);

            DeviceClass *dc = DEVICE_GET_CLASS(obj);

            PCDIMMDevice *dimm = PC_DIMM(obj);

            if (dev->id) {

                di->has_id = true;

                di->id = g_strdup(dev->id);

            }

            di->hotplugged = dev->hotplugged;

            di->hotpluggable = dc->hotpluggable;

            di->addr = dimm->addr;

            di->slot = dimm->slot;

            di->node = dimm->node;

            di->size = object_property_get_int(OBJECT(dimm), PC_DIMM_SIZE_PROP,

                                               NULL);

            di->memdev = object_get_canonical_path(OBJECT(dimm->hostmem));

            info->dimm = di;

            elem->value = info;

            elem->next = NULL;

            **prev = elem;

            *prev = &elem->next;

        }

    }

    object_child_foreach(obj, qmp_pc_dimm_device_list, opaque);

    return 0;

}


static void cmd_args_init(CmdArgs *cmd_args)

{

    cmd_args->name = qstring_new();

    cmd_args->type = cmd_args->flag = cmd_args->optional = 0;

}