static int pte64_check(struct mmu_ctx_hash64 *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 & HPTE64_V_VALID) && (h == !!(pte0 & HPTE64_V_SECONDARY))) {

        bool nx;

        /* Check vsid & api */

        mmask = PTE64_CHECK_MASK;

        pp = (pte1 & HPTE64_R_PP) | ((pte1 & HPTE64_R_PP0) >> 61);

        /* No execute if either noexec or guarded bits set */

        nx = (pte1 & HPTE64_R_N) || (pte1 & HPTE64_R_G);

        if (HPTE64_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_hash64_pp_check(ctx->key, pp, nx);

            /* Keep the matching PTE informations */

            ctx->raddr = pte1;

            ctx->prot = access;

            ret = ppc_hash64_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 uint64_t bmdma_addr_read(void *opaque, target_phys_addr_t addr,

                                unsigned width)

{

    BMDMAState *bm = opaque;

    uint32_t mask = (1ULL << (width * 8)) - 1;

    uint64_t data;

    data = (bm->addr >> (addr * 8)) & mask;

#ifdef DEBUG_IDE

    printf("%s: 0x%08x\n", __func__, (unsigned)*data);

#endif

    return data;

}


static void qerror_abort(const QError *qerr, const char *fmt, ...)

{

    va_list ap;

    fprintf(stderr, "qerror: bad call in function '%s':\n", qerr->func);

    fprintf(stderr, "qerror: -> ");

    va_start(ap, fmt);

    vfprintf(stderr, fmt, ap);

    va_end(ap);

    fprintf(stderr, "\nqerror: call at %s:%d\n", qerr->file, qerr->linenr);

    abort();

}


static void gen_nabs(DisasContext *ctx)

{

    int l1 = gen_new_label();

    int l2 = gen_new_label();

    tcg_gen_brcondi_tl(TCG_COND_GT, cpu_gpr[rA(ctx->opcode)], 0, l1);

    tcg_gen_mov_tl(cpu_gpr[rD(ctx->opcode)], cpu_gpr[rA(ctx->opcode)]);

    tcg_gen_br(l2);

    gen_set_label(l1);

    tcg_gen_neg_tl(cpu_gpr[rD(ctx->opcode)], cpu_gpr[rA(ctx->opcode)]);

    gen_set_label(l2);

    if (unlikely(Rc(ctx->opcode) != 0))

        gen_set_Rc0(ctx, cpu_gpr[rD(ctx->opcode)]);

}


static void vtd_iotlb_page_invalidate(IntelIOMMUState *s, uint16_t domain_id,

                                      hwaddr addr, uint8_t am)

{

    VTDIOTLBPageInvInfo info;

    assert(am <= VTD_MAMV);

    info.domain_id = domain_id;

    info.gfn = addr >> VTD_PAGE_SHIFT_4K;

    info.mask = ~((1 << am) - 1);

    g_hash_table_foreach_remove(s->iotlb, vtd_hash_remove_by_page, &info);

}


static void sh_serial_write(void *opaque, hwaddr offs,

                            uint64_t val, unsigned size)

{

    sh_serial_state *s = opaque;

    unsigned char ch;

#ifdef DEBUG_SERIAL

    printf("sh_serial: write offs=0x%02x val=0x%02x\n",

	   offs, val);

#endif

    switch(offs) {

    case 0x00: /* SMR */

        s->smr = val & ((s->feat & SH_SERIAL_FEAT_SCIF) ? 0x7b : 0xff);

        return;

    case 0x04: /* BRR */

        s->brr = val;

	return;

    case 0x08: /* SCR */

        /* TODO : For SH7751, SCIF mask should be 0xfb. */

        s->scr = val & ((s->feat & SH_SERIAL_FEAT_SCIF) ? 0xfa : 0xff);

        if (!(val & (1 << 5)))

            s->flags |= SH_SERIAL_FLAG_TEND;

        if ((s->feat & SH_SERIAL_FEAT_SCIF) && s->txi) {

	    qemu_set_irq(s->txi, val & (1 << 7));

        }

        if (!(val & (1 << 6))) {

	    qemu_set_irq(s->rxi, 0);

        }

        return;

    case 0x0c: /* FTDR / TDR */

        if (s->chr) {

            ch = val;

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

	}

	s->dr = val;

	s->flags &= ~SH_SERIAL_FLAG_TDE;

        return;

#if 0

    case 0x14: /* FRDR / RDR */

        ret = 0;

        break;

#endif

    }

    if (s->feat & SH_SERIAL_FEAT_SCIF) {

        switch(offs) {

        case 0x10: /* FSR */

            if (!(val & (1 << 6)))

                s->flags &= ~SH_SERIAL_FLAG_TEND;

            if (!(val & (1 << 5)))

                s->flags &= ~SH_SERIAL_FLAG_TDE;

            if (!(val & (1 << 4)))

                s->flags &= ~SH_SERIAL_FLAG_BRK;

            if (!(val & (1 << 1)))

                s->flags &= ~SH_SERIAL_FLAG_RDF;

            if (!(val & (1 << 0)))

                s->flags &= ~SH_SERIAL_FLAG_DR;

            if (!(val & (1 << 1)) || !(val & (1 << 0))) {

                if (s->rxi) {

                    qemu_set_irq(s->rxi, 0);

                }

            }

            return;

        case 0x18: /* FCR */

            s->fcr = val;

            switch ((val >> 6) & 3) {

            case 0:

                s->rtrg = 1;

                break;

            case 1:

                s->rtrg = 4;

                break;

            case 2:

                s->rtrg = 8;

                break;

            case 3:

                s->rtrg = 14;

                break;

            }

            if (val & (1 << 1)) {

                sh_serial_clear_fifo(s);

                s->sr &= ~(1 << 1);

            }

            return;

        case 0x20: /* SPTR */

            s->sptr = val & 0xf3;

            return;

        case 0x24: /* LSR */

            return;

        }

    }

    else {

        switch(offs) {

#if 0

        case 0x0c:

            ret = s->dr;

            break;

        case 0x10:

            ret = 0;

            break;

#endif

        case 0x1c:

            s->sptr = val & 0x8f;

            return;

        }

    }

    fprintf(stderr, "sh_serial: unsupported write to 0x%02"

            HWADDR_PRIx "\n", offs);

    abort();

}


void qmp_x_input_send_event(bool has_console, int64_t console,

                            InputEventList *events, Error **errp)

{

    InputEventList *e;

    QemuConsole *con;

    con = NULL;

    if (has_console) {

        con = qemu_console_lookup_by_index(console);

        if (!con) {

            error_setg(errp, "console %" PRId64 " not found", console);

            return;

        }

    }

    if (!runstate_is_running() && !runstate_check(RUN_STATE_SUSPENDED)) {

        error_setg(errp, "VM not running");

        return;

    }

    for (e = events; e != NULL; e = e->next) {

        InputEvent *event = e->value;

        if (!qemu_input_find_handler(1 << event->kind, con)) {

            error_setg(errp, "Input handler not found for "

                             "event type %s",

                            InputEventKind_lookup[event->kind]);

            return;

        }

    }

    for (e = events; e != NULL; e = e->next) {

        InputEvent *event = e->value;

        qemu_input_event_send(con, event);

    }

    qemu_input_event_sync();

}


static int scsi_event_status_media(SCSIDiskState *s, uint8_t *outbuf)

{

    uint8_t event_code, media_status;

    media_status = 0;

    if (s->tray_open) {

        media_status = MS_TRAY_OPEN;

    } else if (bdrv_is_inserted(s->qdev.conf.bs)) {

        media_status = MS_MEDIA_PRESENT;

    }

    /* Event notification descriptor */

    event_code = MEC_NO_CHANGE;

    if (media_status != MS_TRAY_OPEN) {

        if (s->media_event) {

            event_code = MEC_NEW_MEDIA;

            s->media_event = false;

        } else if (s->eject_request) {

            event_code = MEC_EJECT_REQUESTED;

            s->eject_request = false;

        }

    }

    outbuf[0] = event_code;

    outbuf[1] = media_status;

    /* These fields are reserved, just clear them. */

    outbuf[2] = 0;

    outbuf[3] = 0;

    return 4;

}


static av_cold int targa_encode_init(AVCodecContext *avctx)

{

    avctx->coded_frame = av_frame_alloc();

    if (!avctx->coded_frame)

        return AVERROR(ENOMEM);

    avctx->coded_frame->key_frame = 1;

    avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;

    return 0;

}


void qapi_dealloc_visitor_cleanup(QapiDeallocVisitor *v)

{

    g_free(v);

}


static void imx25_pdk_init(MachineState *machine)

{

    IMX25PDK *s = g_new0(IMX25PDK, 1);

    unsigned int ram_size;

    unsigned int alias_offset;

    int i;

    object_initialize(&s->soc, sizeof(s->soc), TYPE_FSL_IMX25);

    object_property_add_child(OBJECT(machine), "soc", OBJECT(&s->soc),

                              &error_abort);

    object_property_set_bool(OBJECT(&s->soc), true, "realized", &error_fatal);

    /* We need to initialize our memory */

    if (machine->ram_size > (FSL_IMX25_SDRAM0_SIZE + FSL_IMX25_SDRAM1_SIZE)) {

        error_report("WARNING: RAM size " RAM_ADDR_FMT " above max supported, "

                     "reduced to %x", machine->ram_size,

                     FSL_IMX25_SDRAM0_SIZE + FSL_IMX25_SDRAM1_SIZE);

        machine->ram_size = FSL_IMX25_SDRAM0_SIZE + FSL_IMX25_SDRAM1_SIZE;

    }

    memory_region_allocate_system_memory(&s->ram, NULL, "imx25.ram",

                                         machine->ram_size);

    memory_region_add_subregion(get_system_memory(), FSL_IMX25_SDRAM0_ADDR,

                                &s->ram);

    /* initialize the alias memory if any */

    for (i = 0, ram_size = machine->ram_size, alias_offset = 0;

         (i < 2) && ram_size; i++) {

        unsigned int size;

        static const struct {

            hwaddr addr;

            unsigned int size;

        } ram[2] = {

            { FSL_IMX25_SDRAM0_ADDR, FSL_IMX25_SDRAM0_SIZE },

            { FSL_IMX25_SDRAM1_ADDR, FSL_IMX25_SDRAM1_SIZE },

        };

        size = MIN(ram_size, ram[i].size);

        ram_size -= size;

        if (size < ram[i].size) {

            memory_region_init_alias(&s->ram_alias, NULL, "ram.alias",

                                     &s->ram, alias_offset, ram[i].size - size);

            memory_region_add_subregion(get_system_memory(),

                                        ram[i].addr + size, &s->ram_alias);

        }

        alias_offset += ram[i].size;

    }

    imx25_pdk_binfo.ram_size = machine->ram_size;

    imx25_pdk_binfo.kernel_filename = machine->kernel_filename;

    imx25_pdk_binfo.kernel_cmdline = machine->kernel_cmdline;

    imx25_pdk_binfo.initrd_filename = machine->initrd_filename;

    imx25_pdk_binfo.loader_start = FSL_IMX25_SDRAM0_ADDR;

    imx25_pdk_binfo.board_id = 1771,

    imx25_pdk_binfo.nb_cpus = 1;

    /*

     * We test explicitly for qtest here as it is not done (yet?) in

     * arm_load_kernel(). Without this the "make check" command would

     * fail.

     */

    if (!qtest_enabled()) {

        arm_load_kernel(&s->soc.cpu, &imx25_pdk_binfo);

    } else {

        /*

         * This I2C device doesn't exist on the real board.

         * We add it here (only on qtest usage) to be able to do a bit

         * of simple qtest. See "make check" for details.

         */

        i2c_create_slave((I2CBus *)qdev_get_child_bus(DEVICE(&s->soc.i2c[0]),

                                                      "i2c-bus.0"),

                         "ds1338", 0x68);

    }

}


static void gd_ungrab_pointer(GtkDisplayState *s)

{

#if GTK_CHECK_VERSION(3, 0, 0)

    GdkDisplay *display = gtk_widget_get_display(s->drawing_area);

    GdkDeviceManager *mgr = gdk_display_get_device_manager(display);

    GList *devices = gdk_device_manager_list_devices(mgr,

                                                     GDK_DEVICE_TYPE_MASTER);

    GList *tmp = devices;

    while (tmp) {

        GdkDevice *dev = tmp->data;

        if (gdk_device_get_source(dev) == GDK_SOURCE_MOUSE) {

            gdk_device_ungrab(dev,

                              GDK_CURRENT_TIME);

        }

        tmp = tmp->next;

    }

    g_list_free(devices);

#else

    gdk_pointer_ungrab(GDK_CURRENT_TIME);

#endif

}


void machine_register_compat_props(MachineState *machine)

{

    MachineClass *mc = MACHINE_GET_CLASS(machine);

    int i;

    GlobalProperty *p;

    if (!mc->compat_props) {

        return;

    }

    for (i = 0; i < mc->compat_props->len; i++) {

        p = g_array_index(mc->compat_props, GlobalProperty *, i);

        qdev_prop_register_global(p);

    }

}


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

                             int *got_frame, AVPacket *avpkt)

{

    AVFrame *pic = data;

    const uint16_t *src = (uint16_t *)avpkt->data;

    uint16_t *y, *u, *v, aligned_width = FFALIGN(avctx->width, 4);

    int i, j, ret;

    if (avpkt->size < 4 * avctx->height * aligned_width) {

        av_log(avctx, AV_LOG_ERROR, "Insufficient input data.\n");

        return AVERROR(EINVAL);

    }

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

        return ret;

    pic->key_frame = 1;

    pic->pict_type = AV_PICTURE_TYPE_I;

    y = (uint16_t *)pic->data[0];

    u = (uint16_t *)pic->data[1];

    v = (uint16_t *)pic->data[2];

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

        for (j = 0; j < avctx->width >> 1; j++) {

            u[    j    ] = src[4 * j    ] << 2 | src[4 * j    ] >> 14;

            y[2 * j    ] = src[4 * j + 1] << 2 | src[4 * j + 1] >> 14;

            v[    j    ] = src[4 * j + 2] << 2 | src[4 * j + 2] >> 14;

            y[2 * j + 1] = src[4 * j + 3] << 2 | src[4 * j + 3] >> 14;

        }

        y += pic->linesize[0] >> 1;

        u += pic->linesize[1] >> 1;

        v += pic->linesize[2] >> 1;

        src += aligned_width << 1;

    }

    *got_frame = 1;

    return avpkt->size;

}


