static int kvm_mce_in_exception(CPUState *env)

{

    struct kvm_msr_entry msr_mcg_status = {

        .index = MSR_MCG_STATUS,

    };

    int r;

    r = kvm_get_msr(env, &msr_mcg_status, 1);

    if (r == -1 || r == 0) {

        return -1;

    }

    return !!(msr_mcg_status.data & MCG_STATUS_MCIP);

}


static void count_cpreg(gpointer key, gpointer opaque)

{

    ARMCPU *cpu = opaque;

    uint64_t regidx;

    const ARMCPRegInfo *ri;

    regidx = *(uint32_t *)key;

    ri = get_arm_cp_reginfo(cpu->cp_regs, regidx);

    if (!(ri->type & ARM_CP_NO_MIGRATE)) {

        cpu->cpreg_array_len++;

    }

}


static inline uint32_t efsctsiz(uint32_t val)

{

    CPU_FloatU u;

    u.l = val;

    /* NaN are not treated the same way IEEE 754 does */

    if (unlikely(float32_is_nan(u.f)))

        return 0;

    return float32_to_int32_round_to_zero(u.f, &env->vec_status);

}


static void scsi_unrealize(SCSIDevice *s, Error **errp)

{

    scsi_device_purge_requests(s, SENSE_CODE(NO_SENSE));

    blockdev_mark_auto_del(s->conf.blk);

}


int slirp_is_inited(void)

{

    return slirp_inited;

}


int pit_get_gate(PITState *pit, int channel)

{

    PITChannelState *s = &pit->channels[channel];

    return s->gate;

}


void pci_register_bar(PCIDevice *pci_dev, int region_num,

                      uint8_t type, MemoryRegion *memory)

{

    PCIIORegion *r;

    uint32_t addr; /* offset in pci config space */

    uint64_t wmask;

    pcibus_t size = memory_region_size(memory);

    assert(region_num >= 0);

    assert(region_num < PCI_NUM_REGIONS);

    if (size & (size-1)) {

        fprintf(stderr, "ERROR: PCI region size must be pow2 "

                    "type=0x%x, size=0x%"FMT_PCIBUS"\n", type, size);

        exit(1);

    }

    r = &pci_dev->io_regions[region_num];

    r->addr = PCI_BAR_UNMAPPED;

    r->size = size;

    r->type = type;

    r->memory = memory;

    r->address_space = type & PCI_BASE_ADDRESS_SPACE_IO

                        ? pci_dev->bus->address_space_io

                        : pci_dev->bus->address_space_mem;

    wmask = ~(size - 1);

    if (region_num == PCI_ROM_SLOT) {

        /* ROM enable bit is writable */

        wmask |= PCI_ROM_ADDRESS_ENABLE;

    }

    addr = pci_bar(pci_dev, region_num);

    pci_set_long(pci_dev->config + addr, type);

    if (!(r->type & PCI_BASE_ADDRESS_SPACE_IO) &&

        r->type & PCI_BASE_ADDRESS_MEM_TYPE_64) {

        pci_set_quad(pci_dev->wmask + addr, wmask);

        pci_set_quad(pci_dev->cmask + addr, ~0ULL);

    } else {

        pci_set_long(pci_dev->wmask + addr, wmask & 0xffffffff);

        pci_set_long(pci_dev->cmask + addr, 0xffffffff);

    }

}


static int configure_accelerator(void)

{

    const char *p = NULL;

    char buf[10];

    int i, ret;

    bool accel_initalised = 0;

    bool init_failed = 0;

    QemuOptsList *list = qemu_find_opts("machine");

    if (!QTAILQ_EMPTY(&list->head)) {

        p = qemu_opt_get(QTAILQ_FIRST(&list->head), "accel");

    }

    if (p == NULL) {

        /* Use the default "accelerator", tcg */

        p = "tcg";

    }

    while (!accel_initalised && *p != '\0') {

        if (*p == ':') {

            p++;

        }

        p = get_opt_name(buf, sizeof (buf), p, ':');

        for (i = 0; i < ARRAY_SIZE(accel_list); i++) {

            if (strcmp(accel_list[i].opt_name, buf) == 0) {

                ret = accel_list[i].init();

                if (ret < 0) {

                    init_failed = 1;

                    if (!accel_list[i].available()) {

                        printf("%s not supported for this target\n",

                               accel_list[i].name);

                    } else {

                        fprintf(stderr, "failed to initialize %s: %s\n",

                                accel_list[i].name,

                                strerror(-ret));

                    }

                } else {

                    accel_initalised = 1;

                    *(accel_list[i].allowed) = 1;

                }

                break;

            }

        }

        if (i == ARRAY_SIZE(accel_list)) {

            fprintf(stderr, "\"%s\" accelerator does not exist.\n", buf);

        }

    }

    if (!accel_initalised) {

        fprintf(stderr, "No accelerator found!\n");

        exit(1);

    }

    if (init_failed) {

        fprintf(stderr, "Back to %s accelerator.\n", accel_list[i].name);

    }

    return !accel_initalised;

}


static int mss4_decode_frame(AVCodecContext *avctx, void *data, int *got_frame,

                             AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    MSS4Context *c = avctx->priv_data;

    GetBitContext gb;

    GetByteContext bc;

    uint8_t *dst[3];

    int width, height, quality, frame_type;

    int x, y, i, mb_width, mb_height, blk_type;

    int ret;

    if (buf_size < HEADER_SIZE) {

        av_log(avctx, AV_LOG_ERROR,

               "Frame should have at least %d bytes, got %d instead\n",

               HEADER_SIZE, buf_size);

        return AVERROR_INVALIDDATA;

    }

    bytestream2_init(&bc, buf, buf_size);

    width      = bytestream2_get_be16(&bc);

    height     = bytestream2_get_be16(&bc);

    bytestream2_skip(&bc, 2);

    quality    = bytestream2_get_byte(&bc);

    frame_type = bytestream2_get_byte(&bc);

    if (width > avctx->width ||

        height != avctx->height) {

        av_log(avctx, AV_LOG_ERROR, "Invalid frame dimensions %dx%d\n",

               width, height);

        return AVERROR_INVALIDDATA;

    }

    if (quality < 1 || quality > 100) {

        av_log(avctx, AV_LOG_ERROR, "Invalid quality setting %d\n", quality);

        return AVERROR_INVALIDDATA;

    }

    if ((frame_type & ~3) || frame_type == 3) {

        av_log(avctx, AV_LOG_ERROR, "Invalid frame type %d\n", frame_type);

        return AVERROR_INVALIDDATA;

    }

    if (frame_type != SKIP_FRAME && !bytestream2_get_bytes_left(&bc)) {

        av_log(avctx, AV_LOG_ERROR,

               "Empty frame found but it is not a skip frame.\n");

        return AVERROR_INVALIDDATA;

    }

    if ((ret = ff_reget_buffer(avctx, c->pic)) < 0)

        return ret;

    c->pic->key_frame = (frame_type == INTRA_FRAME);

    c->pic->pict_type = (frame_type == INTRA_FRAME) ? AV_PICTURE_TYPE_I

                                                   : AV_PICTURE_TYPE_P;

    if (frame_type == SKIP_FRAME) {

        *got_frame      = 1;

        if ((ret = av_frame_ref(data, c->pic)) < 0)

            return ret;

        return buf_size;

    }

    if (c->quality != quality) {

        c->quality = quality;

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

            ff_mss34_gen_quant_mat(c->quant_mat[i], quality, !i);

    }

    init_get_bits8(&gb, buf + HEADER_SIZE, (buf_size - HEADER_SIZE));

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

    mb_height = FFALIGN(height, 16) >> 4;

    dst[0] = c->pic->data[0];

    dst[1] = c->pic->data[1];

    dst[2] = c->pic->data[2];

    memset(c->prev_vec, 0, sizeof(c->prev_vec));

    for (y = 0; y < mb_height; y++) {

        memset(c->dc_cache, 0, sizeof(c->dc_cache));

        for (x = 0; x < mb_width; x++) {

            blk_type = decode012(&gb);

            switch (blk_type) {

            case DCT_BLOCK:

                if (mss4_decode_dct_block(c, &gb, dst, x, y) < 0) {

                    av_log(avctx, AV_LOG_ERROR,

                           "Error decoding DCT block %d,%d\n",

                           x, y);

                    return AVERROR_INVALIDDATA;

                }

                break;

            case IMAGE_BLOCK:

                if (mss4_decode_image_block(c, &gb, dst, x, y) < 0) {

                    av_log(avctx, AV_LOG_ERROR,

                           "Error decoding VQ block %d,%d\n",

                           x, y);

                    return AVERROR_INVALIDDATA;

                }

                break;

            case SKIP_BLOCK:

                if (frame_type == INTRA_FRAME) {

                    av_log(avctx, AV_LOG_ERROR, "Skip block in intra frame\n");

                    return AVERROR_INVALIDDATA;

                }

                break;

            }

            if (blk_type != DCT_BLOCK)

                mss4_update_dc_cache(c, x);

        }

        dst[0] += c->pic->linesize[0] * 16;

        dst[1] += c->pic->linesize[1] * 16;

        dst[2] += c->pic->linesize[2] * 16;

    }

    if ((ret = av_frame_ref(data, c->pic)) < 0)

        return ret;

    *got_frame      = 1;

    return buf_size;

}


static void guest_phys_blocks_region_add(MemoryListener *listener,

                                         MemoryRegionSection *section)

{

    GuestPhysListener *g;

    uint64_t section_size;

    hwaddr target_start, target_end;

    uint8_t *host_addr;

    GuestPhysBlock *predecessor;

    /* we only care about RAM */

    if (!memory_region_is_ram(section->mr) ||

        memory_region_is_skip_dump(section->mr)) {

        return;

    }

    g            = container_of(listener, GuestPhysListener, listener);

    section_size = int128_get64(section->size);

    target_start = section->offset_within_address_space;

    target_end   = target_start + section_size;

    host_addr    = memory_region_get_ram_ptr(section->mr) +

                   section->offset_within_region;

    predecessor  = NULL;

    /* find continuity in guest physical address space */

    if (!QTAILQ_EMPTY(&g->list->head)) {

        hwaddr predecessor_size;

        predecessor = QTAILQ_LAST(&g->list->head, GuestPhysBlockHead);

        predecessor_size = predecessor->target_end - predecessor->target_start;

        /* the memory API guarantees monotonically increasing traversal */

        g_assert(predecessor->target_end <= target_start);

        /* we want continuity in both guest-physical and host-virtual memory */

        if (predecessor->target_end < target_start ||

            predecessor->host_addr + predecessor_size != host_addr) {

            predecessor = NULL;

        }

    }

    if (predecessor == NULL) {

        /* isolated mapping, allocate it and add it to the list */

        GuestPhysBlock *block = g_malloc0(sizeof *block);

        block->target_start = target_start;

        block->target_end   = target_end;

        block->host_addr    = host_addr;

        block->mr           = section->mr;

        memory_region_ref(section->mr);

        QTAILQ_INSERT_TAIL(&g->list->head, block, next);

        ++g->list->num;

    } else {

        /* expand predecessor until @target_end; predecessor's start doesn't

         * change

         */

        predecessor->target_end = target_end;

    }

#ifdef DEBUG_GUEST_PHYS_REGION_ADD

    fprintf(stderr, "%s: target_start=" TARGET_FMT_plx " target_end="

            TARGET_FMT_plx ": %s (count: %u)\n", __FUNCTION__, target_start,

            target_end, predecessor ? "joined" : "added", g->list->num);

#endif

}


InputEvent *replay_read_input_event(void)

{

    InputEvent evt;

    KeyValue keyValue;

    InputKeyEvent key;

    key.key = &keyValue;

    InputBtnEvent btn;

    InputMoveEvent rel;

    InputMoveEvent abs;

    evt.type = replay_get_dword();

    switch (evt.type) {

    case INPUT_EVENT_KIND_KEY:

        evt.u.key = &key;

        evt.u.key->key->type = replay_get_dword();

        switch (evt.u.key->key->type) {

        case KEY_VALUE_KIND_NUMBER:

            evt.u.key->key->u.number = replay_get_qword();

            evt.u.key->down = replay_get_byte();

            break;

        case KEY_VALUE_KIND_QCODE:

            evt.u.key->key->u.qcode = (QKeyCode)replay_get_dword();

            evt.u.key->down = replay_get_byte();

            break;

        case KEY_VALUE_KIND__MAX:

            /* keep gcc happy */

            break;

        }

        break;

    case INPUT_EVENT_KIND_BTN:

        evt.u.btn = &btn;

        evt.u.btn->button = (InputButton)replay_get_dword();

        evt.u.btn->down = replay_get_byte();

        break;

    case INPUT_EVENT_KIND_REL:

        evt.u.rel = &rel;

        evt.u.rel->axis = (InputAxis)replay_get_dword();

        evt.u.rel->value = replay_get_qword();

        break;

    case INPUT_EVENT_KIND_ABS:

        evt.u.abs = &abs;

        evt.u.abs->axis = (InputAxis)replay_get_dword();

        evt.u.abs->value = replay_get_qword();

        break;

    case INPUT_EVENT_KIND__MAX:

        /* keep gcc happy */

        break;

    }

    return qapi_clone_InputEvent(&evt);

}


