static void gic_dist_writeb(void *opaque, hwaddr offset,

                            uint32_t value, MemTxAttrs attrs)

{

    GICState *s = (GICState *)opaque;

    int irq;

    int i;

    int cpu;

    cpu = gic_get_current_cpu(s);

    if (offset < 0x100) {

        if (offset == 0) {

            s->enabled = (value & 1);

            DPRINTF("Distribution %sabled\n", s->enabled ? "En" : "Dis");

        } else if (offset < 4) {

            /* ignored.  */

        } else if (offset >= 0x80) {

            /* Interrupt Security Registers, RAZ/WI */

        } else {

            goto bad_reg;

        }

    } else if (offset < 0x180) {

        /* Interrupt Set Enable.  */

        irq = (offset - 0x100) * 8 + GIC_BASE_IRQ;

        if (irq >= s->num_irq)

            goto bad_reg;

        if (irq < GIC_NR_SGIS) {

            value = 0xff;

        }

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

            if (value & (1 << i)) {

                int mask =

                    (irq < GIC_INTERNAL) ? (1 << cpu) : GIC_TARGET(irq + i);

                int cm = (irq < GIC_INTERNAL) ? (1 << cpu) : ALL_CPU_MASK;

                if (!GIC_TEST_ENABLED(irq + i, cm)) {

                    DPRINTF("Enabled IRQ %d\n", irq + i);

                }

                GIC_SET_ENABLED(irq + i, cm);

                /* If a raised level triggered IRQ enabled then mark

                   is as pending.  */

                if (GIC_TEST_LEVEL(irq + i, mask)

                        && !GIC_TEST_EDGE_TRIGGER(irq + i)) {

                    DPRINTF("Set %d pending mask %x\n", irq + i, mask);

                    GIC_SET_PENDING(irq + i, mask);

                }

            }

        }

    } else if (offset < 0x200) {

        /* Interrupt Clear Enable.  */

        irq = (offset - 0x180) * 8 + GIC_BASE_IRQ;

        if (irq >= s->num_irq)

            goto bad_reg;

        if (irq < GIC_NR_SGIS) {

            value = 0;

        }

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

            if (value & (1 << i)) {

                int cm = (irq < GIC_INTERNAL) ? (1 << cpu) : ALL_CPU_MASK;

                if (GIC_TEST_ENABLED(irq + i, cm)) {

                    DPRINTF("Disabled IRQ %d\n", irq + i);

                }

                GIC_CLEAR_ENABLED(irq + i, cm);

            }

        }

    } else if (offset < 0x280) {

        /* Interrupt Set Pending.  */

        irq = (offset - 0x200) * 8 + GIC_BASE_IRQ;

        if (irq >= s->num_irq)

            goto bad_reg;

        if (irq < GIC_NR_SGIS) {

            value = 0;

        }

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

            if (value & (1 << i)) {

                GIC_SET_PENDING(irq + i, GIC_TARGET(irq + i));

            }

        }

    } else if (offset < 0x300) {

        /* Interrupt Clear Pending.  */

        irq = (offset - 0x280) * 8 + GIC_BASE_IRQ;

        if (irq >= s->num_irq)

            goto bad_reg;

        if (irq < GIC_NR_SGIS) {

            value = 0;

        }

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

            /* ??? This currently clears the pending bit for all CPUs, even

               for per-CPU interrupts.  It's unclear whether this is the

               corect behavior.  */

            if (value & (1 << i)) {

                GIC_CLEAR_PENDING(irq + i, ALL_CPU_MASK);

            }

        }

    } else if (offset < 0x400) {

        /* Interrupt Active.  */

        goto bad_reg;

    } else if (offset < 0x800) {

        /* Interrupt Priority.  */

        irq = (offset - 0x400) + GIC_BASE_IRQ;

        if (irq >= s->num_irq)

            goto bad_reg;

        gic_set_priority(s, cpu, irq, value);

    } else if (offset < 0xc00) {

        /* Interrupt CPU Target. RAZ/WI on uniprocessor GICs, with the

         * annoying exception of the 11MPCore's GIC.

         */

        if (s->num_cpu != 1 || s->revision == REV_11MPCORE) {

            irq = (offset - 0x800) + GIC_BASE_IRQ;

            if (irq >= s->num_irq) {

                goto bad_reg;

            }

            if (irq < 29) {

                value = 0;

            } else if (irq < GIC_INTERNAL) {

                value = ALL_CPU_MASK;

            }

            s->irq_target[irq] = value & ALL_CPU_MASK;

        }

    } else if (offset < 0xf00) {

        /* Interrupt Configuration.  */

        irq = (offset - 0xc00) * 4 + GIC_BASE_IRQ;

        if (irq >= s->num_irq)

            goto bad_reg;

        if (irq < GIC_NR_SGIS)

            value |= 0xaa;

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

            if (s->revision == REV_11MPCORE || s->revision == REV_NVIC) {

                if (value & (1 << (i * 2))) {

                    GIC_SET_MODEL(irq + i);

                } else {

                    GIC_CLEAR_MODEL(irq + i);

                }

            }

            if (value & (2 << (i * 2))) {

                GIC_SET_EDGE_TRIGGER(irq + i);

            } else {

                GIC_CLEAR_EDGE_TRIGGER(irq + i);

            }

        }

    } else if (offset < 0xf10) {

        /* 0xf00 is only handled for 32-bit writes.  */

        goto bad_reg;

    } else if (offset < 0xf20) {

        /* GICD_CPENDSGIRn */

        if (s->revision == REV_11MPCORE || s->revision == REV_NVIC) {

            goto bad_reg;

        }

        irq = (offset - 0xf10);

        s->sgi_pending[irq][cpu] &= ~value;

        if (s->sgi_pending[irq][cpu] == 0) {

            GIC_CLEAR_PENDING(irq, 1 << cpu);

        }

    } else if (offset < 0xf30) {

        /* GICD_SPENDSGIRn */

        if (s->revision == REV_11MPCORE || s->revision == REV_NVIC) {

            goto bad_reg;

        }

        irq = (offset - 0xf20);

        GIC_SET_PENDING(irq, 1 << cpu);

        s->sgi_pending[irq][cpu] |= value;

    } else {

        goto bad_reg;

    }

    gic_update(s);

    return;

bad_reg:

    qemu_log_mask(LOG_GUEST_ERROR,

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

}


static int colo_packet_compare(Packet *ppkt, Packet *spkt)

{

    trace_colo_compare_ip_info(ppkt->size, inet_ntoa(ppkt->ip->ip_src),

                               inet_ntoa(ppkt->ip->ip_dst), spkt->size,

                               inet_ntoa(spkt->ip->ip_src),

                               inet_ntoa(spkt->ip->ip_dst));

    if (ppkt->size == spkt->size) {

        return memcmp(ppkt->data, spkt->data, spkt->size);

    } else {

        return -1;

    }

}


BlockAIOCB *bdrv_aio_discard(BlockDriverState *bs,

        int64_t sector_num, int nb_sectors,

        BlockCompletionFunc *cb, void *opaque)

{

    Coroutine *co;

    BlockAIOCBCoroutine *acb;

    trace_bdrv_aio_discard(bs, sector_num, nb_sectors, opaque);

    acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);

    acb->need_bh = true;

    acb->req.error = -EINPROGRESS;

    acb->req.sector = sector_num;

    acb->req.nb_sectors = nb_sectors;

    co = qemu_coroutine_create(bdrv_aio_discard_co_entry);

    qemu_coroutine_enter(co, acb);

    bdrv_co_maybe_schedule_bh(acb);

    return &acb->common;

}


static void bdrv_drain_poll(BlockDriverState *bs)

{

    while (bdrv_requests_pending(bs)) {

        /* Keep iterating */

        aio_poll(bdrv_get_aio_context(bs), true);

    }

}


static void quorum_aio_cb(void *opaque, int ret)

{

    QuorumChildRequest *sacb = opaque;

    QuorumAIOCB *acb = sacb->parent;

    BDRVQuorumState *s = acb->common.bs->opaque;

    sacb->ret = ret;

    acb->count++;

    if (ret == 0) {

        acb->success_count++;

    } else {

        quorum_report_bad(acb, sacb->aiocb->bs->node_name, ret);

    }

    assert(acb->count <= s->num_children);

    assert(acb->success_count <= s->num_children);

    if (acb->count < s->num_children) {

        return;

    }

    /* Do the vote on read */

    if (acb->is_read) {

        quorum_vote(acb);

    } else {

        quorum_has_too_much_io_failed(acb);

    }

    quorum_aio_finalize(acb);

}


static const uint8_t *pcx_rle_decode(const uint8_t *src,

                                     const uint8_t *end,

                                     uint8_t *dst,

                                     unsigned int bytes_per_scanline,

                                     int compressed)

{

    unsigned int i = 0;

    unsigned char run, value;

    if (compressed) {

        while (i < bytes_per_scanline && src < end) {

            run   = 1;

            value = *src++;

            if (value >= 0xc0 && src < end) {

                run   = value & 0x3f;

                value = *src++;

            }

            while (i < bytes_per_scanline && run--)

                dst[i++] = value;

        }

    } else {

        memcpy(dst, src, bytes_per_scanline);

        src += bytes_per_scanline;

    }

    return src;

}


void visit_type_int16(Visitor *v, int16_t *obj, const char *name, Error **errp)

{

    int64_t value;

    if (!error_is_set(errp)) {

        if (v->type_int16) {

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

        } else {

            value = *obj;

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

            if (value < INT16_MIN || value > INT16_MAX) {

                error_set(errp, QERR_INVALID_PARAMETER_VALUE, name ? name : "null",

                          "int16_t");

                return;

            }

            *obj = value;

        }

    }

}


static void qdev_prop_set_globals_for_type(DeviceState *dev,

                                const char *typename)

{

    GlobalProperty *prop;

    QTAILQ_FOREACH(prop, &global_props, next) {

        Error *err = NULL;

        if (strcmp(typename, prop->driver) != 0) {

            continue;

        }

        prop->used = true;

        object_property_parse(OBJECT(dev), prop->value, prop->property, &err);

        if (err != NULL) {

            assert(prop->user_provided);

            error_reportf_err(err, "Warning: global %s.%s=%s ignored: ",

                              prop->driver, prop->property, prop->value);

            return;

        }

    }

}


static unsigned char get_ref_idx(AVFrame *frame)

{

    FrameDecodeData *fdd;

    NVDECFrame *cf;

    if (!frame || !frame->private_ref)

        return 255;

    fdd = (FrameDecodeData*)frame->private_ref->data;

    cf  = (NVDECFrame*)fdd->hwaccel_priv;

    return cf->idx;

}


static av_cold int dnxhd_encode_end(AVCodecContext *avctx)

{

    DNXHDEncContext *ctx = avctx->priv_data;

    int max_level        = 1 << (ctx->cid_table->bit_depth + 2);

    int i;

    av_free(ctx->vlc_codes - max_level * 2);

    av_free(ctx->vlc_bits - max_level * 2);

    av_freep(&ctx->run_codes);

    av_freep(&ctx->run_bits);

    av_freep(&ctx->mb_bits);

    av_freep(&ctx->mb_qscale);

    av_freep(&ctx->mb_rc);

    av_freep(&ctx->mb_cmp);

    av_freep(&ctx->slice_size);

    av_freep(&ctx->slice_offs);

    av_freep(&ctx->qmatrix_c);

    av_freep(&ctx->qmatrix_l);

    av_freep(&ctx->qmatrix_c16);

    av_freep(&ctx->qmatrix_l16);

    for (i = 1; i < avctx->thread_count; i++)

        av_freep(&ctx->thread[i]);

    av_frame_free(&avctx->coded_frame);

    return 0;

}


static void *sigwait_compat(void *opaque)

{

    struct sigfd_compat_info *info = opaque;

    int err;

    sigset_t all;

    sigfillset(&all);

    sigprocmask(SIG_BLOCK, &all, NULL);

    do {

        siginfo_t siginfo;

        err = sigwaitinfo(&info->mask, &siginfo);

        if (err == -1 && errno == EINTR) {

            err = 0;

            continue;

        }

        if (err > 0) {

            char buffer[128];

            size_t offset = 0;

            memcpy(buffer, &err, sizeof(err));

            while (offset < sizeof(buffer)) {

                ssize_t len;

                len = write(info->fd, buffer + offset,

                            sizeof(buffer) - offset);

                if (len == -1 && errno == EINTR)

                    continue;

                if (len <= 0) {

                    err = -1;

                    break;

                }

                offset += len;

            }

        }

    } while (err >= 0);

    return NULL;

}


static bool qvirtio_pci_get_queue_isr_status(QVirtioDevice *d, QVirtQueue *vq)