static void nbd_coroutine_start(NbdClientSession *s,

   struct nbd_request *request)

{

    /* Poor man semaphore.  The free_sema is locked when no other request

     * can be accepted, and unlocked after receiving one reply.  */

    if (s->in_flight >= MAX_NBD_REQUESTS - 1) {

        qemu_co_mutex_lock(&s->free_sema);

        assert(s->in_flight < MAX_NBD_REQUESTS);

    }

    s->in_flight++;

    /* s->recv_coroutine[i] is set as soon as we get the send_lock.  */

}


void vga_init(VGAState *s)

{

    int vga_io_memory;

    register_savevm("vga", 0, 2, vga_save, vga_load, s);

    register_ioport_write(0x3c0, 16, 1, vga_ioport_write, s);

    register_ioport_write(0x3b4, 2, 1, vga_ioport_write, s);

    register_ioport_write(0x3d4, 2, 1, vga_ioport_write, s);

    register_ioport_write(0x3ba, 1, 1, vga_ioport_write, s);

    register_ioport_write(0x3da, 1, 1, vga_ioport_write, s);

    register_ioport_read(0x3c0, 16, 1, vga_ioport_read, s);

    register_ioport_read(0x3b4, 2, 1, vga_ioport_read, s);

    register_ioport_read(0x3d4, 2, 1, vga_ioport_read, s);

    register_ioport_read(0x3ba, 1, 1, vga_ioport_read, s);

    register_ioport_read(0x3da, 1, 1, vga_ioport_read, s);

    s->bank_offset = 0;

#ifdef CONFIG_BOCHS_VBE

    s->vbe_regs[VBE_DISPI_INDEX_ID] = VBE_DISPI_ID0;

    s->vbe_bank_mask = ((s->vram_size >> 16) - 1);

#if defined (TARGET_I386)

    register_ioport_read(0x1ce, 1, 2, vbe_ioport_read_index, s);

    register_ioport_read(0x1cf, 1, 2, vbe_ioport_read_data, s);

    register_ioport_write(0x1ce, 1, 2, vbe_ioport_write_index, s);

    register_ioport_write(0x1cf, 1, 2, vbe_ioport_write_data, s);

    /* old Bochs IO ports */

    register_ioport_read(0xff80, 1, 2, vbe_ioport_read_index, s);

    register_ioport_read(0xff81, 1, 2, vbe_ioport_read_data, s);

    register_ioport_write(0xff80, 1, 2, vbe_ioport_write_index, s);

    register_ioport_write(0xff81, 1, 2, vbe_ioport_write_data, s);

#else

    register_ioport_read(0x1ce, 1, 2, vbe_ioport_read_index, s);

    register_ioport_read(0x1d0, 1, 2, vbe_ioport_read_data, s);

    register_ioport_write(0x1ce, 1, 2, vbe_ioport_write_index, s);

    register_ioport_write(0x1d0, 1, 2, vbe_ioport_write_data, s);

#endif

#endif /* CONFIG_BOCHS_VBE */

    vga_io_memory = cpu_register_io_memory(0, vga_mem_read, vga_mem_write, s);

    cpu_register_physical_memory(isa_mem_base + 0x000a0000, 0x20000,

                                 vga_io_memory);

}


void audio_decode_example(const char *outfilename, const char *filename)

{

    AVCodec *codec;

    AVCodecContext *c= NULL;

    int out_size, size, len;

    FILE *f, *outfile;

    uint8_t *outbuf;

    uint8_t inbuf[INBUF_SIZE + FF_INPUT_BUFFER_PADDING_SIZE], *inbuf_ptr;

    printf("Audio decoding\n");

    /* set end of buffer to 0 (this ensures that no overreading happens for damaged mpeg streams) */

    memset(inbuf + INBUF_SIZE, 0, FF_INPUT_BUFFER_PADDING_SIZE);

    /* find the mpeg audio decoder */

    codec = avcodec_find_decoder(CODEC_ID_MP2);

    if (!codec) {

        fprintf(stderr, "codec not found\n");

        exit(1);

    }

    c= avcodec_alloc_context();

    /* open it */

    if (avcodec_open(c, codec) < 0) {

        fprintf(stderr, "could not open codec\n");

        exit(1);

    }

    outbuf = malloc(AVCODEC_MAX_AUDIO_FRAME_SIZE);

    f = fopen(filename, "r");

    if (!f) {

        fprintf(stderr, "could not open %s\n", filename);

        exit(1);

    }

    outfile = fopen(outfilename, "w");

    if (!outfile) {

        free(c);

        exit(1);

    }

    /* decode until eof */

    inbuf_ptr = inbuf;

    for(;;) {

        size = fread(inbuf, 1, INBUF_SIZE, f);

        if (size == 0)

            break;

        inbuf_ptr = inbuf;

        while (size > 0) {

            len = avcodec_decode_audio(c, (short *)outbuf, &out_size,

                                       inbuf_ptr, size);

            if (len < 0) {

                fprintf(stderr, "Error while decoding\n");

                exit(1);

            }

            if (out_size > 0) {

                /* if a frame has been decoded, output it */

                fwrite(outbuf, 1, out_size, outfile);

            }

            size -= len;

            inbuf_ptr += len;

        }

    }

    fclose(outfile);

    fclose(f);

    free(outbuf);

    avcodec_close(c);

    free(c);

}


static int nprobe(AVFormatContext *s, uint8_t *enc_header, const uint8_t *n_val)

{

    OMAContext *oc = s->priv_data;

    uint32_t pos, taglen, datalen;

    struct AVDES av_des;

    if (!enc_header || !n_val)

        return -1;

    pos = OMA_ENC_HEADER_SIZE + oc->k_size;

    if (!memcmp(&enc_header[pos], "EKB ", 4))

        pos += 32;

    if (AV_RB32(&enc_header[pos]) != oc->rid)

        av_log(s, AV_LOG_DEBUG, "Mismatching RID\n");

    taglen = AV_RB32(&enc_header[pos+32]);

    datalen = AV_RB32(&enc_header[pos+36]) >> 4;

    pos += 44 + taglen;

    av_des_init(&av_des, n_val, 192, 1);

    while (datalen-- > 0) {

        av_des_crypt(&av_des, oc->r_val, &enc_header[pos], 2, NULL, 1);

        kset(s, oc->r_val, NULL, 16);

        if (!rprobe(s, enc_header, oc->r_val))

            return 0;

        pos += 16;

    }

    return -1;

}


static void ide_sector_start_dma(IDEState *s, enum ide_dma_cmd dma_cmd)

{

    s->status = READY_STAT | SEEK_STAT | DRQ_STAT | BUSY_STAT;

    s->io_buffer_index = 0;

    s->io_buffer_size = 0;

    s->dma_cmd = dma_cmd;

    switch (dma_cmd) {

    case IDE_DMA_READ:

        block_acct_start(bdrv_get_stats(s->bs), &s->acct,

                         s->nsector * BDRV_SECTOR_SIZE, BLOCK_ACCT_READ);

        break;

    case IDE_DMA_WRITE:

        block_acct_start(bdrv_get_stats(s->bs), &s->acct,

                         s->nsector * BDRV_SECTOR_SIZE, BLOCK_ACCT_WRITE);

        break;

    default:

        break;

    }

    ide_start_dma(s, ide_dma_cb);

}


void s390_feat_bitmap_to_ascii(const S390FeatBitmap bitmap, void *opaque,

                               void (*fn)(const char *name, void *opaque))

{

    S390Feat feat;

    feat = find_first_bit(bitmap, S390_FEAT_MAX);

    while (feat < S390_FEAT_MAX) {

        fn(s390_feat_def(feat)->name, opaque);

        feat = find_next_bit(bitmap, S390_FEAT_MAX, feat + 1);

    };

}


static uint64_t hpet_get_ticks(void)

{

    uint64_t ticks;

    ticks = ns_to_ticks(qemu_get_clock(vm_clock) + hpet_statep->hpet_offset);

    return ticks;

}


static void compute_pkt_fields(AVFormatContext *s, AVStream *st,

                               AVCodecParserContext *pc, AVPacket *pkt)

{

    int num, den, presentation_delayed, delay, i;

    int64_t offset;

    if (s->flags & AVFMT_FLAG_NOFILLIN)

        return;

    if((s->flags & AVFMT_FLAG_IGNDTS) && pkt->pts != AV_NOPTS_VALUE)

        pkt->dts= AV_NOPTS_VALUE;

    if (st->codec->codec_id != CODEC_ID_H264 && pc && pc->pict_type == FF_B_TYPE)

        //FIXME Set low_delay = 0 when has_b_frames = 1

        st->codec->has_b_frames = 1;

    /* do we have a video B-frame ? */

    delay= st->codec->has_b_frames;

    presentation_delayed = 0;

    /* XXX: need has_b_frame, but cannot get it if the codec is

        not initialized */

    if (delay &&

        pc && pc->pict_type != FF_B_TYPE)

        presentation_delayed = 1;

    if(pkt->pts != AV_NOPTS_VALUE && pkt->dts != AV_NOPTS_VALUE && pkt->dts > pkt->pts && st->pts_wrap_bits<63

       /*&& pkt->dts-(1LL<<st->pts_wrap_bits) < pkt->pts*/){

        pkt->dts -= 1LL<<st->pts_wrap_bits;

    }

    // some mpeg2 in mpeg-ps lack dts (issue171 / input_file.mpg)

    // we take the conservative approach and discard both

    // Note, if this is misbehaving for a H.264 file then possibly presentation_delayed is not set correctly.

    if(delay==1 && pkt->dts == pkt->pts && pkt->dts != AV_NOPTS_VALUE && presentation_delayed){

        av_log(s, AV_LOG_WARNING, "invalid dts/pts combination\n");

        pkt->dts= pkt->pts= AV_NOPTS_VALUE;

    }

    if (pkt->duration == 0) {

        compute_frame_duration(&num, &den, st, pc, pkt);

        if (den && num) {

            pkt->duration = av_rescale_rnd(1, num * (int64_t)st->time_base.den, den * (int64_t)st->time_base.num, AV_ROUND_DOWN);

            if(pkt->duration != 0 && s->packet_buffer)

                update_initial_durations(s, st, pkt);

        }

    }

    /* correct timestamps with byte offset if demuxers only have timestamps

       on packet boundaries */

    if(pc && st->need_parsing == AVSTREAM_PARSE_TIMESTAMPS && pkt->size){

        /* this will estimate bitrate based on this frame's duration and size */

        offset = av_rescale(pc->offset, pkt->duration, pkt->size);

        if(pkt->pts != AV_NOPTS_VALUE)

            pkt->pts += offset;

        if(pkt->dts != AV_NOPTS_VALUE)

            pkt->dts += offset;

    }

    if (pc && pc->dts_sync_point >= 0) {

        // we have synchronization info from the parser

        int64_t den = st->codec->time_base.den * (int64_t) st->time_base.num;

        if (den > 0) {

            int64_t num = st->codec->time_base.num * (int64_t) st->time_base.den;

            if (pkt->dts != AV_NOPTS_VALUE) {

                // got DTS from the stream, update reference timestamp

                st->reference_dts = pkt->dts - pc->dts_ref_dts_delta * num / den;

                pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;

            } else if (st->reference_dts != AV_NOPTS_VALUE) {

                // compute DTS based on reference timestamp

                pkt->dts = st->reference_dts + pc->dts_ref_dts_delta * num / den;

                pkt->pts = pkt->dts + pc->pts_dts_delta * num / den;

            }

            if (pc->dts_sync_point > 0)

                st->reference_dts = pkt->dts; // new reference

        }

    }

    /* This may be redundant, but it should not hurt. */

    if(pkt->dts != AV_NOPTS_VALUE && pkt->pts != AV_NOPTS_VALUE && pkt->pts > pkt->dts)

        presentation_delayed = 1;

//    av_log(NULL, AV_LOG_DEBUG, "IN delayed:%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64" st:%d pc:%p\n", presentation_delayed, pkt->pts, pkt->dts, st->cur_dts, pkt->stream_index, pc);

    /* interpolate PTS and DTS if they are not present */

    //We skip H264 currently because delay and has_b_frames are not reliably set

    if((delay==0 || (delay==1 && pc)) && st->codec->codec_id != CODEC_ID_H264){

        if (presentation_delayed) {

            /* DTS = decompression timestamp */

            /* PTS = presentation timestamp */

            if (pkt->dts == AV_NOPTS_VALUE)

                pkt->dts = st->last_IP_pts;

            update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts);

            if (pkt->dts == AV_NOPTS_VALUE)

                pkt->dts = st->cur_dts;

            /* this is tricky: the dts must be incremented by the duration

            of the frame we are displaying, i.e. the last I- or P-frame */

            if (st->last_IP_duration == 0)

                st->last_IP_duration = pkt->duration;

            if(pkt->dts != AV_NOPTS_VALUE)

                st->cur_dts = pkt->dts + st->last_IP_duration;

            st->last_IP_duration  = pkt->duration;

            st->last_IP_pts= pkt->pts;

            /* cannot compute PTS if not present (we can compute it only

            by knowing the future */

        } else if(pkt->pts != AV_NOPTS_VALUE || pkt->dts != AV_NOPTS_VALUE || pkt->duration){

            if(pkt->pts != AV_NOPTS_VALUE && pkt->duration){

                int64_t old_diff= FFABS(st->cur_dts - pkt->duration - pkt->pts);

                int64_t new_diff= FFABS(st->cur_dts - pkt->pts);

                if(old_diff < new_diff && old_diff < (pkt->duration>>3)){

                    pkt->pts += pkt->duration;

    //                av_log(NULL, AV_LOG_DEBUG, "id:%d old:%"PRId64" new:%"PRId64" dur:%d cur:%"PRId64" size:%d\n", pkt->stream_index, old_diff, new_diff, pkt->duration, st->cur_dts, pkt->size);

                }

            }

            /* presentation is not delayed : PTS and DTS are the same */

            if(pkt->pts == AV_NOPTS_VALUE)

                pkt->pts = pkt->dts;

            update_initial_timestamps(s, pkt->stream_index, pkt->pts, pkt->pts);

            if(pkt->pts == AV_NOPTS_VALUE)

                pkt->pts = st->cur_dts;

            pkt->dts = pkt->pts;

            if(pkt->pts != AV_NOPTS_VALUE)

                st->cur_dts = pkt->pts + pkt->duration;

        }

    }

    if(pkt->pts != AV_NOPTS_VALUE && delay <= MAX_REORDER_DELAY){

        st->pts_buffer[0]= pkt->pts;

        for(i=0; i<delay && st->pts_buffer[i] > st->pts_buffer[i+1]; i++)

            FFSWAP(int64_t, st->pts_buffer[i], st->pts_buffer[i+1]);

        if(pkt->dts == AV_NOPTS_VALUE)

            pkt->dts= st->pts_buffer[0];

        if(st->codec->codec_id == CODEC_ID_H264){ //we skiped it above so we try here

            update_initial_timestamps(s, pkt->stream_index, pkt->dts, pkt->pts); // this should happen on the first packet

        }

        if(pkt->dts > st->cur_dts)

            st->cur_dts = pkt->dts;

    }