build_fadt(GArray *table_data, GArray *linker, AcpiPmInfo *pm,

           unsigned facs, unsigned dsdt)

{

    AcpiFadtDescriptorRev1 *fadt = acpi_data_push(table_data, sizeof(*fadt));

    fadt->firmware_ctrl = cpu_to_le32(facs);

    /* FACS address to be filled by Guest linker */

    bios_linker_loader_add_pointer(linker, ACPI_BUILD_TABLE_FILE,

                                   ACPI_BUILD_TABLE_FILE,

                                   table_data, &fadt->firmware_ctrl,

                                   sizeof fadt->firmware_ctrl);

    fadt->dsdt = cpu_to_le32(dsdt);

    /* DSDT address to be filled by Guest linker */

    bios_linker_loader_add_pointer(linker, ACPI_BUILD_TABLE_FILE,

                                   ACPI_BUILD_TABLE_FILE,

                                   table_data, &fadt->dsdt,

                                   sizeof fadt->dsdt);

    fadt_setup(fadt, pm);

    build_header(linker, table_data,

                 (void *)fadt, "FACP", sizeof(*fadt), 1, NULL);

}


vpc_co_pwritev(BlockDriverState *bs, uint64_t offset, uint64_t bytes,

               QEMUIOVector *qiov, int flags)

{

    BDRVVPCState *s = bs->opaque;

    int64_t image_offset;

    int64_t n_bytes;

    int64_t bytes_done = 0;

    int ret;

    VHDFooter *footer =  (VHDFooter *) s->footer_buf;

    QEMUIOVector local_qiov;

    if (be32_to_cpu(footer->type) == VHD_FIXED) {

        return bdrv_co_pwritev(bs->file->bs, offset, bytes, qiov, 0);

    }

    qemu_co_mutex_lock(&s->lock);

    qemu_iovec_init(&local_qiov, qiov->niov);

    while (bytes > 0) {

        image_offset = get_image_offset(bs, offset, true);

        n_bytes = MIN(bytes, s->block_size - (offset % s->block_size));

        if (image_offset == -1) {

            image_offset = alloc_block(bs, offset);

            if (image_offset < 0) {

                ret = image_offset;

                goto fail;

            }

        }

        qemu_iovec_reset(&local_qiov);

        qemu_iovec_concat(&local_qiov, qiov, bytes_done, n_bytes);

        ret = bdrv_co_pwritev(bs->file->bs, image_offset, n_bytes,

                              &local_qiov, 0);

        if (ret < 0) {

            goto fail;

        }

        bytes -= n_bytes;

        offset += n_bytes;

        bytes_done += n_bytes;

    }

    ret = 0;

fail:

    qemu_iovec_destroy(&local_qiov);

    qemu_co_mutex_unlock(&s->lock);

    return ret;

}


static int debugcon_parse(const char *devname)

{

    QemuOpts *opts;

    if (!qemu_chr_new("debugcon", devname, NULL)) {

        exit(1);

    }

    opts = qemu_opts_create(qemu_find_opts("device"), "debugcon", 1, NULL);

    if (!opts) {

        fprintf(stderr, "qemu: already have a debugcon device\n");

        exit(1);

    }

    qemu_opt_set(opts, "driver", "isa-debugcon", &error_abort);

    qemu_opt_set(opts, "chardev", "debugcon", &error_abort);

    return 0;

}


static void qemu_rbd_parse_filename(const char *filename, QDict *options,

                                    Error **errp)

{

    const char *start;

    char *p, *buf, *keypairs;

    char *found_str;

    size_t max_keypair_size;

    Error *local_err = NULL;

    if (!strstart(filename, "rbd:", &start)) {

        error_setg(errp, "File name must start with 'rbd:'");

        return;

    }

    max_keypair_size = strlen(start) + 1;

    buf = g_strdup(start);

    keypairs = g_malloc0(max_keypair_size);

    p = buf;

    found_str = qemu_rbd_next_tok(RBD_MAX_POOL_NAME_SIZE, p,

                                  '/', "pool name", &p, &local_err);

    if (local_err) {

        goto done;

    }

    if (!p) {

        error_setg(errp, "Pool name is required");

        goto done;

    }

    qemu_rbd_unescape(found_str);

    qdict_put(options, "pool", qstring_from_str(found_str));

    if (strchr(p, '@')) {

        found_str = qemu_rbd_next_tok(RBD_MAX_IMAGE_NAME_SIZE, p,

                                      '@', "object name", &p, &local_err);

        if (local_err) {

            goto done;

        }

        qemu_rbd_unescape(found_str);

        qdict_put(options, "image", qstring_from_str(found_str));

        found_str = qemu_rbd_next_tok(RBD_MAX_SNAP_NAME_SIZE, p,

                                      ':', "snap name", &p, &local_err);

        if (local_err) {

            goto done;

        }

        qemu_rbd_unescape(found_str);

        qdict_put(options, "snapshot", qstring_from_str(found_str));

    } else {

        found_str = qemu_rbd_next_tok(RBD_MAX_IMAGE_NAME_SIZE, p,

                                      ':', "object name", &p, &local_err);

        if (local_err) {

            goto done;

        }

        qemu_rbd_unescape(found_str);

        qdict_put(options, "image", qstring_from_str(found_str));

    }

    if (!p) {

        goto done;

    }

    found_str = qemu_rbd_next_tok(RBD_MAX_CONF_NAME_SIZE, p,

                                  '\0', "configuration", &p, &local_err);

    if (local_err) {

        goto done;

    }

    p = found_str;

    /* The following are essentially all key/value pairs, and we treat

     * 'id' and 'conf' a bit special.  Key/value pairs may be in any order. */

    while (p) {

        char *name, *value;

        name = qemu_rbd_next_tok(RBD_MAX_CONF_NAME_SIZE, p,

                                 '=', "conf option name", &p, &local_err);

        if (local_err) {

            break;

        }

        if (!p) {

            error_setg(errp, "conf option %s has no value", name);

            break;

        }

        qemu_rbd_unescape(name);

        value = qemu_rbd_next_tok(RBD_MAX_CONF_VAL_SIZE, p,

                                  ':', "conf option value", &p, &local_err);

        if (local_err) {

            break;

        }

        qemu_rbd_unescape(value);

        if (!strcmp(name, "conf")) {

            qdict_put(options, "conf", qstring_from_str(value));

        } else if (!strcmp(name, "id")) {

            qdict_put(options, "user" , qstring_from_str(value));

        } else {

            /* FIXME: This is pretty ugly, and not the right way to do this.

             *        These should be contained in a structure, and then

             *        passed explicitly as individual key/value pairs to

             *        rados.  Consider this legacy code that needs to be

             *        updated. */

            char *tmp = g_malloc0(max_keypair_size);

            /* only use a delimiter if it is not the first keypair found */

            /* These are sets of unknown key/value pairs we'll pass along

             * to ceph */

            if (keypairs[0]) {

                snprintf(tmp, max_keypair_size, ":%s=%s", name, value);

                pstrcat(keypairs, max_keypair_size, tmp);

            } else {

                snprintf(keypairs, max_keypair_size, "%s=%s", name, value);

            }

            g_free(tmp);

        }

    }

    if (keypairs[0]) {

        qdict_put(options, "keyvalue-pairs", qstring_from_str(keypairs));

    }

done:

    if (local_err) {

        error_propagate(errp, local_err);

    }

    g_free(buf);

    g_free(keypairs);

    return;

}


static void register_multipage(MemoryRegionSection *section)

{

    target_phys_addr_t start_addr = section->offset_within_address_space;

    ram_addr_t size = section->size;

    target_phys_addr_t addr;

    uint16_t section_index = phys_section_add(section);

    assert(size);

    addr = start_addr;

    phys_page_set(addr >> TARGET_PAGE_BITS, size >> TARGET_PAGE_BITS,

                  section_index);

}


static int gdb_breakpoint_insert(CPUState *env, target_ulong addr,

                                 target_ulong len, int type)

{

    switch (type) {

    case GDB_BREAKPOINT_SW:

    case GDB_BREAKPOINT_HW:

        return cpu_breakpoint_insert(env, addr, BP_GDB, NULL);

#ifndef CONFIG_USER_ONLY

    case GDB_WATCHPOINT_WRITE:

    case GDB_WATCHPOINT_READ:

    case GDB_WATCHPOINT_ACCESS:

        return cpu_watchpoint_insert(env, addr, len, xlat_gdb_type[type],

                                     NULL);

#endif

    default:

        return -ENOSYS;

    }

}


ResampleContext *ff_audio_resample_init(AVAudioResampleContext *avr)

{

    ResampleContext *c;

    int out_rate    = avr->out_sample_rate;

    int in_rate     = avr->in_sample_rate;

    double factor   = FFMIN(out_rate * avr->cutoff / in_rate, 1.0);

    int phase_count = 1 << avr->phase_shift;

    int felem_size;

    if (avr->internal_sample_fmt != AV_SAMPLE_FMT_S16P &&

        avr->internal_sample_fmt != AV_SAMPLE_FMT_S32P &&

        avr->internal_sample_fmt != AV_SAMPLE_FMT_FLTP &&

        avr->internal_sample_fmt != AV_SAMPLE_FMT_DBLP) {

        av_log(avr, AV_LOG_ERROR, "Unsupported internal format for "

               "resampling: %s\n",

               av_get_sample_fmt_name(avr->internal_sample_fmt));

        return NULL;

    }

    c = av_mallocz(sizeof(*c));

    if (!c)

        return NULL;

    c->avr           = avr;

    c->phase_shift   = avr->phase_shift;

    c->phase_mask    = phase_count - 1;

    c->linear        = avr->linear_interp;

    c->factor        = factor;

    c->filter_length = FFMAX((int)ceil(avr->filter_size / factor), 1);

    c->filter_type   = avr->filter_type;

    c->kaiser_beta   = avr->kaiser_beta;

    switch (avr->internal_sample_fmt) {

    case AV_SAMPLE_FMT_DBLP:

        c->resample_one  = resample_one_dbl;

        c->resample_nearest = resample_nearest_dbl;

        c->set_filter    = set_filter_dbl;

        break;

    case AV_SAMPLE_FMT_FLTP:

        c->resample_one  = resample_one_flt;

        c->resample_nearest = resample_nearest_flt;

        c->set_filter    = set_filter_flt;

        break;

    case AV_SAMPLE_FMT_S32P:

        c->resample_one  = resample_one_s32;

        c->resample_nearest = resample_nearest_s32;

        c->set_filter    = set_filter_s32;

        break;

    case AV_SAMPLE_FMT_S16P:

        c->resample_one  = resample_one_s16;

        c->resample_nearest = resample_nearest_s16;

        c->set_filter    = set_filter_s16;

        break;

    }

    felem_size = av_get_bytes_per_sample(avr->internal_sample_fmt);

    c->filter_bank = av_mallocz(c->filter_length * (phase_count + 1) * felem_size);

    if (!c->filter_bank)

        goto error;

    if (build_filter(c) < 0)

        goto error;

    memcpy(&c->filter_bank[(c->filter_length * phase_count + 1) * felem_size],

           c->filter_bank, (c->filter_length - 1) * felem_size);

    memcpy(&c->filter_bank[c->filter_length * phase_count * felem_size],

           &c->filter_bank[(c->filter_length - 1) * felem_size], felem_size);

    c->compensation_distance = 0;

    if (!av_reduce(&c->src_incr, &c->dst_incr, out_rate,

                   in_rate * (int64_t)phase_count, INT32_MAX / 2))

        goto error;

    c->ideal_dst_incr = c->dst_incr;

    c->padding_size   = (c->filter_length - 1) / 2;

    c->index = -phase_count * ((c->filter_length - 1) / 2);

    c->frac  = 0;

    /* allocate internal buffer */

    c->buffer = ff_audio_data_alloc(avr->resample_channels, 0,

                                    avr->internal_sample_fmt,

                                    "resample buffer");

    if (!c->buffer)

        goto error;

    av_log(avr, AV_LOG_DEBUG, "resample: %s from %d Hz to %d Hz\n",

           av_get_sample_fmt_name(avr->internal_sample_fmt),

           avr->in_sample_rate, avr->out_sample_rate);

    return c;

error:

    ff_audio_data_free(&c->buffer);

    av_free(c->filter_bank);

    av_free(c);

    return NULL;

}