{

    QVirtioPCIDevice *dev = (QVirtioPCIDevice *)d;

    QVirtQueuePCI *vqpci = (QVirtQueuePCI *)vq;

    uint32_t data;

    if (dev->pdev->msix_enabled) {

        g_assert_cmpint(vqpci->msix_entry, !=, -1);

        if (qpci_msix_masked(dev->pdev, vqpci->msix_entry)) {

            /* No ISR checking should be done if masked, but read anyway */

            return qpci_msix_pending(dev->pdev, vqpci->msix_entry);

        } else {

            data = readl(vqpci->msix_addr);

            writel(vqpci->msix_addr, 0);

            return data == vqpci->msix_data;

        }

    } else {

        return qpci_io_readb(dev->pdev, dev->addr + QVIRTIO_PCI_ISR_STATUS) & 1;

    }

}


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

{

    PXA2xxPCMCIAState *s = PXA2XX_PCMCIA(dev);

    pcmcia_socket_register(&s->slot);

}


static int megasas_ld_get_info_submit(SCSIDevice *sdev, int lun,

                                      MegasasCmd *cmd)

{

    struct mfi_ld_info *info = cmd->iov_buf;

    size_t dcmd_size = sizeof(struct mfi_ld_info);

    uint8_t cdb[6];

    SCSIRequest *req;

    ssize_t len, resid;

    uint16_t sdev_id = ((sdev->id & 0xFF) << 8) | (lun & 0xFF);

    uint64_t ld_size;

    if (!cmd->iov_buf) {

        cmd->iov_buf = g_malloc0(dcmd_size);

        info = cmd->iov_buf;

        megasas_setup_inquiry(cdb, 0x83, sizeof(info->vpd_page83));

        req = scsi_req_new(sdev, cmd->index, lun, cdb, cmd);

        if (!req) {

            trace_megasas_dcmd_req_alloc_failed(cmd->index,

                                                "LD get info vpd inquiry");

            g_free(cmd->iov_buf);

            cmd->iov_buf = NULL;

            return MFI_STAT_FLASH_ALLOC_FAIL;

        }

        trace_megasas_dcmd_internal_submit(cmd->index,

                                           "LD get info vpd inquiry", lun);

        len = scsi_req_enqueue(req);

        if (len > 0) {

            cmd->iov_size = len;

            scsi_req_continue(req);

        }

        return MFI_STAT_INVALID_STATUS;

    }

    info->ld_config.params.state = MFI_LD_STATE_OPTIMAL;

    info->ld_config.properties.ld.v.target_id = lun;

    info->ld_config.params.stripe_size = 3;

    info->ld_config.params.num_drives = 1;

    info->ld_config.params.is_consistent = 1;

    /* Logical device size is in blocks */

    blk_get_geometry(sdev->conf.blk, &ld_size);

    info->size = cpu_to_le64(ld_size);

    memset(info->ld_config.span, 0, sizeof(info->ld_config.span));

    info->ld_config.span[0].start_block = 0;

    info->ld_config.span[0].num_blocks = info->size;

    info->ld_config.span[0].array_ref = cpu_to_le16(sdev_id);

    resid = dma_buf_read(cmd->iov_buf, dcmd_size, &cmd->qsg);

    g_free(cmd->iov_buf);

    cmd->iov_size = dcmd_size - resid;

    cmd->iov_buf = NULL;

    return MFI_STAT_OK;

}


static void *migration_thread(void *opaque)

{

    MigrationState *s = opaque;

    int64_t initial_time = qemu_get_clock_ms(rt_clock);

    int64_t initial_bytes = 0;

    int64_t max_size = 0;

    int64_t start_time = initial_time;

    bool old_vm_running = false;

    DPRINTF("beginning savevm\n");

    qemu_savevm_state_begin(s->file, &s->params);

    while (s->state == MIG_STATE_ACTIVE) {

        int64_t current_time;

        uint64_t pending_size;

        if (!qemu_file_rate_limit(s->file)) {

            DPRINTF("iterate\n");

            pending_size = qemu_savevm_state_pending(s->file, max_size);

            DPRINTF("pending size %lu max %lu\n", pending_size, max_size);

            if (pending_size && pending_size >= max_size) {

                qemu_savevm_state_iterate(s->file);

            } else {

                int ret;

                DPRINTF("done iterating\n");

                qemu_mutex_lock_iothread();

                start_time = qemu_get_clock_ms(rt_clock);

                qemu_system_wakeup_request(QEMU_WAKEUP_REASON_OTHER);

                old_vm_running = runstate_is_running();

                ret = vm_stop_force_state(RUN_STATE_FINISH_MIGRATE);

                if (ret >= 0) {

                    qemu_file_set_rate_limit(s->file, INT_MAX);

                    qemu_savevm_state_complete(s->file);

                }

                qemu_mutex_unlock_iothread();

                if (ret < 0) {

                    migrate_finish_set_state(s, MIG_STATE_ERROR);

                    break;

                }

                if (!qemu_file_get_error(s->file)) {

                    migrate_finish_set_state(s, MIG_STATE_COMPLETED);

                    break;

                }

            }

        }

        if (qemu_file_get_error(s->file)) {

            migrate_finish_set_state(s, MIG_STATE_ERROR);

            break;

        }

        current_time = qemu_get_clock_ms(rt_clock);

        if (current_time >= initial_time + BUFFER_DELAY) {

            uint64_t transferred_bytes = qemu_ftell(s->file) - initial_bytes;

            uint64_t time_spent = current_time - initial_time;

            double bandwidth = transferred_bytes / time_spent;

            max_size = bandwidth * migrate_max_downtime() / 1000000;

            s->mbps = time_spent ? (((double) transferred_bytes * 8.0) /

                    ((double) time_spent / 1000.0)) / 1000.0 / 1000.0 : -1;

            DPRINTF("transferred %" PRIu64 " time_spent %" PRIu64

                    " bandwidth %g max_size %" PRId64 "\n",

                    transferred_bytes, time_spent, bandwidth, max_size);

            /* if we haven't sent anything, we don't want to recalculate

               10000 is a small enough number for our purposes */

            if (s->dirty_bytes_rate && transferred_bytes > 10000) {

                s->expected_downtime = s->dirty_bytes_rate / bandwidth;

            }

            qemu_file_reset_rate_limit(s->file);

            initial_time = current_time;

            initial_bytes = qemu_ftell(s->file);

        }

        if (qemu_file_rate_limit(s->file)) {

            /* usleep expects microseconds */

            g_usleep((initial_time + BUFFER_DELAY - current_time)*1000);

        }

    }

    qemu_mutex_lock_iothread();

    if (s->state == MIG_STATE_COMPLETED) {

        int64_t end_time = qemu_get_clock_ms(rt_clock);

        s->total_time = end_time - s->total_time;

        s->downtime = end_time - start_time;

        runstate_set(RUN_STATE_POSTMIGRATE);

    } else {

        if (old_vm_running) {

            vm_start();

        }

    }

    qemu_bh_schedule(s->cleanup_bh);

    qemu_mutex_unlock_iothread();

    return NULL;

}


static av_always_inline void dnxhd_decode_dct_block(const DNXHDContext *ctx,

                                                    RowContext *row,

                                                    int n,

                                                    int index_bits,

                                                    int level_bias,

                                                    int level_shift)

{

    int i, j, index1, index2, len, flags;

    int level, component, sign;

    const int *scale;

    const uint8_t *weight_matrix;

    const uint8_t *ac_level = ctx->cid_table->ac_level;

    const uint8_t *ac_flags = ctx->cid_table->ac_flags;

    int16_t *block = row->blocks[n];

    const int eob_index     = ctx->cid_table->eob_index;

    OPEN_READER(bs, &row->gb);

    ctx->bdsp.clear_block(block);

    if (!ctx->is_444) {

        if (n & 2) {

            component     = 1 + (n & 1);

            scale = row->chroma_scale;

            weight_matrix = ctx->cid_table->chroma_weight;

        } else {

            component     = 0;

            scale = row->luma_scale;

            weight_matrix = ctx->cid_table->luma_weight;

        }

    } else {

        component = (n >> 1) % 3;

        if (component) {

            scale = row->chroma_scale;

            weight_matrix = ctx->cid_table->chroma_weight;

        } else {

            scale = row->luma_scale;

            weight_matrix = ctx->cid_table->luma_weight;

        }

    }

    UPDATE_CACHE(bs, &row->gb);

    GET_VLC(len, bs, &row->gb, ctx->dc_vlc.table, DNXHD_DC_VLC_BITS, 1);

    if (len) {

        level = GET_CACHE(bs, &row->gb);

        LAST_SKIP_BITS(bs, &row->gb, len);

        sign  = ~level >> 31;

        level = (NEG_USR32(sign ^ level, len) ^ sign) - sign;

        row->last_dc[component] += level;

    }

    block[0] = row->last_dc[component];

    i = 0;

    UPDATE_CACHE(bs, &row->gb);

    GET_VLC(index1, bs, &row->gb, ctx->ac_vlc.table,

            DNXHD_VLC_BITS, 2);

    while (index1 != eob_index) {

        level = ac_level[index1];

        flags = ac_flags[index1];

        sign = SHOW_SBITS(bs, &row->gb, 1);

        SKIP_BITS(bs, &row->gb, 1);

        if (flags & 1) {

            level += SHOW_UBITS(bs, &row->gb, index_bits) << 7;

            SKIP_BITS(bs, &row->gb, index_bits);

        }

        if (flags & 2) {

            UPDATE_CACHE(bs, &row->gb);

            GET_VLC(index2, bs, &row->gb, ctx->run_vlc.table,

                    DNXHD_VLC_BITS, 2);

            i += ctx->cid_table->run[index2];

        }

        if (++i > 63) {

            av_log(ctx->avctx, AV_LOG_ERROR, "ac tex damaged %d, %d\n", n, i);

            break;

        }

        j     = ctx->scantable.permutated[i];

        level *= scale[i];

        if (level_bias < 32 || weight_matrix[i] != level_bias)

            level += level_bias;

        level >>= level_shift;

        block[j] = (level ^ sign) - sign;

        UPDATE_CACHE(bs, &row->gb);

        GET_VLC(index1, bs, &row->gb, ctx->ac_vlc.table,

                DNXHD_VLC_BITS, 2);

    }

    CLOSE_READER(bs, &row->gb);

}


static void coroutine_fn qed_co_pwrite_zeroes_cb(void *opaque, int ret)

{

    QEDWriteZeroesCB *cb = opaque;

    cb->done = true;

    cb->ret = ret;

    if (cb->co) {

        qemu_coroutine_enter(cb->co, NULL);

    }

}


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

                                      int buf_size, AVSubtitle *sub)

{

    DVBSubContext *ctx = avctx->priv_data;

    DVBSubDisplayDefinition *display_def = ctx->display_definition;

    DVBSubRegion *region;

    DVBSubRegionDisplay *display;

    AVSubtitleRect *rect;

    DVBSubCLUT *clut;

    uint32_t *clut_table;

    int i;

    int offset_x=0, offset_y=0;

    sub->rects = NULL;

    sub->start_display_time = 0;

    sub->end_display_time = ctx->time_out * 1000;

    sub->format = 0;

    if (display_def) {

        offset_x = display_def->x;

        offset_y = display_def->y;

    }

    sub->num_rects = ctx->display_list_size;

    if (sub->num_rects <= 0)

        return AVERROR_INVALIDDATA;

    sub->rects = av_mallocz_array(sub->num_rects * sub->num_rects,

                                  sizeof(*sub->rects));

    if (!sub->rects)

        return AVERROR(ENOMEM);

    i = 0;

    for (display = ctx->display_list; display; display = display->next) {

        region = get_region(ctx, display->region_id);

        rect = sub->rects[i];

        if (!region)

            continue;

        rect->x = display->x_pos + offset_x;

        rect->y = display->y_pos + offset_y;

        rect->w = region->width;

        rect->h = region->height;

        rect->nb_colors = 16;

        rect->type      = SUBTITLE_BITMAP;

        rect->linesize[0] = region->width;

        clut = get_clut(ctx, region->clut);

        if (!clut)

            clut = &default_clut;

        switch (region->depth) {

        case 2:

            clut_table = clut->clut4;

            break;

        case 8:

            clut_table = clut->clut256;

            break;

        case 4:

        default:

            clut_table = clut->clut16;

            break;

        }

        rect->data[1] = av_mallocz(AVPALETTE_SIZE);

        if (!rect->data[1]) {

            av_free(sub->rects);

            return AVERROR(ENOMEM);

        }

        memcpy(rect->data[1], clut_table, (1 << region->depth) * sizeof(uint32_t));

        rect->data[0] = av_malloc(region->buf_size);

        if (!rect->data[0]) {

            av_free(rect->data[1]);

            av_free(sub->rects);

            return AVERROR(ENOMEM);

        }

        memcpy(rect->data[0], region->pbuf, region->buf_size);

#if FF_API_AVPICTURE

FF_DISABLE_DEPRECATION_WARNINGS

{

        int j;

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

            rect->pict.data[j] = rect->data[j];

            rect->pict.linesize[j] = rect->linesize[j];

        }

}

FF_ENABLE_DEPRECATION_WARNINGS

#endif

        i++;

    }

    sub->num_rects = i;