//    av_log(NULL, AV_LOG_ERROR, "OUTdelayed:%d/%d pts:%"PRId64", dts:%"PRId64" cur_dts:%"PRId64"\n", presentation_delayed, delay, pkt->pts, pkt->dts, st->cur_dts);

    /* update flags */

    if(is_intra_only(st->codec))

        pkt->flags |= AV_PKT_FLAG_KEY;

    else if (pc) {

        pkt->flags = 0;

        /* keyframe computation */

        if (pc->key_frame == 1)

            pkt->flags |= AV_PKT_FLAG_KEY;

        else if (pc->key_frame == -1 && pc->pict_type == FF_I_TYPE)

            pkt->flags |= AV_PKT_FLAG_KEY;

    }

    if (pc)

        pkt->convergence_duration = pc->convergence_duration;

}


static void avc_biwgt_8width_msa(uint8_t *src, int32_t src_stride,

                                 uint8_t *dst, int32_t dst_stride,

                                 int32_t height, int32_t log2_denom,

                                 int32_t src_weight, int32_t dst_weight,

                                 int32_t offset_in)

{

    uint8_t cnt;

    v16i8 src_wgt, dst_wgt, wgt;

    v16i8 src0, src1, src2, src3;

    v16i8 dst0, dst1, dst2, dst3;

    v8i16 temp0, temp1, temp2, temp3;

    v8i16 denom, offset, add_val;

    int32_t val = 128 * (src_weight + dst_weight);

    offset_in = ((offset_in + 1) | 1) << log2_denom;

    src_wgt = __msa_fill_b(src_weight);

    dst_wgt = __msa_fill_b(dst_weight);

    offset = __msa_fill_h(offset_in);

    denom = __msa_fill_h(log2_denom + 1);

    add_val = __msa_fill_h(val);

    offset += add_val;

    wgt = __msa_ilvev_b(dst_wgt, src_wgt);

    for (cnt = height / 4; cnt--;) {

        LOAD_4VECS_SB(src, src_stride, src0, src1, src2, src3);

        src += (4 * src_stride);

        LOAD_4VECS_SB(dst, dst_stride, dst0, dst1, dst2, dst3);

        XORI_B_4VECS_SB(src0, src1, src2, src3, src0, src1, src2, src3, 128);

        XORI_B_4VECS_SB(dst0, dst1, dst2, dst3, dst0, dst1, dst2, dst3, 128);

        ILVR_B_4VECS_SH(src0, src1, src2, src3, dst0, dst1, dst2, dst3,

                        temp0, temp1, temp2, temp3);

        temp0 = __msa_dpadd_s_h(offset, wgt, (v16i8) temp0);

        temp1 = __msa_dpadd_s_h(offset, wgt, (v16i8) temp1);

        temp2 = __msa_dpadd_s_h(offset, wgt, (v16i8) temp2);

        temp3 = __msa_dpadd_s_h(offset, wgt, (v16i8) temp3);

        SRA_4VECS(temp0, temp1, temp2, temp3,

                  temp0, temp1, temp2, temp3, denom);

        temp0 = CLIP_UNSIGNED_CHAR_H(temp0);

        temp1 = CLIP_UNSIGNED_CHAR_H(temp1);

        temp2 = CLIP_UNSIGNED_CHAR_H(temp2);

        temp3 = CLIP_UNSIGNED_CHAR_H(temp3);

        PCKEV_B_STORE_8_BYTES_4(temp0, temp1, temp2, temp3, dst, dst_stride);

        dst += 4 * dst_stride;

    }

}


static void add_input_streams(OptionsContext *o, AVFormatContext *ic)

{

    int i;

    char *next, *codec_tag = NULL;

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

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

        AVCodecContext *dec = st->codec;

        InputStream *ist = av_mallocz(sizeof(*ist));

        char *framerate = NULL;

        if (!ist)

            exit(1);

        GROW_ARRAY(input_streams, nb_input_streams);

        input_streams[nb_input_streams - 1] = ist;

        ist->st = st;

        ist->file_index = nb_input_files;

        ist->discard = 1;

        st->discard  = AVDISCARD_ALL;

        ist->ts_scale = 1.0;

        MATCH_PER_STREAM_OPT(ts_scale, dbl, ist->ts_scale, ic, st);

        MATCH_PER_STREAM_OPT(codec_tags, str, codec_tag, ic, st);

        if (codec_tag) {

            uint32_t tag = strtol(codec_tag, &next, 0);

            if (*next)

                tag = AV_RL32(codec_tag);

            st->codec->codec_tag = tag;

        }

        ist->dec = choose_decoder(o, ic, st);

        ist->opts = filter_codec_opts(o->g->codec_opts, ist->st->codec->codec_id, ic, st, ist->dec);

        ist->reinit_filters = -1;

        MATCH_PER_STREAM_OPT(reinit_filters, i, ist->reinit_filters, ic, st);

        ist->filter_in_rescale_delta_last = AV_NOPTS_VALUE;

        switch (dec->codec_type) {

        case AVMEDIA_TYPE_VIDEO:

            if(!ist->dec)

                ist->dec = avcodec_find_decoder(dec->codec_id);

            if (dec->lowres) {

                dec->flags |= CODEC_FLAG_EMU_EDGE;

            }

            ist->resample_height  = dec->height;

            ist->resample_width   = dec->width;

            ist->resample_pix_fmt = dec->pix_fmt;

            MATCH_PER_STREAM_OPT(frame_rates, str, framerate, ic, st);

            if (framerate && av_parse_video_rate(&ist->framerate,

                                                 framerate) < 0) {

                av_log(NULL, AV_LOG_ERROR, "Error parsing framerate %s.\n",

                       framerate);

                exit(1);

            }

            ist->top_field_first = -1;

            MATCH_PER_STREAM_OPT(top_field_first, i, ist->top_field_first, ic, st);

            break;

        case AVMEDIA_TYPE_AUDIO:

            ist->guess_layout_max = INT_MAX;

            MATCH_PER_STREAM_OPT(guess_layout_max, i, ist->guess_layout_max, ic, st);

            guess_input_channel_layout(ist);

            ist->resample_sample_fmt     = dec->sample_fmt;

            ist->resample_sample_rate    = dec->sample_rate;

            ist->resample_channels       = dec->channels;

            ist->resample_channel_layout = dec->channel_layout;

            break;

        case AVMEDIA_TYPE_DATA:

        case AVMEDIA_TYPE_SUBTITLE:

            if(!ist->dec)

                ist->dec = avcodec_find_decoder(dec->codec_id);

            MATCH_PER_STREAM_OPT(fix_sub_duration, i, ist->fix_sub_duration, ic, st);

            break;

        case AVMEDIA_TYPE_ATTACHMENT:

        case AVMEDIA_TYPE_UNKNOWN:

            break;

        default:

            abort();

        }

    }

}


static av_cold int asink_init(AVFilterContext *ctx, void *opaque)

{

    BufferSinkContext *buf = ctx->priv;

    AVABufferSinkParams *params = opaque;

    if (params && params->sample_fmts) {

        buf->sample_fmts = ff_copy_int_list(params->sample_fmts);

        if (!buf->sample_fmts)

            return AVERROR(ENOMEM);

    }

    if (params && params->sample_rates) {

        buf->sample_rates = ff_copy_int_list(params->sample_rates);

        if (!buf->sample_rates)

            return AVERROR(ENOMEM);

    }

    if (params && (params->channel_layouts || params->channel_counts)) {

        if (params->all_channel_counts) {

            av_log(ctx, AV_LOG_ERROR,

                   "Conflicting all_channel_counts and list in parameters\n");

            return AVERROR(EINVAL);

        }

        buf->channel_layouts = concat_channels_lists(params->channel_layouts,

                                                     params->channel_counts);

        if (!buf->channel_layouts)

            return AVERROR(ENOMEM);

    }

    if (params)

        buf->all_channel_counts = params->all_channel_counts;

    return common_init(ctx);

}


FWCfgState *pc_memory_init(PCMachineState *pcms,

                           MemoryRegion *system_memory,

                           MemoryRegion *rom_memory,

                           MemoryRegion **ram_memory,

                           PcGuestInfo *guest_info)