static inline void stl_phys_internal(target_phys_addr_t addr, uint32_t val,

                                     enum device_endian endian)

{

    uint8_t *ptr;

    MemoryRegionSection *section;

    section = phys_page_find(addr >> TARGET_PAGE_BITS);

    if (!memory_region_is_ram(section->mr) || section->readonly) {

        addr = memory_region_section_addr(section, addr);

        if (memory_region_is_ram(section->mr)) {

            section = &phys_sections[phys_section_rom];

        }

#if defined(TARGET_WORDS_BIGENDIAN)

        if (endian == DEVICE_LITTLE_ENDIAN) {

            val = bswap32(val);

        }

#else

        if (endian == DEVICE_BIG_ENDIAN) {

            val = bswap32(val);

        }

#endif

        io_mem_write(section->mr, addr, val, 4);

    } else {

        unsigned long addr1;

        addr1 = (memory_region_get_ram_addr(section->mr) & TARGET_PAGE_MASK)

            + memory_region_section_addr(section, addr);

        /* RAM case */

        ptr = qemu_get_ram_ptr(addr1);

        switch (endian) {

        case DEVICE_LITTLE_ENDIAN:

            stl_le_p(ptr, val);

            break;

        case DEVICE_BIG_ENDIAN:

            stl_be_p(ptr, val);

            break;

        default:

            stl_p(ptr, val);

            break;

        }

        invalidate_and_set_dirty(addr1, 4);

    }

}


static int usb_hub_handle_control(USBDevice *dev, int request, int value,

                                  int index, int length, uint8_t *data)

{

    USBHubState *s = (USBHubState *)dev;

    int ret;

    ret = usb_desc_handle_control(dev, request, value, index, length, data);

    if (ret >= 0) {

        return ret;

    }

    switch(request) {

    case DeviceRequest | USB_REQ_GET_STATUS:

        data[0] = (1 << USB_DEVICE_SELF_POWERED) |

            (dev->remote_wakeup << USB_DEVICE_REMOTE_WAKEUP);

        data[1] = 0x00;

        ret = 2;

        break;

    case DeviceOutRequest | USB_REQ_CLEAR_FEATURE:

        if (value == USB_DEVICE_REMOTE_WAKEUP) {

            dev->remote_wakeup = 0;

        } else {

            goto fail;

        }

        ret = 0;

        break;

    case EndpointOutRequest | USB_REQ_CLEAR_FEATURE:

        if (value == 0 && index != 0x81) { /* clear ep halt */

            goto fail;

        }

        ret = 0;

        break;

    case DeviceOutRequest | USB_REQ_SET_FEATURE:

        if (value == USB_DEVICE_REMOTE_WAKEUP) {

            dev->remote_wakeup = 1;

        } else {

            goto fail;

        }

        ret = 0;

        break;

    case DeviceRequest | USB_REQ_GET_CONFIGURATION:

        data[0] = 1;

        ret = 1;

        break;

    case DeviceOutRequest | USB_REQ_SET_CONFIGURATION:

        ret = 0;

        break;

    case DeviceRequest | USB_REQ_GET_INTERFACE:

        data[0] = 0;

        ret = 1;

        break;

    case DeviceOutRequest | USB_REQ_SET_INTERFACE:

        ret = 0;

        break;

        /* usb specific requests */

    case GetHubStatus:

        data[0] = 0;

        data[1] = 0;

        data[2] = 0;

        data[3] = 0;

        ret = 4;

        break;

    case GetPortStatus:

        {

            unsigned int n = index - 1;

            USBHubPort *port;

            if (n >= NUM_PORTS) {

                goto fail;

            }

            port = &s->ports[n];

            data[0] = port->wPortStatus;

            data[1] = port->wPortStatus >> 8;

            data[2] = port->wPortChange;

            data[3] = port->wPortChange >> 8;

            ret = 4;

        }

        break;

    case SetHubFeature:

    case ClearHubFeature:

        if (value == 0 || value == 1) {

        } else {

            goto fail;

        }

        ret = 0;

        break;

    case SetPortFeature:

        {

            unsigned int n = index - 1;

            USBHubPort *port;

            USBDevice *dev;

            if (n >= NUM_PORTS) {

                goto fail;

            }

            port = &s->ports[n];

            dev = port->port.dev;

            switch(value) {

            case PORT_SUSPEND:

                port->wPortStatus |= PORT_STAT_SUSPEND;

                break;

            case PORT_RESET:

                if (dev) {

                    usb_send_msg(dev, USB_MSG_RESET);

                    port->wPortChange |= PORT_STAT_C_RESET;

                    /* set enable bit */

                    port->wPortStatus |= PORT_STAT_ENABLE;

                }

                break;

            case PORT_POWER:

                break;

            default:

                goto fail;

            }

            ret = 0;

        }

        break;

    case ClearPortFeature:

        {

            unsigned int n = index - 1;

            USBHubPort *port;

            if (n >= NUM_PORTS) {

                goto fail;

            }

            port = &s->ports[n];

            switch(value) {

            case PORT_ENABLE:

                port->wPortStatus &= ~PORT_STAT_ENABLE;

                break;

            case PORT_C_ENABLE:

                port->wPortChange &= ~PORT_STAT_C_ENABLE;

                break;

            case PORT_SUSPEND:

                port->wPortStatus &= ~PORT_STAT_SUSPEND;

                break;

            case PORT_C_SUSPEND:

                port->wPortChange &= ~PORT_STAT_C_SUSPEND;

                break;

            case PORT_C_CONNECTION:

                port->wPortChange &= ~PORT_STAT_C_CONNECTION;

                break;

            case PORT_C_OVERCURRENT:

                port->wPortChange &= ~PORT_STAT_C_OVERCURRENT;

                break;

            case PORT_C_RESET:

                port->wPortChange &= ~PORT_STAT_C_RESET;

                break;

            default:

                goto fail;

            }

            ret = 0;

        }

        break;

    case GetHubDescriptor:

        {

            unsigned int n, limit, var_hub_size = 0;

            memcpy(data, qemu_hub_hub_descriptor,

                   sizeof(qemu_hub_hub_descriptor));

            data[2] = NUM_PORTS;

            /* fill DeviceRemovable bits */

            limit = ((NUM_PORTS + 1 + 7) / 8) + 7;

            for (n = 7; n < limit; n++) {

                data[n] = 0x00;

                var_hub_size++;

            }

            /* fill PortPwrCtrlMask bits */

            limit = limit + ((NUM_PORTS + 7) / 8);

            for (;n < limit; n++) {

                data[n] = 0xff;

                var_hub_size++;

            }

            ret = sizeof(qemu_hub_hub_descriptor) + var_hub_size;

            data[0] = ret;

            break;

        }

    default:

    fail:

        ret = USB_RET_STALL;

        break;

    }

    return ret;

}


void nbd_client_close(BlockDriverState *bs)

{

    NbdClientSession *client = nbd_get_client_session(bs);

    struct nbd_request request = {

        .type = NBD_CMD_DISC,

        .from = 0,

        .len = 0

    };

    if (client->ioc == NULL) {

        return;

    }

    nbd_send_request(client->ioc, &request);

    nbd_teardown_connection(bs);

}


static int handle_tsch(S390CPU *cpu)

{

    CPUS390XState *env = &cpu->env;

    CPUState *cs = CPU(cpu);

    struct kvm_run *run = cs->kvm_run;

    int ret;

    cpu_synchronize_state(cs);

    ret = ioinst_handle_tsch(env, env->regs[1], run->s390_tsch.ipb);

    if (ret >= 0) {

        /* Success; set condition code. */

        setcc(cpu, ret);

        ret = 0;

    } else if (ret < -1) {

        /*

         * Failure.

         * If an I/O interrupt had been dequeued, we have to reinject it.

         */

        if (run->s390_tsch.dequeued) {

            uint16_t subchannel_id = run->s390_tsch.subchannel_id;

            uint16_t subchannel_nr = run->s390_tsch.subchannel_nr;

            uint32_t io_int_parm = run->s390_tsch.io_int_parm;

            uint32_t io_int_word = run->s390_tsch.io_int_word;

            uint32_t type = ((subchannel_id & 0xff00) << 24) |

                ((subchannel_id & 0x00060) << 22) | (subchannel_nr << 16);

            kvm_s390_interrupt_internal(cpu, type,

                                        ((uint32_t)subchannel_id << 16)

                                        | subchannel_nr,

                                        ((uint64_t)io_int_parm << 32)

                                        | io_int_word, 1);

        }

        ret = 0;

    }

    return ret;

}


static int read_password(char *buf, int buf_size)

{

    uint8_t ch;

    int i, ret;

    printf("password: ");

    fflush(stdout);

    term_init();

    i = 0;

    for(;;) {

        ret = read(0, &ch, 1);

        if (ret == -1) {

            if (errno == EAGAIN || errno == EINTR) {

                continue;

            } else {

                break;

            }

        } else if (ret == 0) {

            ret = -1;

            break;

        } else {

            if (ch == '\r') {

                ret = 0;

                break;

            }

            if (i < (buf_size - 1))

                buf[i++] = ch;

        }

    }

    term_exit();

    buf[i] = '\0';

    printf("\n");

    return ret;

}


static uint64_t exynos4210_rtc_read(void *opaque, target_phys_addr_t offset,

        unsigned size)

{

    uint32_t value = 0;

    Exynos4210RTCState *s = (Exynos4210RTCState *)opaque;

    switch (offset) {

    case INTP:

        value = s->reg_intp;

        break;

    case RTCCON:

        value = s->reg_rtccon;

        break;

    case TICCNT:

        value = s->reg_ticcnt;

        break;

    case RTCALM:

        value = s->reg_rtcalm;

        break;

    case ALMSEC:

        value = s->reg_almsec;

        break;

    case ALMMIN:

        value = s->reg_almmin;

        break;

    case ALMHOUR:

        value = s->reg_almhour;

        break;

    case ALMDAY:

        value = s->reg_almday;

        break;

    case ALMMON:

        value = s->reg_almmon;

        break;

    case ALMYEAR:

        value = s->reg_almyear;

        break;

    case BCDSEC:

        value = (uint32_t)to_bcd((uint8_t)s->current_tm.tm_sec);

        break;

    case BCDMIN:

        value = (uint32_t)to_bcd((uint8_t)s->current_tm.tm_min);

        break;

    case BCDHOUR:

        value = (uint32_t)to_bcd((uint8_t)s->current_tm.tm_hour);

        break;

    case BCDDAYWEEK:

        value = (uint32_t)to_bcd((uint8_t)s->current_tm.tm_wday);

        break;

    case BCDDAY:

        value = (uint32_t)to_bcd((uint8_t)s->current_tm.tm_mday);

        break;

    case BCDMON:

        value = (uint32_t)to_bcd((uint8_t)s->current_tm.tm_mon + 1);

        break;

    case BCDYEAR:

        value = BCD3DIGITS(s->current_tm.tm_year);

        break;

    case CURTICNT:

        s->reg_curticcnt = ptimer_get_count(s->ptimer);

        value = s->reg_curticcnt;

        break;

    default:

        fprintf(stderr,

                "[exynos4210.rtc: bad read offset " TARGET_FMT_plx "]\n",

                offset);

        break;

    }

    return value;

}


static int read_tfra(MOVContext *mov, AVIOContext *f)

{

    MOVFragmentIndex* index = NULL;

    int version, fieldlength, i, j, err;

    int64_t pos = avio_tell(f);

    uint32_t size = avio_rb32(f);

    if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) {

        return -1;

    }

    av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n");

    index = av_mallocz(sizeof(MOVFragmentIndex));

    if (!index) {

        return AVERROR(ENOMEM);

    }

    mov->fragment_index_count++;

    if ((err = av_reallocp(&mov->fragment_index_data,

                           mov->fragment_index_count *

                           sizeof(MOVFragmentIndex*))) < 0) {

        av_freep(&index);

        return err;

    }

    mov->fragment_index_data[mov->fragment_index_count - 1] =

        index;

    version = avio_r8(f);

    avio_rb24(f);

    index->track_id = avio_rb32(f);

    fieldlength = avio_rb32(f);

    index->item_count = avio_rb32(f);

    index->items = av_mallocz(

            index->item_count * sizeof(MOVFragmentIndexItem));

    if (!index->items) {

        return AVERROR(ENOMEM);

    }

    for (i = 0; i < index->item_count; i++) {

        int64_t time, offset;

        if (version == 1) {

            time   = avio_rb64(f);

            offset = avio_rb64(f);

        } else {

            time   = avio_rb32(f);

            offset = avio_rb32(f);

        }

        index->items[i].time = time;

        index->items[i].moof_offset = offset;

        for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++)

            avio_r8(f);

        for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++)

            avio_r8(f);

        for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++)

            avio_r8(f);

    }

    avio_seek(f, pos + size, SEEK_SET);

    return 0;

}