#ifdef DEBUG

    save_display_set(ctx);

#endif

    return 1;

}


DisplayState *init_displaystate(void)

{

    gchar *name;

    int i;

    if (!display_state) {

        display_state = g_new0(DisplayState, 1);

    }

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

        if (consoles[i]->console_type != GRAPHIC_CONSOLE &&

            consoles[i]->ds == NULL) {

            text_console_do_init(consoles[i]->chr, display_state);

        }

        /* Hook up into the qom tree here (not in new_console()), once

         * all QemuConsoles are created and the order / numbering

         * doesn't change any more */

        name = g_strdup_printf("console[%d]", i);

        object_property_add_child(container_get(object_get_root(), "/backend"),

                                  name, OBJECT(consoles[i]), &error_abort);

        g_free(name);

    }

    return display_state;

}


static void e1000e_device_init(QPCIBus *bus, e1000e_device *d)

{

    uint32_t val;

    d->pci_dev = e1000e_device_find(bus);

    /* Enable the device */

    qpci_device_enable(d->pci_dev);

    /* Map BAR0 (mac registers) */

    d->mac_regs = qpci_iomap(d->pci_dev, 0, NULL);

    g_assert_nonnull(d->mac_regs);

    /* Reset the device */

    val = e1000e_macreg_read(d, E1000E_CTRL);

    e1000e_macreg_write(d, E1000E_CTRL, val | E1000E_CTRL_RESET);

    /* Enable and configure MSI-X */

    qpci_msix_enable(d->pci_dev);

    e1000e_macreg_write(d, E1000E_IVAR, E1000E_IVAR_TEST_CFG);

    /* Check the device status - link and speed */

    val = e1000e_macreg_read(d, E1000E_STATUS);

    g_assert_cmphex(val & (E1000E_STATUS_LU | E1000E_STATUS_ASDV1000),

        ==, E1000E_STATUS_LU | E1000E_STATUS_ASDV1000);

    /* Initialize TX/RX logic */

    e1000e_macreg_write(d, E1000E_RCTL, 0);

    e1000e_macreg_write(d, E1000E_TCTL, 0);

    /* Notify the device that the driver is ready */

    val = e1000e_macreg_read(d, E1000E_CTRL_EXT);

    e1000e_macreg_write(d, E1000E_CTRL_EXT,

        val | E1000E_CTRL_EXT_DRV_LOAD | E1000E_CTRL_EXT_TXLSFLOW);

    /* Allocate and setup TX ring */

    d->tx_ring = guest_alloc(test_alloc, E1000E_RING_LEN);

    g_assert(d->tx_ring != 0);

    e1000e_macreg_write(d, E1000E_TDBAL, (uint32_t) d->tx_ring);

    e1000e_macreg_write(d, E1000E_TDBAH, (uint32_t) (d->tx_ring >> 32));

    e1000e_macreg_write(d, E1000E_TDLEN, E1000E_RING_LEN);

    e1000e_macreg_write(d, E1000E_TDT, 0);

    e1000e_macreg_write(d, E1000E_TDH, 0);

    /* Enable transmit */

    e1000e_macreg_write(d, E1000E_TCTL, E1000E_TCTL_EN);

    /* Allocate and setup RX ring */

    d->rx_ring = guest_alloc(test_alloc, E1000E_RING_LEN);

    g_assert(d->rx_ring != 0);

    e1000e_macreg_write(d, E1000E_RDBAL, (uint32_t)d->rx_ring);

    e1000e_macreg_write(d, E1000E_RDBAH, (uint32_t)(d->rx_ring >> 32));

    e1000e_macreg_write(d, E1000E_RDLEN, E1000E_RING_LEN);

    e1000e_macreg_write(d, E1000E_RDT, 0);

    e1000e_macreg_write(d, E1000E_RDH, 0);

    /* Enable receive */

    e1000e_macreg_write(d, E1000E_RFCTL, E1000E_RFCTL_EXTEN);

    e1000e_macreg_write(d, E1000E_RCTL, E1000E_RCTL_EN  |

                                        E1000E_RCTL_UPE |

                                        E1000E_RCTL_MPE);

    /* Enable all interrupts */

    e1000e_macreg_write(d, E1000E_IMS, 0xFFFFFFFF);

}


static int scsi_disk_emulate_mode_sense(SCSIDiskReq *r, uint8_t *outbuf)

{

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

    uint64_t nb_sectors;

    int page, dbd, buflen, ret, page_control;

    uint8_t *p;

    uint8_t dev_specific_param;

    dbd = r->req.cmd.buf[1]  & 0x8;

    page = r->req.cmd.buf[2] & 0x3f;

    page_control = (r->req.cmd.buf[2] & 0xc0) >> 6;

    DPRINTF("Mode Sense(%d) (page %d, xfer %zd, page_control %d)\n",

        (r->req.cmd.buf[0] == MODE_SENSE) ? 6 : 10, page, r->req.cmd.xfer, page_control);

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

    p = outbuf;

    if (bdrv_is_read_only(s->qdev.conf.bs)) {

        dev_specific_param = 0x80; /* Readonly.  */

    } else {

        dev_specific_param = 0x00;

    }

    if (r->req.cmd.buf[0] == MODE_SENSE) {

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

        p[2] = dev_specific_param;

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

        p += 4;

    } else { /* MODE_SENSE_10 */

        p[2] = 0; /* Default media type.  */

        p[3] = dev_specific_param;

        p[6] = p[7] = 0; /* Block descriptor length.  */

        p += 8;

    }

    /* MMC prescribes that CD/DVD drives have no block descriptors.  */

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

    if (!dbd && s->qdev.type == TYPE_DISK && nb_sectors) {

        if (r->req.cmd.buf[0] == MODE_SENSE) {

            outbuf[3] = 8; /* Block descriptor length  */

        } else { /* MODE_SENSE_10 */

            outbuf[7] = 8; /* Block descriptor length  */

        }

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

        if (nb_sectors > 0xffffff) {

            nb_sectors = 0;

        }

        p[0] = 0; /* media density code */

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

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

        p[3] = nb_sectors & 0xff;

        p[4] = 0; /* reserved */

        p[5] = 0; /* bytes 5-7 are the sector size in bytes */

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

        p[7] = 0;

        p += 8;

    }

    if (page_control == 3) {

        /* Saved Values */

        scsi_check_condition(r, SENSE_CODE(SAVING_PARAMS_NOT_SUPPORTED));

        return -1;

    }

    if (page == 0x3f) {

        for (page = 0; page <= 0x3e; page++) {

            mode_sense_page(s, page, &p, page_control);

        }

    } else {

        ret = mode_sense_page(s, page, &p, page_control);

        if (ret == -1) {

            return -1;

        }

    }

    buflen = p - outbuf;

    /*

     * The mode data length field specifies the length in bytes of the

     * following data that is available to be transferred. The mode data

     * length does not include itself.

     */

    if (r->req.cmd.buf[0] == MODE_SENSE) {

        outbuf[0] = buflen - 1;

    } else { /* MODE_SENSE_10 */

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

        outbuf[1] = (buflen - 2) & 0xff;

    }

    if (buflen > r->req.cmd.xfer) {

        buflen = r->req.cmd.xfer;

    }

    return buflen;

}


static int decode_block(MJpegDecodeContext *s, DCTELEM *block,

                        int component, int dc_index, int ac_index, int16_t *quant_matrix)

{

    int code, i, j, level, val;

    /* DC coef */

    val = mjpeg_decode_dc(s, dc_index);

    if (val == 0xffff) {

        av_log(s->avctx, AV_LOG_ERROR, "error dc\n");

        return -1;

    }

    val = val * quant_matrix[0] + s->last_dc[component];

    s->last_dc[component] = val;

    block[0] = val;

    /* AC coefs */

    i = 0;

    {OPEN_READER(re, &s->gb)

    for(;;) {

        UPDATE_CACHE(re, &s->gb);

        GET_VLC(code, re, &s->gb, s->vlcs[1][ac_index].table, 9, 2)

        /* EOB */

        if (code == 0x10)

            break;

        i += ((unsigned)code) >> 4;

            code &= 0xf;

        if(code){

            if(code > MIN_CACHE_BITS - 16){

                UPDATE_CACHE(re, &s->gb)

            }

            {

                int cache=GET_CACHE(re,&s->gb);

                int sign=(~cache)>>31;

                level = (NEG_USR32(sign ^ cache,code) ^ sign) - sign;

            }

            LAST_SKIP_BITS(re, &s->gb, code)

            if (i >= 63) {

                if(i == 63){

                    j = s->scantable.permutated[63];

                    block[j] = level * quant_matrix[j];

                    break;

                }

                av_log(s->avctx, AV_LOG_ERROR, "error count: %d\n", i);

                return -1;

            }

            j = s->scantable.permutated[i];

            block[j] = level * quant_matrix[j];

        }

    }

    CLOSE_READER(re, &s->gb)}

    return 0;

}


static int decode_ext_header(Wmv2Context *w){

    MpegEncContext * const s= &w->s;

    GetBitContext gb;

    int fps;

    int code;

    if(s->avctx->extradata_size<4) return -1;

    init_get_bits(&gb, s->avctx->extradata, s->avctx->extradata_size*8);

    fps                = get_bits(&gb, 5);

    s->bit_rate        = get_bits(&gb, 11)*1024;

    w->mspel_bit       = get_bits1(&gb);

    s->loop_filter     = get_bits1(&gb);

    w->abt_flag        = get_bits1(&gb);

    w->j_type_bit      = get_bits1(&gb);

    w->top_left_mv_flag= get_bits1(&gb);

    w->per_mb_rl_bit   = get_bits1(&gb);

    code               = get_bits(&gb, 3);

    if(code==0) return -1;

    s->slice_height = s->mb_height / code;

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

        av_log(s->avctx, AV_LOG_DEBUG, "fps:%d, br:%d, qpbit:%d, abt_flag:%d, j_type_bit:%d, tl_mv_flag:%d, mbrl_bit:%d, code:%d, loop_filter:%d, slices:%d\n",

        fps, s->bit_rate, w->mspel_bit, w->abt_flag, w->j_type_bit, w->top_left_mv_flag, w->per_mb_rl_bit, code, s->loop_filter,

        code);

    }

    return 0;

}


static void tlb_flush_nocheck(CPUState *cpu)

{

    CPUArchState *env = cpu->env_ptr;

    /* The QOM tests will trigger tlb_flushes without setting up TCG

     * so we bug out here in that case.

     */

    if (!tcg_enabled()) {

        return;

    }

    assert_cpu_is_self(cpu);

    tlb_debug("(count: %d)\n", tlb_flush_count++);

    tb_lock();

    memset(env->tlb_table, -1, sizeof(env->tlb_table));

    memset(env->tlb_v_table, -1, sizeof(env->tlb_v_table));

    memset(cpu->tb_jmp_cache, 0, sizeof(cpu->tb_jmp_cache));

    env->vtlb_index = 0;

    env->tlb_flush_addr = -1;

    env->tlb_flush_mask = 0;

    tb_unlock();

    atomic_mb_set(&cpu->pending_tlb_flush, 0);

}


static void liveness_pass_1(TCGContext *s)