{

    int linux_boot, i;

    MemoryRegion *ram, *option_rom_mr;

    MemoryRegion *ram_below_4g, *ram_above_4g;

    FWCfgState *fw_cfg;

    MachineState *machine = MACHINE(pcms);

    assert(machine->ram_size == pcms->below_4g_mem_size +

                                pcms->above_4g_mem_size);

    linux_boot = (machine->kernel_filename != NULL);

    /* Allocate RAM.  We allocate it as a single memory region and use

     * aliases to address portions of it, mostly for backwards compatibility

     * with older qemus that used qemu_ram_alloc().

     */

    ram = g_malloc(sizeof(*ram));

    memory_region_allocate_system_memory(ram, NULL, "pc.ram",

                                         machine->ram_size);

    *ram_memory = ram;

    ram_below_4g = g_malloc(sizeof(*ram_below_4g));

    memory_region_init_alias(ram_below_4g, NULL, "ram-below-4g", ram,

                             0, pcms->below_4g_mem_size);

    memory_region_add_subregion(system_memory, 0, ram_below_4g);

    e820_add_entry(0, pcms->below_4g_mem_size, E820_RAM);

    if (pcms->above_4g_mem_size > 0) {

        ram_above_4g = g_malloc(sizeof(*ram_above_4g));

        memory_region_init_alias(ram_above_4g, NULL, "ram-above-4g", ram,

                                 pcms->below_4g_mem_size,

                                 pcms->above_4g_mem_size);

        memory_region_add_subregion(system_memory, 0x100000000ULL,

                                    ram_above_4g);

        e820_add_entry(0x100000000ULL, pcms->above_4g_mem_size, E820_RAM);

    }

    if (!guest_info->has_reserved_memory &&

        (machine->ram_slots ||

         (machine->maxram_size > machine->ram_size))) {

        MachineClass *mc = MACHINE_GET_CLASS(machine);

        error_report("\"-memory 'slots|maxmem'\" is not supported by: %s",

                     mc->name);

        exit(EXIT_FAILURE);

    }

    /* initialize hotplug memory address space */

    if (guest_info->has_reserved_memory &&

        (machine->ram_size < machine->maxram_size)) {

        ram_addr_t hotplug_mem_size =

            machine->maxram_size - machine->ram_size;

        if (machine->ram_slots > ACPI_MAX_RAM_SLOTS) {

            error_report("unsupported amount of memory slots: %"PRIu64,

                         machine->ram_slots);

            exit(EXIT_FAILURE);

        }

        if (QEMU_ALIGN_UP(machine->maxram_size,

                          TARGET_PAGE_SIZE) != machine->maxram_size) {

            error_report("maximum memory size must by aligned to multiple of "

                         "%d bytes", TARGET_PAGE_SIZE);

            exit(EXIT_FAILURE);

        }

        pcms->hotplug_memory.base =

            ROUND_UP(0x100000000ULL + pcms->above_4g_mem_size, 1ULL << 30);

        if (pcms->enforce_aligned_dimm) {

            /* size hotplug region assuming 1G page max alignment per slot */

            hotplug_mem_size += (1ULL << 30) * machine->ram_slots;

        }

        if ((pcms->hotplug_memory.base + hotplug_mem_size) <

            hotplug_mem_size) {

            error_report("unsupported amount of maximum memory: " RAM_ADDR_FMT,

                         machine->maxram_size);

            exit(EXIT_FAILURE);

        }

        memory_region_init(&pcms->hotplug_memory.mr, OBJECT(pcms),

                           "hotplug-memory", hotplug_mem_size);

        memory_region_add_subregion(system_memory, pcms->hotplug_memory.base,

                                    &pcms->hotplug_memory.mr);

    }

    /* Initialize PC system firmware */

    pc_system_firmware_init(rom_memory, guest_info->isapc_ram_fw);

    option_rom_mr = g_malloc(sizeof(*option_rom_mr));

    memory_region_init_ram(option_rom_mr, NULL, "pc.rom", PC_ROM_SIZE,

                           &error_abort);

    vmstate_register_ram_global(option_rom_mr);

    memory_region_add_subregion_overlap(rom_memory,

                                        PC_ROM_MIN_VGA,

                                        option_rom_mr,

                                        1);

    fw_cfg = bochs_bios_init();

    rom_set_fw(fw_cfg);

    if (guest_info->has_reserved_memory && pcms->hotplug_memory.base) {

        uint64_t *val = g_malloc(sizeof(*val));

        uint64_t res_mem_end = pcms->hotplug_memory.base +

                               memory_region_size(&pcms->hotplug_memory.mr);

        *val = cpu_to_le64(ROUND_UP(res_mem_end, 0x1ULL << 30));

        fw_cfg_add_file(fw_cfg, "etc/reserved-memory-end", val, sizeof(*val));

    }

    if (linux_boot) {

        load_linux(pcms, fw_cfg);

    }

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

        rom_add_option(option_rom[i].name, option_rom[i].bootindex);

    }

    guest_info->fw_cfg = fw_cfg;

    return fw_cfg;

}


static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,

                                            int64_t sector_num,

                                            QEMUIOVector *iov,

                                            int nb_sectors,

                                            BlockDriverCompletionFunc *cb,

                                            void *opaque,

                                            int is_write)

{

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

    BlockDriverAIOCB *aiocb = qemu_aio_get(bs, cb, opaque);

    s->this_aiocb = aiocb;

    s->iov = iov;

    s->bounce = qemu_memalign(512, nb_sectors * 512);

    s->is_write = is_write;

    if (is_write) {

        qemu_iovec_to_buffer(s->iov, s->bounce);

        s->aiocb = bdrv_aio_write(bs, sector_num, s->bounce, nb_sectors,

                                  bdrv_aio_rw_vector_cb, s);

    } else {

        s->aiocb = bdrv_aio_read(bs, sector_num, s->bounce, nb_sectors,

                                 bdrv_aio_rw_vector_cb, s);

    }

    return aiocb;

}


static void pc_machine_set_max_ram_below_4g(Object *obj, Visitor *v,

                                            const char *name, void *opaque,

                                            Error **errp)

{

    PCMachineState *pcms = PC_MACHINE(obj);

    Error *error = NULL;

    uint64_t value;

    visit_type_size(v, name, &value, &error);

    if (error) {

        error_propagate(errp, error);

        return;

    }

    if (value > (1ULL << 32)) {

        error_setg(&error,

                   "Machine option 'max-ram-below-4g=%"PRIu64

                   "' expects size less than or equal to 4G", value);

        error_propagate(errp, error);

        return;

    }

    if (value < (1ULL << 20)) {

        error_report("Warning: small max_ram_below_4g(%"PRIu64

                     ") less than 1M.  BIOS may not work..",

                     value);

    }

    pcms->max_ram_below_4g = value;

}


static int rv30_decode_intra_types(RV34DecContext *r, GetBitContext *gb, int8_t *dst)

{

    int i, j, k;

    for(i = 0; i < 4; i++, dst += r->intra_types_stride - 4){

        for(j = 0; j < 4; j+= 2){

            int code = svq3_get_ue_golomb(gb) << 1;

            if(code >= 81*2){

                av_log(r->s.avctx, AV_LOG_ERROR, "Incorrect intra prediction code\n");

                return -1;

            }

            for(k = 0; k < 2; k++){

                int A = dst[-r->intra_types_stride] + 1;

                int B = dst[-1] + 1;

                *dst++ = rv30_itype_from_context[A * 90 + B * 9 + rv30_itype_code[code + k]];

                if(dst[-1] == 9){

                    av_log(r->s.avctx, AV_LOG_ERROR, "Incorrect intra prediction mode\n");

                    return -1;

                }

            }

        }

    }

    return 0;

}


static int stdio_get_buffer(void *opaque, uint8_t *buf, int64_t pos, int size)

{

    QEMUFileStdio *s = opaque;

    FILE *fp = s->stdio_file;

    int bytes;

    do {

        clearerr(fp);

        bytes = fread(buf, 1, size, fp);

    } while ((bytes == 0) && ferror(fp) && (errno == EINTR));

    return bytes;

}


static av_cold int set_channel_info(AC3EncodeContext *s, int channels,

                                    int64_t *channel_layout)

{

    int ch_layout;

    if (channels < 1 || channels > AC3_MAX_CHANNELS)

        return AVERROR(EINVAL);

    if ((uint64_t)*channel_layout > 0x7FF)

        return AVERROR(EINVAL);

    ch_layout = *channel_layout;

    if (!ch_layout)

        ch_layout = avcodec_guess_channel_layout(channels, CODEC_ID_AC3, NULL);

    if (av_get_channel_layout_nb_channels(ch_layout) != channels)

        return AVERROR(EINVAL);

    s->lfe_on       = !!(ch_layout & AV_CH_LOW_FREQUENCY);

    s->channels     = channels;

    s->fbw_channels = channels - s->lfe_on;

    s->lfe_channel  = s->lfe_on ? s->fbw_channels : -1;

    if (s->lfe_on)

        ch_layout -= AV_CH_LOW_FREQUENCY;

    switch (ch_layout) {

    case AV_CH_LAYOUT_MONO:           s->channel_mode = AC3_CHMODE_MONO;   break;

    case AV_CH_LAYOUT_STEREO:         s->channel_mode = AC3_CHMODE_STEREO; break;

    case AV_CH_LAYOUT_SURROUND:       s->channel_mode = AC3_CHMODE_3F;     break;

    case AV_CH_LAYOUT_2_1:            s->channel_mode = AC3_CHMODE_2F1R;   break;

    case AV_CH_LAYOUT_4POINT0:        s->channel_mode = AC3_CHMODE_3F1R;   break;

    case AV_CH_LAYOUT_QUAD:

    case AV_CH_LAYOUT_2_2:            s->channel_mode = AC3_CHMODE_2F2R;   break;

    case AV_CH_LAYOUT_5POINT0:

    case AV_CH_LAYOUT_5POINT0_BACK:   s->channel_mode = AC3_CHMODE_3F2R;   break;

    default:

        return AVERROR(EINVAL);

    }

    s->has_center   = (s->channel_mode & 0x01) && s->channel_mode != AC3_CHMODE_MONO;

    s->has_surround =  s->channel_mode & 0x04;

    s->channel_map  = ff_ac3_enc_channel_map[s->channel_mode][s->lfe_on];

    *channel_layout = ch_layout;

    if (s->lfe_on)

        *channel_layout |= AV_CH_LOW_FREQUENCY;

    return 0;

}


static MemoryRegionSection *phys_page_find(PhysPageEntry lp, hwaddr index,

                                           Node *nodes, MemoryRegionSection *sections)

{

    PhysPageEntry *p;

    int i;

    for (i = P_L2_LEVELS - 1; i >= 0 && !lp.is_leaf; i--) {

        if (lp.ptr == PHYS_MAP_NODE_NIL) {

            return &sections[PHYS_SECTION_UNASSIGNED];

        }

        p = nodes[lp.ptr];

        lp = p[(index >> (i * L2_BITS)) & (L2_SIZE - 1)];

    }

    return &sections[lp.ptr];

}


static int ram_save_block(QEMUFile *f, bool last_stage)

{

    RAMBlock *block = last_seen_block;

    ram_addr_t offset = last_offset;

    int bytes_sent = -1;

    MemoryRegion *mr;

    ram_addr_t current_addr;

    if (!block)

        block = QTAILQ_FIRST(&ram_list.blocks);

    do {

        mr = block->mr;

        if (migration_bitmap_test_and_reset_dirty(mr, offset)) {

            uint8_t *p;

            int cont = (block == last_sent_block) ?

                RAM_SAVE_FLAG_CONTINUE : 0;

            p = memory_region_get_ram_ptr(mr) + offset;

            if (is_dup_page(p)) {

                acct_info.dup_pages++;

                save_block_hdr(f, block, offset, cont, RAM_SAVE_FLAG_COMPRESS);

                qemu_put_byte(f, *p);

                bytes_sent = 1;

            } else if (migrate_use_xbzrle()) {

                current_addr = block->offset + offset;

                bytes_sent = save_xbzrle_page(f, p, current_addr, block,

                                              offset, cont, last_stage);

                if (!last_stage) {

                    p = get_cached_data(XBZRLE.cache, current_addr);

                }

            }

            /* either we didn't send yet (we may have had XBZRLE overflow) */

            if (bytes_sent == -1) {

                save_block_hdr(f, block, offset, cont, RAM_SAVE_FLAG_PAGE);

                qemu_put_buffer(f, p, TARGET_PAGE_SIZE);

                bytes_sent = TARGET_PAGE_SIZE;

                acct_info.norm_pages++;

            }

            /* if page is unmodified, continue to the next */

            if (bytes_sent != 0) {

                last_sent_block = block;

                break;

            }

        }

        offset += TARGET_PAGE_SIZE;

        if (offset >= block->length) {

            offset = 0;

            block = QTAILQ_NEXT(block, next);

            if (!block)

                block = QTAILQ_FIRST(&ram_list.blocks);

        }

    } while (block != last_seen_block || offset != last_offset);

    last_seen_block = block;

    last_offset = offset;

    return bytes_sent;

}


static int os_host_main_loop_wait(int64_t timeout)

{

    int ret;

    static int spin_counter;

    glib_pollfds_fill(&timeout);

    /* If the I/O thread is very busy or we are incorrectly busy waiting in

     * the I/O thread, this can lead to starvation of the BQL such that the

     * VCPU threads never run.  To make sure we can detect the later case,

     * print a message to the screen.  If we run into this condition, create

     * a fake timeout in order to give the VCPU threads a chance to run.

     */

    if (!timeout && (spin_counter > MAX_MAIN_LOOP_SPIN)) {

        static bool notified;

        if (!notified && !qtest_driver()) {

            fprintf(stderr,

                    "main-loop: WARNING: I/O thread spun for %d iterations\n",

                    MAX_MAIN_LOOP_SPIN);

            notified = true;

        }

        timeout = SCALE_MS;

    }

    if (timeout) {

        spin_counter = 0;

        qemu_mutex_unlock_iothread();

    } else {

        spin_counter++;

    }

    ret = qemu_poll_ns((GPollFD *)gpollfds->data, gpollfds->len, timeout);

    if (timeout) {

        qemu_mutex_lock_iothread();

    }

    glib_pollfds_poll();

    return ret;

}


static void qemu_kill_report(void)

{

    if (!qtest_driver() && shutdown_signal != -1) {

        fprintf(stderr, "qemu: terminating on signal %d", shutdown_signal);

        if (shutdown_pid == 0) {

            /* This happens for eg ^C at the terminal, so it's worth

             * avoiding printing an odd message in that case.

             */

            fputc('\n', stderr);

        } else {

            fprintf(stderr, " from pid " FMT_pid "\n", shutdown_pid);

        }

        shutdown_signal = -1;

    }

}


static void term_bol(void)

{

    term_cmd_buf_index = 0;

}


static void imx_serial_write(void *opaque, target_phys_addr_t offset,

                      uint64_t value, unsigned size)