void ff_h264_direct_ref_list_init(H264Context * const h){

    MpegEncContext * const s = &h->s;

    Picture * const ref1 = &h->ref_list[1][0];

    Picture * const cur = s->current_picture_ptr;

    int list, j, field;

    int sidx= (s->picture_structure&1)^1;

    int ref1sidx = (ref1->f.reference&1)^1;

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

        cur->ref_count[sidx][list] = h->ref_count[list];

        for(j=0; j<h->ref_count[list]; j++)

            cur->ref_poc[sidx][list][j] = 4 * h->ref_list[list][j].frame_num + (h->ref_list[list][j].f.reference & 3);

    }

    if(s->picture_structure == PICT_FRAME){

        memcpy(cur->ref_count[1], cur->ref_count[0], sizeof(cur->ref_count[0]));

        memcpy(cur->ref_poc  [1], cur->ref_poc  [0], sizeof(cur->ref_poc  [0]));

    }

    cur->mbaff= FRAME_MBAFF;

    h->col_fieldoff= 0;

    if(s->picture_structure == PICT_FRAME){

        int cur_poc = s->current_picture_ptr->poc;

        int *col_poc = h->ref_list[1]->field_poc;

        h->col_parity= (FFABS(col_poc[0] - cur_poc) >= FFABS(col_poc[1] - cur_poc));

        ref1sidx=sidx= h->col_parity;

    } else if (!(s->picture_structure & h->ref_list[1][0].f.reference) && !h->ref_list[1][0].mbaff) { // FL -> FL & differ parity

        h->col_fieldoff = 2 * h->ref_list[1][0].f.reference - 3;

    }

    if (cur->f.pict_type != AV_PICTURE_TYPE_B || h->direct_spatial_mv_pred)

        return;

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

        fill_colmap(h, h->map_col_to_list0, list, sidx, ref1sidx, 0);

        if(FRAME_MBAFF)

        for(field=0; field<2; field++)

            fill_colmap(h, h->map_col_to_list0_field[field], list, field, field, 1);

    }

}


static int make_ydt24_entry(int p1, int p2, int16_t *ydt)

{

    int lo, hi;

    lo = ydt[p1];

    hi = ydt[p2];

    return (lo + (hi << 8) + (hi << 16)) << 1;

}


static uint64_t fw_cfg_comb_read(void *opaque, hwaddr addr,

                                 unsigned size)

{

    return fw_cfg_read(opaque);

}


static int xan_decode_frame(AVCodecContext *avctx,
                            void *data, int *data_size,
                            AVPacket *avpkt)
{
    const uint8_t *buf = avpkt->data;
    int ret, buf_size = avpkt->size;
    XanContext *s = avctx->priv_data;
    if (avctx->codec->id == CODEC_ID_XAN_WC3) {
        const uint8_t *buf_end = buf + buf_size;
        int tag = 0;
        while (buf_end - buf > 8 && tag != VGA__TAG) {
            unsigned *tmpptr;
            uint32_t new_pal;
            int size;
            int i;
            tag  = bytestream_get_le32(&buf);
            size = bytestream_get_be32(&buf);
            size = FFMIN(size, buf_end - buf);
            switch (tag) {
            case PALT_TAG:
                if (size < PALETTE_SIZE)
                if (s->palettes_count >= PALETTES_MAX)
                tmpptr = av_realloc(s->palettes, (s->palettes_count + 1) * AVPALETTE_SIZE);
                if (!tmpptr)
                    return AVERROR(ENOMEM);
                s->palettes = tmpptr;
                tmpptr += s->palettes_count * AVPALETTE_COUNT;
                for (i = 0; i < PALETTE_COUNT; i++) {
#if RUNTIME_GAMMA
                    int r = gamma_corr(*buf++);
                    int g = gamma_corr(*buf++);
                    int b = gamma_corr(*buf++);
#else
                    int r = gamma_lookup[*buf++];
                    int g = gamma_lookup[*buf++];
                    int b = gamma_lookup[*buf++];
#endif
                    *tmpptr++ = (r << 16) | (g << 8) | b;
                }
                s->palettes_count++;
                break;
            case SHOT_TAG:
                if (size < 4)
                new_pal = bytestream_get_le32(&buf);
                if (new_pal < s->palettes_count) {
                    s->cur_palette = new_pal;
                } else
                    av_log(avctx, AV_LOG_ERROR, "Invalid palette selected\n");
                break;
            case VGA__TAG:
                break;
            default:
                buf += size;
                break;
            }
        }
        buf_size = buf_end - buf;
    }
    if ((ret = avctx->get_buffer(avctx, &s->current_frame))) {
        av_log(s->avctx, AV_LOG_ERROR, "get_buffer() failed\n");
        return ret;
    }
    s->current_frame.reference = 3;
    if (!s->frame_size)
        s->frame_size = s->current_frame.linesize[0] * s->avctx->height;
    memcpy(s->current_frame.data[1], s->palettes + s->cur_palette * AVPALETTE_COUNT, AVPALETTE_SIZE);
    s->buf = buf;
    s->size = buf_size;
    if (xan_wc3_decode_frame(s) < 0)
    /* release the last frame if it is allocated */
    if (s->last_frame.data[0])
        avctx->release_buffer(avctx, &s->last_frame);
    *data_size = sizeof(AVFrame);
    *(AVFrame*)data = s->current_frame;
    /* shuffle frames */
    FFSWAP(AVFrame, s->current_frame, s->last_frame);
    /* always report that the buffer was completely consumed */
    return buf_size;
}


void *grow_array(void *array, int elem_size, int *size, int new_size)

{

    if (new_size >= INT_MAX / elem_size) {

        av_log(NULL, AV_LOG_ERROR, "Array too big.\n");

        exit(1);

    }

    if (*size < new_size) {

        uint8_t *tmp = av_realloc(array, new_size*elem_size);

        if (!tmp) {

            av_log(NULL, AV_LOG_ERROR, "Could not alloc buffer.\n");

            exit(1);

        }

        memset(tmp + *size*elem_size, 0, (new_size-*size) * elem_size);

        *size = new_size;

        return tmp;

    }

    return array;

}


static int select_input_file(uint8_t *no_packet)

{

    int64_t ipts_min = INT64_MAX;

    int i, file_index = -1;

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

        InputStream *ist = input_streams[i];

        int64_t ipts     = ist->pts;

        if (ist->discard || no_packet[ist->file_index])

            continue;

        if (!input_files[ist->file_index]->eof_reached) {

            if (ipts < ipts_min) {

                ipts_min = ipts;

                file_index = ist->file_index;

            }

        }

    }

    return file_index;

}


static target_ulong get_psr(void)

{

    helper_compute_psr();

#if !defined (TARGET_SPARC64)

    return env->version | (env->psr & PSR_ICC) |

        (env->psref? PSR_EF : 0) |

        (env->psrpil << 8) |

        (env->psrs? PSR_S : 0) |

        (env->psrps? PSR_PS : 0) |

        (env->psret? PSR_ET : 0) | env->cwp;

#else

    return env->version | (env->psr & PSR_ICC) |

        (env->psref? PSR_EF : 0) |

        (env->psrpil << 8) |

        (env->psrs? PSR_S : 0) |

        (env->psrps? PSR_PS : 0) | env->cwp;

#endif

}


void qpci_iounmap(QPCIDevice *dev, void *data)

{

    /* FIXME */

}