{

    int nb_globals = s->nb_globals;

    int oi, oi_prev;

    tcg_la_func_end(s);

    for (oi = s->gen_op_buf[0].prev; oi != 0; oi = oi_prev) {

        int i, nb_iargs, nb_oargs;

        TCGOpcode opc_new, opc_new2;

        bool have_opc_new2;

        TCGLifeData arg_life = 0;

        TCGTemp *arg_ts;

        TCGOp * const op = &s->gen_op_buf[oi];

        TCGOpcode opc = op->opc;

        const TCGOpDef *def = &tcg_op_defs[opc];

        oi_prev = op->prev;

        switch (opc) {

        case INDEX_op_call:

            {

                int call_flags;

                nb_oargs = op->callo;

                nb_iargs = op->calli;

                call_flags = op->args[nb_oargs + nb_iargs + 1];

                /* pure functions can be removed if their result is unused */

                if (call_flags & TCG_CALL_NO_SIDE_EFFECTS) {

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

                        arg_ts = arg_temp(op->args[i]);

                        if (arg_ts->state != TS_DEAD) {

                            goto do_not_remove_call;

                        }

                    }

                    goto do_remove;

                } else {

                do_not_remove_call:

                    /* output args are dead */

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

                        arg_ts = arg_temp(op->args[i]);

                        if (arg_ts->state & TS_DEAD) {

                            arg_life |= DEAD_ARG << i;

                        }

                        if (arg_ts->state & TS_MEM) {

                            arg_life |= SYNC_ARG << i;

                        }

                        arg_ts->state = TS_DEAD;

                    }

                    if (!(call_flags & (TCG_CALL_NO_WRITE_GLOBALS |

                                        TCG_CALL_NO_READ_GLOBALS))) {

                        /* globals should go back to memory */

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

                            s->temps[i].state = TS_DEAD | TS_MEM;

                        }

                    } else if (!(call_flags & TCG_CALL_NO_READ_GLOBALS)) {

                        /* globals should be synced to memory */

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

                            s->temps[i].state |= TS_MEM;

                        }

                    }

                    /* record arguments that die in this helper */

                    for (i = nb_oargs; i < nb_iargs + nb_oargs; i++) {

                        arg_ts = arg_temp(op->args[i]);

                        if (arg_ts && arg_ts->state & TS_DEAD) {

                            arg_life |= DEAD_ARG << i;

                        }

                    }

                    /* input arguments are live for preceding opcodes */

                    for (i = nb_oargs; i < nb_iargs + nb_oargs; i++) {

                        arg_ts = arg_temp(op->args[i]);

                        if (arg_ts) {

                            arg_ts->state &= ~TS_DEAD;

                        }

                    }

                }

            }

            break;

        case INDEX_op_insn_start:

            break;

        case INDEX_op_discard:

            /* mark the temporary as dead */

            arg_temp(op->args[0])->state = TS_DEAD;

            break;

        case INDEX_op_add2_i32:

            opc_new = INDEX_op_add_i32;

            goto do_addsub2;

        case INDEX_op_sub2_i32:

            opc_new = INDEX_op_sub_i32;

            goto do_addsub2;

        case INDEX_op_add2_i64:

            opc_new = INDEX_op_add_i64;

            goto do_addsub2;

        case INDEX_op_sub2_i64:

            opc_new = INDEX_op_sub_i64;

        do_addsub2:

            nb_iargs = 4;

            nb_oargs = 2;

            /* Test if the high part of the operation is dead, but not

               the low part.  The result can be optimized to a simple

               add or sub.  This happens often for x86_64 guest when the

               cpu mode is set to 32 bit.  */

            if (arg_temp(op->args[1])->state == TS_DEAD) {

                if (arg_temp(op->args[0])->state == TS_DEAD) {

                    goto do_remove;

                }

                /* Replace the opcode and adjust the args in place,

                   leaving 3 unused args at the end.  */

                op->opc = opc = opc_new;

                op->args[1] = op->args[2];

                op->args[2] = op->args[4];

                /* Fall through and mark the single-word operation live.  */

                nb_iargs = 2;

                nb_oargs = 1;

            }

            goto do_not_remove;

        case INDEX_op_mulu2_i32:

            opc_new = INDEX_op_mul_i32;

            opc_new2 = INDEX_op_muluh_i32;

            have_opc_new2 = TCG_TARGET_HAS_muluh_i32;

            goto do_mul2;

        case INDEX_op_muls2_i32:

            opc_new = INDEX_op_mul_i32;

            opc_new2 = INDEX_op_mulsh_i32;

            have_opc_new2 = TCG_TARGET_HAS_mulsh_i32;

            goto do_mul2;

        case INDEX_op_mulu2_i64:

            opc_new = INDEX_op_mul_i64;

            opc_new2 = INDEX_op_muluh_i64;

            have_opc_new2 = TCG_TARGET_HAS_muluh_i64;

            goto do_mul2;

        case INDEX_op_muls2_i64:

            opc_new = INDEX_op_mul_i64;

            opc_new2 = INDEX_op_mulsh_i64;

            have_opc_new2 = TCG_TARGET_HAS_mulsh_i64;

            goto do_mul2;

        do_mul2:

            nb_iargs = 2;

            nb_oargs = 2;

            if (arg_temp(op->args[1])->state == TS_DEAD) {

                if (arg_temp(op->args[0])->state == TS_DEAD) {

                    /* Both parts of the operation are dead.  */

                    goto do_remove;

                }

                /* The high part of the operation is dead; generate the low. */

                op->opc = opc = opc_new;

                op->args[1] = op->args[2];

                op->args[2] = op->args[3];

            } else if (arg_temp(op->args[0])->state == TS_DEAD && have_opc_new2) {

                /* The low part of the operation is dead; generate the high. */

                op->opc = opc = opc_new2;

                op->args[0] = op->args[1];

                op->args[1] = op->args[2];

                op->args[2] = op->args[3];

            } else {

                goto do_not_remove;

            }

            /* Mark the single-word operation live.  */

            nb_oargs = 1;

            goto do_not_remove;

        default:

            /* XXX: optimize by hardcoding common cases (e.g. triadic ops) */

            nb_iargs = def->nb_iargs;

            nb_oargs = def->nb_oargs;

            /* Test if the operation can be removed because all

               its outputs are dead. We assume that nb_oargs == 0

               implies side effects */

            if (!(def->flags & TCG_OPF_SIDE_EFFECTS) && nb_oargs != 0) {

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

                    if (arg_temp(op->args[i])->state != TS_DEAD) {

                        goto do_not_remove;

                    }

                }

            do_remove:

                tcg_op_remove(s, op);

            } else {

            do_not_remove:

                /* output args are dead */

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

                    arg_ts = arg_temp(op->args[i]);

                    if (arg_ts->state & TS_DEAD) {

                        arg_life |= DEAD_ARG << i;

                    }

                    if (arg_ts->state & TS_MEM) {

                        arg_life |= SYNC_ARG << i;

                    }

                    arg_ts->state = TS_DEAD;

                }

                /* if end of basic block, update */

                if (def->flags & TCG_OPF_BB_END) {

                    tcg_la_bb_end(s);

                } else if (def->flags & TCG_OPF_SIDE_EFFECTS) {

                    /* globals should be synced to memory */

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

                        s->temps[i].state |= TS_MEM;

                    }

                }

                /* record arguments that die in this opcode */

                for (i = nb_oargs; i < nb_oargs + nb_iargs; i++) {

                    arg_ts = arg_temp(op->args[i]);

                    if (arg_ts->state & TS_DEAD) {

                        arg_life |= DEAD_ARG << i;

                    }

                }

                /* input arguments are live for preceding opcodes */

                for (i = nb_oargs; i < nb_oargs + nb_iargs; i++) {

                    arg_temp(op->args[i])->state &= ~TS_DEAD;

                }

            }

            break;

        }

        op->life = arg_life;

    }

}


static uint64_t addrrange_end(AddrRange r)

{

    return r.start + r.size;

}


static void cqueue_free(cqueue *q)

{

    av_free(q->elements);

    av_free(q);

}


static int alloc_scratch_buffers(H264SliceContext *sl, int linesize)

{

    const H264Context *h = sl->h264;

    int alloc_size = FFALIGN(FFABS(linesize) + 32, 32);

    av_fast_malloc(&sl->bipred_scratchpad, &sl->bipred_scratchpad_allocated, 16 * 6 * alloc_size);

    // edge emu needs blocksize + filter length - 1

    // (= 21x21 for  h264)

    av_fast_malloc(&sl->edge_emu_buffer, &sl->edge_emu_buffer_allocated, alloc_size * 2 * 21);

    av_fast_malloc(&sl->top_borders[0], &sl->top_borders_allocated[0],

                   h->mb_width * 16 * 3 * sizeof(uint8_t) * 2);

    av_fast_malloc(&sl->top_borders[1], &sl->top_borders_allocated[1],

                   h->mb_width * 16 * 3 * sizeof(uint8_t) * 2);

    if (!sl->bipred_scratchpad || !sl->edge_emu_buffer ||

        !sl->top_borders[0]    || !sl->top_borders[1]) {

        av_freep(&sl->bipred_scratchpad);

        av_freep(&sl->edge_emu_buffer);

        av_freep(&sl->top_borders[0]);

        av_freep(&sl->top_borders[1]);

        sl->bipred_scratchpad_allocated = 0;

        sl->edge_emu_buffer_allocated   = 0;

        sl->top_borders_allocated[0]    = 0;

        sl->top_borders_allocated[1]    = 0;

        return AVERROR(ENOMEM);

    }

    return 0;

}


static inline void RENAME(nv21ToUV)(uint8_t *dstU, uint8_t *dstV,

                                    const uint8_t *src1, const uint8_t *src2,

                                    int width, uint32_t *unused)

{

    RENAME(nvXXtoUV)(dstV, dstU, src1, width);

}


static void ehci_advance_periodic_state(EHCIState *ehci)

{

    uint32_t entry;

    uint32_t list;

    const int async = 0;

    // 4.6

    switch(ehci_get_state(ehci, async)) {

    case EST_INACTIVE:

        if ( !(ehci->frindex & 7) && (ehci->usbcmd & USBCMD_PSE)) {

            ehci_set_usbsts(ehci, USBSTS_PSS);

            ehci_set_state(ehci, async, EST_ACTIVE);

            // No break, fall through to ACTIVE

        } else

            break;

    case EST_ACTIVE:

        if ( !(ehci->frindex & 7) && !(ehci->usbcmd & USBCMD_PSE)) {

            ehci_clear_usbsts(ehci, USBSTS_PSS);

            ehci_set_state(ehci, async, EST_INACTIVE);

            break;

        }

        list = ehci->periodiclistbase & 0xfffff000;

        /* check that register has been set */

        if (list == 0) {

            break;

        }

        list |= ((ehci->frindex & 0x1ff8) >> 1);

        pci_dma_read(&ehci->dev, list, &entry, sizeof entry);

        entry = le32_to_cpu(entry);

        DPRINTF("PERIODIC state adv fr=%d.  [%08X] -> %08X\n",

                ehci->frindex / 8, list, entry);

        ehci_set_fetch_addr(ehci, async,entry);

        ehci_set_state(ehci, async, EST_FETCHENTRY);

        ehci_advance_state(ehci, async);

        ehci_queues_rip_unused(ehci, async);

        break;

    default:

        /* this should only be due to a developer mistake */

        fprintf(stderr, "ehci: Bad periodic state %d. "

                "Resetting to active\n", ehci->pstate);

        assert(0);

    }

}