{

    IMXSerialState *s = (IMXSerialState *)opaque;

    unsigned char ch;

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

            offset >> 2,

            (unsigned int)value, s->chr ? s->chr->label : "NODEV");

    switch (offset >> 2) {

    case 0x10: /* UTXD */

        ch = value;

        if (s->ucr2 & UCR2_TXEN) {

            if (s->chr) {

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

            }

            s->usr1 &= ~USR1_TRDY;

            imx_update(s);

            s->usr1 |= USR1_TRDY;

            imx_update(s);

        }

        break;

    case 0x20: /* UCR1 */

        s->ucr1 = value & 0xffff;

        DPRINTF("write(ucr1=%x)\n", (unsigned int)value);

        imx_update(s);

        break;

    case 0x21: /* UCR2 */

        /*

         * Only a few bits in control register 2 are implemented as yet.

         * If it's intended to use a real serial device as a back-end, this

         * register will have to be implemented more fully.

         */

        if (!(value & UCR2_SRST)) {

            imx_serial_reset(s);

            imx_update(s);

            value |= UCR2_SRST;

        }

        if (value & UCR2_RXEN) {

            if (!(s->ucr2 & UCR2_RXEN)) {

                qemu_chr_accept_input(s->chr);

            }

        }

        s->ucr2 = value & 0xffff;

        break;

    case 0x25: /* USR1 */

        value &= USR1_AWAKE | USR1_AIRINT | USR1_DTRD | USR1_AGTIM |

            USR1_FRAMERR | USR1_ESCF | USR1_RTSD | USR1_PARTYER;

        s->usr1 &= ~value;

        break;

    case 0x26: /* USR2 */

       /*

        * Writing 1 to some bits clears them; all other

        * values are ignored

        */

        value &= USR2_ADET | USR2_DTRF | USR2_IDLE | USR2_ACST |

            USR2_RIDELT | USR2_IRINT | USR2_WAKE |

            USR2_DCDDELT | USR2_RTSF | USR2_BRCD | USR2_ORE;

        s->usr2 &= ~value;

        break;

        /*

         * Linux expects to see what it writes to these registers

         * We don't currently alter the baud rate

         */

    case 0x29: /* UBIR */

        s->ubrc = value & 0xffff;

        break;

    case 0x2a: /* UBMR */

        s->ubmr = value & 0xffff;

        break;

    case 0x2c: /* One ms reg */

        s->onems = value & 0xffff;

        break;

    case 0x24: /* FIFO control register */

        s->ufcr = value & 0xffff;

        break;

    case 0x22: /* UCR3 */

        s->ucr3 = value & 0xffff;

        break;

    case 0x2d: /* UTS1 */

    case 0x23: /* UCR4 */

        IPRINTF("Unimplemented Register %x written to\n", offset >> 2);

        /* TODO */

        break;

    default:

        IPRINTF("imx_serial_write: Bad offset 0x%x\n", (int)offset);

    }

}


static int cinepak_decode (CinepakContext *s)

{

    uint8_t      *eod = (s->data + s->size);

    int           i, result, strip_size, frame_flags, num_strips;

    int           y0 = 0;

    int           encoded_buf_size;

    /* if true, Cinepak data is from a Sega FILM/CPK file */

    int           sega_film_data = 0;

    if (s->size < 10)

        return -1;

    frame_flags = s->data[0];

    num_strips  = BE_16 (&s->data[8]);

    encoded_buf_size = ((s->data[1] << 16) | BE_16 (&s->data[2]));

    if (encoded_buf_size != s->size)

        sega_film_data = 1;

    if (sega_film_data)

        s->data    += 12;

    else

        s->data    += 10;

    if (num_strips > MAX_STRIPS)

        num_strips = MAX_STRIPS;

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

        if ((s->data + 12) > eod)

            return -1;

        s->strips[i].id = BE_16 (s->data);

        s->strips[i].y1 = y0;

        s->strips[i].x1 = 0;

        s->strips[i].y2 = y0 + BE_16 (&s->data[8]);

        s->strips[i].x2 = s->avctx->width;

        strip_size = BE_16 (&s->data[2]) - 12;

        s->data   += 12;

        strip_size = ((s->data + strip_size) > eod) ? (eod - s->data) : strip_size;

        if ((i > 0) && !(frame_flags & 0x01)) {

            memcpy (s->strips[i].v4_codebook, s->strips[i-1].v4_codebook,

                sizeof(s->strips[i].v4_codebook));

            memcpy (s->strips[i].v1_codebook, s->strips[i-1].v1_codebook,

                sizeof(s->strips[i].v1_codebook));

        }

        result = cinepak_decode_strip (s, &s->strips[i], s->data, strip_size);

        if (result != 0)

            return result;

        s->data += strip_size;

        y0    = s->strips[i].y2;

    }

    return 0;

}


int qcow2_check_refcounts(BlockDriverState *bs, BdrvCheckResult *res)

{

    BDRVQcowState *s = bs->opaque;

    int64_t size;

    int nb_clusters, refcount1, refcount2, i;

    QCowSnapshot *sn;

    uint16_t *refcount_table;

    int ret;

    size = bdrv_getlength(bs->file);

    nb_clusters = size_to_clusters(s, size);

    refcount_table = qemu_mallocz(nb_clusters * sizeof(uint16_t));

    /* header */

    inc_refcounts(bs, res, refcount_table, nb_clusters,

        0, s->cluster_size);

    /* current L1 table */

    ret = check_refcounts_l1(bs, res, refcount_table, nb_clusters,

                       s->l1_table_offset, s->l1_size, 1);

    if (ret < 0) {

        return ret;

    }

    /* snapshots */

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

        sn = s->snapshots + i;

        ret = check_refcounts_l1(bs, res, refcount_table, nb_clusters,

            sn->l1_table_offset, sn->l1_size, 0);

        if (ret < 0) {

            return ret;

        }

    }

    inc_refcounts(bs, res, refcount_table, nb_clusters,

        s->snapshots_offset, s->snapshots_size);

    /* refcount data */

    inc_refcounts(bs, res, refcount_table, nb_clusters,

        s->refcount_table_offset,

        s->refcount_table_size * sizeof(uint64_t));

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

        uint64_t offset, cluster;

        offset = s->refcount_table[i];

        cluster = offset >> s->cluster_bits;

        /* Refcount blocks are cluster aligned */

        if (offset & (s->cluster_size - 1)) {

            fprintf(stderr, "ERROR refcount block %d is not "

                "cluster aligned; refcount table entry corrupted\n", i);

            res->corruptions++;

            continue;

        }

        if (cluster >= nb_clusters) {

            fprintf(stderr, "ERROR refcount block %d is outside image\n", i);

            res->corruptions++;

            continue;

        }

        if (offset != 0) {

            inc_refcounts(bs, res, refcount_table, nb_clusters,

                offset, s->cluster_size);

            if (refcount_table[cluster] != 1) {

                fprintf(stderr, "ERROR refcount block %d refcount=%d\n",

                    i, refcount_table[cluster]);

                res->corruptions++;

            }

        }

    }

    /* compare ref counts */

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

        refcount1 = get_refcount(bs, i);

        if (refcount1 < 0) {

            fprintf(stderr, "Can't get refcount for cluster %d: %s\n",

                i, strerror(-refcount1));

            res->check_errors++;

            continue;

        }

        refcount2 = refcount_table[i];

        if (refcount1 != refcount2) {

            fprintf(stderr, "%s cluster %d refcount=%d reference=%d\n",

                   refcount1 < refcount2 ? "ERROR" : "Leaked",

                   i, refcount1, refcount2);

            if (refcount1 < refcount2) {

                res->corruptions++;

            } else {

                res->leaks++;

            }

        }

    }

    qemu_free(refcount_table);

    return 0;

}


static int gen_set_psr_im(DisasContext *s, uint32_t mask, int spsr, uint32_t val)

{

    TCGv tmp;

    tmp = new_tmp();

    tcg_gen_movi_i32(tmp, val);

    return gen_set_psr(s, mask, spsr, tmp);

}


int configure_filtergraph(FilterGraph *fg)

{

    AVFilterInOut *inputs, *outputs, *cur;

    int ret, i, simple = !fg->graph_desc;

    const char *graph_desc = simple ? fg->outputs[0]->ost->avfilter :

                                      fg->graph_desc;

    avfilter_graph_free(&fg->graph);

    if (!(fg->graph = avfilter_graph_alloc()))

        return AVERROR(ENOMEM);

    if (simple) {

        OutputStream *ost = fg->outputs[0]->ost;

        char args[512];

        AVDictionaryEntry *e = NULL;

        args[0] = 0;

        while ((e = av_dict_get(ost->sws_dict, "", e,

                                AV_DICT_IGNORE_SUFFIX))) {

            av_strlcatf(args, sizeof(args), "%s=%s:", e->key, e->value);

        }

        if (strlen(args))

            args[strlen(args)-1] = 0;

        fg->graph->scale_sws_opts = av_strdup(args);

        args[0] = 0;

        while ((e = av_dict_get(ost->swr_opts, "", e,

                                AV_DICT_IGNORE_SUFFIX))) {

            av_strlcatf(args, sizeof(args), "%s=%s:", e->key, e->value);

        }

        if (strlen(args))

            args[strlen(args)-1] = 0;

        av_opt_set(fg->graph, "aresample_swr_opts", args, 0);

        args[0] = '\0';

        while ((e = av_dict_get(fg->outputs[0]->ost->resample_opts, "", e,

                                AV_DICT_IGNORE_SUFFIX))) {

            av_strlcatf(args, sizeof(args), "%s=%s:", e->key, e->value);

        }

        if (strlen(args))

            args[strlen(args) - 1] = '\0';

        fg->graph->resample_lavr_opts = av_strdup(args);

        e = av_dict_get(ost->encoder_opts, "threads", NULL, 0);

        if (e)

            av_opt_set(fg->graph, "threads", e->value, 0);

    }

    if ((ret = avfilter_graph_parse2(fg->graph, graph_desc, &inputs, &outputs)) < 0)

        return ret;

    if (simple && (!inputs || inputs->next || !outputs || outputs->next)) {

        const char *num_inputs;

        const char *num_outputs;

        if (!outputs) {

            num_outputs = "0";

        } else if (outputs->next) {

            num_outputs = ">1";

        } else {

            num_outputs = "1";

        }

        if (!inputs) {

            num_inputs = "0";

        } else if (inputs->next) {

            num_inputs = ">1";

        } else {

            num_inputs = "1";

        }

        av_log(NULL, AV_LOG_ERROR, "Simple filtergraph '%s' was expected "

               "to have exactly 1 input and 1 output."

               " However, it had %s input(s) and %s output(s)."

               " Please adjust, or use a complex filtergraph (-filter_complex) instead.\n",

               graph_desc, num_inputs, num_outputs);

        return AVERROR(EINVAL);

    }

    for (cur = inputs, i = 0; cur; cur = cur->next, i++)

        if ((ret = configure_input_filter(fg, fg->inputs[i], cur)) < 0) {

            avfilter_inout_free(&inputs);

            avfilter_inout_free(&outputs);

            return ret;

        }

    avfilter_inout_free(&inputs);

    for (cur = outputs, i = 0; cur; cur = cur->next, i++)

        configure_output_filter(fg, fg->outputs[i], cur);

    avfilter_inout_free(&outputs);

    if ((ret = avfilter_graph_config(fg->graph, NULL)) < 0)

        return ret;

    fg->reconfiguration = 1;

    for (i = 0; i < fg->nb_outputs; i++) {

        OutputStream *ost = fg->outputs[i]->ost;

        if (!ost->enc) {

            /* identical to the same check in ffmpeg.c, needed because

               complex filter graphs are initialized earlier */

            av_log(NULL, AV_LOG_ERROR, "Encoder (codec %s) not found for output stream #%d:%d\n",

                     avcodec_get_name(ost->st->codec->codec_id), ost->file_index, ost->index);

            return AVERROR(EINVAL);

        }

        if (ost &&

            ost->enc->type == AVMEDIA_TYPE_AUDIO &&

            !(ost->enc->capabilities & AV_CODEC_CAP_VARIABLE_FRAME_SIZE))

            av_buffersink_set_frame_size(ost->filter->filter,

                                         ost->enc_ctx->frame_size);

    }

    return 0;

}


static void vhost_ccw_scsi_realize(VirtioCcwDevice *ccw_dev, Error **errp)

{

    VHostSCSICcw *dev = VHOST_SCSI_CCW(ccw_dev);

    DeviceState *vdev = DEVICE(&dev->vdev);

    Error *err = NULL;

    qdev_set_parent_bus(vdev, BUS(&ccw_dev->bus));

    object_property_set_bool(OBJECT(vdev), true, "realized", &err);

    if (err) {

        error_propagate(errp, err);

    }

}


ssize_t nbd_send_request(int csock, struct nbd_request *request)