int rom_add_file(const char *file, const char *fw_dir,
                 hwaddr addr, int32_t bootindex,
                 bool option_rom, MemoryRegion *mr)
{
    MachineClass *mc = MACHINE_GET_CLASS(qdev_get_machine());
    Rom *rom;
    int rc, fd = -1;
    char devpath[100];
    rom = g_malloc0(sizeof(*rom));
    rom->name = g_strdup(file);
    rom->path = qemu_find_file(QEMU_FILE_TYPE_BIOS, rom->name);
    if (rom->path == NULL) {
        rom->path = g_strdup(file);
    fd = open(rom->path, O_RDONLY | O_BINARY);
    if (fd == -1) {
        fprintf(stderr, "Could not open option rom '%s': %s\n",
                rom->path, strerror(errno));
        goto err;
        rom->fw_dir  = g_strdup(fw_dir);
        rom->fw_file = g_strdup(file);
    rom->addr     = addr;
    rom->romsize  = lseek(fd, 0, SEEK_END);
    if (rom->romsize == -1) {
        fprintf(stderr, "rom: file %-20s: get size error: %s\n",
                rom->name, strerror(errno));
        goto err;
    rom->datasize = rom->romsize;
    rom->data     = g_malloc0(rom->datasize);
    lseek(fd, 0, SEEK_SET);
    rc = read(fd, rom->data, rom->datasize);
    if (rc != rom->datasize) {
        fprintf(stderr, "rom: file %-20s: read error: rc=%d (expected %zd)\n",
                rom->name, rc, rom->datasize);
        goto err;
    close(fd);
    rom_insert(rom);
    if (rom->fw_file && fw_cfg) {
        const char *basename;
        char fw_file_name[FW_CFG_MAX_FILE_PATH];
        void *data;
        basename = strrchr(rom->fw_file, '/');
        if (basename) {
            basename++;
        } else {
            basename = rom->fw_file;
        snprintf(fw_file_name, sizeof(fw_file_name), "%s/%s", rom->fw_dir,
                 basename);
        snprintf(devpath, sizeof(devpath), "/rom@%s", fw_file_name);
        if ((!option_rom || mc->option_rom_has_mr) && mc->rom_file_has_mr) {
            data = rom_set_mr(rom, OBJECT(fw_cfg), devpath);
        } else {
            data = rom->data;
        fw_cfg_add_file(fw_cfg, fw_file_name, data, rom->romsize);
    } else {
        if (mr) {
            rom->mr = mr;
            snprintf(devpath, sizeof(devpath), "/rom@%s", file);
        } else {
            snprintf(devpath, sizeof(devpath), "/rom@" TARGET_FMT_plx, addr);
    add_boot_device_path(bootindex, NULL, devpath);
    return 0;
err:
    if (fd != -1)
        close(fd);
    g_free(rom->data);
    g_free(rom->path);
    g_free(rom->name);
    g_free(rom);
    return -1;


static inline int find_pte (CPUState *env, mmu_ctx_t *ctx, int h, int rw)

{

#if defined(TARGET_PPC64)

    if (env->mmu_model == POWERPC_MMU_64B ||

        env->mmu_model == POWERPC_MMU_64BRIDGE)

        return find_pte64(ctx, h, rw);

#endif

    return find_pte32(ctx, h, rw);

}


static void vfio_probe_nvidia_bar5_quirk(VFIOPCIDevice *vdev, int nr)

{

    VFIOQuirk *quirk;

    VFIONvidiaBAR5Quirk *bar5;

    VFIOConfigWindowQuirk *window;

    if (!vfio_pci_is(vdev, PCI_VENDOR_ID_NVIDIA, PCI_ANY_ID) ||

        !vdev->has_vga || nr != 5) {

        return;

    }

    quirk = g_malloc0(sizeof(*quirk));

    quirk->mem = g_malloc0(sizeof(MemoryRegion) * 4);

    quirk->nr_mem = 4;

    bar5 = quirk->data = g_malloc0(sizeof(*bar5) +

                                   (sizeof(VFIOConfigWindowMatch) * 2));

    window = &bar5->window;

    window->vdev = vdev;

    window->address_offset = 0x8;

    window->data_offset = 0xc;

    window->nr_matches = 2;

    window->matches[0].match = 0x1800;

    window->matches[0].mask = PCI_CONFIG_SPACE_SIZE - 1;

    window->matches[1].match = 0x88000;

    window->matches[1].mask = PCIE_CONFIG_SPACE_SIZE - 1;

    window->bar = nr;

    window->addr_mem = bar5->addr_mem = &quirk->mem[0];

    window->data_mem = bar5->data_mem = &quirk->mem[1];

    memory_region_init_io(window->addr_mem, OBJECT(vdev),

                          &vfio_generic_window_address_quirk, window,

                          "vfio-nvidia-bar5-window-address-quirk", 4);

    memory_region_add_subregion_overlap(&vdev->bars[nr].region.mem,

                                        window->address_offset,

                                        window->addr_mem, 1);

    memory_region_set_enabled(window->addr_mem, false);

    memory_region_init_io(window->data_mem, OBJECT(vdev),

                          &vfio_generic_window_data_quirk, window,

                          "vfio-nvidia-bar5-window-data-quirk", 4);

    memory_region_add_subregion_overlap(&vdev->bars[nr].region.mem,

                                        window->data_offset,

                                        window->data_mem, 1);

    memory_region_set_enabled(window->data_mem, false);

    memory_region_init_io(&quirk->mem[2], OBJECT(vdev),

                          &vfio_nvidia_bar5_quirk_master, bar5,

                          "vfio-nvidia-bar5-master-quirk", 4);

    memory_region_add_subregion_overlap(&vdev->bars[nr].region.mem,

                                        0, &quirk->mem[2], 1);

    memory_region_init_io(&quirk->mem[3], OBJECT(vdev),

                          &vfio_nvidia_bar5_quirk_enable, bar5,

                          "vfio-nvidia-bar5-enable-quirk", 4);

    memory_region_add_subregion_overlap(&vdev->bars[nr].region.mem,

                                        4, &quirk->mem[3], 1);

    QLIST_INSERT_HEAD(&vdev->bars[nr].quirks, quirk, next);

    trace_vfio_quirk_nvidia_bar5_probe(vdev->vbasedev.name);

}


static PXA2xxI2SState *pxa2xx_i2s_init(MemoryRegion *sysmem,

                hwaddr base,

                qemu_irq irq, qemu_irq rx_dma, qemu_irq tx_dma)

{

    PXA2xxI2SState *s = (PXA2xxI2SState *)

            g_malloc0(sizeof(PXA2xxI2SState));

    s->irq = irq;

    s->rx_dma = rx_dma;

    s->tx_dma = tx_dma;

    s->data_req = pxa2xx_i2s_data_req;

    pxa2xx_i2s_reset(s);

    memory_region_init_io(&s->iomem, NULL, &pxa2xx_i2s_ops, s,

                          "pxa2xx-i2s", 0x100000);

    memory_region_add_subregion(sysmem, base, &s->iomem);

    vmstate_register(NULL, base, &vmstate_pxa2xx_i2s, s);

    return s;

}


static void unimp_class_init(ObjectClass *klass, void *data)

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    dc->realize = unimp_realize;

    dc->props = unimp_properties;

}


int ff_get_qtpalette(int codec_id, AVIOContext *pb, uint32_t *palette)

{

    int tmp, bit_depth, color_table_id, greyscale, i;

    avio_seek(pb, 82, SEEK_CUR);

    /* Get the bit depth and greyscale state */

    tmp = avio_rb16(pb);

    bit_depth = tmp & 0x1F;

    greyscale = tmp & 0x20;

    /* Get the color table ID */

    color_table_id = avio_rb16(pb);

    /* Do not create a greyscale palette for Cinepak */

    if (greyscale && codec_id == AV_CODEC_ID_CINEPAK)

        return 0;

    /* If the depth is 1, 2, 4, or 8 bpp, file is palettized. */

    if ((bit_depth == 1 || bit_depth == 2 || bit_depth == 4 || bit_depth == 8)) {

        int color_count, color_start, color_end;

        uint32_t a, r, g, b;

        /* Ignore the greyscale bit for 1-bit video and sample

         * descriptions containing a color table. */

        if (greyscale && bit_depth > 1 && color_table_id) {

            int color_index, color_dec;

            /* compute the greyscale palette */

            color_count = 1 << bit_depth;

            color_index = 255;

            color_dec   = 256 / (color_count - 1);

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

                r = g = b = color_index;

                palette[i] = (0xFFU << 24) | (r << 16) | (g << 8) | (b);

                color_index -= color_dec;

                if (color_index < 0)

                    color_index = 0;

            }

        } else if (color_table_id) {

            /* The color table ID is non-zero. Interpret this as

             * being -1, which means use the default Macintosh

             * color table */

            const uint8_t *color_table;

            color_count = 1 << bit_depth;

            if (bit_depth == 1)

                color_table = ff_qt_default_palette_2;

            else if (bit_depth == 2)

                color_table = ff_qt_default_palette_4;

            else if (bit_depth == 4)

                color_table = ff_qt_default_palette_16;

            else

                color_table = ff_qt_default_palette_256;

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

                r = color_table[i * 3 + 0];

                g = color_table[i * 3 + 1];

                b = color_table[i * 3 + 2];

                palette[i] = (0xFFU << 24) | (r << 16) | (g << 8) | (b);

            }

        } else {

            /* The color table ID is 0; the color table is in the sample

             * description */

            color_start = avio_rb32(pb);

            avio_rb16(pb); /* color table flags */

            color_end = avio_rb16(pb);

            if ((color_start <= 255) && (color_end <= 255)) {

                for (i = color_start; i <= color_end; i++) {

                    /* each A, R, G, or B component is 16 bits;

                     * only use the top 8 bits */

                    a = avio_r8(pb);

                    avio_r8(pb);

                    r = avio_r8(pb);

                    avio_r8(pb);

                    g = avio_r8(pb);

                    avio_r8(pb);

                    b = avio_r8(pb);

                    avio_r8(pb);

                    palette[i] = (a << 24 ) | (r << 16) | (g << 8) | (b);

                }

            }

        }

        return 1;

    }

    return 0;

}


AVCodecParserContext *av_parser_init(int codec_id)

{

    AVCodecParserContext *s = NULL;

    AVCodecParser *parser;

    int ret;

    if(codec_id == AV_CODEC_ID_NONE)

        return NULL;

    for(parser = av_first_parser; parser != NULL; parser = parser->next) {

        if (parser->codec_ids[0] == codec_id ||

            parser->codec_ids[1] == codec_id ||

            parser->codec_ids[2] == codec_id ||

            parser->codec_ids[3] == codec_id ||

            parser->codec_ids[4] == codec_id)

            goto found;

    }

    return NULL;

 found:

    s = av_mallocz(sizeof(AVCodecParserContext));

    if (!s)

        goto err_out;

    s->parser = parser;

    s->priv_data = av_mallocz(parser->priv_data_size);

    if (!s->priv_data)

        goto err_out;

    s->fetch_timestamp=1;

    s->pict_type = AV_PICTURE_TYPE_I;

    if (parser->parser_init) {

        if (ff_lock_avcodec(NULL) < 0)

            goto err_out;

        ret = parser->parser_init(s);

        ff_unlock_avcodec();

        if (ret != 0)

            goto err_out;

    }

    s->key_frame = -1;

    s->convergence_duration = 0;

    s->dts_sync_point       = INT_MIN;

    s->dts_ref_dts_delta    = INT_MIN;

    s->pts_dts_delta        = INT_MIN;

    return s;

err_out:

    if (s)

        av_freep(&s->priv_data);

    av_free(s);

    return NULL;

}


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

                              int *got_frame_ptr, AVPacket *avpkt)

{

    AVFrame *frame     = data;

    const uint8_t *buf = avpkt->data;

    int buf_size = avpkt->size;

    float *out;

    int i, ret;

    RA288Context *ractx = avctx->priv_data;

    GetBitContext gb;

    if (buf_size < avctx->block_align) {

        av_log(avctx, AV_LOG_ERROR,

               "Error! Input buffer is too small [%d<%d]\n",

               buf_size, avctx->block_align);

        return AVERROR_INVALIDDATA;

    }

    /* get output buffer */

    frame->nb_samples = RA288_BLOCK_SIZE * RA288_BLOCKS_PER_FRAME;

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

        return ret;

    out = (float *)frame->data[0];

    init_get_bits8(&gb, buf, avctx->block_align);

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

        float gain = amptable[get_bits(&gb, 3)];

        int cb_coef = get_bits(&gb, 6 + (i&1));

        decode(ractx, gain, cb_coef);

        memcpy(out, &ractx->sp_hist[70 + 36], RA288_BLOCK_SIZE * sizeof(*out));

        out += RA288_BLOCK_SIZE;

        if ((i & 7) == 3) {

            backward_filter(ractx, ractx->sp_hist, ractx->sp_rec, syn_window,

                            ractx->sp_lpc, syn_bw_tab, 36, 40, 35, 70);

            backward_filter(ractx, ractx->gain_hist, ractx->gain_rec, gain_window,

                            ractx->gain_lpc, gain_bw_tab, 10, 8, 20, 28);

        }

    }

    *got_frame_ptr = 1;

    return avctx->block_align;

}


int avcodec_check_dimensions(void *av_log_ctx, unsigned int w, unsigned int h){

    if((int)w>0 && (int)h>0 && (w+128)*(uint64_t)(h+128) < INT_MAX/4)

        return 0;

    av_log(av_log_ctx, AV_LOG_ERROR, "picture size invalid (%ux%u)\n", w, h);

    return -1;

}


static int find_unused_picture(MpegEncContext *s, int shared)

{

    int i;

    if (shared) {

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

            if (s->picture[i].f.data[0] == NULL)

                return i;

        }

    } else {

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

            if (pic_is_unused(s, &s->picture[i]))

                return i;

        }

    }

    return AVERROR_INVALIDDATA;

}


static int av_always_inline mlp_thd_probe(AVProbeData *p, uint32_t sync)

{

    const uint8_t *buf, *last_buf = p->buf, *end = p->buf + p->buf_size;

    int frames = 0, valid = 0, size = 0;

    for (buf = p->buf; buf + 8 <= end; buf++) {

        if (AV_RB32(buf + 4) == sync) {

            frames++;

            if (last_buf + size == buf) {

                valid++;

            }

            last_buf = buf;

            size = (AV_RB16(buf) & 0xfff) * 2;

        } else if (buf - last_buf == size) {

            size += (AV_RB16(buf) & 0xfff) * 2;

        }

    }

    if (valid >= 100)

        return AVPROBE_SCORE_MAX;

    return 0;

}


void gic_complete_irq(GICState *s, int cpu, int irq)

{

    int update = 0;

    int cm = 1 << cpu;

    DPRINTF("EOI %d\n", irq);

    if (irq >= s->num_irq) {

        /* This handles two cases:

         * 1. If software writes the ID of a spurious interrupt [ie 1023]

         * to the GICC_EOIR, the GIC ignores that write.

         * 2. If software writes the number of a non-existent interrupt

         * this must be a subcase of "value written does not match the last

         * valid interrupt value read from the Interrupt Acknowledge

         * register" and so this is UNPREDICTABLE. We choose to ignore it.

         */

        return;

    }

    if (s->running_irq[cpu] == 1023)

        return; /* No active IRQ.  */

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

        /* Mark level triggered interrupts as pending if they are still

           raised.  */

        if (!GIC_TEST_EDGE_TRIGGER(irq) && GIC_TEST_ENABLED(irq, cm)

            && GIC_TEST_LEVEL(irq, cm) && (GIC_TARGET(irq) & cm) != 0) {

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

            GIC_SET_PENDING(irq, cm);

            update = 1;

        }

    }

    if (irq != s->running_irq[cpu]) {

        /* Complete an IRQ that is not currently running.  */

        int tmp = s->running_irq[cpu];

        while (s->last_active[tmp][cpu] != 1023) {

            if (s->last_active[tmp][cpu] == irq) {

                s->last_active[tmp][cpu] = s->last_active[irq][cpu];

                break;

            }

            tmp = s->last_active[tmp][cpu];

        }

        if (update) {

            gic_update(s);

        }

    } else {

        /* Complete the current running IRQ.  */

        gic_set_running_irq(s, cpu, s->last_active[s->running_irq[cpu]][cpu]);

    }

}


static void core_commit(MemoryListener *listener)

{

    PhysPageMap info = cur_map;

    cur_map = next_map;

    phys_sections_clear(&info);

}


static int ppc_hash32_pte_update_flags(struct mmu_ctx_hash32 *ctx, target_ulong *pte1p,

                                       int ret, int rwx)

{

    int store = 0;

    /* Update page flags */

    if (!(*pte1p & HPTE32_R_R)) {

        /* Update accessed flag */

        *pte1p |= HPTE32_R_R;

        store = 1;

    }

    if (!(*pte1p & HPTE32_R_C)) {

        if (rwx == 1 && ret == 0) {

            /* Update changed flag */

            *pte1p |= HPTE32_R_C;

            store = 1;

        } else {

            /* Force page fault for first write access */

            ctx->prot &= ~PAGE_WRITE;

        }

    }

    return store;

}


static int raw_eject(BlockDriverState *bs, int eject_flag)

{

    BDRVRawState *s = bs->opaque;

    switch(s->type) {

    case FTYPE_CD:

        if (eject_flag) {

            if (ioctl (s->fd, CDROMEJECT, NULL) < 0)

                perror("CDROMEJECT");

        } else {

            if (ioctl (s->fd, CDROMCLOSETRAY, NULL) < 0)

                perror("CDROMEJECT");

        }

        break;

    case FTYPE_FD:

        {

            int fd;

            if (s->fd >= 0) {

                close(s->fd);

                s->fd = -1;

                raw_close_fd_pool(s);

            }

            fd = open(bs->filename, s->fd_open_flags | O_NONBLOCK);

            if (fd >= 0) {

                if (ioctl(fd, FDEJECT, 0) < 0)

                    perror("FDEJECT");

                close(fd);

            }

        }

        break;

    default:

        return -ENOTSUP;

    }

    return 0;

}


static void usage(void)

{

    const struct qemu_argument *arginfo;

    int maxarglen;

    int maxenvlen;

    printf("usage: qemu-" TARGET_ARCH " [options] program [arguments...]\n"

           "Linux CPU emulator (compiled for " TARGET_ARCH " emulation)\n"

           "\n"

           "Options and associated environment variables:\n"

           "\n");

    maxarglen = maxenvlen = 0;

    for (arginfo = arg_table; arginfo->handle_opt != NULL; arginfo++) {

        if (strlen(arginfo->env) > maxenvlen) {

            maxenvlen = strlen(arginfo->env);

        }

        if (strlen(arginfo->argv) > maxarglen) {

            maxarglen = strlen(arginfo->argv);

        }

    }

    printf("%-*s%-*sDescription\n", maxarglen+3, "Argument",

            maxenvlen+1, "Env-variable");

    for (arginfo = arg_table; arginfo->handle_opt != NULL; arginfo++) {

        if (arginfo->has_arg) {

            printf("-%s %-*s %-*s %s\n", arginfo->argv,

                    (int)(maxarglen-strlen(arginfo->argv)), arginfo->example,

                    maxenvlen, arginfo->env, arginfo->help);

        } else {

            printf("-%-*s %-*s %s\n", maxarglen+1, arginfo->argv,

                    maxenvlen, arginfo->env,

                    arginfo->help);

        }

    }

    printf("\n"

           "Defaults:\n"

           "QEMU_LD_PREFIX  = %s\n"

           "QEMU_STACK_SIZE = %ld byte\n",

           interp_prefix,

           guest_stack_size);

    printf("\n"

           "You can use -E and -U options or the QEMU_SET_ENV and\n"

           "QEMU_UNSET_ENV environment variables to set and unset\n"

           "environment variables for the target process.\n"

           "It is possible to provide several variables by separating them\n"

           "by commas in getsubopt(3) style. Additionally it is possible to\n"

           "provide the -E and -U options multiple times.\n"

           "The following lines are equivalent:\n"

           "    -E var1=val2 -E var2=val2 -U LD_PRELOAD -U LD_DEBUG\n"

           "    -E var1=val2,var2=val2 -U LD_PRELOAD,LD_DEBUG\n"

           "    QEMU_SET_ENV=var1=val2,var2=val2 QEMU_UNSET_ENV=LD_PRELOAD,LD_DEBUG\n"

           "Note that if you provide several changes to a single variable\n"

           "the last change will stay in effect.\n");

    exit(1);

}


static void qemu_rbd_complete_aio(RADOSCB *rcb)

{

    RBDAIOCB *acb = rcb->acb;

    int64_t r;

    r = rcb->ret;

    if (acb->cmd == RBD_AIO_WRITE ||

        acb->cmd == RBD_AIO_DISCARD) {

        if (r < 0) {

            acb->ret = r;

            acb->error = 1;

        } else if (!acb->error) {

            acb->ret = rcb->size;

        }

    } else {

        if (r < 0) {

            memset(rcb->buf, 0, rcb->size);

            acb->ret = r;

            acb->error = 1;

        } else if (r < rcb->size) {

            memset(rcb->buf + r, 0, rcb->size - r);

            if (!acb->error) {

                acb->ret = rcb->size;

            }

        } else if (!acb->error) {

            acb->ret = r;

        }

    }

    /* Note that acb->bh can be NULL in case where the aio was cancelled */

    acb->bh = qemu_bh_new(rbd_aio_bh_cb, acb);

    qemu_bh_schedule(acb->bh);

    g_free(rcb);

}


static gboolean gd_window_key_event(GtkWidget *widget, GdkEventKey *key, void *opaque)

{

    GtkDisplayState *s = opaque;

    GtkAccelGroupEntry *entries;

    guint n_entries = 0;

    gboolean propagate_accel = TRUE;

    gboolean handled = FALSE;

    entries = gtk_accel_group_query(s->accel_group, key->keyval,

                                    key->state, &n_entries);

    if (n_entries) {

        const char *quark = g_quark_to_string(entries[0].accel_path_quark);

        if (gd_is_grab_active(s) && strstart(quark, "<QEMU>/File/", NULL)) {

            propagate_accel = FALSE;

        }

    }

    if (!handled && propagate_accel) {

        handled = gtk_window_activate_key(GTK_WINDOW(widget), key);

    }

    if (handled) {

        gtk_release_modifiers(s);

    } else {

        handled = gtk_window_propagate_key_event(GTK_WINDOW(widget), key);

    }

    return handled;

}


static av_always_inline void hl_decode_mb_predict_luma(H264Context *h,

                                                       int mb_type, int is_h264,

                                                       int simple,

                                                       int transform_bypass,

                                                       int pixel_shift,

                                                       int *block_offset,

                                                       int linesize,

                                                       uint8_t *dest_y, int p)

{

    void (*idct_add)(uint8_t *dst, int16_t *block, int stride);

    void (*idct_dc_add)(uint8_t *dst, int16_t *block, int stride);

    int i;

    int qscale = p == 0 ? h->qscale : h->chroma_qp[p - 1];

    block_offset += 16 * p;

    if (IS_INTRA4x4(mb_type)) {

        if (IS_8x8DCT(mb_type)) {

            if (transform_bypass) {

                idct_dc_add =

                idct_add    = h->h264dsp.h264_add_pixels8_clear;

            } else {

                idct_dc_add = h->h264dsp.h264_idct8_dc_add;

                idct_add    = h->h264dsp.h264_idct8_add;

            }

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

                uint8_t *const ptr = dest_y + block_offset[i];

                const int dir      = h->intra4x4_pred_mode_cache[scan8[i]];

                if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {

                    h->hpc.pred8x8l_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);

                } else {

                    const int nnz = h->non_zero_count_cache[scan8[i + p * 16]];

                    h->hpc.pred8x8l[dir](ptr, (h->topleft_samples_available << i) & 0x8000,

                                         (h->topright_samples_available << i) & 0x4000, linesize);

                    if (nnz) {

                        if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))

                            idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);

                        else

                            idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);

                    }

                }

            }

        } else {

            if (transform_bypass) {

                idct_dc_add  =

                idct_add     = h->h264dsp.h264_add_pixels4_clear;

            } else {

                idct_dc_add = h->h264dsp.h264_idct_dc_add;

                idct_add    = h->h264dsp.h264_idct_add;

            }

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

                uint8_t *const ptr = dest_y + block_offset[i];

                const int dir      = h->intra4x4_pred_mode_cache[scan8[i]];

                if (transform_bypass && h->sps.profile_idc == 244 && dir <= 1) {

                    h->hpc.pred4x4_add[dir](ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);

                } else {

                    uint8_t *topright;

                    int nnz, tr;

                    uint64_t tr_high;

                    if (dir == DIAG_DOWN_LEFT_PRED || dir == VERT_LEFT_PRED) {

                        const int topright_avail = (h->topright_samples_available << i) & 0x8000;

                        av_assert2(h->mb_y || linesize <= block_offset[i]);

                        if (!topright_avail) {

                            if (pixel_shift) {

                                tr_high  = ((uint16_t *)ptr)[3 - linesize / 2] * 0x0001000100010001ULL;

                                topright = (uint8_t *)&tr_high;

                            } else {

                                tr       = ptr[3 - linesize] * 0x01010101u;

                                topright = (uint8_t *)&tr;

                            }

                        } else

                            topright = ptr + (4 << pixel_shift) - linesize;

                    } else

                        topright = NULL;

                    h->hpc.pred4x4[dir](ptr, topright, linesize);

                    nnz = h->non_zero_count_cache[scan8[i + p * 16]];

                    if (nnz) {

                        if (is_h264) {

                            if (nnz == 1 && dctcoef_get(h->mb, pixel_shift, i * 16 + p * 256))

                                idct_dc_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);

                            else

                                idct_add(ptr, h->mb + (i * 16 + p * 256 << pixel_shift), linesize);

                        } else if (CONFIG_SVQ3_DECODER)

                            ff_svq3_add_idct_c(ptr, h->mb + i * 16 + p * 256, linesize, qscale, 0);

                    }

                }

            }

        }

    } else {

        h->hpc.pred16x16[h->intra16x16_pred_mode](dest_y, linesize);

        if (is_h264) {

            if (h->non_zero_count_cache[scan8[LUMA_DC_BLOCK_INDEX + p]]) {

                if (!transform_bypass)

                    h->h264dsp.h264_luma_dc_dequant_idct(h->mb + (p * 256 << pixel_shift),

                                                         h->mb_luma_dc[p],

                                                         h->dequant4_coeff[p][qscale][0]);

                else {

                    static const uint8_t dc_mapping[16] = {

                         0 * 16,  1 * 16,  4 * 16,  5 * 16,

                         2 * 16,  3 * 16,  6 * 16,  7 * 16,

                         8 * 16,  9 * 16, 12 * 16, 13 * 16,

                        10 * 16, 11 * 16, 14 * 16, 15 * 16

                    };

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

                        dctcoef_set(h->mb + (p * 256 << pixel_shift),

                                    pixel_shift, dc_mapping[i],

                                    dctcoef_get(h->mb_luma_dc[p],

                                                pixel_shift, i));

                }

            }

        } else if (CONFIG_SVQ3_DECODER)

            ff_svq3_luma_dc_dequant_idct_c(h->mb + p * 256,

                                           h->mb_luma_dc[p], qscale);

    }

}