static void close_connection(HTTPContext *c)
{
    HTTPContext **cp, *c1;
    int i, nb_streams;
    AVFormatContext *ctx;
    URLContext *h;
    AVStream *st;
    /* remove connection from list */
    cp = &first_http_ctx;
    while ((*cp) != NULL) {
        c1 = *cp;
        if (c1 == c) {
            *cp = c->next;
        } else {
            cp = &c1->next;
    /* remove connection associated resources */
    if (c->fd >= 0)
        close(c->fd);
    if (c->fmt_in) {
        /* close each frame parser */
        for(i=0;i<c->fmt_in->nb_streams;i++) {
            st = c->fmt_in->streams[i];
            if (st->codec.codec) {
                avcodec_close(&st->codec);
        av_close_input_file(c->fmt_in);
    /* free RTP output streams if any */
    nb_streams = 0;
    if (c->stream)
        nb_streams = c->stream->nb_streams;
    for(i=0;i<nb_streams;i++) {
        ctx = c->rtp_ctx[i];
        if (ctx) {
            av_free(ctx);
        h = c->rtp_handles[i];
        if (h) {
            url_close(h);
    if (c->stream)
        current_bandwidth -= c->stream->bandwidth;
    av_freep(&c->pb_buffer);
    av_free(c->buffer);
    av_free(c);
    nb_connections--;


static void test_bh_schedule10(void)

{

    BHTestData data = { .n = 0, .max = 10 };

    data.bh = aio_bh_new(ctx, bh_test_cb, &data);

    qemu_bh_schedule(data.bh);

    g_assert_cmpint(data.n, ==, 0);

    g_assert(aio_poll(ctx, false));

    g_assert_cmpint(data.n, ==, 1);

    g_assert(aio_poll(ctx, true));

    g_assert_cmpint(data.n, ==, 2);

    wait_for_aio();

    g_assert_cmpint(data.n, ==, 10);

    g_assert(!aio_poll(ctx, false));

    g_assert_cmpint(data.n, ==, 10);

    qemu_bh_delete(data.bh);

}


static void vexpress_modify_dtb(const struct arm_boot_info *info, void *fdt)

{

    uint32_t acells, scells, intc;

    const VEDBoardInfo *daughterboard = (const VEDBoardInfo *)info;

    acells = qemu_fdt_getprop_cell(fdt, "/", "#address-cells",

                                   NULL, &error_fatal);

    scells = qemu_fdt_getprop_cell(fdt, "/", "#size-cells",

                                   NULL, &error_fatal);

    intc = find_int_controller(fdt);

    if (!intc) {

        /* Not fatal, we just won't provide virtio. This will

         * happen with older device tree blobs.

         */

        fprintf(stderr, "QEMU: warning: couldn't find interrupt controller in "

                "dtb; will not include virtio-mmio devices in the dtb.\n");

    } else {

        int i;

        const hwaddr *map = daughterboard->motherboard_map;

        /* We iterate backwards here because adding nodes

         * to the dtb puts them in last-first.

         */

        for (i = NUM_VIRTIO_TRANSPORTS - 1; i >= 0; i--) {

            add_virtio_mmio_node(fdt, acells, scells,

                                 map[VE_VIRTIO] + 0x200 * i,

                                 0x200, intc, 40 + i);

        }

    }

}


static int cpu_gdb_write_register(CPUPPCState *env, uint8_t *mem_buf, int n)

{

    if (n < 32) {

        /* gprs */

        env->gpr[n] = ldtul_p(mem_buf);

        return sizeof(target_ulong);

    } else if (n < 64) {

        /* fprs */

        if (gdb_has_xml)

            return 0;

        env->fpr[n-32] = ldfq_p(mem_buf);

        return 8;

    } else {

        switch (n) {

        case 64:

            env->nip = ldtul_p(mem_buf);

            return sizeof(target_ulong);

        case 65:

            ppc_store_msr(env, ldtul_p(mem_buf));

            return sizeof(target_ulong);

        case 66:

            {

                uint32_t cr = ldl_p(mem_buf);

                int i;

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

                    env->crf[i] = (cr >> (32 - ((i + 1) * 4))) & 0xF;

                return 4;

            }

        case 67:

            env->lr = ldtul_p(mem_buf);

            return sizeof(target_ulong);

        case 68:

            env->ctr = ldtul_p(mem_buf);

            return sizeof(target_ulong);

        case 69:

            env->xer = ldtul_p(mem_buf);

            return sizeof(target_ulong);

        case 70:

            /* fpscr */

            if (gdb_has_xml)

                return 0;

            return 4;

        }

    }

    return 0;

}


static void tcg_out_ri(TCGContext *s, int const_arg, TCGArg arg)

{

    if (const_arg) {

        assert(const_arg == 1);

        tcg_out8(s, TCG_CONST);

        tcg_out_i(s, arg);

    } else {

        tcg_out_r(s, arg);

    }

}


static bool get_vt_profile_level(AVCodecContext *avctx,

                                 CFStringRef    *profile_level_val)

{

    VTEncContext *vtctx = avctx->priv_data;

    int64_t profile = vtctx->profile;

    if (profile == H264_PROF_AUTO && vtctx->level) {

        //Need to pick a profile if level is not auto-selected.

        profile = vtctx->has_b_frames ? H264_PROF_MAIN : H264_PROF_BASELINE;

    }

    *profile_level_val = NULL;

    switch (profile) {

        case H264_PROF_AUTO:

            return true;

        case H264_PROF_BASELINE:

            switch (vtctx->level) {

                case  0: *profile_level_val = kVTProfileLevel_H264_Baseline_AutoLevel; break;

                case 13: *profile_level_val = kVTProfileLevel_H264_Baseline_1_3;       break;

                case 30: *profile_level_val = kVTProfileLevel_H264_Baseline_3_0;       break;

                case 31: *profile_level_val = kVTProfileLevel_H264_Baseline_3_1;       break;

                case 32: *profile_level_val = kVTProfileLevel_H264_Baseline_3_2;       break;

                case 40: *profile_level_val = kVTProfileLevel_H264_Baseline_4_0;       break;

                case 41: *profile_level_val = kVTProfileLevel_H264_Baseline_4_1;       break;

                case 42: *profile_level_val = kVTProfileLevel_H264_Baseline_4_2;       break;

                case 50: *profile_level_val = kVTProfileLevel_H264_Baseline_5_0;       break;

                case 51: *profile_level_val = kVTProfileLevel_H264_Baseline_5_1;       break;

                case 52: *profile_level_val = kVTProfileLevel_H264_Baseline_5_2;       break;

            }

            break;

        case H264_PROF_MAIN:

            switch (vtctx->level) {

                case  0: *profile_level_val = kVTProfileLevel_H264_Main_AutoLevel; break;

                case 30: *profile_level_val = kVTProfileLevel_H264_Main_3_0;       break;

                case 31: *profile_level_val = kVTProfileLevel_H264_Main_3_1;       break;

                case 32: *profile_level_val = kVTProfileLevel_H264_Main_3_2;       break;

                case 40: *profile_level_val = kVTProfileLevel_H264_Main_4_0;       break;

                case 41: *profile_level_val = kVTProfileLevel_H264_Main_4_1;       break;

                case 42: *profile_level_val = kVTProfileLevel_H264_Main_4_2;       break;

                case 50: *profile_level_val = kVTProfileLevel_H264_Main_5_0;       break;

                case 51: *profile_level_val = kVTProfileLevel_H264_Main_5_1;       break;

                case 52: *profile_level_val = kVTProfileLevel_H264_Main_5_2;       break;

            }

            break;

        case H264_PROF_HIGH:

            switch (vtctx->level) {

                case  0: *profile_level_val = kVTProfileLevel_H264_High_AutoLevel; break;

                case 30: *profile_level_val = kVTProfileLevel_H264_High_3_0;       break;

                case 31: *profile_level_val = kVTProfileLevel_H264_High_3_1;       break;

                case 32: *profile_level_val = kVTProfileLevel_H264_High_3_2;       break;

                case 40: *profile_level_val = kVTProfileLevel_H264_High_4_0;       break;

                case 41: *profile_level_val = kVTProfileLevel_H264_High_4_1;       break;

                case 42: *profile_level_val = kVTProfileLevel_H264_High_4_2;       break;

                case 50: *profile_level_val = kVTProfileLevel_H264_High_5_0;       break;

                case 51: *profile_level_val = kVTProfileLevel_H264_High_5_1;       break;

                case 52: *profile_level_val = kVTProfileLevel_H264_High_5_2;       break;

            }

            break;

    }

    if (!*profile_level_val) {

        av_log(avctx, AV_LOG_ERROR, "Invalid Profile/Level.\n");

        return false;

    }

    return true;

}


void *qemu_ram_mmap(int fd, size_t size, size_t align, bool shared)

{

    /*

     * Note: this always allocates at least one extra page of virtual address

     * space, even if size is already aligned.

     */

    size_t total = size + align;

#if defined(__powerpc64__) && defined(__linux__)

    /* On ppc64 mappings in the same segment (aka slice) must share the same

     * page size. Since we will be re-allocating part of this segment

     * from the supplied fd, we should make sure to use the same page size,

     * unless we are using the system page size, in which case anonymous memory

     * is OK. Use align as a hint for the page size.

     * In this case, set MAP_NORESERVE to avoid allocating backing store memory.

     */

    int anonfd = fd == -1 || qemu_fd_getpagesize(fd) == getpagesize() ? -1 : fd;

    int flags = anonfd == -1 ? MAP_ANONYMOUS : MAP_NORESERVE;

    void *ptr = mmap(0, total, PROT_NONE, flags | MAP_PRIVATE, anonfd, 0);

#else

    void *ptr = mmap(0, total, PROT_NONE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);

#endif

    size_t offset = QEMU_ALIGN_UP((uintptr_t)ptr, align) - (uintptr_t)ptr;

    void *ptr1;

    if (ptr == MAP_FAILED) {

        return MAP_FAILED;

    }

    /* Make sure align is a power of 2 */

    assert(!(align & (align - 1)));

    /* Always align to host page size */

    assert(align >= getpagesize());

    ptr1 = mmap(ptr + offset, size, PROT_READ | PROT_WRITE,

                MAP_FIXED |

                (fd == -1 ? MAP_ANONYMOUS : 0) |

                (shared ? MAP_SHARED : MAP_PRIVATE),

                fd, 0);

    if (ptr1 == MAP_FAILED) {

        munmap(ptr, total);

        return MAP_FAILED;

    }

    ptr += offset;

    total -= offset;

    if (offset > 0) {

        munmap(ptr - offset, offset);

    }

    /*

     * Leave a single PROT_NONE page allocated after the RAM block, to serve as

     * a guard page guarding against potential buffer overflows.

     */

    if (total > size + getpagesize()) {

        munmap(ptr + size + getpagesize(), total - size - getpagesize());

    }

    return ptr;

}


static void rtas_set_tce_bypass(PowerPCCPU *cpu, sPAPREnvironment *spapr,

                                uint32_t token,

                                uint32_t nargs, target_ulong args,

                                uint32_t nret, target_ulong rets)

{

    VIOsPAPRBus *bus = spapr->vio_bus;

    VIOsPAPRDevice *dev;

    uint32_t unit, enable;

    if (nargs != 2) {

        rtas_st(rets, 0, RTAS_OUT_PARAM_ERROR);

        return;

    }

    unit = rtas_ld(args, 0);

    enable = rtas_ld(args, 1);

    dev = spapr_vio_find_by_reg(bus, unit);

    if (!dev) {

        rtas_st(rets, 0, RTAS_OUT_PARAM_ERROR);

        return;

    }

    if (!dev->tcet) {

        rtas_st(rets, 0, RTAS_OUT_PARAM_ERROR);

        return;

    }

    spapr_tce_set_bypass(dev->tcet, !!enable);

    rtas_st(rets, 0, RTAS_OUT_SUCCESS);

}


static void virtio_scsi_change(SCSIBus *bus, SCSIDevice *dev, SCSISense sense)

{

    VirtIOSCSI *s = container_of(bus, VirtIOSCSI, bus);

    if (((s->vdev.guest_features >> VIRTIO_SCSI_F_CHANGE) & 1) &&

        (s->vdev.status & VIRTIO_CONFIG_S_DRIVER_OK) &&

        dev->type != TYPE_ROM) {

        virtio_scsi_push_event(s, dev, VIRTIO_SCSI_T_PARAM_CHANGE,

                               sense.asc | (sense.ascq << 8));

    }

}


static int usb_hid_initfn(USBDevice *dev, int kind)

{

    USBHIDState *us = DO_UPCAST(USBHIDState, dev, dev);

    usb_desc_init(dev);

    hid_init(&us->hid, kind, usb_hid_changed);

    /* Force poll routine to be run and grab input the first time.  */

    us->changed = 1;

    return 0;

}


int target_to_host_signal(int sig)

{

    if (sig >= _NSIG)

        return sig;

    return target_to_host_signal_table[sig];

}


int net_init_tap(const NetClientOptions *opts, const char *name,

                 NetClientState *peer, Error **errp)

{

    /* FIXME error_setg(errp, ...) on failure */

    const NetdevTapOptions *tap;

    assert(opts->kind == NET_CLIENT_OPTIONS_KIND_TAP);

    tap = opts->tap;

    if (!tap->has_ifname) {

        error_report("tap: no interface name");

        return -1;

    }

    if (tap_win32_init(peer, "tap", name, tap->ifname) == -1) {

        return -1;

    }

    return 0;

}


clk_setup_cb ppc_emb_timers_init (CPUState *env, uint32_t freq)

{

    ppc_tb_t *tb_env;

    ppcemb_timer_t *ppcemb_timer;

    tb_env = qemu_mallocz(sizeof(ppc_tb_t));

    env->tb_env = tb_env;

    ppcemb_timer = qemu_mallocz(sizeof(ppcemb_timer_t));

    tb_env->tb_freq = freq;

    tb_env->decr_freq = freq;

    tb_env->opaque = ppcemb_timer;

    LOG_TB("%s freq %" PRIu32 "\n", __func__, freq);

    if (ppcemb_timer != NULL) {

        /* We use decr timer for PIT */

        tb_env->decr_timer = qemu_new_timer(vm_clock, &cpu_4xx_pit_cb, env);

        ppcemb_timer->fit_timer =

            qemu_new_timer(vm_clock, &cpu_4xx_fit_cb, env);

        ppcemb_timer->wdt_timer =

            qemu_new_timer(vm_clock, &cpu_4xx_wdt_cb, env);

    }

    return &ppc_emb_set_tb_clk;

}


static int htab_save_iterate(QEMUFile *f, void *opaque)

{

    sPAPRMachineState *spapr = opaque;

    int fd;

    int rc = 0;

    /* Iteration header */

    if (!spapr->htab_shift) {

        qemu_put_be32(f, -1);

        return 0;

    } else {

        qemu_put_be32(f, 0);

    }

    if (!spapr->htab) {

        assert(kvm_enabled());

        fd = get_htab_fd(spapr);

        if (fd < 0) {

            return fd;

        }

        rc = kvmppc_save_htab(f, fd, MAX_KVM_BUF_SIZE, MAX_ITERATION_NS);

        if (rc < 0) {

            return rc;

        }

    } else  if (spapr->htab_first_pass) {

        htab_save_first_pass(f, spapr, MAX_ITERATION_NS);

    } else {

        rc = htab_save_later_pass(f, spapr, MAX_ITERATION_NS);

    }

    /* End marker */

    qemu_put_be32(f, 0);

    qemu_put_be16(f, 0);

    qemu_put_be16(f, 0);

    return rc;

}


static int drive_init_func(QemuOpts *opts, void *opaque)

{

    int *use_scsi = opaque;

    return drive_init(opts, *use_scsi) == NULL;

}


static int adpcm_encode_frame(AVCodecContext *avctx,

                            unsigned char *frame, int buf_size, void *data)

{

    int n, i, st;

    short *samples;

    unsigned char *dst;

    ADPCMContext *c = avctx->priv_data;

    dst = frame;

    samples = (short *)data;

    st= avctx->channels == 2;

/*    n = (BLKSIZE - 4 * avctx->channels) / (2 * 8 * avctx->channels); */

    switch(avctx->codec->id) {

    case CODEC_ID_ADPCM_IMA_QT: /* XXX: can't test until we get .mov writer */

        break;

    case CODEC_ID_ADPCM_IMA_WAV:

        n = avctx->frame_size / 8;

            c->status[0].prev_sample = (signed short)samples[0]; /* XXX */

/*            c->status[0].step_index = 0; *//* XXX: not sure how to init the state machine */

            bytestream_put_le16(&dst, c->status[0].prev_sample);

            *dst++ = (unsigned char)c->status[0].step_index;

            *dst++ = 0; /* unknown */

            samples++;

            if (avctx->channels == 2) {

                c->status[1].prev_sample = (signed short)samples[1];

/*                c->status[1].step_index = 0; */

                bytestream_put_le16(&dst, c->status[1].prev_sample);

                *dst++ = (unsigned char)c->status[1].step_index;

                *dst++ = 0;

                samples++;

            }

            /* stereo: 4 bytes (8 samples) for left, 4 bytes for right, 4 bytes left, ... */

            if(avctx->trellis > 0) {

                uint8_t buf[2][n*8];

                adpcm_compress_trellis(avctx, samples, buf[0], &c->status[0], n*8);

                if(avctx->channels == 2)

                    adpcm_compress_trellis(avctx, samples+1, buf[1], &c->status[1], n*8);

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

                    *dst++ = buf[0][8*i+0] | (buf[0][8*i+1] << 4);

                    *dst++ = buf[0][8*i+2] | (buf[0][8*i+3] << 4);

                    *dst++ = buf[0][8*i+4] | (buf[0][8*i+5] << 4);

                    *dst++ = buf[0][8*i+6] | (buf[0][8*i+7] << 4);

                    if (avctx->channels == 2) {

                        *dst++ = buf[1][8*i+0] | (buf[1][8*i+1] << 4);

                        *dst++ = buf[1][8*i+2] | (buf[1][8*i+3] << 4);

                        *dst++ = buf[1][8*i+4] | (buf[1][8*i+5] << 4);

                        *dst++ = buf[1][8*i+6] | (buf[1][8*i+7] << 4);

                    }

                }

            } else

            for (; n>0; n--) {

                *dst = adpcm_ima_compress_sample(&c->status[0], samples[0]) & 0x0F;

                *dst |= (adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels]) << 4) & 0xF0;

                dst++;

                *dst = adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels * 2]) & 0x0F;

                *dst |= (adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels * 3]) << 4) & 0xF0;

                dst++;

                *dst = adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels * 4]) & 0x0F;

                *dst |= (adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels * 5]) << 4) & 0xF0;

                dst++;

                *dst = adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels * 6]) & 0x0F;

                *dst |= (adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels * 7]) << 4) & 0xF0;

                dst++;

                /* right channel */

                if (avctx->channels == 2) {

                    *dst = adpcm_ima_compress_sample(&c->status[1], samples[1]);

                    *dst |= adpcm_ima_compress_sample(&c->status[1], samples[3]) << 4;

                    dst++;

                    *dst = adpcm_ima_compress_sample(&c->status[1], samples[5]);

                    *dst |= adpcm_ima_compress_sample(&c->status[1], samples[7]) << 4;

                    dst++;

                    *dst = adpcm_ima_compress_sample(&c->status[1], samples[9]);

                    *dst |= adpcm_ima_compress_sample(&c->status[1], samples[11]) << 4;

                    dst++;

                    *dst = adpcm_ima_compress_sample(&c->status[1], samples[13]);

                    *dst |= adpcm_ima_compress_sample(&c->status[1], samples[15]) << 4;

                    dst++;

                }

                samples += 8 * avctx->channels;

            }

        break;

    case CODEC_ID_ADPCM_SWF:

    {

        int i;

        PutBitContext pb;

        init_put_bits(&pb, dst, buf_size*8);

        n = avctx->frame_size-1;

        //Store AdpcmCodeSize

        put_bits(&pb, 2, 2);                //Set 4bits flash adpcm format

        //Init the encoder state

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

            c->status[i].step_index = av_clip(c->status[i].step_index, 0, 63); // clip step so it fits 6 bits

            put_bits(&pb, 16, samples[i] & 0xFFFF);

            put_bits(&pb, 6, c->status[i].step_index);

            c->status[i].prev_sample = (signed short)samples[i];

        }

        if(avctx->trellis > 0) {

            uint8_t buf[2][n];

            adpcm_compress_trellis(avctx, samples+2, buf[0], &c->status[0], n);

            if (avctx->channels == 2)

                adpcm_compress_trellis(avctx, samples+3, buf[1], &c->status[1], n);

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

                put_bits(&pb, 4, buf[0][i]);

                if (avctx->channels == 2)

                    put_bits(&pb, 4, buf[1][i]);

            }

        } else {

            for (i=1; i<avctx->frame_size; i++) {

                put_bits(&pb, 4, adpcm_ima_compress_sample(&c->status[0], samples[avctx->channels*i]) & 0xF);

                if (avctx->channels == 2)

                    put_bits(&pb, 4, adpcm_ima_compress_sample(&c->status[1], samples[2*i+1]) & 0xF);

            }

        }

        flush_put_bits(&pb);

        dst += put_bits_count(&pb)>>3;

        break;

    }

    case CODEC_ID_ADPCM_MS:

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

            int predictor=0;

            *dst++ = predictor;

            c->status[i].coeff1 = AdaptCoeff1[predictor];

            c->status[i].coeff2 = AdaptCoeff2[predictor];

        }

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

            if (c->status[i].idelta < 16)

                c->status[i].idelta = 16;

            bytestream_put_le16(&dst, c->status[i].idelta);

        }

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

            c->status[i].sample1= *samples++;

            bytestream_put_le16(&dst, c->status[i].sample1);

        }

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

            c->status[i].sample2= *samples++;

            bytestream_put_le16(&dst, c->status[i].sample2);

        }

        if(avctx->trellis > 0) {

            int n = avctx->block_align - 7*avctx->channels;

            uint8_t buf[2][n];

            if(avctx->channels == 1) {

                n *= 2;

                adpcm_compress_trellis(avctx, samples, buf[0], &c->status[0], n);

                for(i=0; i<n; i+=2)

                    *dst++ = (buf[0][i] << 4) | buf[0][i+1];

            } else {

                adpcm_compress_trellis(avctx, samples, buf[0], &c->status[0], n);

                adpcm_compress_trellis(avctx, samples+1, buf[1], &c->status[1], n);

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

                    *dst++ = (buf[0][i] << 4) | buf[1][i];

            }

        } else

        for(i=7*avctx->channels; i<avctx->block_align; i++) {

            int nibble;

            nibble = adpcm_ms_compress_sample(&c->status[ 0], *samples++)<<4;

            nibble|= adpcm_ms_compress_sample(&c->status[st], *samples++);

            *dst++ = nibble;

        }

        break;

    case CODEC_ID_ADPCM_YAMAHA:

        n = avctx->frame_size / 2;

        if(avctx->trellis > 0) {

            uint8_t buf[2][n*2];

            n *= 2;

            if(avctx->channels == 1) {

                adpcm_compress_trellis(avctx, samples, buf[0], &c->status[0], n);

                for(i=0; i<n; i+=2)

                    *dst++ = buf[0][i] | (buf[0][i+1] << 4);

            } else {

                adpcm_compress_trellis(avctx, samples, buf[0], &c->status[0], n);

                adpcm_compress_trellis(avctx, samples+1, buf[1], &c->status[1], n);

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

                    *dst++ = buf[0][i] | (buf[1][i] << 4);

            }

        } else

        for (; n>0; n--) {

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

                int nibble;

                nibble  = adpcm_yamaha_compress_sample(&c->status[i], samples[i]);

                nibble |= adpcm_yamaha_compress_sample(&c->status[i], samples[i+avctx->channels]) << 4;

                *dst++ = nibble;

            }

            samples += 2 * avctx->channels;

        }

        break;

    default:

        return -1;

    }

    return dst - frame;

}