{

    uint8_t buf[4 + 4 + 8 + 8 + 4];

    cpu_to_be32w((uint32_t*)buf, NBD_REQUEST_MAGIC);

    cpu_to_be32w((uint32_t*)(buf + 4), request->type);

    cpu_to_be64w((uint64_t*)(buf + 8), request->handle);

    cpu_to_be64w((uint64_t*)(buf + 16), request->from);

    cpu_to_be32w((uint32_t*)(buf + 24), request->len);

    TRACE("Sending request to client: "

          "{ .from = %" PRIu64", .len = %u, .handle = %" PRIu64", .type=%i}",

          request->from, request->len, request->handle, request->type);

    if (write_sync(csock, buf, sizeof(buf)) != sizeof(buf)) {

        LOG("writing to socket failed");

        errno = EINVAL;

        return -1;

    }

    return 0;

}


static void dmg_close(BlockDriverState *bs)

{

    BDRVDMGState *s = bs->opaque;

    close(s->fd);

    if(s->n_chunks>0) {

	free(s->types);

	free(s->offsets);

	free(s->lengths);

	free(s->sectors);

	free(s->sectorcounts);

    }

    free(s->compressed_chunk);

    free(s->uncompressed_chunk);

    inflateEnd(&s->zstream);

}


static void lance_mem_write(void *opaque, target_phys_addr_t addr,

                            uint64_t val, unsigned size)

{

    SysBusPCNetState *d = opaque;

    trace_lance_mem_writew(addr, val & 0xffff);

    pcnet_ioport_writew(&d->state, addr, val & 0xffff);

}


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

{

    AVIOContext *pb      = s->pb;

    AVCodecContext *enc  = s->streams[pkt->stream_index]->codec;

    FLVContext *flv      = s->priv_data;

    FLVStreamContext *sc = s->streams[pkt->stream_index]->priv_data;

    unsigned ts;

    int size = pkt->size;

    uint8_t *data = NULL;

    int flags = 0, flags_size;

    if (enc->codec_id == AV_CODEC_ID_VP6F || enc->codec_id == AV_CODEC_ID_VP6A ||

        enc->codec_id == AV_CODEC_ID_AAC)

        flags_size = 2;

    else if (enc->codec_id == AV_CODEC_ID_H264)

        flags_size = 5;

    else

        flags_size = 1;

    if (flv->delay == AV_NOPTS_VALUE)

        flv->delay = -pkt->dts;

    if (pkt->dts < -flv->delay) {

        av_log(s, AV_LOG_WARNING,

               "Packets are not in the proper order with respect to DTS\n");

        return AVERROR(EINVAL);

    }

    ts = pkt->dts + flv->delay; // add delay to force positive dts

    if (s->event_flags & AVSTREAM_EVENT_FLAG_METADATA_UPDATED) {

        write_metadata(s, ts);

        s->event_flags &= ~AVSTREAM_EVENT_FLAG_METADATA_UPDATED;

    }

    switch (enc->codec_type) {

    case AVMEDIA_TYPE_VIDEO:

        avio_w8(pb, FLV_TAG_TYPE_VIDEO);

        flags = enc->codec_tag;

        if (flags == 0) {

            av_log(s, AV_LOG_ERROR,

                   "video codec %X not compatible with flv\n",

                   enc->codec_id);

            return -1;

        }

        flags |= pkt->flags & AV_PKT_FLAG_KEY ? FLV_FRAME_KEY : FLV_FRAME_INTER;

        break;

    case AVMEDIA_TYPE_AUDIO:

        flags = get_audio_flags(s, enc);

        assert(size);

        avio_w8(pb, FLV_TAG_TYPE_AUDIO);

        break;

    case AVMEDIA_TYPE_DATA:

        avio_w8(pb, FLV_TAG_TYPE_META);

        break;

    default:

        return AVERROR(EINVAL);

    }

    if (enc->codec_id == AV_CODEC_ID_H264)

        /* check if extradata looks like MP4 */

        if (enc->extradata_size > 0 && *(uint8_t*)enc->extradata != 1)

            if (ff_avc_parse_nal_units_buf(pkt->data, &data, &size) < 0)

                return -1;

    /* check Speex packet duration */

    if (enc->codec_id == AV_CODEC_ID_SPEEX && ts - sc->last_ts > 160)

        av_log(s, AV_LOG_WARNING, "Warning: Speex stream has more than "

                                  "8 frames per packet. Adobe Flash "

                                  "Player cannot handle this!\n");

    if (sc->last_ts < ts)

        sc->last_ts = ts;

    avio_wb24(pb, size + flags_size);

    avio_wb24(pb, ts);

    avio_w8(pb, (ts >> 24) & 0x7F); // timestamps are 32 bits _signed_

    avio_wb24(pb, flv->reserved);

    if (enc->codec_type == AVMEDIA_TYPE_DATA) {

        int data_size;

        int64_t metadata_size_pos = avio_tell(pb);

        avio_w8(pb, AMF_DATA_TYPE_STRING);

        put_amf_string(pb, "onTextData");

        avio_w8(pb, AMF_DATA_TYPE_MIXEDARRAY);

        avio_wb32(pb, 2);

        put_amf_string(pb, "type");

        avio_w8(pb, AMF_DATA_TYPE_STRING);

        put_amf_string(pb, "Text");

        put_amf_string(pb, "text");

        avio_w8(pb, AMF_DATA_TYPE_STRING);

        put_amf_string(pb, pkt->data);

        put_amf_string(pb, "");

        avio_w8(pb, AMF_END_OF_OBJECT);

        /* write total size of tag */

        data_size = avio_tell(pb) - metadata_size_pos;

        avio_seek(pb, metadata_size_pos - 10, SEEK_SET);

        avio_wb24(pb, data_size);

        avio_seek(pb, data_size + 10 - 3, SEEK_CUR);

        avio_wb32(pb, data_size + 11);

    } else {

        avio_w8(pb,flags);

        if (enc->codec_id == AV_CODEC_ID_VP6F || enc->codec_id == AV_CODEC_ID_VP6A) {

            if (enc->extradata_size)

                avio_w8(pb, enc->extradata[0]);

            else

                avio_w8(pb, ((FFALIGN(enc->width,  16) - enc->width) << 4) |

                             (FFALIGN(enc->height, 16) - enc->height));

        } else if (enc->codec_id == AV_CODEC_ID_AAC)

            avio_w8(pb, 1); // AAC raw

        else if (enc->codec_id == AV_CODEC_ID_H264) {

            avio_w8(pb, 1); // AVC NALU

            avio_wb24(pb, pkt->pts - pkt->dts);

        }

        avio_write(pb, data ? data : pkt->data, size);

        avio_wb32(pb, size + flags_size + 11); // previous tag size

        flv->duration = FFMAX(flv->duration,

                              pkt->pts + flv->delay + pkt->duration);

    }

    av_free(data);

    return pb->error;

}


matroska_probe (AVProbeData *p)

{

    uint64_t total = 0;

    int len_mask = 0x80, size = 1, n = 1;

    uint8_t probe_data[] = { 'm', 'a', 't', 'r', 'o', 's', 'k', 'a' };

    if (p->buf_size < 5)

        return 0;

    /* ebml header? */

    if ((p->buf[0] << 24 | p->buf[1] << 16 |

         p->buf[2] << 8 | p->buf[3]) != EBML_ID_HEADER)

        return 0;

    /* length of header */

    total = p->buf[4];

    while (size <= 8 && !(total & len_mask)) {

        size++;

        len_mask >>= 1;

    }

    if (size > 8)

      return 0;

    total &= (len_mask - 1);

    while (n < size)

        total = (total << 8) | p->buf[4 + n++];

    /* does the probe data contain the whole header? */

    if (p->buf_size < 4 + size + total)

      return 0;

    /* the header must contain the document type 'matroska'. For now,

     * we don't parse the whole header but simply check for the

     * availability of that array of characters inside the header.

     * Not fully fool-proof, but good enough. */

    for (n = 4 + size; n <= 4 + size + total - sizeof(probe_data); n++)

        if (!memcmp (&p->buf[n], probe_data, sizeof(probe_data)))

            return AVPROBE_SCORE_MAX;

    return 0;

}


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

{

    SIFFContext *c = s->priv_data;

    int size;

    if (c->has_video){

        if (c->cur_frame >= c->frames)

            return AVERROR_EOF;

        if (c->curstrm == -1){

            c->pktsize = avio_rl32(s->pb) - 4;

            c->flags = avio_rl16(s->pb);

            c->gmcsize = (c->flags & VB_HAS_GMC) ? 4 : 0;

            if (c->gmcsize)

                avio_read(s->pb, c->gmc, c->gmcsize);

            c->sndsize = (c->flags & VB_HAS_AUDIO) ? avio_rl32(s->pb): 0;

            c->curstrm = !!(c->flags & VB_HAS_AUDIO);

        }

        if (!c->curstrm){

            size = c->pktsize - c->sndsize - c->gmcsize - 2;

            size = ffio_limit(s->pb, size);

            if(size < 0 || c->pktsize < c->sndsize)

                return AVERROR_INVALIDDATA;

            if (av_new_packet(pkt, size + c->gmcsize + 2) < 0)

                return AVERROR(ENOMEM);

            AV_WL16(pkt->data, c->flags);

            if (c->gmcsize)

                memcpy(pkt->data + 2, c->gmc, c->gmcsize);

            avio_read(s->pb, pkt->data + 2 + c->gmcsize, size);

            pkt->stream_index = 0;

            c->curstrm = -1;

        }else{

            if ((size = av_get_packet(s->pb, pkt, c->sndsize - 4)) < 0)

                return AVERROR(EIO);

            pkt->stream_index = 1;

            pkt->duration     = size;

            c->curstrm = 0;

        }

        if(!c->cur_frame || c->curstrm)

            pkt->flags |= AV_PKT_FLAG_KEY;

        if (c->curstrm == -1)

            c->cur_frame++;

    }else{

        size = av_get_packet(s->pb, pkt, c->block_align);

        if(!size)

            return AVERROR_EOF;

        if(size < 0)

            return AVERROR(EIO);

        pkt->duration = size;

    }

    return pkt->size;

}


static void dequantization_float(int x, int y, Jpeg2000Cblk *cblk,

                                 Jpeg2000Component *comp,

                                 Jpeg2000T1Context *t1, Jpeg2000Band *band)

{

    int i, j, idx;

    float *datap = &comp->data[(comp->coord[0][1] - comp->coord[0][0]) * y + x];

    for (j = 0; j < (cblk->coord[1][1] - cblk->coord[1][0]); ++j)

        for (i = 0; i < (cblk->coord[0][1] - cblk->coord[0][0]); ++i) {

            idx        = (comp->coord[0][1] - comp->coord[0][0]) * j + i;

            datap[idx] = (float)(t1->data[j][i]) * band->f_stepsize;

        }

}


device_init(usb_host_register_devices)

USBDevice *usb_host_device_open(const char *devname)

{

    struct USBAutoFilter filter = { 0, 0, 0, 0 };

    USBDevice *dev;

    USBHostDevice *s;

    char *p;

    dev = usb_create(NULL /* FIXME */, "USB Host Device");

    s = DO_UPCAST(USBHostDevice, dev, dev);

    if (strstr(devname, "auto:")) {

        if (parse_filter(devname+5, &filter) < 0)

            goto fail;

    } else {

        if ((p = strchr(devname, '.'))) {

            filter.bus_num = strtoul(devname, NULL, 0);

            filter.addr    = strtoul(devname, NULL, 0);

        } else if ((p = strchr(devname, ':'))) {

            filter.vendor_id  = strtoul(devname, NULL, 16);

            filter.product_id = strtoul(devname, NULL, 16);

        } else {

            goto fail;

        }

    }

    qdev_prop_set_uint32(&dev->qdev, "bus",       filter.bus_num);

    qdev_prop_set_uint32(&dev->qdev, "addr",      filter.addr);

    qdev_prop_set_uint32(&dev->qdev, "vendorid",  filter.vendor_id);

    qdev_prop_set_uint32(&dev->qdev, "productid", filter.product_id);

    qdev_init(&dev->qdev);

    return dev;

fail:

    qdev_free(&dev->qdev);

    return NULL;

}


void qemu_error_internal(const char *file, int linenr, const char *func,

                         const char *fmt, ...)

{

    va_list va;

    QError *qerror;

    assert(qemu_error_sink != NULL);

    va_start(va, fmt);

    qerror = qerror_from_info(file, linenr, func, fmt, &va);

    va_end(va);

    switch (qemu_error_sink->dest) {

    case ERR_SINK_FILE:

        qerror_print(qerror);

        QDECREF(qerror);

        break;

    case ERR_SINK_MONITOR:

        assert(qemu_error_sink->mon->error == NULL);

        qemu_error_sink->mon->error = qerror;

        break;

    }

}