static void mcf_fec_do_tx(mcf_fec_state *s)

{

    uint32_t addr;

    mcf_fec_bd bd;

    int frame_size;

    int len;

    uint8_t frame[FEC_MAX_FRAME_SIZE];

    uint8_t *ptr;

    DPRINTF("do_tx\n");

    ptr = frame;

    frame_size = 0;

    addr = s->tx_descriptor;

    while (1) {

        mcf_fec_read_bd(&bd, addr);

        DPRINTF("tx_bd %x flags %04x len %d data %08x\n",

                addr, bd.flags, bd.length, bd.data);

        if ((bd.flags & FEC_BD_R) == 0) {

            /* Run out of descriptors to transmit.  */

            break;

        }

        len = bd.length;

        if (frame_size + len > FEC_MAX_FRAME_SIZE) {

            len = FEC_MAX_FRAME_SIZE - frame_size;

            s->eir |= FEC_INT_BABT;

        }

        cpu_physical_memory_read(bd.data, ptr, len);

        ptr += len;

        frame_size += len;

        if (bd.flags & FEC_BD_L) {

            /* Last buffer in frame.  */

            DPRINTF("Sending packet\n");

            qemu_send_packet(qemu_get_queue(s->nic), frame, len);

            ptr = frame;

            frame_size = 0;

            s->eir |= FEC_INT_TXF;

        }

        s->eir |= FEC_INT_TXB;

        bd.flags &= ~FEC_BD_R;

        /* Write back the modified descriptor.  */

        mcf_fec_write_bd(&bd, addr);

        /* Advance to the next descriptor.  */

        if ((bd.flags & FEC_BD_W) != 0) {

            addr = s->etdsr;

        } else {

            addr += 8;

        }

    }

    s->tx_descriptor = addr;

}


static void bonito_spciconf_writel(void *opaque, target_phys_addr_t addr,

                                   uint32_t val)