static void migration_bitmap_sync(void)

{

    uint64_t num_dirty_pages_init = ram_list.dirty_pages;

    trace_migration_bitmap_sync_start();

    memory_global_sync_dirty_bitmap(get_system_memory());

    trace_migration_bitmap_sync_end(ram_list.dirty_pages

                                    - num_dirty_pages_init);

}


static inline int ucf64_exceptbits_from_host(int host_bits)

{

    int target_bits = 0;

    if (host_bits & float_flag_invalid) {

        target_bits |= UCF64_FPSCR_FLAG_INVALID;

    }

    if (host_bits & float_flag_divbyzero) {

        target_bits |= UCF64_FPSCR_FLAG_DIVZERO;

    }

    if (host_bits & float_flag_overflow) {

        target_bits |= UCF64_FPSCR_FLAG_OVERFLOW;

    }

    if (host_bits & float_flag_underflow) {

        target_bits |= UCF64_FPSCR_FLAG_UNDERFLOW;

    }

    if (host_bits & float_flag_inexact) {

        target_bits |= UCF64_FPSCR_FLAG_INEXACT;

    }

    return target_bits;

}


static void gen_mtfsf(DisasContext *ctx)

{

    TCGv_i32 t0;

    int L = ctx->opcode & 0x02000000;

    if (unlikely(!ctx->fpu_enabled)) {

        gen_exception(ctx, POWERPC_EXCP_FPU);

        return;

    }

    /* NIP cannot be restored if the memory exception comes from an helper */

    gen_update_nip(ctx, ctx->nip - 4);

    gen_reset_fpstatus();

    if (L)

        t0 = tcg_const_i32(0xff);

    else

        t0 = tcg_const_i32(FM(ctx->opcode));

    gen_helper_store_fpscr(cpu_env, cpu_fpr[rB(ctx->opcode)], t0);

    tcg_temp_free_i32(t0);

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

        tcg_gen_trunc_tl_i32(cpu_crf[1], cpu_fpscr);

        tcg_gen_shri_i32(cpu_crf[1], cpu_crf[1], FPSCR_OX);

    }

    /* We can raise a differed exception */

    gen_helper_float_check_status(cpu_env);

}


static int qcow2_save_vmstate(BlockDriverState *bs, QEMUIOVector *qiov,

                              int64_t pos)

{

    BDRVQcow2State *s = bs->opaque;

    int64_t total_sectors = bs->total_sectors;

    bool zero_beyond_eof = bs->zero_beyond_eof;

    int ret;

    BLKDBG_EVENT(bs->file, BLKDBG_VMSTATE_SAVE);

    bs->zero_beyond_eof = false;

    ret = bdrv_pwritev(bs, qcow2_vm_state_offset(s) + pos, qiov);

    bs->zero_beyond_eof = zero_beyond_eof;

    /* bdrv_co_do_writev will have increased the total_sectors value to include

     * the VM state - the VM state is however not an actual part of the block

     * device, therefore, we need to restore the old value. */

    bs->total_sectors = total_sectors;

    return ret;

}


int ioinst_handle_schm(CPUS390XState *env, uint64_t reg1, uint64_t reg2,

                       uint32_t ipb)

{

    uint8_t mbk;

    int update;

    int dct;

    trace_ioinst("schm");

    if (SCHM_REG1_RES(reg1)) {

        program_interrupt(env, PGM_OPERAND, 2);

        return -EIO;

    }

    mbk = SCHM_REG1_MBK(reg1);

    update = SCHM_REG1_UPD(reg1);

    dct = SCHM_REG1_DCT(reg1);

    if (update && (reg2 & 0x0000000000000fff)) {

        program_interrupt(env, PGM_OPERAND, 2);

        return -EIO;

    }

    css_do_schm(mbk, update, dct, update ? reg2 : 0);

    return 0;

}


static int read_ir(AVFilterLink *inlink, AVFrame *frame)

{

    AVFilterContext *ctx = inlink->dst;

    HeadphoneContext *s = ctx->priv;

    int ir_len, max_ir_len, input_number;

    for (input_number = 0; input_number < s->nb_inputs; input_number++)

        if (inlink == ctx->inputs[input_number])

            break;

    av_audio_fifo_write(s->in[input_number].fifo, (void **)frame->extended_data,

                        frame->nb_samples);

    av_frame_free(&frame);

    ir_len = av_audio_fifo_size(s->in[input_number].fifo);

    max_ir_len = 65536;

    if (ir_len > max_ir_len) {

        av_log(ctx, AV_LOG_ERROR, "Too big length of IRs: %d > %d.\n", ir_len, max_ir_len);

        return AVERROR(EINVAL);

    }

    s->in[input_number].ir_len = ir_len;

    s->ir_len = FFMAX(ir_len, s->ir_len);

    return 0;

}


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