av_cold void ff_vc1dsp_init(VC1DSPContext* dsp) {

    dsp->vc1_inv_trans_8x8 = vc1_inv_trans_8x8_c;

    dsp->vc1_inv_trans_4x8 = vc1_inv_trans_4x8_c;

    dsp->vc1_inv_trans_8x4 = vc1_inv_trans_8x4_c;

    dsp->vc1_inv_trans_4x4 = vc1_inv_trans_4x4_c;

    dsp->vc1_inv_trans_8x8_dc = vc1_inv_trans_8x8_dc_c;

    dsp->vc1_inv_trans_4x8_dc = vc1_inv_trans_4x8_dc_c;

    dsp->vc1_inv_trans_8x4_dc = vc1_inv_trans_8x4_dc_c;

    dsp->vc1_inv_trans_4x4_dc = vc1_inv_trans_4x4_dc_c;

    dsp->vc1_h_overlap = vc1_h_overlap_c;

    dsp->vc1_v_overlap = vc1_v_overlap_c;

    dsp->vc1_v_loop_filter4 = vc1_v_loop_filter4_c;

    dsp->vc1_h_loop_filter4 = vc1_h_loop_filter4_c;

    dsp->vc1_v_loop_filter8 = vc1_v_loop_filter8_c;

    dsp->vc1_h_loop_filter8 = vc1_h_loop_filter8_c;

    dsp->vc1_v_loop_filter16 = vc1_v_loop_filter16_c;

    dsp->vc1_h_loop_filter16 = vc1_h_loop_filter16_c;

    dsp->put_vc1_mspel_pixels_tab[ 0] = ff_put_pixels8x8_c;

    dsp->put_vc1_mspel_pixels_tab[ 1] = put_vc1_mspel_mc10_c;

    dsp->put_vc1_mspel_pixels_tab[ 2] = put_vc1_mspel_mc20_c;

    dsp->put_vc1_mspel_pixels_tab[ 3] = put_vc1_mspel_mc30_c;

    dsp->put_vc1_mspel_pixels_tab[ 4] = put_vc1_mspel_mc01_c;

    dsp->put_vc1_mspel_pixels_tab[ 5] = put_vc1_mspel_mc11_c;

    dsp->put_vc1_mspel_pixels_tab[ 6] = put_vc1_mspel_mc21_c;

    dsp->put_vc1_mspel_pixels_tab[ 7] = put_vc1_mspel_mc31_c;

    dsp->put_vc1_mspel_pixels_tab[ 8] = put_vc1_mspel_mc02_c;

    dsp->put_vc1_mspel_pixels_tab[ 9] = put_vc1_mspel_mc12_c;

    dsp->put_vc1_mspel_pixels_tab[10] = put_vc1_mspel_mc22_c;

    dsp->put_vc1_mspel_pixels_tab[11] = put_vc1_mspel_mc32_c;

    dsp->put_vc1_mspel_pixels_tab[12] = put_vc1_mspel_mc03_c;

    dsp->put_vc1_mspel_pixels_tab[13] = put_vc1_mspel_mc13_c;

    dsp->put_vc1_mspel_pixels_tab[14] = put_vc1_mspel_mc23_c;

    dsp->put_vc1_mspel_pixels_tab[15] = put_vc1_mspel_mc33_c;

    dsp->avg_vc1_mspel_pixels_tab[ 0] = ff_avg_pixels8x8_c;

    dsp->avg_vc1_mspel_pixels_tab[ 1] = avg_vc1_mspel_mc10_c;

    dsp->avg_vc1_mspel_pixels_tab[ 2] = avg_vc1_mspel_mc20_c;

    dsp->avg_vc1_mspel_pixels_tab[ 3] = avg_vc1_mspel_mc30_c;

    dsp->avg_vc1_mspel_pixels_tab[ 4] = avg_vc1_mspel_mc01_c;

    dsp->avg_vc1_mspel_pixels_tab[ 5] = avg_vc1_mspel_mc11_c;

    dsp->avg_vc1_mspel_pixels_tab[ 6] = avg_vc1_mspel_mc21_c;

    dsp->avg_vc1_mspel_pixels_tab[ 7] = avg_vc1_mspel_mc31_c;

    dsp->avg_vc1_mspel_pixels_tab[ 8] = avg_vc1_mspel_mc02_c;

    dsp->avg_vc1_mspel_pixels_tab[ 9] = avg_vc1_mspel_mc12_c;

    dsp->avg_vc1_mspel_pixels_tab[10] = avg_vc1_mspel_mc22_c;

    dsp->avg_vc1_mspel_pixels_tab[11] = avg_vc1_mspel_mc32_c;

    dsp->avg_vc1_mspel_pixels_tab[12] = avg_vc1_mspel_mc03_c;

    dsp->avg_vc1_mspel_pixels_tab[13] = avg_vc1_mspel_mc13_c;

    dsp->avg_vc1_mspel_pixels_tab[14] = avg_vc1_mspel_mc23_c;

    dsp->avg_vc1_mspel_pixels_tab[15] = avg_vc1_mspel_mc33_c;

    dsp->put_no_rnd_vc1_chroma_pixels_tab[0]= put_no_rnd_vc1_chroma_mc8_c;

    dsp->avg_no_rnd_vc1_chroma_pixels_tab[0]= avg_no_rnd_vc1_chroma_mc8_c;

    if (HAVE_ALTIVEC)

        ff_vc1dsp_init_altivec(dsp);

    if (HAVE_MMX)

        ff_vc1dsp_init_mmx(dsp);

}


static void intra_predict_vert_8x8_msa(uint8_t *src, uint8_t *dst,

                                       int32_t dst_stride)

{

    uint32_t row;

    uint32_t src_data1, src_data2;

    src_data1 = LW(src);

    src_data2 = LW(src + 4);

    for (row = 8; row--;) {

        SW(src_data1, dst);

        SW(src_data2, (dst + 4));

        dst += dst_stride;

    }

}


static void spapr_phb_placement(sPAPRMachineState *spapr, uint32_t index,

                                uint64_t *buid, hwaddr *pio, hwaddr *mmio,

                                unsigned n_dma, uint32_t *liobns, Error **errp)

{

    const uint64_t base_buid = 0x800000020000000ULL;

    const hwaddr phb_spacing = 0x1000000000ULL; /* 64 GiB */

    const hwaddr mmio_offset = 0xa0000000; /* 2 GiB + 512 MiB */

    const hwaddr pio_offset = 0x80000000; /* 2 GiB */

    const uint32_t max_index = 255;

    const hwaddr phb0_alignment = 0x10000000000ULL; /* 1 TiB */

    uint64_t ram_top = MACHINE(spapr)->ram_size;

    hwaddr phb0_base, phb_base;

    int i;

    /* Do we have hotpluggable memory? */

    if (MACHINE(spapr)->maxram_size > ram_top) {

        /* Can't just use maxram_size, because there may be an

         * alignment gap between normal and hotpluggable memory

         * regions */

        ram_top = spapr->hotplug_memory.base +

            memory_region_size(&spapr->hotplug_memory.mr);

    }

    phb0_base = QEMU_ALIGN_UP(ram_top, phb0_alignment);

    if (index > max_index) {

        error_setg(errp, "\"index\" for PAPR PHB is too large (max %u)",

                   max_index);

        return;

    }

    *buid = base_buid + index;

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

        liobns[i] = SPAPR_PCI_LIOBN(index, i);

    }

    phb_base = phb0_base + index * phb_spacing;

    *pio = phb_base + pio_offset;

    *mmio = phb_base + mmio_offset;

}


int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,

                      int64_t pos, int size)

{

    QEMUIOVector qiov;

    struct iovec iov = {

        .iov_base   = (void *) buf,

        .iov_len    = size,

    };

    qemu_iovec_init_external(&qiov, &iov, 1);

    return bdrv_writev_vmstate(bs, &qiov, pos);

}


static int swr_convert_internal(struct SwrContext *s, AudioData *out, int out_count,

                                                      AudioData *in , int  in_count){

    AudioData *postin, *midbuf, *preout;

    int ret/*, in_max*/;

    AudioData preout_tmp, midbuf_tmp;

    if(s->full_convert){

        av_assert0(!s->resample);

        swri_audio_convert(s->full_convert, out, in, in_count);

        return out_count;

    }

//     in_max= out_count*(int64_t)s->in_sample_rate / s->out_sample_rate + resample_filter_taps;

//     in_count= FFMIN(in_count, in_in + 2 - s->hist_buffer_count);

    if((ret=swri_realloc_audio(&s->postin, in_count))<0)

        return ret;

    if(s->resample_first){

        av_assert0(s->midbuf.ch_count == s->used_ch_count);

        if((ret=swri_realloc_audio(&s->midbuf, out_count))<0)

            return ret;

    }else{

        av_assert0(s->midbuf.ch_count ==  s->out.ch_count);

        if((ret=swri_realloc_audio(&s->midbuf,  in_count))<0)

            return ret;

    }

    if((ret=swri_realloc_audio(&s->preout, out_count))<0)

        return ret;

    postin= &s->postin;

    midbuf_tmp= s->midbuf;

    midbuf= &midbuf_tmp;

    preout_tmp= s->preout;

    preout= &preout_tmp;

    if(s->int_sample_fmt == s-> in_sample_fmt && s->in.planar && !s->channel_map)

        postin= in;

    if(s->resample_first ? !s->resample : !s->rematrix)

        midbuf= postin;

    if(s->resample_first ? !s->rematrix : !s->resample)

        preout= midbuf;

    if(s->int_sample_fmt == s->out_sample_fmt && s->out.planar

       && !(s->out_sample_fmt==AV_SAMPLE_FMT_S32P && (s->dither.output_sample_bits&31))){

        if(preout==in){

            out_count= FFMIN(out_count, in_count); //TODO check at the end if this is needed or redundant

            av_assert0(s->in.planar); //we only support planar internally so it has to be, we support copying non planar though

            copy(out, in, out_count);

            return out_count;

        }

        else if(preout==postin) preout= midbuf= postin= out;

        else if(preout==midbuf) preout= midbuf= out;

        else                    preout= out;

    }

    if(in != postin){

        swri_audio_convert(s->in_convert, postin, in, in_count);

    }

    if(s->resample_first){

        if(postin != midbuf)

            out_count= resample(s, midbuf, out_count, postin, in_count);

        if(midbuf != preout)

            swri_rematrix(s, preout, midbuf, out_count, preout==out);

    }else{

        if(postin != midbuf)

            swri_rematrix(s, midbuf, postin, in_count, midbuf==out);

        if(midbuf != preout)

            out_count= resample(s, preout, out_count, midbuf, in_count);

    }

    if(preout != out && out_count){

        AudioData *conv_src = preout;

        if(s->dither.method){

            int ch;

            int dither_count= FFMAX(out_count, 1<<16);

            if (preout == in) {

                conv_src = &s->dither.temp;

                if((ret=swri_realloc_audio(&s->dither.temp, dither_count))<0)

                    return ret;

            }

            if((ret=swri_realloc_audio(&s->dither.noise, dither_count))<0)

                return ret;

            if(ret)

                for(ch=0; ch<s->dither.noise.ch_count; ch++)

                    swri_get_dither(s, s->dither.noise.ch[ch], s->dither.noise.count, 12345678913579<<ch, s->dither.noise.fmt);

            av_assert0(s->dither.noise.ch_count == preout->ch_count);

            if(s->dither.noise_pos + out_count > s->dither.noise.count)

                s->dither.noise_pos = 0;

            if (s->dither.method < SWR_DITHER_NS){

                if (s->mix_2_1_simd) {

                    int len1= out_count&~15;

                    int off = len1 * preout->bps;

                    if(len1)

                        for(ch=0; ch<preout->ch_count; ch++)

                            s->mix_2_1_simd(conv_src->ch[ch], preout->ch[ch], s->dither.noise.ch[ch] + s->dither.noise.bps * s->dither.noise_pos, s->native_simd_one, 0, 0, len1);

                    if(out_count != len1)

                        for(ch=0; ch<preout->ch_count; ch++)

                            s->mix_2_1_f(conv_src->ch[ch] + off, preout->ch[ch] + off, s->dither.noise.ch[ch] + s->dither.noise.bps * s->dither.noise_pos + off + len1, s->native_one, 0, 0, out_count - len1);

                } else {

                    for(ch=0; ch<preout->ch_count; ch++)

                        s->mix_2_1_f(conv_src->ch[ch], preout->ch[ch], s->dither.noise.ch[ch] + s->dither.noise.bps * s->dither.noise_pos, s->native_one, 0, 0, out_count);

                }

            } else {

                switch(s->int_sample_fmt) {

                case AV_SAMPLE_FMT_S16P :swri_noise_shaping_int16(s, conv_src, preout, &s->dither.noise, out_count); break;

                case AV_SAMPLE_FMT_S32P :swri_noise_shaping_int32(s, conv_src, preout, &s->dither.noise, out_count); break;

                case AV_SAMPLE_FMT_FLTP :swri_noise_shaping_float(s, conv_src, preout, &s->dither.noise, out_count); break;

                case AV_SAMPLE_FMT_DBLP :swri_noise_shaping_double(s,conv_src, preout, &s->dither.noise, out_count); break;

                }

            }

            s->dither.noise_pos += out_count;

        }

//FIXME packed doesn't need more than 1 chan here!

        swri_audio_convert(s->out_convert, out, conv_src, out_count);

    }

    return out_count;

}


void helper_fcmpo (uint64_t arg1, uint64_t arg2, uint32_t crfD)