{

    PCIBonitoState *s = opaque;

    uint32_t pciaddr;

    uint16_t status;

    DPRINTF("bonito_spciconf_writel "TARGET_FMT_plx" val %x \n", addr, val);

    assert((addr&0x3)==0);

    pciaddr = bonito_sbridge_pciaddr(s, addr);

    if (pciaddr == 0xffffffff) {

        return;

    }

    /* set the pci address in s->config_reg */

    s->pcihost->config_reg = (pciaddr) | (1u << 31);

    pci_data_write(s->pcihost->bus, s->pcihost->config_reg, val, 4);

    /* clear PCI_STATUS_REC_MASTER_ABORT and PCI_STATUS_REC_TARGET_ABORT */

    status = pci_get_word(s->dev.config + PCI_STATUS);

    status &= ~(PCI_STATUS_REC_MASTER_ABORT | PCI_STATUS_REC_TARGET_ABORT);

    pci_set_word(s->dev.config + PCI_STATUS, status);

}


void ide_init2_with_non_qdev_drives(IDEBus *bus, DriveInfo *hd0,

                                    DriveInfo *hd1, qemu_irq irq)

{

    int i;

    DriveInfo *dinfo;

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

        dinfo = i == 0 ? hd0 : hd1;

        ide_init1(bus, i);

        if (dinfo) {

            if (ide_init_drive(&bus->ifs[i], dinfo->bdrv,

                               dinfo->media_cd ? IDE_CD : IDE_HD, NULL,

                               *dinfo->serial ? dinfo->serial : NULL) < 0) {

                error_report("Can't set up IDE drive %s", dinfo->id);

                exit(1);

            }

            bdrv_attach_dev_nofail(dinfo->bdrv, &bus->ifs[i]);

        } else {

            ide_reset(&bus->ifs[i]);

        }

    }

    bus->irq = irq;

    bus->dma = &ide_dma_nop;

}


static void pxa2xx_ssp_write(void *opaque, hwaddr addr,

                             uint64_t value64, unsigned size)

{

    PXA2xxSSPState *s = (PXA2xxSSPState *) opaque;

    uint32_t value = value64;

    switch (addr) {

    case SSCR0:

        s->sscr[0] = value & 0xc7ffffff;

        s->enable = value & SSCR0_SSE;

        if (value & SSCR0_MOD)

            printf("%s: Attempt to use network mode\n", __FUNCTION__);

        if (s->enable && SSCR0_DSS(value) < 4)

            printf("%s: Wrong data size: %i bits\n", __FUNCTION__,

                            SSCR0_DSS(value));

        if (!(value & SSCR0_SSE)) {

            s->sssr = 0;

            s->ssitr = 0;

            s->rx_level = 0;

        }

        pxa2xx_ssp_fifo_update(s);

        break;

    case SSCR1:

        s->sscr[1] = value;

        if (value & (SSCR1_LBM | SSCR1_EFWR))

            printf("%s: Attempt to use SSP test mode\n", __FUNCTION__);

        pxa2xx_ssp_fifo_update(s);

        break;

    case SSPSP:

        s->sspsp = value;

        break;

    case SSTO:

        s->ssto = value;

        break;

    case SSITR:

        s->ssitr = value & SSITR_INT;

        pxa2xx_ssp_int_update(s);

        break;

    case SSSR:

        s->sssr &= ~(value & SSSR_RW);

        pxa2xx_ssp_int_update(s);

        break;

    case SSDR:

        if (SSCR0_UWIRE(s->sscr[0])) {

            if (s->sscr[1] & SSCR1_MWDS)

                value &= 0xffff;

            else

                value &= 0xff;

        } else

            /* Note how 32bits overflow does no harm here */

            value &= (1 << SSCR0_DSS(s->sscr[0])) - 1;

        /* Data goes from here to the Tx FIFO and is shifted out from

         * there directly to the slave, no need to buffer it.

         */

        if (s->enable) {

            uint32_t readval;

            readval = ssi_transfer(s->bus, value);

            if (s->rx_level < 0x10) {

                s->rx_fifo[(s->rx_start + s->rx_level ++) & 0xf] = readval;

            } else {

                s->sssr |= SSSR_ROR;

            }

        }

        pxa2xx_ssp_fifo_update(s);

        break;

    case SSTSA:

        s->sstsa = value;

        break;

    case SSRSA:

        s->ssrsa = value;

        break;

    case SSACD:

        s->ssacd = value;

        break;

    default:

        printf("%s: Bad register " REG_FMT "\n", __FUNCTION__, addr);

        break;

    }

}


static int pci_ne2000_init(PCIDevice *pci_dev)

{

    PCINE2000State *d = DO_UPCAST(PCINE2000State, dev, pci_dev);

    NE2000State *s;

    uint8_t *pci_conf;

    pci_conf = d->dev.config;

    pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_REALTEK);

    pci_config_set_device_id(pci_conf, PCI_DEVICE_ID_REALTEK_8029);

    pci_config_set_class(pci_conf, PCI_CLASS_NETWORK_ETHERNET);

    /* TODO: RST# value should be 0. PCI spec 6.2.4 */

    pci_conf[PCI_INTERRUPT_PIN] = 1; // interrupt pin 0

    pci_register_bar(&d->dev, 0, 0x100,

                           PCI_BASE_ADDRESS_SPACE_IO, ne2000_map);

    s = &d->ne2000;

    s->irq = d->dev.irq[0];

    qemu_macaddr_default_if_unset(&s->c.macaddr);

    ne2000_reset(s);

    s->nic = qemu_new_nic(&net_ne2000_info, &s->c,

                          pci_dev->qdev.info->name, pci_dev->qdev.id, s);

    qemu_format_nic_info_str(&s->nic->nc, s->c.macaddr.a);

    if (!pci_dev->qdev.hotplugged) {

        static int loaded = 0;

        if (!loaded) {

            rom_add_option("pxe-ne2k_pci.rom", -1);

            loaded = 1;

        }

    }

    add_boot_device_path(s->c.bootindex, &pci_dev->qdev, "/ethernet-phy@0");

    return 0;

}


static void inc_refcounts(BlockDriverState *bs,

                          uint16_t *refcount_table,

                          int refcount_table_size,

                          int64_t offset, int64_t size)

{

    BDRVQcowState *s = bs->opaque;

    int64_t start, last, cluster_offset;

    int k;

    if (size <= 0)

        return;

    start = offset & ~(s->cluster_size - 1);

    last = (offset + size - 1) & ~(s->cluster_size - 1);

    for(cluster_offset = start; cluster_offset <= last;

        cluster_offset += s->cluster_size) {

        k = cluster_offset >> s->cluster_bits;

        if (k < 0 || k >= refcount_table_size) {

            fprintf(stderr, "ERROR: invalid cluster offset=0x%" PRIx64 "\n",

                cluster_offset);

        } else {

            if (++refcount_table[k] == 0) {

                fprintf(stderr, "ERROR: overflow cluster offset=0x%" PRIx64

                    "\n", cluster_offset);

            }

        }

    }

}


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

                            target_ulong pte1, int h, int rw, int type)

{

    target_ulong mmask;

    int access, ret, pp;

    ret = -1;

    /* Check validity and table match */

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

        /* Check vsid & api */

        mmask = PTE_CHECK_MASK;

        pp = pte1 & HPTE32_R_PP;

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

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

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

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

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

                    return -3;

                }

            }

            /* Compute access rights */

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

            /* Keep the matching PTE informations */

            ctx->raddr = pte1;

            ctx->prot = access;

            ret = ppc_hash32_check_prot(ctx->prot, rw, type);

            if (ret == 0) {

                /* Access granted */

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

            } else {

                /* Access right violation */

                LOG_MMU("PTE access rejected\n");

            }

        }

    }

    return ret;

}


static int aio_read_f(int argc, char **argv)

{

    int nr_iov, c;

    struct aio_ctx *ctx = calloc(1, sizeof(struct aio_ctx));

    while ((c = getopt(argc, argv, "CP:qv")) != EOF) {

        switch (c) {

        case 'C':

            ctx->Cflag = 1;

            break;

        case 'P':

            ctx->Pflag = 1;

            ctx->pattern = parse_pattern(optarg);

            if (ctx->pattern < 0) {

                free(ctx);

                return 0;

            }

            break;

        case 'q':

            ctx->qflag = 1;

            break;

        case 'v':

            ctx->vflag = 1;

            break;

        default:

            free(ctx);

            return command_usage(&aio_read_cmd);

        }

    }

    if (optind > argc - 2) {

        free(ctx);

        return command_usage(&aio_read_cmd);

    }

    ctx->offset = cvtnum(argv[optind]);

    if (ctx->offset < 0) {

        printf("non-numeric length argument -- %s\n", argv[optind]);

        free(ctx);

        return 0;

    }

    optind++;

    if (ctx->offset & 0x1ff) {

        printf("offset %" PRId64 " is not sector aligned\n",

               ctx->offset);

        free(ctx);

        return 0;

    }

    nr_iov = argc - optind;

    ctx->buf = create_iovec(&ctx->qiov, &argv[optind], nr_iov, 0xab);

    if (ctx->buf == NULL) {

        free(ctx);

        return 0;

    }

    gettimeofday(&ctx->t1, NULL);

    bdrv_aio_readv(bs, ctx->offset >> 9, &ctx->qiov,

                   ctx->qiov.size >> 9, aio_read_done, ctx);

    return 0;

}


static void scsi_free_request(SCSIRequest *req)

{

    SCSIDiskReq *r = DO_UPCAST(SCSIDiskReq, req, req);

    qemu_vfree(r->iov.iov_base);

}


void ff_mjpeg_encode_picture_header(AVCodecContext *avctx, PutBitContext *pb,

                                    ScanTable *intra_scantable,

                                    uint16_t intra_matrix[64])

{

    int chroma_h_shift, chroma_v_shift;

    const int lossless = avctx->codec_id != AV_CODEC_ID_MJPEG;

    int hsample[3], vsample[3];

    av_pix_fmt_get_chroma_sub_sample(avctx->pix_fmt, &chroma_h_shift,

                                     &chroma_v_shift);

    if (avctx->codec->id == AV_CODEC_ID_LJPEG &&

        avctx->pix_fmt   == AV_PIX_FMT_BGR24) {

        vsample[0] = hsample[0] =

        vsample[1] = hsample[1] =

        vsample[2] = hsample[2] = 1;

    } else {

        vsample[0] = 2;

        vsample[1] = 2 >> chroma_v_shift;

        vsample[2] = 2 >> chroma_v_shift;

        hsample[0] = 2;

        hsample[1] = 2 >> chroma_h_shift;

        hsample[2] = 2 >> chroma_h_shift;

    }

    put_marker(pb, SOI);

    jpeg_put_comments(avctx, pb);

    jpeg_table_header(pb, intra_scantable, intra_matrix);

    switch (avctx->codec_id) {

    case AV_CODEC_ID_MJPEG:  put_marker(pb, SOF0 ); break;

    case AV_CODEC_ID_LJPEG:  put_marker(pb, SOF3 ); break;

    default: assert(0);

    }

    put_bits(pb, 16, 17);

    if (lossless && avctx->pix_fmt == AV_PIX_FMT_BGR24)

        put_bits(pb, 8, 9); /* 9 bits/component RCT */

    else

        put_bits(pb, 8, 8); /* 8 bits/component */

    put_bits(pb, 16, avctx->height);

    put_bits(pb, 16, avctx->width);

    put_bits(pb, 8, 3); /* 3 components */

    /* Y component */

    put_bits(pb, 8, 1); /* component number */

    put_bits(pb, 4, hsample[0]); /* H factor */

    put_bits(pb, 4, vsample[0]); /* V factor */

    put_bits(pb, 8, 0); /* select matrix */

    /* Cb component */

    put_bits(pb, 8, 2); /* component number */

    put_bits(pb, 4, hsample[1]); /* H factor */

    put_bits(pb, 4, vsample[1]); /* V factor */

    put_bits(pb, 8, 0); /* select matrix */

    /* Cr component */

    put_bits(pb, 8, 3); /* component number */

    put_bits(pb, 4, hsample[2]); /* H factor */

    put_bits(pb, 4, vsample[2]); /* V factor */

    put_bits(pb, 8, 0); /* select matrix */

    /* scan header */

    put_marker(pb, SOS);

    put_bits(pb, 16, 12); /* length */

    put_bits(pb, 8, 3); /* 3 components */

    /* Y component */

    put_bits(pb, 8, 1); /* index */

    put_bits(pb, 4, 0); /* DC huffman table index */

    put_bits(pb, 4, 0); /* AC huffman table index */

    /* Cb component */

    put_bits(pb, 8, 2); /* index */

    put_bits(pb, 4, 1); /* DC huffman table index */

    put_bits(pb, 4, lossless ? 0 : 1); /* AC huffman table index */

    /* Cr component */

    put_bits(pb, 8, 3); /* index */

    put_bits(pb, 4, 1); /* DC huffman table index */

    put_bits(pb, 4, lossless ? 0 : 1); /* AC huffman table index */

    put_bits(pb, 8, lossless ? avctx->prediction_method + 1 : 0); /* Ss (not used) */

    switch (avctx->codec_id) {

    case AV_CODEC_ID_MJPEG:  put_bits(pb, 8, 63); break; /* Se (not used) */

    case AV_CODEC_ID_LJPEG:  put_bits(pb, 8,  0); break; /* not used */

    default: assert(0);

    }

    put_bits(pb, 8, 0); /* Ah/Al (not used) */

}