{

    x86_reg idx = 15 - src_size;

    const uint8_t *s = src-idx;

    uint8_t *d = dst-idx;

#if COMPILE_TEMPLATE_MMX

    __asm__ volatile(

        "test          %0, %0           \n\t"

        "jns           2f               \n\t"

        PREFETCH"       (%1, %0)        \n\t"

        "movq          %3, %%mm7        \n\t"

        "pxor          %4, %%mm7        \n\t"

        "movq       %%mm7, %%mm6        \n\t"

        "pxor          %5, %%mm7        \n\t"

        ".p2align       4               \n\t"

        "1:                             \n\t"

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

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

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

# if COMPILE_TEMPLATE_MMX2

        "pshufw      $177, %%mm0, %%mm3 \n\t"

        "pshufw      $177, %%mm1, %%mm5 \n\t"

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

        "pand       %%mm6, %%mm3        \n\t"

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

        "pand       %%mm6, %%mm5        \n\t"

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

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

# else

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

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

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

        "pand       %%mm6, %%mm2        \n\t"

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

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

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

        "movq       %%mm4, %%mm5        \n\t"

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

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

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

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

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

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

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

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

# endif

        MOVNTQ"     %%mm0,  (%2, %0)    \n\t"

        MOVNTQ"     %%mm1, 8(%2, %0)    \n\t"

        "add          $16, %0           \n\t"

        "js            1b               \n\t"

        SFENCE"                         \n\t"

        EMMS"                           \n\t"

        "2:                             \n\t"

        : "+&r"(idx)

        : "r" (s), "r" (d), "m" (mask32b), "m" (mask32r), "m" (mmx_one)

        : "memory");

#endif

    for (; idx<15; idx+=4) {

        register int v = *(const uint32_t *)&s[idx], g = v & 0xff00ff00;

        v &= 0xff00ff;

        *(uint32_t *)&d[idx] = (v>>16) + g + (v<<16);

    }

}


static int slice_end(AVCodecContext *avctx, AVFrame *pict)

{

    Mpeg1Context *s1  = avctx->priv_data;

    MpegEncContext *s = &s1->mpeg_enc_ctx;

    if (!s1->mpeg_enc_ctx_allocated || !s->current_picture_ptr)

        return 0;

    if (s->avctx->hwaccel) {

        if (s->avctx->hwaccel->end_frame(s->avctx) < 0)

            av_log(avctx, AV_LOG_ERROR,

                   "hardware accelerator failed to decode picture\n");

    }

#if FF_API_XVMC

FF_DISABLE_DEPRECATION_WARNINGS

    if (CONFIG_MPEG_XVMC_DECODER && s->avctx->xvmc_acceleration)

        ff_xvmc_field_end(s);

FF_ENABLE_DEPRECATION_WARNINGS

#endif /* FF_API_XVMC */

    /* end of slice reached */

    if (/* s->mb_y << field_pic == s->mb_height && */ !s->first_field) {

        /* end of image */

        ff_er_frame_end(&s->er);

        ff_mpv_frame_end(s);

        if (s->pict_type == AV_PICTURE_TYPE_B || s->low_delay) {

            int ret = av_frame_ref(pict, s->current_picture_ptr->f);

            if (ret < 0)

                return ret;

            ff_print_debug_info(s, s->current_picture_ptr);

        } else {

            if (avctx->active_thread_type & FF_THREAD_FRAME)

                s->picture_number++;

            /* latency of 1 frame for I- and P-frames */

            /* XXX: use another variable than picture_number */

            if (s->last_picture_ptr != NULL) {

                int ret = av_frame_ref(pict, s->last_picture_ptr->f);

                if (ret < 0)

                    return ret;

                ff_print_debug_info(s, s->last_picture_ptr);

            }

        }

        return 1;

    } else {

        return 0;

    }

}


av_cold void ff_audio_mix_init_x86(AudioMix *am)

{

#if HAVE_YASM

    int mm_flags = av_get_cpu_flags();

    if (mm_flags & AV_CPU_FLAG_SSE && HAVE_SSE) {

        ff_audio_mix_set_func(am, AV_SAMPLE_FMT_FLTP, AV_MIX_COEFF_TYPE_FLT,

                              2, 1, 16, 8, "SSE", ff_mix_2_to_1_fltp_flt_sse);

        ff_audio_mix_set_func(am, AV_SAMPLE_FMT_FLTP, AV_MIX_COEFF_TYPE_FLT,

                              1, 2, 16, 4, "SSE", ff_mix_1_to_2_fltp_flt_sse);

    }

    if (mm_flags & AV_CPU_FLAG_SSE2 && HAVE_SSE) {

        ff_audio_mix_set_func(am, AV_SAMPLE_FMT_S16P, AV_MIX_COEFF_TYPE_FLT,

                              2, 1, 16, 8, "SSE2", ff_mix_2_to_1_s16p_flt_sse2);

        ff_audio_mix_set_func(am, AV_SAMPLE_FMT_S16P, AV_MIX_COEFF_TYPE_Q8,

                              2, 1, 16, 8, "SSE2", ff_mix_2_to_1_s16p_q8_sse2);

        ff_audio_mix_set_func(am, AV_SAMPLE_FMT_S16P, AV_MIX_COEFF_TYPE_FLT,

                              1, 2, 16, 8, "SSE2", ff_mix_1_to_2_s16p_flt_sse2);

    }

    if (mm_flags & AV_CPU_FLAG_SSE4 && HAVE_SSE) {

        ff_audio_mix_set_func(am, AV_SAMPLE_FMT_S16P, AV_MIX_COEFF_TYPE_FLT,

                              2, 1, 16, 8, "SSE4", ff_mix_2_to_1_s16p_flt_sse4);

        ff_audio_mix_set_func(am, AV_SAMPLE_FMT_S16P, AV_MIX_COEFF_TYPE_FLT,

                              1, 2, 16, 8, "SSE4", ff_mix_1_to_2_s16p_flt_sse4);

    }

    if (mm_flags & AV_CPU_FLAG_AVX && HAVE_AVX) {

        ff_audio_mix_set_func(am, AV_SAMPLE_FMT_FLTP, AV_MIX_COEFF_TYPE_FLT,

                              2, 1, 32, 16, "AVX", ff_mix_2_to_1_fltp_flt_avx);

        ff_audio_mix_set_func(am, AV_SAMPLE_FMT_FLTP, AV_MIX_COEFF_TYPE_FLT,

                              1, 2, 32, 8, "AVX", ff_mix_1_to_2_fltp_flt_avx);

        ff_audio_mix_set_func(am, AV_SAMPLE_FMT_S16P, AV_MIX_COEFF_TYPE_FLT,

                              1, 2, 16, 8, "AVX", ff_mix_1_to_2_s16p_flt_avx);

    }

    SET_MIX_3_8_TO_1_2(3)

    SET_MIX_3_8_TO_1_2(4)

    SET_MIX_3_8_TO_1_2(5)

    SET_MIX_3_8_TO_1_2(6)

    SET_MIX_3_8_TO_1_2(7)

    SET_MIX_3_8_TO_1_2(8)

#endif /* HAVE_YASM */

}


static int opt_map(OptionsContext *o, const char *opt, const char *arg)

{

    StreamMap *m = NULL;

    int i, negative = 0, file_idx;

    int sync_file_idx = -1, sync_stream_idx;

    char *p, *sync;

    char *map;

    if (*arg == '-') {

        negative = 1;

        arg++;

    }

    map = av_strdup(arg);

    /* parse sync stream first, just pick first matching stream */

    if (sync = strchr(map, ',')) {

        *sync = 0;

        sync_file_idx = strtol(sync + 1, &sync, 0);

        if (sync_file_idx >= nb_input_files || sync_file_idx < 0) {

            av_log(NULL, AV_LOG_FATAL, "Invalid sync file index: %d.\n", sync_file_idx);

            exit_program(1);

        }

        if (*sync)

            sync++;

        for (i = 0; i < input_files[sync_file_idx].nb_streams; i++)

            if (check_stream_specifier(input_files[sync_file_idx].ctx,

                                       input_files[sync_file_idx].ctx->streams[i], sync) == 1) {

                sync_stream_idx = i;

                break;

            }

        if (i == input_files[sync_file_idx].nb_streams) {

            av_log(NULL, AV_LOG_FATAL, "Sync stream specification in map %s does not "

                                       "match any streams.\n", arg);

            exit_program(1);

        }

    }

    file_idx = strtol(map, &p, 0);

    if (file_idx >= nb_input_files || file_idx < 0) {

        av_log(NULL, AV_LOG_FATAL, "Invalid input file index: %d.\n", file_idx);

        exit_program(1);

    }

    if (negative)

        /* disable some already defined maps */

        for (i = 0; i < o->nb_stream_maps; i++) {

            m = &o->stream_maps[i];

            if (check_stream_specifier(input_files[m->file_index].ctx,

                                       input_files[m->file_index].ctx->streams[m->stream_index],

                                       *p == ':' ? p + 1 : p) > 0)

                m->disabled = 1;

        }

    else

        for (i = 0; i < input_files[file_idx].nb_streams; i++) {

            if (check_stream_specifier(input_files[file_idx].ctx, input_files[file_idx].ctx->streams[i],

                        *p == ':' ? p + 1 : p) <= 0)

                continue;

            o->stream_maps = grow_array(o->stream_maps, sizeof(*o->stream_maps),

                                        &o->nb_stream_maps, o->nb_stream_maps + 1);

            m = &o->stream_maps[o->nb_stream_maps - 1];

            m->file_index   = file_idx;

            m->stream_index = i;

            if (sync_file_idx >= 0) {

                m->sync_file_index   = sync_file_idx;

                m->sync_stream_index = sync_stream_idx;

            } else {

                m->sync_file_index   = file_idx;

                m->sync_stream_index = i;

            }

        }

    if (!m) {

        av_log(NULL, AV_LOG_FATAL, "Stream map '%s' matches no streams.\n", arg);

        exit_program(1);

    }

    av_freep(&map);

    return 0;

}


MemoryRegion *iotlb_to_region(target_phys_addr_t index)

{

    return phys_sections[index & ~TARGET_PAGE_MASK].mr;

}


static void *do_data_compress(void *opaque)

{

    CompressParam *param = opaque;

    while (!quit_comp_thread) {

        qemu_mutex_lock(&param->mutex);

        /* Re-check the quit_comp_thread in case of

         * terminate_compression_threads is called just before

         * qemu_mutex_lock(&param->mutex) and after

         * while(!quit_comp_thread), re-check it here can make

         * sure the compression thread terminate as expected.

         */

        while (!param->start && !quit_comp_thread) {

            qemu_cond_wait(&param->cond, &param->mutex);

        }

        if (!quit_comp_thread) {

            do_compress_ram_page(param);

        }

        param->start = false;

        qemu_mutex_unlock(&param->mutex);

        qemu_mutex_lock(comp_done_lock);

        param->done = true;

        qemu_cond_signal(comp_done_cond);

        qemu_mutex_unlock(comp_done_lock);

    }

    return NULL;

}


int nbd_client_session_co_readv(NbdClientSession *client, int64_t sector_num,

    int nb_sectors, QEMUIOVector *qiov)

{

    int offset = 0;

    int ret;

    while (nb_sectors > NBD_MAX_SECTORS) {

        ret = nbd_co_readv_1(client, sector_num,

                             NBD_MAX_SECTORS, qiov, offset);

        if (ret < 0) {

            return ret;

        }

        offset += NBD_MAX_SECTORS * 512;

        sector_num += NBD_MAX_SECTORS;

        nb_sectors -= NBD_MAX_SECTORS;

    }

    return nbd_co_readv_1(client, sector_num, nb_sectors, qiov, offset);

}


static int find_pte64(CPUPPCState *env, struct mmu_ctx_hash64 *ctx,

                      ppc_slb_t *slb, target_ulong eaddr, int rwx)