{

    CPU_DoubleU farg1, farg2;

    uint32_t ret = 0;

    farg1.ll = arg1;

    farg2.ll = arg2;

    if (unlikely(float64_is_nan(farg1.d) ||

                 float64_is_nan(farg2.d))) {

        ret = 0x01UL;

    } else if (float64_lt(farg1.d, farg2.d, &env->fp_status)) {

        ret = 0x08UL;

    } else if (!float64_le(farg1.d, farg2.d, &env->fp_status)) {

        ret = 0x04UL;

    } else {

        ret = 0x02UL;

    }

    env->fpscr &= ~(0x0F << FPSCR_FPRF);

    env->fpscr |= ret << FPSCR_FPRF;

    env->crf[crfD] = ret;

    if (unlikely (ret == 0x01UL)) {

        if (float64_is_signaling_nan(farg1.d) ||

            float64_is_signaling_nan(farg2.d)) {

            /* sNaN comparison */

            fload_invalid_op_excp(POWERPC_EXCP_FP_VXSNAN |

                                  POWERPC_EXCP_FP_VXVC);

        } else {

            /* qNaN comparison */

            fload_invalid_op_excp(POWERPC_EXCP_FP_VXVC);

        }

    }

}


int qcow2_check_refcounts(BlockDriverState *bs, BdrvCheckResult *res,

                          BdrvCheckMode fix)

{

    BDRVQcowState *s = bs->opaque;

    int64_t size, i, highest_cluster;

    int nb_clusters, refcount1, refcount2;

    QCowSnapshot *sn;

    uint16_t *refcount_table;

    int ret;

    size = bdrv_getlength(bs->file);

    nb_clusters = size_to_clusters(s, size);

    refcount_table = g_malloc0(nb_clusters * sizeof(uint16_t));

    /* header */

    inc_refcounts(bs, res, refcount_table, nb_clusters,

        0, s->cluster_size);

    /* current L1 table */

    ret = check_refcounts_l1(bs, res, refcount_table, nb_clusters,

                       s->l1_table_offset, s->l1_size, 1);

    if (ret < 0) {

        goto fail;

    }

    /* snapshots */

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

        sn = s->snapshots + i;

        ret = check_refcounts_l1(bs, res, refcount_table, nb_clusters,

            sn->l1_table_offset, sn->l1_size, 0);

        if (ret < 0) {

            goto fail;

        }

    }

    inc_refcounts(bs, res, refcount_table, nb_clusters,

        s->snapshots_offset, s->snapshots_size);

    /* refcount data */

    inc_refcounts(bs, res, refcount_table, nb_clusters,

        s->refcount_table_offset,

        s->refcount_table_size * sizeof(uint64_t));

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

        uint64_t offset, cluster;

        offset = s->refcount_table[i];

        cluster = offset >> s->cluster_bits;

        /* Refcount blocks are cluster aligned */

        if (offset & (s->cluster_size - 1)) {

            fprintf(stderr, "ERROR refcount block %" PRId64 " is not "

                "cluster aligned; refcount table entry corrupted\n", i);

            res->corruptions++;

            continue;

        }

        if (cluster >= nb_clusters) {

            fprintf(stderr, "ERROR refcount block %" PRId64

                    " is outside image\n", i);

            res->corruptions++;

            continue;

        }

        if (offset != 0) {

            inc_refcounts(bs, res, refcount_table, nb_clusters,

                offset, s->cluster_size);

            if (refcount_table[cluster] != 1) {

                fprintf(stderr, "ERROR refcount block %" PRId64

                    " refcount=%d\n",

                    i, refcount_table[cluster]);

                res->corruptions++;

            }

        }

    }

    /* compare ref counts */

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

        refcount1 = get_refcount(bs, i);

        if (refcount1 < 0) {

            fprintf(stderr, "Can't get refcount for cluster %" PRId64 ": %s\n",

                i, strerror(-refcount1));

            res->check_errors++;

            continue;

        }

        refcount2 = refcount_table[i];

        if (refcount1 > 0 || refcount2 > 0) {

            highest_cluster = i;

        }

        if (refcount1 != refcount2) {

            /* Check if we're allowed to fix the mismatch */

            int *num_fixed = NULL;

            if (refcount1 > refcount2 && (fix & BDRV_FIX_LEAKS)) {

                num_fixed = &res->leaks_fixed;

            } else if (refcount1 < refcount2 && (fix & BDRV_FIX_ERRORS)) {

                num_fixed = &res->corruptions_fixed;

            }

            fprintf(stderr, "%s cluster %" PRId64 " refcount=%d reference=%d\n",

                   num_fixed != NULL     ? "Repairing" :

                   refcount1 < refcount2 ? "ERROR" :

                                           "Leaked",

                   i, refcount1, refcount2);

            if (num_fixed) {

                ret = update_refcount(bs, i << s->cluster_bits, 1,

                                      refcount2 - refcount1);

                if (ret >= 0) {

                    (*num_fixed)++;

                    continue;

                }

            }

            /* And if we couldn't, print an error */

            if (refcount1 < refcount2) {

                res->corruptions++;

            } else {

                res->leaks++;

            }

        }

    }

    res->image_end_offset = (highest_cluster + 1) * s->cluster_size;

    ret = 0;

fail:

    g_free(refcount_table);

    return ret;

}


void qmp_x_blockdev_set_iothread(const char *node_name, StrOrNull *iothread,

                                 Error **errp)

{

    AioContext *old_context;

    AioContext *new_context;

    BlockDriverState *bs;

    bs = bdrv_find_node(node_name);

    if (!bs) {

        error_setg(errp, "Cannot find node %s", node_name);

        return;

    }

    /* If we want to allow more extreme test scenarios this guard could be

     * removed.  For now it protects against accidents. */

    if (bdrv_has_blk(bs)) {

        error_setg(errp, "Node %s is in use", node_name);

        return;

    }

    if (iothread->type == QTYPE_QSTRING) {

        IOThread *obj = iothread_by_id(iothread->u.s);

        if (!obj) {

            error_setg(errp, "Cannot find iothread %s", iothread->u.s);

            return;

        }

        new_context = iothread_get_aio_context(obj);

    } else {

        new_context = qemu_get_aio_context();

    }

    old_context = bdrv_get_aio_context(bs);

    aio_context_acquire(old_context);

    bdrv_set_aio_context(bs, new_context);

    aio_context_release(old_context);

}


static void test_dealloc_partial(void)

{

    static const char text[] = "don't leak me";

    UserDefTwo *ud2 = NULL;

    Error *err = NULL;

    /* create partial object */

    {

        QDict *ud2_dict;

        QmpInputVisitor *qiv;

        ud2_dict = qdict_new();

        qdict_put_obj(ud2_dict, "string0", QOBJECT(qstring_from_str(text)));

        qiv = qmp_input_visitor_new(QOBJECT(ud2_dict), false);

        visit_type_UserDefTwo(qmp_input_get_visitor(qiv), NULL, &ud2, &err);

        qmp_input_visitor_cleanup(qiv);

        QDECREF(ud2_dict);

    }

    /* verify partial success */

    assert(ud2 != NULL);

    assert(ud2->string0 != NULL);

    assert(strcmp(ud2->string0, text) == 0);

    assert(ud2->dict1 == NULL);

    /* confirm & release construction error */

    error_free_or_abort(&err);

    /* tear down partial object */

    qapi_free_UserDefTwo(ud2);

}


size_t tcg_code_size(void)

{

    unsigned int i;

    size_t total;

    qemu_mutex_lock(&region.lock);

    total = region.agg_size_full;

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

        const TCGContext *s = tcg_ctxs[i];

        size_t size;

        size = atomic_read(&s->code_gen_ptr) - s->code_gen_buffer;

        g_assert(size <= s->code_gen_buffer_size);

        total += size;

    }

    qemu_mutex_unlock(&region.lock);

    return total;

}


static inline abi_long host_to_target_stat64(void *cpu_env,

                                             abi_ulong target_addr,

                                             struct stat *host_st)

{

#ifdef TARGET_ARM

    if (((CPUARMState *)cpu_env)->eabi) {

        struct target_eabi_stat64 *target_st;

        if (!lock_user_struct(VERIFY_WRITE, target_st, target_addr, 0))

            return -TARGET_EFAULT;

        memset(target_st, 0, sizeof(struct target_eabi_stat64));

        __put_user(host_st->st_dev, &target_st->st_dev);

        __put_user(host_st->st_ino, &target_st->st_ino);

#ifdef TARGET_STAT64_HAS_BROKEN_ST_INO

        __put_user(host_st->st_ino, &target_st->__st_ino);

#endif

        __put_user(host_st->st_mode, &target_st->st_mode);

        __put_user(host_st->st_nlink, &target_st->st_nlink);

        __put_user(host_st->st_uid, &target_st->st_uid);

        __put_user(host_st->st_gid, &target_st->st_gid);

        __put_user(host_st->st_rdev, &target_st->st_rdev);

        __put_user(host_st->st_size, &target_st->st_size);

        __put_user(host_st->st_blksize, &target_st->st_blksize);

        __put_user(host_st->st_blocks, &target_st->st_blocks);

        __put_user(host_st->st_atime, &target_st->target_st_atime);

        __put_user(host_st->st_mtime, &target_st->target_st_mtime);

        __put_user(host_st->st_ctime, &target_st->target_st_ctime);

        unlock_user_struct(target_st, target_addr, 1);

    } else

#endif

    {

#if TARGET_LONG_BITS == 64

        struct target_stat *target_st;

#else

        struct target_stat64 *target_st;

#endif

        if (!lock_user_struct(VERIFY_WRITE, target_st, target_addr, 0))

            return -TARGET_EFAULT;

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

        __put_user(host_st->st_dev, &target_st->st_dev);

        __put_user(host_st->st_ino, &target_st->st_ino);

#ifdef TARGET_STAT64_HAS_BROKEN_ST_INO

        __put_user(host_st->st_ino, &target_st->__st_ino);

#endif

        __put_user(host_st->st_mode, &target_st->st_mode);

        __put_user(host_st->st_nlink, &target_st->st_nlink);

        __put_user(host_st->st_uid, &target_st->st_uid);

        __put_user(host_st->st_gid, &target_st->st_gid);

        __put_user(host_st->st_rdev, &target_st->st_rdev);

        /* XXX: better use of kernel struct */

        __put_user(host_st->st_size, &target_st->st_size);

        __put_user(host_st->st_blksize, &target_st->st_blksize);

        __put_user(host_st->st_blocks, &target_st->st_blocks);

        __put_user(host_st->st_atime, &target_st->target_st_atime);

        __put_user(host_st->st_mtime, &target_st->target_st_mtime);

        __put_user(host_st->st_ctime, &target_st->target_st_ctime);

        unlock_user_struct(target_st, target_addr, 1);

    }

    return 0;

}


static abi_ulong setup_arg_pages(abi_ulong p, struct linux_binprm *bprm,

                                 struct image_info *info)

{

    abi_ulong stack_base, size, error;

    int i;

    /* Create enough stack to hold everything.  If we don't use

     * it for args, we'll use it for something else...

     */

    size = x86_stack_size;

    if (size < MAX_ARG_PAGES*TARGET_PAGE_SIZE)

        size = MAX_ARG_PAGES*TARGET_PAGE_SIZE;

    error = target_mmap(0,

                        size + qemu_host_page_size,

                        PROT_READ | PROT_WRITE,

                        MAP_PRIVATE | MAP_ANONYMOUS,

                        -1, 0);

    if (error == -1) {

        perror("stk mmap");

        exit(-1);

    }

    /* we reserve one extra page at the top of the stack as guard */

    target_mprotect(error + size, qemu_host_page_size, PROT_NONE);

    stack_base = error + size - MAX_ARG_PAGES*TARGET_PAGE_SIZE;

    p += stack_base;

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

	if (bprm->page[i]) {

	    info->rss++;

            /* FIXME - check return value of memcpy_to_target() for failure */

	    memcpy_to_target(stack_base, bprm->page[i], TARGET_PAGE_SIZE);

	    free(bprm->page[i]);

	}

        stack_base += TARGET_PAGE_SIZE;

    }

    return p;

}


void xen_map_cache_init(void)

{

    unsigned long size;

    struct rlimit rlimit_as;

    mapcache = g_malloc0(sizeof (MapCache));

    QTAILQ_INIT(&mapcache->locked_entries);

    mapcache->last_address_index = -1;

    getrlimit(RLIMIT_AS, &rlimit_as);

    if (rlimit_as.rlim_max < MCACHE_MAX_SIZE) {

        rlimit_as.rlim_cur = rlimit_as.rlim_max;

    } else {

        rlimit_as.rlim_cur = MCACHE_MAX_SIZE;

    }

    setrlimit(RLIMIT_AS, &rlimit_as);

    mapcache->max_mcache_size = rlimit_as.rlim_cur;

    mapcache->nr_buckets =

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

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

         (MCACHE_BUCKET_SHIFT - XC_PAGE_SHIFT));

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

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

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

            mapcache->nr_buckets, size);

    mapcache->entry = g_malloc0(size);

}


static BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,

                                   const char *filename)

{

    int score_max = 0, score;

    BlockDriver *drv = NULL, *d;

    QLIST_FOREACH(d, &bdrv_drivers, list) {

        if (d->bdrv_probe) {

            score = d->bdrv_probe(buf, buf_size, filename);

            if (score > score_max) {

                score_max = score;

                drv = d;

            }

        }

    }

    return drv;

}


static void do_change(const char *device, const char *target)

{

    if (strcmp(device, "vnc") == 0) {

	do_change_vnc(target);

    } else {

	do_change_block(device, target);

    }

}