int qemu_paio_error(struct qemu_paiocb *aiocb)

{

    ssize_t ret = qemu_paio_return(aiocb);

    if (ret < 0)

        ret = -ret;

    else

        ret = 0;

    return ret;

}


static void arm_gic_common_reset(DeviceState *dev)

{

    GICState *s = ARM_GIC_COMMON(dev);

    int i;

    memset(s->irq_state, 0, GIC_MAXIRQ * sizeof(gic_irq_state));

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

        if (s->revision == REV_11MPCORE) {

            s->priority_mask[i] = 0xf0;

        } else {

            s->priority_mask[i] = 0;

        }

        s->current_pending[i] = 1023;

        s->running_irq[i] = 1023;

        s->running_priority[i] = 0x100;

        s->cpu_enabled[i] = false;

    }

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

        GIC_SET_ENABLED(i, ALL_CPU_MASK);

        GIC_SET_EDGE_TRIGGER(i);

    }

    if (s->num_cpu == 1) {

        /* For uniprocessor GICs all interrupts always target the sole CPU */

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

            s->irq_target[i] = 1;

        }

    }

    s->ctlr = 0;

}


static int guess_disk_lchs(BlockDriverState *bs,

                           int *pcylinders, int *pheads, int *psectors)

{

    uint8_t buf[BDRV_SECTOR_SIZE];

    int i, heads, sectors, cylinders;

    struct partition *p;

    uint32_t nr_sects;

    uint64_t nb_sectors;

    bdrv_get_geometry(bs, &nb_sectors);

    /**

     * The function will be invoked during startup not only in sync I/O mode,

     * but also in async I/O mode. So the I/O throttling function has to

     * be disabled temporarily here, not permanently.

     */

    if (bdrv_read_unthrottled(bs, 0, buf, 1) < 0) {

        return -1;

    }

    /* test msdos magic */

    if (buf[510] != 0x55 || buf[511] != 0xaa) {

        return -1;

    }

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

        p = ((struct partition *)(buf + 0x1be)) + i;

        nr_sects = le32_to_cpu(p->nr_sects);

        if (nr_sects && p->end_head) {

            /* We make the assumption that the partition terminates on

               a cylinder boundary */

            heads = p->end_head + 1;

            sectors = p->end_sector & 63;

            if (sectors == 0) {

                continue;

            }

            cylinders = nb_sectors / (heads * sectors);

            if (cylinders < 1 || cylinders > 16383) {

                continue;

            }

            *pheads = heads;

            *psectors = sectors;

            *pcylinders = cylinders;

            trace_hd_geometry_lchs_guess(bs, cylinders, heads, sectors);

            return 0;

        }

    }

    return -1;

}


static mode_t v9mode_to_mode(uint32_t mode, V9fsString *extension)

{

    mode_t ret;

    ret = mode & 0777;

    if (mode & P9_STAT_MODE_DIR) {

        ret |= S_IFDIR;

    }

    if (mode & P9_STAT_MODE_SYMLINK) {

        ret |= S_IFLNK;

    }

    if (mode & P9_STAT_MODE_SOCKET) {

        ret |= S_IFSOCK;

    }

    if (mode & P9_STAT_MODE_NAMED_PIPE) {

        ret |= S_IFIFO;

    }

    if (mode & P9_STAT_MODE_DEVICE) {

        if (extension && extension->data[0] == 'c') {

            ret |= S_IFCHR;

        } else {

            ret |= S_IFBLK;

        }

    }

    if (!(ret&~0777)) {

        ret |= S_IFREG;

    }

    if (mode & P9_STAT_MODE_SETUID) {

        ret |= S_ISUID;

    }

    if (mode & P9_STAT_MODE_SETGID) {

        ret |= S_ISGID;

    }

    if (mode & P9_STAT_MODE_SETVTX) {

        ret |= S_ISVTX;

    }

    return ret;

}


int kvm_cpu_exec(CPUState *cpu)

{

    struct kvm_run *run = cpu->kvm_run;

    int ret, run_ret;

    DPRINTF("kvm_cpu_exec()\n");

    if (kvm_arch_process_async_events(cpu)) {

        cpu->exit_request = 0;

        return EXCP_HLT;

    }

    do {

        MemTxAttrs attrs;

        if (cpu->kvm_vcpu_dirty) {

            kvm_arch_put_registers(cpu, KVM_PUT_RUNTIME_STATE);

            cpu->kvm_vcpu_dirty = false;

        }

        kvm_arch_pre_run(cpu, run);

        if (cpu->exit_request) {

            DPRINTF("interrupt exit requested\n");

            /*

             * KVM requires us to reenter the kernel after IO exits to complete

             * instruction emulation. This self-signal will ensure that we

             * leave ASAP again.

             */

            qemu_cpu_kick_self();

        }

        qemu_mutex_unlock_iothread();

        run_ret = kvm_vcpu_ioctl(cpu, KVM_RUN, 0);

        qemu_mutex_lock_iothread();

        attrs = kvm_arch_post_run(cpu, run);

        if (run_ret < 0) {

            if (run_ret == -EINTR || run_ret == -EAGAIN) {

                DPRINTF("io window exit\n");

                ret = EXCP_INTERRUPT;

                break;

            }

            fprintf(stderr, "error: kvm run failed %s\n",

                    strerror(-run_ret));

#ifdef TARGET_PPC

            if (run_ret == -EBUSY) {

                fprintf(stderr,

                        "This is probably because your SMT is enabled.\n"

                        "VCPU can only run on primary threads with all "

                        "secondary threads offline.\n");

            }

#endif

            ret = -1;

            break;

        }

        trace_kvm_run_exit(cpu->cpu_index, run->exit_reason);

        switch (run->exit_reason) {

        case KVM_EXIT_IO:

            DPRINTF("handle_io\n");

            kvm_handle_io(run->io.port, attrs,

                          (uint8_t *)run + run->io.data_offset,

                          run->io.direction,

                          run->io.size,

                          run->io.count);

            ret = 0;

            break;

        case KVM_EXIT_MMIO:

            DPRINTF("handle_mmio\n");

            address_space_rw(&address_space_memory,

                             run->mmio.phys_addr, attrs,

                             run->mmio.data,

                             run->mmio.len,

                             run->mmio.is_write);

            ret = 0;

            break;

        case KVM_EXIT_IRQ_WINDOW_OPEN:

            DPRINTF("irq_window_open\n");

            ret = EXCP_INTERRUPT;

            break;

        case KVM_EXIT_SHUTDOWN:

            DPRINTF("shutdown\n");

            qemu_system_reset_request();

            ret = EXCP_INTERRUPT;

            break;

        case KVM_EXIT_UNKNOWN:

            fprintf(stderr, "KVM: unknown exit, hardware reason %" PRIx64 "\n",

                    (uint64_t)run->hw.hardware_exit_reason);

            ret = -1;

            break;

        case KVM_EXIT_INTERNAL_ERROR:

            ret = kvm_handle_internal_error(cpu, run);

            break;

        case KVM_EXIT_SYSTEM_EVENT:

            switch (run->system_event.type) {

            case KVM_SYSTEM_EVENT_SHUTDOWN:

                qemu_system_shutdown_request();

                ret = EXCP_INTERRUPT;

                break;

            case KVM_SYSTEM_EVENT_RESET:

                qemu_system_reset_request();

                ret = EXCP_INTERRUPT;

                break;

            default:

                DPRINTF("kvm_arch_handle_exit\n");

                ret = kvm_arch_handle_exit(cpu, run);

                break;

            }

            break;

        default:

            DPRINTF("kvm_arch_handle_exit\n");

            ret = kvm_arch_handle_exit(cpu, run);

            break;

        }

    } while (ret == 0);

    if (ret < 0) {

        cpu_dump_state(cpu, stderr, fprintf, CPU_DUMP_CODE);

        vm_stop(RUN_STATE_INTERNAL_ERROR);

    }

    cpu->exit_request = 0;

    return ret;

}


Visitor *string_output_get_visitor(StringOutputVisitor *sov)

{

    return &sov->visitor;

}


static void spr_write_tbl (DisasContext *ctx, int sprn, int gprn)

{

    if (use_icount) {

        gen_io_start();

    }

    gen_helper_store_tbl(cpu_env, cpu_gpr[gprn]);

    if (use_icount) {

        gen_io_end();

        gen_stop_exception(ctx);

    }

}


static int mig_save_device_dirty(QEMUFile *f, BlkMigDevState *bmds,

                                 int is_async)

{

    BlkMigBlock *blk;

    BlockDriverState *bs = blk_bs(bmds->blk);

    int64_t total_sectors = bmds->total_sectors;

    int64_t sector;

    int nr_sectors;

    int ret = -EIO;

    for (sector = bmds->cur_dirty; sector < bmds->total_sectors;) {

        blk_mig_lock();

        if (bmds_aio_inflight(bmds, sector)) {

            blk_mig_unlock();

            blk_drain(bmds->blk);

        } else {

            blk_mig_unlock();

        }

        if (bdrv_get_dirty(bs, bmds->dirty_bitmap, sector)) {

            if (total_sectors - sector < BDRV_SECTORS_PER_DIRTY_CHUNK) {

                nr_sectors = total_sectors - sector;

            } else {

                nr_sectors = BDRV_SECTORS_PER_DIRTY_CHUNK;

            }

            bdrv_reset_dirty_bitmap(bmds->dirty_bitmap, sector, nr_sectors);

            blk = g_new(BlkMigBlock, 1);

            blk->buf = g_malloc(BLOCK_SIZE);

            blk->bmds = bmds;

            blk->sector = sector;

            blk->nr_sectors = nr_sectors;

            if (is_async) {

                blk->iov.iov_base = blk->buf;

                blk->iov.iov_len = nr_sectors * BDRV_SECTOR_SIZE;

                qemu_iovec_init_external(&blk->qiov, &blk->iov, 1);

                blk->aiocb = blk_aio_preadv(bmds->blk,

                                            sector * BDRV_SECTOR_SIZE,

                                            &blk->qiov, 0, blk_mig_read_cb,

                                            blk);

                blk_mig_lock();

                block_mig_state.submitted++;

                bmds_set_aio_inflight(bmds, sector, nr_sectors, 1);

                blk_mig_unlock();

            } else {

                ret = blk_pread(bmds->blk, sector * BDRV_SECTOR_SIZE, blk->buf,

                                nr_sectors * BDRV_SECTOR_SIZE);

                if (ret < 0) {

                    goto error;

                }

                blk_send(f, blk);

                g_free(blk->buf);

                g_free(blk);

            }

            sector += nr_sectors;

            bmds->cur_dirty = sector;

            break;

        }

        sector += BDRV_SECTORS_PER_DIRTY_CHUNK;

        bmds->cur_dirty = sector;

    }

    return (bmds->cur_dirty >= bmds->total_sectors);

error:

    DPRINTF("Error reading sector %" PRId64 "\n", sector);

    g_free(blk->buf);

    g_free(blk);

    return ret;

}


static int kvm_get_xcrs(X86CPU *cpu)

{

    CPUX86State *env = &cpu->env;

    int i, ret;

    struct kvm_xcrs xcrs;

    if (!kvm_has_xcrs()) {

        return 0;

    }

    ret = kvm_vcpu_ioctl(CPU(cpu), KVM_GET_XCRS, &xcrs);

    if (ret < 0) {

        return ret;

    }

    for (i = 0; i < xcrs.nr_xcrs; i++) {

        /* Only support xcr0 now */

        if (xcrs.xcrs[i].xcr == 0) {

            env->xcr0 = xcrs.xcrs[i].value;

            break;

        }

    }

    return 0;

}


uint64_t timer_expire_time_ns(QEMUTimer *ts)

{

    return timer_pending(ts) ? ts->expire_time : -1;

}


static int default_fdset_dup_fd_add(int64_t fdset_id, int dup_fd)

{

    return -1;

}