{

    hwaddr pteg_off, pte_offset;

    ppc_hash_pte64_t pte;

    uint64_t vsid, pageaddr, ptem;

    hwaddr hash;

    int segment_bits, target_page_bits;

    int ret;

    ret = -1; /* No entry found */

    if (slb->vsid & SLB_VSID_B) {

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

        segment_bits = 40;

    } else {

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

        segment_bits = 28;

    }

    target_page_bits = (slb->vsid & SLB_VSID_L)

        ? TARGET_PAGE_BITS_16M : TARGET_PAGE_BITS;

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

                  : (slb->vsid & SLB_VSID_KS));

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

                            - (1ULL << target_page_bits));

    if (slb->vsid & SLB_VSID_B) {

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

    } else {

        hash = vsid ^ (pageaddr >> target_page_bits);

    }

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

    ptem = (slb->vsid & SLB_VSID_PTEM) |

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

    ret = -1;

    /* Page address translation */

    LOG_MMU("htab_base " TARGET_FMT_plx " htab_mask " TARGET_FMT_plx

            " hash " TARGET_FMT_plx "\n",

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

    /* Primary PTEG lookup */

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

            " vsid=" TARGET_FMT_lx " ptem=" TARGET_FMT_lx

            " hash=" TARGET_FMT_plx "\n",

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

    pteg_off = (hash * HASH_PTEG_SIZE_64) & env->htab_mask;

    pte_offset = ppc_hash64_pteg_search(env, pteg_off, 0, ptem, &pte);

    if (pte_offset == -1) {

        /* Secondary PTEG lookup */

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

                " vsid=" TARGET_FMT_lx " api=" TARGET_FMT_lx

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

                env->htab_mask, vsid, ptem, ~hash);

        pteg_off = (~hash * HASH_PTEG_SIZE_64) & env->htab_mask;

        pte_offset = ppc_hash64_pteg_search(env, pteg_off, 1, ptem, &pte);

    }

    if (pte_offset != -1) {

        ret = pte64_check(ctx, pte.pte0, pte.pte1, rwx);

        LOG_MMU("found PTE at addr %08" HWADDR_PRIx " prot=%01x ret=%d\n",

                ctx->raddr, ctx->prot, ret);

        /* Update page flags */

        if (ppc_hash64_pte_update_flags(ctx, &pte.pte1, ret, rwx) == 1) {

            ppc_hash64_store_hpte1(env, pte_offset, pte.pte1);

        }

    }

    /* We have a TLB that saves 4K pages, so let's

     * split a huge page to 4k chunks */

    if (target_page_bits != TARGET_PAGE_BITS) {

        ctx->raddr |= (eaddr & ((1 << target_page_bits) - 1))

                      & TARGET_PAGE_MASK;

    }

    return ret;

}


static int monitor_check_qmp_args(const mon_cmd_t *cmd, QDict *args)

{

    int err;

    const char *p;

    CmdArgs cmd_args;

    QemuOptsList *opts_list;

    if (cmd->args_type == NULL) {

        return (qdict_size(args) == 0 ? 0 : -1);

    }

    err = 0;

    cmd_args_init(&cmd_args);

    opts_list = NULL;

    for (p = cmd->args_type;; p++) {

        if (*p == ':') {

            cmd_args.type = *++p;

            p++;

            if (cmd_args.type == '-') {

                cmd_args.flag = *p++;

                cmd_args.optional = 1;

            } else if (cmd_args.type == 'O') {

                opts_list = qemu_find_opts(qstring_get_str(cmd_args.name));

                assert(opts_list);

            } else if (*p == '?') {

                cmd_args.optional = 1;

                p++;

            }

            assert(*p == ',' || *p == '\0');

            if (opts_list) {

                err = check_opts(opts_list, args);

                opts_list = NULL;

            } else {

                err = check_arg(&cmd_args, args);

                QDECREF(cmd_args.name);

                cmd_args_init(&cmd_args);

            }

            if (err < 0) {

                break;

            }

        } else {

            qstring_append_chr(cmd_args.name, *p);

        }

        if (*p == '\0') {

            break;

        }

    }

    QDECREF(cmd_args.name);

    return err;

}


static void dec_bcc(DisasContext *dc)

{

    unsigned int cc;

    unsigned int dslot;

    cc = EXTRACT_FIELD(dc->ir, 21, 23);

    dslot = dc->ir & (1 << 25);

    LOG_DIS("bcc%s r%d %x\n", dslot ? "d" : "", dc->ra, dc->imm);

    dc->delayed_branch = 1;

    if (dslot) {

        dc->delayed_branch = 2;

        dc->tb_flags |= D_FLAG;

        tcg_gen_st_tl(tcg_const_tl(dc->type_b && (dc->tb_flags & IMM_FLAG)),

                      cpu_env, offsetof(CPUState, bimm));

    }

    if (dec_alu_op_b_is_small_imm(dc)) {

        int32_t offset = (int32_t)((int16_t)dc->imm); /* sign-extend.  */

        tcg_gen_movi_tl(env_btarget, dc->pc + offset);

    } else {

        tcg_gen_movi_tl(env_btarget, dc->pc);

        tcg_gen_add_tl(env_btarget, env_btarget, *(dec_alu_op_b(dc)));

    }

    dc->jmp = JMP_INDIRECT;

    eval_cc(dc, cc, env_btaken, cpu_R[dc->ra], tcg_const_tl(0));

}


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

{

    QEMUFileBuffered *s = opaque;

    ssize_t error;

    DPRINTF("putting %d bytes at %" PRId64 "\n", size, pos);

    error = qemu_file_get_error(s->file);

    if (error) {

        DPRINTF("flush when error, bailing: %s\n", strerror(-error));

        return error;

    }

    if (size <= 0) {

        return size;

    }

    if (size > (s->buffer_capacity - s->buffer_size)) {

        DPRINTF("increasing buffer capacity from %zu by %zu\n",

                s->buffer_capacity, size + 1024);

        s->buffer_capacity += size + 1024;

        s->buffer = g_realloc(s->buffer, s->buffer_capacity);

    }

    memcpy(s->buffer + s->buffer_size, buf, size);

    s->buffer_size += size;

    return size;

}


static void id3v2_parse(AVIOContext *pb, AVDictionary **metadata,

                        AVFormatContext *s, int len, uint8_t version,

                        uint8_t flags, ID3v2ExtraMeta **extra_meta)

{

    int isv34, unsync;

    unsigned tlen;

    char tag[5];

    int64_t next, end = avio_tell(pb) + len;

    int taghdrlen;

    const char *reason = NULL;

    AVIOContext pb_local;

    AVIOContext *pbx;

    unsigned char *buffer = NULL;

    int buffer_size       = 0;

    const ID3v2EMFunc *extra_func = NULL;

    unsigned char *uncompressed_buffer = NULL;

    av_unused int uncompressed_buffer_size = 0;

    av_log(s, AV_LOG_DEBUG, "id3v2 ver:%d flags:%02X len:%d\n", version, flags, len);

    switch (version) {

    case 2:

        if (flags & 0x40) {

            reason = "compression";

            goto error;

        }

        isv34     = 0;

        taghdrlen = 6;

        break;

    case 3:

    case 4:

        isv34     = 1;

        taghdrlen = 10;

        break;

    default:

        reason = "version";

        goto error;

    }

    unsync = flags & 0x80;

    if (isv34 && flags & 0x40) { /* Extended header present, just skip over it */

        int extlen = get_size(pb, 4);

        if (version == 4)

            /* In v2.4 the length includes the length field we just read. */

            extlen -= 4;

        if (extlen < 0) {

            reason = "invalid extended header length";

            goto error;

        }

        avio_skip(pb, extlen);

        len -= extlen + 4;

        if (len < 0) {

            reason = "extended header too long.";

            goto error;

        }

    }

    while (len >= taghdrlen) {

        unsigned int tflags = 0;

        int tunsync         = 0;

        int tcomp           = 0;

        int tencr           = 0;

        unsigned long av_unused dlen;

        if (isv34) {

            if (avio_read(pb, tag, 4) < 4)

                break;

            tag[4] = 0;

            if (version == 3) {

                tlen = avio_rb32(pb);

            } else

                tlen = get_size(pb, 4);

            tflags  = avio_rb16(pb);

            tunsync = tflags & ID3v2_FLAG_UNSYNCH;

        } else {

            if (avio_read(pb, tag, 3) < 3)

                break;

            tag[3] = 0;

            tlen   = avio_rb24(pb);

        }

        if (tlen > (1<<28))

            break;

        len -= taghdrlen + tlen;

        if (len < 0)

            break;

        next = avio_tell(pb) + tlen;

        if (!tlen) {

            if (tag[0])

                av_log(s, AV_LOG_DEBUG, "Invalid empty frame %s, skipping.\n",

                       tag);

            continue;

        }

        if (tflags & ID3v2_FLAG_DATALEN) {

            if (tlen < 4)

                break;

            dlen = avio_rb32(pb);

            tlen -= 4;

        } else

            dlen = tlen;

        tcomp = tflags & ID3v2_FLAG_COMPRESSION;

        tencr = tflags & ID3v2_FLAG_ENCRYPTION;

        /* skip encrypted tags and, if no zlib, compressed tags */

        if (tencr || (!CONFIG_ZLIB && tcomp)) {

            const char *type;

            if (!tcomp)

                type = "encrypted";

            else if (!tencr)

                type = "compressed";

            else

                type = "encrypted and compressed";

            av_log(s, AV_LOG_WARNING, "Skipping %s ID3v2 frame %s.\n", type, tag);

            avio_skip(pb, tlen);

        /* check for text tag or supported special meta tag */

        } else if (tag[0] == 'T' ||

                   (extra_meta &&

                    (extra_func = get_extra_meta_func(tag, isv34)))) {

            pbx = pb;

            if (unsync || tunsync || tcomp) {

                av_fast_malloc(&buffer, &buffer_size, tlen);

                if (!buffer) {

                    av_log(s, AV_LOG_ERROR, "Failed to alloc %d bytes\n", tlen);

                    goto seek;

                }

            }

            if (unsync || tunsync) {

                int64_t end = avio_tell(pb) + tlen;

                uint8_t *b;

                b = buffer;

                while (avio_tell(pb) < end && b - buffer < tlen && !pb->eof_reached) {

                    *b++ = avio_r8(pb);

                    if (*(b - 1) == 0xff && avio_tell(pb) < end - 1 &&

                        b - buffer < tlen &&

                        !pb->eof_reached ) {

                        uint8_t val = avio_r8(pb);

                        *b++ = val ? val : avio_r8(pb);

                    }

                }

                ffio_init_context(&pb_local, buffer, b - buffer, 0, NULL, NULL, NULL,

                                  NULL);

                tlen = b - buffer;

                pbx  = &pb_local; // read from sync buffer

            }

#if CONFIG_ZLIB

                if (tcomp) {

                    int err;

                    av_log(s, AV_LOG_DEBUG, "Compresssed frame %s tlen=%d dlen=%ld\n", tag, tlen, dlen);

                    av_fast_malloc(&uncompressed_buffer, &uncompressed_buffer_size, dlen);

                    if (!uncompressed_buffer) {

                        av_log(s, AV_LOG_ERROR, "Failed to alloc %ld bytes\n", dlen);

                        goto seek;

                    }

                    if (!(unsync || tunsync)) {

                        err = avio_read(pb, buffer, tlen);

                        if (err < 0) {

                            av_log(s, AV_LOG_ERROR, "Failed to read compressed tag\n");

                            goto seek;

                        }

                        tlen = err;

                    }

                    err = uncompress(uncompressed_buffer, &dlen, buffer, tlen);

                    if (err != Z_OK) {

                        av_log(s, AV_LOG_ERROR, "Failed to uncompress tag: %d\n", err);

                        goto seek;

                    }

                    ffio_init_context(&pb_local, uncompressed_buffer, dlen, 0, NULL, NULL, NULL, NULL);

                    tlen = dlen;

                    pbx = &pb_local; // read from sync buffer

                }

#endif

            if (tag[0] == 'T')

                /* parse text tag */

                read_ttag(s, pbx, tlen, metadata, tag);

            else

                /* parse special meta tag */

                extra_func->read(s, pbx, tlen, tag, extra_meta, isv34);

        } else if (!tag[0]) {

            if (tag[1])

                av_log(s, AV_LOG_WARNING, "invalid frame id, assuming padding\n");

            avio_skip(pb, tlen);

            break;

        }

        /* Skip to end of tag */

seek:

        avio_seek(pb, next, SEEK_SET);

    }

    /* Footer preset, always 10 bytes, skip over it */

    if (version == 4 && flags & 0x10)

        end += 10;

error:

    if (reason)

        av_log(s, AV_LOG_INFO, "ID3v2.%d tag skipped, cannot handle %s\n",

               version, reason);

    avio_seek(pb, end, SEEK_SET);

    av_free(buffer);

    av_free(uncompressed_buffer);

    return;

}


void op_mfc0_ebase (void)

{

    T0 = (int32_t)env->CP0_EBase;

    RETURN();

}


static void init_blk_migration_it(void *opaque, BlockDriverState *bs)

{

    Monitor *mon = opaque;

    BlkMigDevState *bmds;

    int64_t sectors;

    if (!bdrv_is_read_only(bs)) {

        sectors = bdrv_getlength(bs) >> BDRV_SECTOR_BITS;

        if (sectors <= 0) {

            return;

        }

        bmds = g_malloc0(sizeof(BlkMigDevState));

        bmds->bs = bs;

        bmds->bulk_completed = 0;

        bmds->total_sectors = sectors;

        bmds->completed_sectors = 0;

        bmds->shared_base = block_mig_state.shared_base;

        alloc_aio_bitmap(bmds);

        drive_get_ref(drive_get_by_blockdev(bs));

        bdrv_set_in_use(bs, 1);

        block_mig_state.total_sector_sum += sectors;

        if (bmds->shared_base) {

            monitor_printf(mon, "Start migration for %s with shared base "

                                "image\n",

                           bs->device_name);

        } else {

            monitor_printf(mon, "Start full migration for %s\n",

                           bs->device_name);

        }

        QSIMPLEQ_INSERT_TAIL(&block_mig_state.bmds_list, bmds, entry);

    }

}