static int qcow2_create2(const char *filename, int64_t total_size,

                         const char *backing_file, const char *backing_format,

                         int flags, size_t cluster_size, PreallocMode prealloc,

                         QemuOpts *opts, int version, int refcount_order,

                         const char *encryptfmt, Error **errp)

{

    int cluster_bits;

    QDict *options;

    /* Calculate cluster_bits */

    cluster_bits = ctz32(cluster_size);

    if (cluster_bits < MIN_CLUSTER_BITS || cluster_bits > MAX_CLUSTER_BITS ||

        (1 << cluster_bits) != cluster_size)

    {

        error_setg(errp, "Cluster size must be a power of two between %d and "

                   "%dk", 1 << MIN_CLUSTER_BITS, 1 << (MAX_CLUSTER_BITS - 10));

        return -EINVAL;

    }

    /*

     * Open the image file and write a minimal qcow2 header.

     *

     * We keep things simple and start with a zero-sized image. We also

     * do without refcount blocks or a L1 table for now. We'll fix the

     * inconsistency later.

     *

     * We do need a refcount table because growing the refcount table means

     * allocating two new refcount blocks - the seconds of which would be at

     * 2 GB for 64k clusters, and we don't want to have a 2 GB initial file

     * size for any qcow2 image.

     */

    BlockBackend *blk;

    QCowHeader *header;

    uint64_t* refcount_table;

    Error *local_err = NULL;

    int ret;

    if (prealloc == PREALLOC_MODE_FULL || prealloc == PREALLOC_MODE_FALLOC) {

        int64_t prealloc_size =

            qcow2_calc_prealloc_size(total_size, cluster_size, refcount_order);

        qemu_opt_set_number(opts, BLOCK_OPT_SIZE, prealloc_size, &error_abort);

        qemu_opt_set(opts, BLOCK_OPT_PREALLOC, PreallocMode_lookup[prealloc],

                     &error_abort);

    }

    ret = bdrv_create_file(filename, opts, &local_err);

    if (ret < 0) {

        error_propagate(errp, local_err);

        return ret;

    }

    blk = blk_new_open(filename, NULL, NULL,

                       BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_PROTOCOL,

                       &local_err);

    if (blk == NULL) {

        error_propagate(errp, local_err);

        return -EIO;

    }

    blk_set_allow_write_beyond_eof(blk, true);

    /* Write the header */

    QEMU_BUILD_BUG_ON((1 << MIN_CLUSTER_BITS) < sizeof(*header));

    header = g_malloc0(cluster_size);

    *header = (QCowHeader) {

        .magic                      = cpu_to_be32(QCOW_MAGIC),

        .version                    = cpu_to_be32(version),

        .cluster_bits               = cpu_to_be32(cluster_bits),

        .size                       = cpu_to_be64(0),

        .l1_table_offset            = cpu_to_be64(0),

        .l1_size                    = cpu_to_be32(0),

        .refcount_table_offset      = cpu_to_be64(cluster_size),

        .refcount_table_clusters    = cpu_to_be32(1),

        .refcount_order             = cpu_to_be32(refcount_order),

        .header_length              = cpu_to_be32(sizeof(*header)),

    };

    /* We'll update this to correct value later */

    header->crypt_method = cpu_to_be32(QCOW_CRYPT_NONE);

    if (flags & BLOCK_FLAG_LAZY_REFCOUNTS) {

        header->compatible_features |=

            cpu_to_be64(QCOW2_COMPAT_LAZY_REFCOUNTS);

    }

    ret = blk_pwrite(blk, 0, header, cluster_size, 0);

    g_free(header);

    if (ret < 0) {

        error_setg_errno(errp, -ret, "Could not write qcow2 header");

        goto out;

    }

    /* Write a refcount table with one refcount block */

    refcount_table = g_malloc0(2 * cluster_size);

    refcount_table[0] = cpu_to_be64(2 * cluster_size);

    ret = blk_pwrite(blk, cluster_size, refcount_table, 2 * cluster_size, 0);

    g_free(refcount_table);

    if (ret < 0) {

        error_setg_errno(errp, -ret, "Could not write refcount table");

        goto out;

    }

    blk_unref(blk);

    blk = NULL;

    /*

     * And now open the image and make it consistent first (i.e. increase the

     * refcount of the cluster that is occupied by the header and the refcount

     * table)

     */

    options = qdict_new();

    qdict_put_str(options, "driver", "qcow2");

    blk = blk_new_open(filename, NULL, options,

                       BDRV_O_RDWR | BDRV_O_RESIZE | BDRV_O_NO_FLUSH,

                       &local_err);

    if (blk == NULL) {

        error_propagate(errp, local_err);

        ret = -EIO;

        goto out;

    }

    ret = qcow2_alloc_clusters(blk_bs(blk), 3 * cluster_size);

    if (ret < 0) {

        error_setg_errno(errp, -ret, "Could not allocate clusters for qcow2 "

                         "header and refcount table");

        goto out;

    } else if (ret != 0) {

        error_report("Huh, first cluster in empty image is already in use?");

        abort();

    }

    /* Create a full header (including things like feature table) */

    ret = qcow2_update_header(blk_bs(blk));

    if (ret < 0) {

        error_setg_errno(errp, -ret, "Could not update qcow2 header");

        goto out;

    }

    /* Okay, now that we have a valid image, let's give it the right size */

    ret = blk_truncate(blk, total_size, errp);

    if (ret < 0) {

        error_prepend(errp, "Could not resize image: ");

        goto out;

    }

    /* Want a backing file? There you go.*/

    if (backing_file) {

        ret = bdrv_change_backing_file(blk_bs(blk), backing_file, backing_format);

        if (ret < 0) {

            error_setg_errno(errp, -ret, "Could not assign backing file '%s' "

                             "with format '%s'", backing_file, backing_format);

            goto out;

        }

    }

    /* Want encryption? There you go. */

    if (encryptfmt) {

        ret = qcow2_set_up_encryption(blk_bs(blk), encryptfmt, opts, errp);

        if (ret < 0) {

            goto out;

        }

    }

    /* And if we're supposed to preallocate metadata, do that now */

    if (prealloc != PREALLOC_MODE_OFF) {

        BDRVQcow2State *s = blk_bs(blk)->opaque;

        qemu_co_mutex_lock(&s->lock);

        ret = preallocate(blk_bs(blk));

        qemu_co_mutex_unlock(&s->lock);

        if (ret < 0) {

            error_setg_errno(errp, -ret, "Could not preallocate metadata");

            goto out;

        }

    }

    blk_unref(blk);

    blk = NULL;

    /* Reopen the image without BDRV_O_NO_FLUSH to flush it before returning.

     * Using BDRV_O_NO_IO, since encryption is now setup we don't want to

     * have to setup decryption context. We're not doing any I/O on the top

     * level BlockDriverState, only lower layers, where BDRV_O_NO_IO does

     * not have effect.

     */

    options = qdict_new();

    qdict_put_str(options, "driver", "qcow2");

    blk = blk_new_open(filename, NULL, options,

                       BDRV_O_RDWR | BDRV_O_NO_BACKING | BDRV_O_NO_IO,

                       &local_err);

    if (blk == NULL) {

        error_propagate(errp, local_err);

        ret = -EIO;

        goto out;

    }

    ret = 0;

out:

    if (blk) {

        blk_unref(blk);

    }

    return ret;

}


static int protocol_version(VncState *vs, char *version, size_t len)

{

    char local[13];

    int maj, min;

    memcpy(local, version, 12);

    local[12] = 0;

    if (sscanf(local, "RFB %03d.%03d\n", &maj, &min) != 2) {

	vnc_client_error(vs);

	return 0;

    }

    vnc_write_u32(vs, 1); /* None */

    vnc_flush(vs);

    vnc_read_when(vs, protocol_client_init, 1);

    return 0;

}


void ppce500_init(MachineState *machine, PPCE500Params *params)

{

    MemoryRegion *address_space_mem = get_system_memory();

    MemoryRegion *ram = g_new(MemoryRegion, 1);

    PCIBus *pci_bus;

    CPUPPCState *env = NULL;

    uint64_t elf_entry;

    uint64_t elf_lowaddr;

    hwaddr entry=0;

    hwaddr loadaddr=UIMAGE_LOAD_BASE;

    target_long kernel_size=0;

    target_ulong dt_base = 0;

    target_ulong initrd_base = 0;

    target_long initrd_size = 0;

    target_ulong cur_base = 0;

    int i;

    /* irq num for pin INTA, INTB, INTC and INTD is 1, 2, 3 and

     * 4 respectively */

    unsigned int pci_irq_nrs[PCI_NUM_PINS] = {1, 2, 3, 4};

    qemu_irq **irqs, *mpic;

    DeviceState *dev;

    CPUPPCState *firstenv = NULL;

    MemoryRegion *ccsr_addr_space;

    SysBusDevice *s;

    PPCE500CCSRState *ccsr;

    /* Setup CPUs */

    if (machine->cpu_model == NULL) {

        machine->cpu_model = "e500v2_v30";

    }

    irqs = g_malloc0(smp_cpus * sizeof(qemu_irq *));

    irqs[0] = g_malloc0(smp_cpus * sizeof(qemu_irq) * OPENPIC_OUTPUT_NB);

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

        PowerPCCPU *cpu;

        CPUState *cs;

        qemu_irq *input;

        cpu = cpu_ppc_init(machine->cpu_model);

        if (cpu == NULL) {

            fprintf(stderr, "Unable to initialize CPU!\n");

            exit(1);

        }

        env = &cpu->env;

        cs = CPU(cpu);

        if (!firstenv) {

            firstenv = env;

        }

        irqs[i] = irqs[0] + (i * OPENPIC_OUTPUT_NB);

        input = (qemu_irq *)env->irq_inputs;

        irqs[i][OPENPIC_OUTPUT_INT] = input[PPCE500_INPUT_INT];

        irqs[i][OPENPIC_OUTPUT_CINT] = input[PPCE500_INPUT_CINT];

        env->spr_cb[SPR_BOOKE_PIR].default_value = cs->cpu_index = i;

        env->mpic_iack = MPC8544_CCSRBAR_BASE +

                         MPC8544_MPIC_REGS_OFFSET + 0xa0;

        ppc_booke_timers_init(cpu, 400000000, PPC_TIMER_E500);

        /* Register reset handler */

        if (!i) {

            /* Primary CPU */

            struct boot_info *boot_info;

            boot_info = g_malloc0(sizeof(struct boot_info));

            qemu_register_reset(ppce500_cpu_reset, cpu);

            env->load_info = boot_info;

        } else {

            /* Secondary CPUs */

            qemu_register_reset(ppce500_cpu_reset_sec, cpu);

        }

    }

    env = firstenv;

    /* Fixup Memory size on a alignment boundary */

    ram_size &= ~(RAM_SIZES_ALIGN - 1);

    machine->ram_size = ram_size;

    /* Register Memory */

    memory_region_init_ram(ram, NULL, "mpc8544ds.ram", ram_size);

    vmstate_register_ram_global(ram);

    memory_region_add_subregion(address_space_mem, 0, ram);

    dev = qdev_create(NULL, "e500-ccsr");

    object_property_add_child(qdev_get_machine(), "e500-ccsr",

                              OBJECT(dev), NULL);

    qdev_init_nofail(dev);

    ccsr = CCSR(dev);

    ccsr_addr_space = &ccsr->ccsr_space;

    memory_region_add_subregion(address_space_mem, MPC8544_CCSRBAR_BASE,

                                ccsr_addr_space);

    mpic = ppce500_init_mpic(params, ccsr_addr_space, irqs);

    /* Serial */

    if (serial_hds[0]) {

        serial_mm_init(ccsr_addr_space, MPC8544_SERIAL0_REGS_OFFSET,

                       0, mpic[42], 399193,

                       serial_hds[0], DEVICE_BIG_ENDIAN);

    }

    if (serial_hds[1]) {

        serial_mm_init(ccsr_addr_space, MPC8544_SERIAL1_REGS_OFFSET,

                       0, mpic[42], 399193,

                       serial_hds[1], DEVICE_BIG_ENDIAN);

    }

    /* General Utility device */

    dev = qdev_create(NULL, "mpc8544-guts");

    qdev_init_nofail(dev);

    s = SYS_BUS_DEVICE(dev);

    memory_region_add_subregion(ccsr_addr_space, MPC8544_UTIL_OFFSET,

                                sysbus_mmio_get_region(s, 0));

    /* PCI */

    dev = qdev_create(NULL, "e500-pcihost");

    qdev_prop_set_uint32(dev, "first_slot", params->pci_first_slot);

    qdev_prop_set_uint32(dev, "first_pin_irq", pci_irq_nrs[0]);

    qdev_init_nofail(dev);

    s = SYS_BUS_DEVICE(dev);

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

        sysbus_connect_irq(s, i, mpic[pci_irq_nrs[i]]);

    }

    memory_region_add_subregion(ccsr_addr_space, MPC8544_PCI_REGS_OFFSET,

                                sysbus_mmio_get_region(s, 0));

    pci_bus = (PCIBus *)qdev_get_child_bus(dev, "pci.0");

    if (!pci_bus)

        printf("couldn't create PCI controller!\n");

    sysbus_mmio_map(SYS_BUS_DEVICE(dev), 1, MPC8544_PCI_IO);

    if (pci_bus) {

        /* Register network interfaces. */

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

            pci_nic_init_nofail(&nd_table[i], pci_bus, "virtio", NULL);

        }

    }

    /* Register spinning region */

    sysbus_create_simple("e500-spin", MPC8544_SPIN_BASE, NULL);

    /* Load kernel. */

    if (machine->kernel_filename) {

        kernel_size = load_uimage(machine->kernel_filename, &entry,

                                  &loadaddr, NULL);

        if (kernel_size < 0) {

            kernel_size = load_elf(machine->kernel_filename, NULL, NULL,

                                   &elf_entry, &elf_lowaddr, NULL, 1,

                                   ELF_MACHINE, 0);

            entry = elf_entry;

            loadaddr = elf_lowaddr;

        }

        /* XXX try again as binary */

        if (kernel_size < 0) {

            fprintf(stderr, "qemu: could not load kernel '%s'\n",

                    machine->kernel_filename);

            exit(1);

        }

        cur_base = loadaddr + kernel_size;

        /* Reserve space for dtb */

        dt_base = (cur_base + DTC_LOAD_PAD) & ~DTC_PAD_MASK;

        cur_base += DTB_MAX_SIZE;

    }

    /* Load initrd. */

    if (machine->initrd_filename) {

        initrd_base = (cur_base + INITRD_LOAD_PAD) & ~INITRD_PAD_MASK;

        initrd_size = load_image_targphys(machine->initrd_filename, initrd_base,

                                          ram_size - initrd_base);

        if (initrd_size < 0) {

            fprintf(stderr, "qemu: could not load initial ram disk '%s'\n",

                    machine->initrd_filename);

            exit(1);

        }

        cur_base = initrd_base + initrd_size;

    }

    /* If we're loading a kernel directly, we must load the device tree too. */

    if (machine->kernel_filename) {

        struct boot_info *boot_info;

        int dt_size;

        dt_size = ppce500_prep_device_tree(machine, params, dt_base,

                                           initrd_base, initrd_size);

        if (dt_size < 0) {

            fprintf(stderr, "couldn't load device tree\n");

            exit(1);

        }

        assert(dt_size < DTB_MAX_SIZE);

        boot_info = env->load_info;

        boot_info->entry = entry;

        boot_info->dt_base = dt_base;

        boot_info->dt_size = dt_size;

    }

    if (kvm_enabled()) {

        kvmppc_init();

    }

}


static void virtio_net_set_mrg_rx_bufs(VirtIONet *n, int mergeable_rx_bufs)

{

    int i;

    NetClientState *nc;

    n->mergeable_rx_bufs = mergeable_rx_bufs;

    n->guest_hdr_len = n->mergeable_rx_bufs ?

        sizeof(struct virtio_net_hdr_mrg_rxbuf) : sizeof(struct virtio_net_hdr);

    for (i = 0; i < n->max_queues; i++) {

        nc = qemu_get_subqueue(n->nic, i);

        if (peer_has_vnet_hdr(n) &&

            tap_has_vnet_hdr_len(nc->peer, n->guest_hdr_len)) {

            tap_set_vnet_hdr_len(nc->peer, n->guest_hdr_len);

            n->host_hdr_len = n->guest_hdr_len;

        }

    }

}


void qemu_acl_reset(qemu_acl *acl)

{

    qemu_acl_entry *entry;

    /* Put back to deny by default, so there is no window

     * of "open access" while the user re-initializes the

     * access control list */

    acl->defaultDeny = 1;

    TAILQ_FOREACH(entry, &acl->entries, next) {

        TAILQ_REMOVE(&acl->entries, entry, next);

        free(entry->match);

        free(entry);

    }

    acl->nentries = 0;

}


static void mov_fix_index(MOVContext *mov, AVStream *st)

{

    MOVStreamContext *msc = st->priv_data;

    AVIndexEntry *e_old = st->index_entries;

    int nb_old = st->nb_index_entries;

    const AVIndexEntry *e_old_end = e_old + nb_old;

    const AVIndexEntry *current = NULL;

    MOVStts *ctts_data_old = msc->ctts_data;

    int64_t ctts_index_old = 0;

    int64_t ctts_sample_old = 0;

    int64_t ctts_count_old = msc->ctts_count;

    int64_t edit_list_media_time = 0;

    int64_t edit_list_duration = 0;

    int64_t frame_duration = 0;

    int64_t edit_list_dts_counter = 0;

    int64_t edit_list_dts_entry_end = 0;

    int64_t edit_list_start_ctts_sample = 0;

    int64_t curr_cts;

    int64_t edit_list_index = 0;

    int64_t index;

    int64_t index_ctts_count;

    int flags;

    unsigned int ctts_allocated_size = 0;

    int64_t start_dts = 0;

    int64_t edit_list_media_time_dts = 0;

    int64_t edit_list_start_encountered = 0;

    int64_t search_timestamp = 0;

    int64_t* frame_duration_buffer = NULL;

    int num_discarded_begin = 0;

    int first_non_zero_audio_edit = -1;

    int packet_skip_samples = 0;

    MOVIndexRange *current_index_range;

    if (!msc->elst_data || msc->elst_count <= 0 || nb_old <= 0) {

        return;

    }

    // allocate the index ranges array

    msc->index_ranges = av_malloc((msc->elst_count + 1) * sizeof(msc->index_ranges[0]));

    if (!msc->index_ranges) {

        av_log(mov->fc, AV_LOG_ERROR, "Cannot allocate index ranges buffer\n");

        return;

    }

    msc->current_index_range = msc->index_ranges;

    current_index_range = msc->index_ranges - 1;

    // Clean AVStream from traces of old index

    st->index_entries = NULL;

    st->index_entries_allocated_size = 0;

    st->nb_index_entries = 0;

    // Clean ctts fields of MOVStreamContext

    msc->ctts_data = NULL;

    msc->ctts_count = 0;

    msc->ctts_index = 0;

    msc->ctts_sample = 0;

    // If the dts_shift is positive (in case of negative ctts values in mov),

    // then negate the DTS by dts_shift

    if (msc->dts_shift > 0)

        edit_list_dts_entry_end -= msc->dts_shift;

    // Offset the DTS by ctts[0] to make the PTS of the first frame 0

    if (ctts_data_old && ctts_count_old > 0) {

        edit_list_dts_entry_end -= ctts_data_old[0].duration;

        av_log(mov->fc, AV_LOG_DEBUG, "Offset DTS by ctts[%d].duration: %d\n", 0, ctts_data_old[0].duration);

    }

    start_dts = edit_list_dts_entry_end;

    while (get_edit_list_entry(mov, msc, edit_list_index, &edit_list_media_time,

                               &edit_list_duration, mov->time_scale)) {

        av_log(mov->fc, AV_LOG_DEBUG, "Processing st: %d, edit list %"PRId64" - media time: %"PRId64", duration: %"PRId64"\n",

               st->index, edit_list_index, edit_list_media_time, edit_list_duration);

        edit_list_index++;

        edit_list_dts_counter = edit_list_dts_entry_end;

        edit_list_dts_entry_end += edit_list_duration;

        num_discarded_begin = 0;

        if (edit_list_media_time == -1) {

            continue;

        }

        // If we encounter a non-negative edit list reset the skip_samples/start_pad fields and set them

        // according to the edit list below.

        if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {

            if (first_non_zero_audio_edit < 0) {

                first_non_zero_audio_edit = 1;

            } else {

                first_non_zero_audio_edit = 0;

            }

            if (first_non_zero_audio_edit > 0)

                st->skip_samples = msc->start_pad = 0;

        }

        //find closest previous key frame

        edit_list_media_time_dts = edit_list_media_time;

        if (msc->dts_shift > 0) {

            edit_list_media_time_dts -= msc->dts_shift;

        }

        // While reordering frame index according to edit list we must handle properly

        // the scenario when edit list entry starts from none key frame.

        // We find closest previous key frame and preserve it and consequent frames in index.

        // All frames which are outside edit list entry time boundaries will be dropped after decoding.

        search_timestamp = edit_list_media_time_dts;

        if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {

            // Audio decoders like AAC need need a decoder delay samples previous to the current sample,

            // to correctly decode this frame. Hence for audio we seek to a frame 1 sec. before the

            // edit_list_media_time to cover the decoder delay.

            search_timestamp = FFMAX(search_timestamp - msc->time_scale, e_old[0].timestamp);

        }

        index = find_prev_closest_index(st, e_old, nb_old, search_timestamp, 0);

        if (index == -1) {

            av_log(mov->fc, AV_LOG_WARNING,

                   "st: %d edit list: %"PRId64" Missing key frame while searching for timestamp: %"PRId64"\n",

                   st->index, edit_list_index, search_timestamp);

            index = find_prev_closest_index(st, e_old, nb_old, search_timestamp, AVSEEK_FLAG_ANY);

            if (index == -1) {

                av_log(mov->fc, AV_LOG_WARNING,

                       "st: %d edit list %"PRId64" Cannot find an index entry before timestamp: %"PRId64".\n"

                       "Rounding edit list media time to zero.\n",

                       st->index, edit_list_index, search_timestamp);

                index = 0;

                edit_list_media_time = 0;

            }

        }

        current = e_old + index;

        ctts_index_old = 0;

        ctts_sample_old = 0;

        // set ctts_index properly for the found key frame

        for (index_ctts_count = 0; index_ctts_count < index; index_ctts_count++) {

            if (ctts_data_old && ctts_index_old < ctts_count_old) {

                ctts_sample_old++;

                if (ctts_data_old[ctts_index_old].count == ctts_sample_old) {

                    ctts_index_old++;

                    ctts_sample_old = 0;

                }

            }

        }

        edit_list_start_ctts_sample = ctts_sample_old;

        // Iterate over index and arrange it according to edit list

        edit_list_start_encountered = 0;

        for (; current < e_old_end; current++, index++) {

            // check  if frame outside edit list mark it for discard

            frame_duration = (current + 1 <  e_old_end) ?

                             ((current + 1)->timestamp - current->timestamp) : edit_list_duration;

            flags = current->flags;

            // frames (pts) before or after edit list

            curr_cts = current->timestamp + msc->dts_shift;

            if (ctts_data_old && ctts_index_old < ctts_count_old) {

                av_log(mov->fc, AV_LOG_DEBUG, "shifted frame pts, curr_cts: %"PRId64" @ %"PRId64", ctts: %d, ctts_count: %"PRId64"\n",

                       curr_cts, ctts_index_old, ctts_data_old[ctts_index_old].duration, ctts_count_old);

                curr_cts += ctts_data_old[ctts_index_old].duration;

                ctts_sample_old++;

                if (ctts_sample_old == ctts_data_old[ctts_index_old].count) {

                    if (add_ctts_entry(&msc->ctts_data, &msc->ctts_count,

                                       &ctts_allocated_size,

                                       ctts_data_old[ctts_index_old].count - edit_list_start_ctts_sample,

                                       ctts_data_old[ctts_index_old].duration) == -1) {

                        av_log(mov->fc, AV_LOG_ERROR, "Cannot add CTTS entry %"PRId64" - {%"PRId64", %d}\n",

                               ctts_index_old,

                               ctts_data_old[ctts_index_old].count - edit_list_start_ctts_sample,

                               ctts_data_old[ctts_index_old].duration);

                        break;

                    }

                    ctts_index_old++;

                    ctts_sample_old = 0;

                    edit_list_start_ctts_sample = 0;

                }

            }

            if (curr_cts < edit_list_media_time || curr_cts >= (edit_list_duration + edit_list_media_time)) {

                if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->codec_id != AV_CODEC_ID_VORBIS &&

                    curr_cts < edit_list_media_time && curr_cts + frame_duration > edit_list_media_time &&

                    first_non_zero_audio_edit > 0) {

                    packet_skip_samples = edit_list_media_time - curr_cts;

                    st->skip_samples += packet_skip_samples;

                    // Shift the index entry timestamp by packet_skip_samples to be correct.

                    edit_list_dts_counter -= packet_skip_samples;

                    if (edit_list_start_encountered == 0)  {

                        edit_list_start_encountered = 1;

                        // Make timestamps strictly monotonically increasing for audio, by rewriting timestamps for

                        // discarded packets.

                        if (frame_duration_buffer) {

                            fix_index_entry_timestamps(st, st->nb_index_entries, edit_list_dts_counter,

                                                       frame_duration_buffer, num_discarded_begin);

                            av_freep(&frame_duration_buffer);

                        }

                    }

                    av_log(mov->fc, AV_LOG_DEBUG, "skip %d audio samples from curr_cts: %"PRId64"\n", packet_skip_samples, curr_cts);

                } else {

                    flags |= AVINDEX_DISCARD_FRAME;

                    av_log(mov->fc, AV_LOG_DEBUG, "drop a frame at curr_cts: %"PRId64" @ %"PRId64"\n", curr_cts, index);

                    if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && edit_list_start_encountered == 0) {

                        num_discarded_begin++;

                        frame_duration_buffer = av_realloc(frame_duration_buffer,

                                                           num_discarded_begin * sizeof(int64_t));

                        if (!frame_duration_buffer) {

                            av_log(mov->fc, AV_LOG_ERROR, "Cannot reallocate frame duration buffer\n");

                            break;

                        }

                        frame_duration_buffer[num_discarded_begin - 1] = frame_duration;

                        // Increment skip_samples for the first non-zero audio edit list

                        if (first_non_zero_audio_edit > 0 && st->codecpar->codec_id != AV_CODEC_ID_VORBIS) {

                            st->skip_samples += frame_duration;

                            msc->start_pad = st->skip_samples;

                        }

                    }

                }

            } else if (edit_list_start_encountered == 0) {

                edit_list_start_encountered = 1;

                // Make timestamps strictly monotonically increasing for audio, by rewriting timestamps for

                // discarded packets.

                if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && frame_duration_buffer) {

                    fix_index_entry_timestamps(st, st->nb_index_entries, edit_list_dts_counter,

                                               frame_duration_buffer, num_discarded_begin);

                    av_freep(&frame_duration_buffer);

                }

            }

            if (add_index_entry(st, current->pos, edit_list_dts_counter, current->size,

                                current->min_distance, flags) == -1) {

                av_log(mov->fc, AV_LOG_ERROR, "Cannot add index entry\n");

                break;

            }

            // Update the index ranges array

            if (current_index_range < msc->index_ranges || index != current_index_range->end) {

                current_index_range++;

                current_index_range->start = index;

            }

            current_index_range->end = index + 1;

            // Only start incrementing DTS in frame_duration amounts, when we encounter a frame in edit list.

            if (edit_list_start_encountered > 0) {

                edit_list_dts_counter = edit_list_dts_counter + frame_duration;

            }

            // Break when found first key frame after edit entry completion

            if (((curr_cts + frame_duration) >= (edit_list_duration + edit_list_media_time)) &&

                ((flags & AVINDEX_KEYFRAME) || ((st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)))) {

                if (ctts_data_old && ctts_sample_old != 0) {

                    if (add_ctts_entry(&msc->ctts_data, &msc->ctts_count,

                                       &ctts_allocated_size,

                                       ctts_sample_old - edit_list_start_ctts_sample,

                                       ctts_data_old[ctts_index_old].duration) == -1) {

                        av_log(mov->fc, AV_LOG_ERROR, "Cannot add CTTS entry %"PRId64" - {%"PRId64", %d}\n",

                               ctts_index_old, ctts_sample_old - edit_list_start_ctts_sample,

                               ctts_data_old[ctts_index_old].duration);

                        break;

                    }

                }

                break;

            }

        }

    }

    // Update av stream length

    st->duration = edit_list_dts_entry_end - start_dts;

    // Free the old index and the old CTTS structures

    av_free(e_old);

    av_free(ctts_data_old);

    // Null terminate the index ranges array

    current_index_range++;

    current_index_range->start = 0;

    current_index_range->end = 0;

    msc->current_index = msc->index_ranges[0].start;

}


int scsi_bus_legacy_handle_cmdline(SCSIBus *bus)

{

    Location loc;

    DriveInfo *dinfo;

    int res = 0, unit;

    loc_push_none(&loc);

    for (unit = 0; unit < MAX_SCSI_DEVS; unit++) {

        dinfo = drive_get(IF_SCSI, bus->busnr, unit);

        if (dinfo == NULL) {

            continue;

        }

        qemu_opts_loc_restore(dinfo->opts);

        if (!scsi_bus_legacy_add_drive(bus, dinfo->bdrv, unit)) {

            res = -1;

            break;

        }

    }

    loc_pop(&loc);

    return res;

}


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

{

    DeviceClass *k = DEVICE_CLASS(klass);

    k->realize = hda_codec_dev_realize;

    k->exit = hda_codec_dev_exit;

    set_bit(DEVICE_CATEGORY_SOUND, k->categories);

    k->bus_type = TYPE_HDA_BUS;

    k->props = hda_props;

}


static inline void downmix_stereo_to_mono(float *samples)

{

    int i;

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

        samples[i] += samples[i + 256];

        samples[i + 256] = 0;

    }

}


static int thread_execute2(AVCodecContext *avctx, action_func2* func2, void *arg, int *ret, int job_count)

{

    ThreadContext *c= avctx->thread_opaque;

    c->func2 = func2;

    return thread_execute(avctx, NULL, arg, ret, job_count, 0);

}


static void flat_print_section_header(WriterContext *wctx)

{

    FlatContext *flat = wctx->priv;

    AVBPrint *buf = &flat->section_header[wctx->level];

    int i;

    /* build section header */

    av_bprint_clear(buf);

    for (i = 1; i <= wctx->level; i++) {

        if (flat->hierarchical ||

            !(wctx->section[i]->flags & (SECTION_FLAG_IS_ARRAY|SECTION_FLAG_IS_WRAPPER)))

            av_bprintf(buf, "%s%s", wctx->section[i]->name, flat->sep_str);

    }

}


static int write_header(AVFormatContext *s)

{

    AVCodecContext *codec = s->streams[0]->codec;

    if (s->nb_streams > 1) {

        av_log(s, AV_LOG_ERROR, "only one stream is supported\n");

        return AVERROR(EINVAL);

    }

    if (codec->codec_id != AV_CODEC_ID_WAVPACK) {

        av_log(s, AV_LOG_ERROR, "unsupported codec\n");

        return AVERROR(EINVAL);

    }

    if (codec->extradata_size > 0) {

        avpriv_report_missing_feature(s, "remuxing from matroska container");

        return AVERROR_PATCHWELCOME;

    }

    avpriv_set_pts_info(s->streams[0], 64, 1, codec->sample_rate);

    return 0;

}


static int default_start_frame(AVFilterLink *inlink, AVFilterBufferRef *picref)

{

    AVFilterLink *outlink = NULL;

    if (inlink->dst->nb_outputs)

        outlink = inlink->dst->outputs[0];

    if (outlink) {

        outlink->out_buf = ff_get_video_buffer(outlink, AV_PERM_WRITE, outlink->w, outlink->h);

        if (!outlink->out_buf)

            return AVERROR(ENOMEM);

        avfilter_copy_buffer_ref_props(outlink->out_buf, picref);

        return ff_start_frame(outlink, avfilter_ref_buffer(outlink->out_buf, ~0));

    }

    return 0;

}


static uint64_t ivshmem_io_read(void *opaque, target_phys_addr_t addr,

                                unsigned size)

{

    IVShmemState *s = opaque;

    uint32_t ret;

    switch (addr)

    {

        case INTRMASK:

            ret = ivshmem_IntrMask_read(s);

            break;

        case INTRSTATUS:

            ret = ivshmem_IntrStatus_read(s);

            break;

        case IVPOSITION:

            /* return my VM ID if the memory is mapped */

            if (s->shm_fd > 0) {

                ret = s->vm_id;

            } else {

                ret = -1;

            }

            break;

        default:

            IVSHMEM_DPRINTF("why are we reading " TARGET_FMT_plx "\n", addr);

            ret = 0;

    }

    return ret;

}


static void omap_os_timer_write(void *opaque, target_phys_addr_t addr,

                                uint64_t value, unsigned size)

{

    struct omap_32khz_timer_s *s = (struct omap_32khz_timer_s *) opaque;

    int offset = addr & OMAP_MPUI_REG_MASK;

    if (size != 4) {

        return omap_badwidth_write32(opaque, addr, value);

    }

    switch (offset) {

    case 0x00:	/* TVR */

        s->timer.reset_val = value & 0x00ffffff;

        break;

    case 0x04:	/* TCR */

        OMAP_RO_REG(addr);

        break;

    case 0x08:	/* CR */

        s->timer.ar = (value >> 3) & 1;

        s->timer.it_ena = (value >> 2) & 1;

        if (s->timer.st != (value & 1) || (value & 2)) {

            omap_timer_sync(&s->timer);

            s->timer.enable = value & 1;

            s->timer.st = value & 1;

            omap_timer_update(&s->timer);

        }

        break;

    default:

        OMAP_BAD_REG(addr);

    }

}


static void tcg_out_setcond(TCGContext *s, TCGType type, TCGCond cond,

                            TCGArg arg0, TCGArg arg1, TCGArg arg2,

                            int const_arg2)

{

    int crop, sh;

    assert(TCG_TARGET_REG_BITS == 64 || type == TCG_TYPE_I32);

    /* Ignore high bits of a potential constant arg2.  */

    if (type == TCG_TYPE_I32) {

        arg2 = (uint32_t)arg2;

    }

    /* Handle common and trivial cases before handling anything else.  */

    if (arg2 == 0) {

        switch (cond) {

        case TCG_COND_EQ:

            tcg_out_setcond_eq0(s, type, arg0, arg1);

            return;

        case TCG_COND_NE:

            if (TCG_TARGET_REG_BITS == 64 && type == TCG_TYPE_I32) {

                tcg_out_ext32u(s, TCG_REG_R0, arg1);

                arg1 = TCG_REG_R0;

            }

            tcg_out_setcond_ne0(s, arg0, arg1);

            return;

        case TCG_COND_GE:

            tcg_out32(s, NOR | SAB(arg1, arg0, arg1));

            arg1 = arg0;

            /* FALLTHRU */

        case TCG_COND_LT:

            /* Extract the sign bit.  */

            if (type == TCG_TYPE_I32) {

                tcg_out_shri32(s, arg0, arg1, 31);

            } else {

                tcg_out_shri64(s, arg0, arg1, 63);

            }

            return;

        default:

            break;

        }

    }

    /* If we have ISEL, we can implement everything with 3 or 4 insns.

       All other cases below are also at least 3 insns, so speed up the

       code generator by not considering them and always using ISEL.  */

    if (HAVE_ISEL) {

        int isel, tab;

        tcg_out_cmp(s, cond, arg1, arg2, const_arg2, 7, type);

        isel = tcg_to_isel[cond];

        tcg_out_movi(s, type, arg0, 1);

        if (isel & 1) {

            /* arg0 = (bc ? 0 : 1) */

            tab = TAB(arg0, 0, arg0);

            isel &= ~1;

        } else {

            /* arg0 = (bc ? 1 : 0) */

            tcg_out_movi(s, type, TCG_REG_R0, 0);

            tab = TAB(arg0, arg0, TCG_REG_R0);

        }

        tcg_out32(s, isel | tab);

        return;

    }

    switch (cond) {

    case TCG_COND_EQ:

        arg1 = tcg_gen_setcond_xor(s, arg1, arg2, const_arg2);

        tcg_out_setcond_eq0(s, type, arg0, arg1);

        return;

    case TCG_COND_NE:

        arg1 = tcg_gen_setcond_xor(s, arg1, arg2, const_arg2);

        /* Discard the high bits only once, rather than both inputs.  */

        if (TCG_TARGET_REG_BITS == 64 && type == TCG_TYPE_I32) {

            tcg_out_ext32u(s, TCG_REG_R0, arg1);

            arg1 = TCG_REG_R0;

        }

        tcg_out_setcond_ne0(s, arg0, arg1);

        return;

    case TCG_COND_GT:

    case TCG_COND_GTU:

        sh = 30;

        crop = 0;

        goto crtest;

    case TCG_COND_LT:

    case TCG_COND_LTU:

        sh = 29;

        crop = 0;

        goto crtest;

    case TCG_COND_GE:

    case TCG_COND_GEU:

        sh = 31;

        crop = CRNOR | BT(7, CR_EQ) | BA(7, CR_LT) | BB(7, CR_LT);

        goto crtest;

    case TCG_COND_LE:

    case TCG_COND_LEU:

        sh = 31;

        crop = CRNOR | BT(7, CR_EQ) | BA(7, CR_GT) | BB(7, CR_GT);

    crtest:

        tcg_out_cmp(s, cond, arg1, arg2, const_arg2, 7, type);

        if (crop) {

            tcg_out32(s, crop);

        }

        tcg_out32(s, MFOCRF | RT(TCG_REG_R0) | FXM(7));

        tcg_out_rlw(s, RLWINM, arg0, TCG_REG_R0, sh, 31, 31);

        break;

    default:

        tcg_abort();

    }

}


static void qmp_input_optional(Visitor *v, const char *name, bool *present)

{

    QmpInputVisitor *qiv = to_qiv(v);

    QObject *qobj = qmp_input_get_object(qiv, name, false, NULL);

    if (!qobj) {

        *present = false;

        return;

    }

    *present = true;

}


static int intel_hda_send_command(IntelHDAState *d, uint32_t verb)

{

    uint32_t cad, nid, data;

    HDACodecDevice *codec;

    HDACodecDeviceClass *cdc;

    cad = (verb >> 28) & 0x0f;

    if (verb & (1 << 27)) {

        /* indirect node addressing, not specified in HDA 1.0 */

        dprint(d, 1, "%s: indirect node addressing (guest bug?)\n", __FUNCTION__);

        return -1;

    }

    nid = (verb >> 20) & 0x7f;

    data = verb & 0xfffff;

    codec = hda_codec_find(&d->codecs, cad);

    if (codec == NULL) {

        dprint(d, 1, "%s: addressed non-existing codec\n", __FUNCTION__);

        return -1;

    }

    cdc = HDA_CODEC_DEVICE_GET_CLASS(codec);

    cdc->command(codec, nid, data);

    return 0;

}


static void timerblock_write(void *opaque, target_phys_addr_t addr,

                             uint64_t value, unsigned size)

{

    timerblock *tb = (timerblock *)opaque;

    int64_t old;

    switch (addr) {

    case 0: /* Load */

        tb->load = value;

        /* Fall through.  */

    case 4: /* Counter.  */

        if ((tb->control & 1) && tb->count) {

            /* Cancel the previous timer.  */

            qemu_del_timer(tb->timer);

        }

        tb->count = value;

        if (tb->control & 1) {

            timerblock_reload(tb, 1);

        }

        break;

    case 8: /* Control.  */

        old = tb->control;

        tb->control = value;

        if (((old & 1) == 0) && (value & 1)) {

            if (tb->count == 0 && (tb->control & 2)) {

                tb->count = tb->load;

            }

            timerblock_reload(tb, 1);

        }

        break;

    case 12: /* Interrupt status.  */

        tb->status &= ~value;

        timerblock_update_irq(tb);

        break;

    }

}


int av_find_best_stream(AVFormatContext *ic,

                        enum AVMediaType type,

                        int wanted_stream_nb,

                        int related_stream,

                        AVCodec **decoder_ret,

                        int flags)

{

    int i, nb_streams = ic->nb_streams, stream_number = 0;

    int ret = AVERROR_STREAM_NOT_FOUND, best_count = -1;

    unsigned *program = NULL;

    AVCodec *decoder = NULL, *best_decoder = NULL;

    if (related_stream >= 0 && wanted_stream_nb < 0) {

        AVProgram *p = find_program_from_stream(ic, related_stream);

        if (p) {

            program = p->stream_index;

            nb_streams = p->nb_stream_indexes;

        }

    }

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

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

        AVCodecContext *avctx = st->codec;

        if (avctx->codec_type != type)

            continue;

        if (wanted_stream_nb >= 0 && stream_number++ != wanted_stream_nb)

            continue;

        if (st->disposition & (AV_DISPOSITION_HEARING_IMPAIRED|AV_DISPOSITION_VISUAL_IMPAIRED))

            continue;

        if (decoder_ret) {

            decoder = avcodec_find_decoder(st->codec->codec_id);

            if (!decoder) {

                if (ret < 0)

                    ret = AVERROR_DECODER_NOT_FOUND;

                continue;

            }

        }

        if (best_count >= st->codec_info_nb_frames)

            continue;

        best_count = st->codec_info_nb_frames;

        ret = program ? program[i] : i;

        best_decoder = decoder;

        if (program && i == nb_streams - 1 && ret < 0) {

            program = NULL;

            nb_streams = ic->nb_streams;

            i = 0; /* no related stream found, try again with everything */

        }

    }

    if (decoder_ret)

        *decoder_ret = best_decoder;

    return ret;

}


BlockDriverState *bdrv_new(const char *device_name, Error **errp)

{

    BlockDriverState *bs;

    int i;

    if (*device_name && !bdrv_is_valid_name(device_name)) {

        error_setg(errp, "Invalid device name");

        return NULL;

    }

    if (bdrv_find(device_name)) {

        error_setg(errp, "Device with id '%s' already exists",

                   device_name);

        return NULL;

    }

    if (bdrv_find_node(device_name)) {

        error_setg(errp,

                   "Device name '%s' conflicts with an existing node name",

                   device_name);

        return NULL;

    }

    bs = g_new0(BlockDriverState, 1);

    QLIST_INIT(&bs->dirty_bitmaps);

    pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);

    if (device_name[0] != '\0') {

        QTAILQ_INSERT_TAIL(&bdrv_states, bs, device_list);

    }

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

        QLIST_INIT(&bs->op_blockers[i]);

    }

    bdrv_iostatus_disable(bs);

    notifier_list_init(&bs->close_notifiers);

    notifier_with_return_list_init(&bs->before_write_notifiers);

    qemu_co_queue_init(&bs->throttled_reqs[0]);

    qemu_co_queue_init(&bs->throttled_reqs[1]);

    bs->refcnt = 1;

    bs->aio_context = qemu_get_aio_context();

    return bs;

}


static void readline_completion(ReadLineState *rs)

{

    int len, i, j, max_width, nb_cols, max_prefix;

    char *cmdline;

    rs->nb_completions = 0;

    cmdline = g_malloc(rs->cmd_buf_index + 1);

    memcpy(cmdline, rs->cmd_buf, rs->cmd_buf_index);

    cmdline[rs->cmd_buf_index] = '\0';

    rs->completion_finder(rs->mon, cmdline);

    g_free(cmdline);

    /* no completion found */

    if (rs->nb_completions <= 0)

        return;

    if (rs->nb_completions == 1) {

        len = strlen(rs->completions[0]);

        for(i = rs->completion_index; i < len; i++) {

            readline_insert_char(rs, rs->completions[0][i]);

        }

        /* extra space for next argument. XXX: make it more generic */

        if (len > 0 && rs->completions[0][len - 1] != '/')

            readline_insert_char(rs, ' ');

    } else {

        monitor_printf(rs->mon, "\n");

        max_width = 0;

        max_prefix = 0;

        for(i = 0; i < rs->nb_completions; i++) {

            len = strlen(rs->completions[i]);

            if (i==0) {

                max_prefix = len;

            } else {

                if (len < max_prefix)

                    max_prefix = len;

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

                    if (rs->completions[i][j] != rs->completions[0][j])

                        max_prefix = j;

                }

            }

            if (len > max_width)

                max_width = len;

        }

        if (max_prefix > 0)

            for(i = rs->completion_index; i < max_prefix; i++) {

                readline_insert_char(rs, rs->completions[0][i]);

            }

        max_width += 2;

        if (max_width < 10)

            max_width = 10;

        else if (max_width > 80)

            max_width = 80;

        nb_cols = 80 / max_width;

        j = 0;

        for(i = 0; i < rs->nb_completions; i++) {

            monitor_printf(rs->mon, "%-*s", max_width, rs->completions[i]);

            if (++j == nb_cols || i == (rs->nb_completions - 1)) {

                monitor_printf(rs->mon, "\n");

                j = 0;

            }

        }

        readline_show_prompt(rs);

    }

    for (i = 0; i < rs->nb_completions; i++) {

        g_free(rs->completions[i]);

    }

}


static void tlb_unprotect_code_phys(CPUState *env, ram_addr_t ram_addr,

                                    target_ulong vaddr)

{

    phys_ram_dirty[ram_addr >> TARGET_PAGE_BITS] |= CODE_DIRTY_FLAG;

}


float64 helper_fqtod(CPUSPARCState *env)

{

    float64 ret;

    clear_float_exceptions(env);

    ret = float128_to_float64(QT1, &env->fp_status);

    check_ieee_exceptions(env);

    return ret;

}


static bool vhost_section(MemoryRegionSection *section)

{

    return section->address_space == get_system_memory()

        && memory_region_is_ram(section->mr);

}


static int parse_str(StringInputVisitor *siv, const char *name, Error **errp)

{

    char *str = (char *) siv->string;

    long long start, end;

    Range *cur;

    char *endptr;

    if (siv->ranges) {

        return 0;

    }

    do {

        errno = 0;

        start = strtoll(str, &endptr, 0);

        if (errno == 0 && endptr > str) {

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

                cur = g_malloc0(sizeof(*cur));

                cur->begin = start;

                cur->end = start + 1;

                siv->ranges = range_list_insert(siv->ranges, cur);

                cur = NULL;

                str = NULL;

            } else if (*endptr == '-') {

                str = endptr + 1;

                errno = 0;

                end = strtoll(str, &endptr, 0);

                if (errno == 0 && endptr > str && start <= end &&

                    (start > INT64_MAX - 65536 ||

                     end < start + 65536)) {

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

                        cur = g_malloc0(sizeof(*cur));

                        cur->begin = start;

                        cur->end = end + 1;

                        siv->ranges = range_list_insert(siv->ranges, cur);

                        cur = NULL;

                        str = NULL;

                    } else if (*endptr == ',') {

                        str = endptr + 1;

                        cur = g_malloc0(sizeof(*cur));

                        cur->begin = start;

                        cur->end = end + 1;

                        siv->ranges = range_list_insert(siv->ranges, cur);

                        cur = NULL;

                    } else {

                        goto error;

                    }

                } else {

                    goto error;

                }

            } else if (*endptr == ',') {

                str = endptr + 1;

                cur = g_malloc0(sizeof(*cur));

                cur->begin = start;

                cur->end = start + 1;

                siv->ranges = range_list_insert(siv->ranges, cur);

                cur = NULL;

            } else {

                goto error;

            }

        } else {

            goto error;

        }

    } while (str);

    return 0;

error:

    g_list_foreach(siv->ranges, free_range, NULL);

    g_list_free(siv->ranges);

    siv->ranges = NULL;

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

               "an int64 value or range");

    return -1;

}


static void address_space_update_topology(AddressSpace *as)

{

    FlatView old_view = as->current_map;

    FlatView new_view = generate_memory_topology(as->root);

    address_space_update_topology_pass(as, old_view, new_view, false);

    address_space_update_topology_pass(as, old_view, new_view, true);

    as->current_map = new_view;

    flatview_destroy(&old_view);

    address_space_update_ioeventfds(as);

}


static int vqf_probe(AVProbeData *probe_packet)
{
    if (AV_RL32(probe_packet->buf) != MKTAG('T','W','I','N'))
        return 0;
    if (!memcmp(probe_packet->buf + 4, "97012000", 8))
        return AVPROBE_SCORE_MAX;
    if (!memcmp(probe_packet->buf + 4, "00052200", 8))
        return AVPROBE_SCORE_MAX;
    return AVPROBE_SCORE_EXTENSION;
}


static void boston_platreg_write(void *opaque, hwaddr addr,

                                 uint64_t val, unsigned size)

{

    if (size != 4) {

        qemu_log_mask(LOG_UNIMP, "%uB platform register write", size);

        return;

    }

    switch (addr & 0xffff) {

    case PLAT_FPGA_BUILD:

    case PLAT_CORE_CL:

    case PLAT_WRAPPER_CL:

    case PLAT_DDR3_STATUS:

    case PLAT_PCIE_STATUS:

    case PLAT_MMCM_DIV:

    case PLAT_BUILD_CFG:

    case PLAT_DDR_CFG:

        /* read only */

        break;

    case PLAT_SOFTRST_CTL:

        if (val & PLAT_SOFTRST_CTL_SYSRESET) {

            qemu_system_reset_request();

        }

        break;

    default:

        qemu_log_mask(LOG_UNIMP, "Write platform register 0x%" HWADDR_PRIx

                      " = 0x%" PRIx64, addr & 0xffff, val);

        break;

    }

}


static int nbd_co_send_reply(NBDRequest *req, struct nbd_reply *reply,

                             int len)

{

    NBDClient *client = req->client;

    int csock = client->sock;

    int rc, ret;

    qemu_co_mutex_lock(&client->send_lock);

    qemu_set_fd_handler2(csock, nbd_can_read, nbd_read,

                         nbd_restart_write, client);

    client->send_coroutine = qemu_coroutine_self();

    if (!len) {

        rc = nbd_send_reply(csock, reply);

        if (rc == -1) {

            rc = -errno;

        }

    } else {

        socket_set_cork(csock, 1);

        rc = nbd_send_reply(csock, reply);

        if (rc != -1) {

            ret = qemu_co_send(csock, req->data, len);

            if (ret != len) {

                errno = EIO;

                rc = -1;

            }

        }

        if (rc == -1) {

            rc = -errno;

        }

        socket_set_cork(csock, 0);

    }

    client->send_coroutine = NULL;

    qemu_set_fd_handler2(csock, nbd_can_read, nbd_read, NULL, client);

    qemu_co_mutex_unlock(&client->send_lock);

    return rc;

}


static int mxf_get_d10_aes3_packet(AVIOContext *pb, AVStream *st, AVPacket *pkt, int64_t length)

{

    const uint8_t *buf_ptr, *end_ptr;

    uint8_t *data_ptr;

    int i;

    if (length > 61444) /* worst case PAL 1920 samples 8 channels */

        return -1;

    av_new_packet(pkt, length);

    avio_read(pb, pkt->data, length);

    data_ptr = pkt->data;

    end_ptr = pkt->data + length;

    buf_ptr = pkt->data + 4; /* skip SMPTE 331M header */

    for (; buf_ptr < end_ptr; ) {

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

            uint32_t sample = bytestream_get_le32(&buf_ptr);

            if (st->codec->bits_per_coded_sample == 24)

                bytestream_put_le24(&data_ptr, (sample >> 4) & 0xffffff);

            else

                bytestream_put_le16(&data_ptr, (sample >> 12) & 0xffff);

        }

        buf_ptr += 32 - st->codec->channels*4; // always 8 channels stored SMPTE 331M

    }

    pkt->size = data_ptr - pkt->data;

    return 0;

}


static int cavs_decode_frame(AVCodecContext * avctx,void *data, int *data_size,

                             uint8_t * buf, int buf_size) {

    AVSContext *h = avctx->priv_data;

    MpegEncContext *s = &h->s;

    int input_size;

    const uint8_t *buf_end;

    const uint8_t *buf_ptr;

    AVFrame *picture = data;

    uint32_t stc;

    s->avctx = avctx;

    if (buf_size == 0) {

        if(!s->low_delay && h->DPB[0].data[0]) {

            *data_size = sizeof(AVPicture);

            *picture = *(AVFrame *) &h->DPB[0];

        }

        return 0;

    }

    buf_ptr = buf;

    buf_end = buf + buf_size;

    for(;;) {

        buf_ptr = ff_find_start_code(buf_ptr,buf_end, &stc);

        if(stc & 0xFFFFFE00)

            return FFMAX(0, buf_ptr - buf - s->parse_context.last_index);

        input_size = (buf_end - buf_ptr)*8;

        switch(stc) {

        case CAVS_START_CODE:

            init_get_bits(&s->gb, buf_ptr, input_size);

            decode_seq_header(h);

            break;

        case PIC_I_START_CODE:

            if(!h->got_keyframe) {

                if(h->DPB[0].data[0])

                    avctx->release_buffer(avctx, (AVFrame *)&h->DPB[0]);

                if(h->DPB[1].data[0])

                    avctx->release_buffer(avctx, (AVFrame *)&h->DPB[1]);

                h->got_keyframe = 1;

            }

        case PIC_PB_START_CODE:

            *data_size = 0;

            if(!h->got_keyframe)

                break;

            init_get_bits(&s->gb, buf_ptr, input_size);

            h->stc = stc;

            if(decode_pic(h))

                break;

            *data_size = sizeof(AVPicture);

            if(h->pic_type != FF_B_TYPE) {

                if(h->DPB[1].data[0]) {

                    *picture = *(AVFrame *) &h->DPB[1];

                } else {

                    *data_size = 0;

                }

            } else

                *picture = *(AVFrame *) &h->picture;

            break;

        case EXT_START_CODE:

            //mpeg_decode_extension(avctx,buf_ptr, input_size);

            break;

        case USER_START_CODE:

            //mpeg_decode_user_data(avctx,buf_ptr, input_size);

            break;

        default:

            if (stc >= SLICE_MIN_START_CODE &&

                stc <= SLICE_MAX_START_CODE) {

                init_get_bits(&s->gb, buf_ptr, input_size);

                decode_slice_header(h, &s->gb);

            }

            break;

        }

    }

}


static int decode_end(AVCodecContext *avctx)

{

    SmackVContext * const smk = (SmackVContext *)avctx->priv_data;

    if(smk->mmap_tbl)

        av_free(smk->mmap_tbl);

    if(smk->mclr_tbl)

        av_free(smk->mclr_tbl);

    if(smk->full_tbl)

        av_free(smk->full_tbl);

    if(smk->type_tbl)

        av_free(smk->type_tbl);

    if (smk->pic.data[0])

        avctx->release_buffer(avctx, &smk->pic);

    return 0;

}


static void test_sum_square(void)

{

    INTFLOAT res0;

    INTFLOAT res1;

    LOCAL_ALIGNED_16(INTFLOAT, src, [256], [2]);

    declare_func(INTFLOAT, INTFLOAT (*x)[2], int n);

    randomize((INTFLOAT *)src, 256 * 2);

    res0 = call_ref(src, 256);

    res1 = call_new(src, 256);

    if (!float_near_abs_eps(res0, res1, EPS))

        fail();

    bench_new(src, 256);

}


static int decode_residuals(FLACContext *s, int32_t *decoded, int pred_order)

{

    int i, tmp, partition, method_type, rice_order;

    int rice_bits, rice_esc;

    int samples;

    method_type = get_bits(&s->gb, 2);

    if (method_type > 1) {

        av_log(s->avctx, AV_LOG_ERROR, "illegal residual coding method %d\n",

               method_type);

        return AVERROR_INVALIDDATA;

    }

    rice_order = get_bits(&s->gb, 4);

    samples= s->blocksize >> rice_order;

    if (samples << rice_order != s->blocksize) {

        av_log(s->avctx, AV_LOG_ERROR, "invalid rice order: %i blocksize %i\n",

               rice_order, s->blocksize);

        return AVERROR_INVALIDDATA;

    }

    if (pred_order > samples) {

        av_log(s->avctx, AV_LOG_ERROR, "invalid predictor order: %i > %i\n",

               pred_order, samples);

        return AVERROR_INVALIDDATA;

    }

    rice_bits = 4 + method_type;

    rice_esc  = (1 << rice_bits) - 1;

    decoded += pred_order;

    i= pred_order;

    for (partition = 0; partition < (1 << rice_order); partition++) {

        tmp = get_bits(&s->gb, rice_bits);

        if (tmp == rice_esc) {

            tmp = get_bits(&s->gb, 5);

            for (; i < samples; i++)

                *decoded++ = get_sbits_long(&s->gb, tmp);

        } else {

            for (; i < samples; i++) {

                *decoded++ = get_sr_golomb_flac(&s->gb, tmp, INT_MAX, 0);

            }

        }

        i= 0;

    }

    return 0;

}


MemoryRegion *pci_address_space(PCIDevice *dev)

{

    return dev->bus->address_space_mem;

}


static void net_socket_accept(void *opaque)

{

    NetSocketListenState *s = opaque;

    NetSocketState *s1;

    struct sockaddr_in saddr;

    socklen_t len;

    int fd;

    for(;;) {

        len = sizeof(saddr);

        fd = qemu_accept(s->fd, (struct sockaddr *)&saddr, &len);

        if (fd < 0 && errno != EINTR) {

            return;

        } else if (fd >= 0) {

            break;

        }

    }

    s1 = net_socket_fd_init(s->peer, s->model, s->name, fd, 1);

    if (s1) {

        snprintf(s1->nc.info_str, sizeof(s1->nc.info_str),

                 "socket: connection from %s:%d",

                 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));

    }

}


static int vvfat_open(BlockDriverState *bs, QDict *options, int flags,

                      Error **errp)

{

    BDRVVVFATState *s = bs->opaque;

    int cyls, heads, secs;

    bool floppy;

    const char *dirname, *label;

    QemuOpts *opts;

    Error *local_err = NULL;

    int ret;

#ifdef DEBUG

    vvv = s;

#endif

    opts = qemu_opts_create(&runtime_opts, NULL, 0, &error_abort);

    qemu_opts_absorb_qdict(opts, options, &local_err);

    if (local_err) {

        error_propagate(errp, local_err);

        ret = -EINVAL;

        goto fail;

    }

    dirname = qemu_opt_get(opts, "dir");

    if (!dirname) {

        error_setg(errp, "vvfat block driver requires a 'dir' option");

        ret = -EINVAL;

        goto fail;

    }

    s->fat_type = qemu_opt_get_number(opts, "fat-type", 0);

    floppy = qemu_opt_get_bool(opts, "floppy", false);

    memset(s->volume_label, ' ', sizeof(s->volume_label));

    label = qemu_opt_get(opts, "label");

    if (label) {

        size_t label_length = strlen(label);

        if (label_length > 11) {

            error_setg(errp, "vvfat label cannot be longer than 11 bytes");

            ret = -EINVAL;

            goto fail;

        }

        memcpy(s->volume_label, label, label_length);

    } else {

        memcpy(s->volume_label, "QEMU VVFAT", 10);

    }

    if (floppy) {

        /* 1.44MB or 2.88MB floppy.  2.88MB can be FAT12 (default) or FAT16. */

        if (!s->fat_type) {

            s->fat_type = 12;

            secs = 36;

            s->sectors_per_cluster = 2;

        } else {

            secs = s->fat_type == 12 ? 18 : 36;

            s->sectors_per_cluster = 1;

        }

        cyls = 80;

        heads = 2;

    } else {

        /* 32MB or 504MB disk*/

        if (!s->fat_type) {

            s->fat_type = 16;

        }

        s->offset_to_bootsector = 0x3f;

        cyls = s->fat_type == 12 ? 64 : 1024;

        heads = 16;

        secs = 63;

    }

    switch (s->fat_type) {

    case 32:

            fprintf(stderr, "Big fat greek warning: FAT32 has not been tested. "

                "You are welcome to do so!\n");

        break;

    case 16:

    case 12:

        break;

    default:

        error_setg(errp, "Valid FAT types are only 12, 16 and 32");

        ret = -EINVAL;

        goto fail;

    }

    s->bs = bs;

    /* LATER TODO: if FAT32, adjust */

    s->sectors_per_cluster=0x10;

    s->current_cluster=0xffffffff;

    s->qcow = NULL;

    s->qcow_filename = NULL;

    s->fat2 = NULL;

    s->downcase_short_names = 1;

    fprintf(stderr, "vvfat %s chs %d,%d,%d\n",

            dirname, cyls, heads, secs);

    s->sector_count = cyls * heads * secs - s->offset_to_bootsector;

    if (qemu_opt_get_bool(opts, "rw", false)) {

        if (!bdrv_is_read_only(bs)) {

            ret = enable_write_target(bs, errp);

            if (ret < 0) {

                goto fail;

            }

        } else {

            ret = -EPERM;

            error_setg(errp,

                       "Unable to set VVFAT to 'rw' when drive is read-only");

            goto fail;

        }

    } else  {

        /* read only is the default for safety */

        ret = bdrv_set_read_only(bs, true, &local_err);

        if (ret < 0) {

            error_propagate(errp, local_err);

            goto fail;

        }

    }

    bs->total_sectors = cyls * heads * secs;

    if (init_directories(s, dirname, heads, secs, errp)) {

        ret = -EIO;

        goto fail;

    }

    s->sector_count = s->offset_to_root_dir

                    + s->sectors_per_cluster * s->cluster_count;

    /* Disable migration when vvfat is used rw */

    if (s->qcow) {

        error_setg(&s->migration_blocker,

                   "The vvfat (rw) format used by node '%s' "

                   "does not support live migration",

                   bdrv_get_device_or_node_name(bs));

        ret = migrate_add_blocker(s->migration_blocker, &local_err);

        if (local_err) {

            error_propagate(errp, local_err);

            error_free(s->migration_blocker);

            goto fail;

        }

    }

    if (s->offset_to_bootsector > 0) {

        init_mbr(s, cyls, heads, secs);

    }

    qemu_co_mutex_init(&s->lock);

    ret = 0;

fail:

    qemu_opts_del(opts);

    return ret;

}


static void qemu_opt_del(QemuOpt *opt)

{

    TAILQ_REMOVE(&opt->opts->head, opt, next);

    qemu_free((/* !const */ char*)opt->name);

    qemu_free((/* !const */ char*)opt->str);

    qemu_free(opt);

}


static void bamboo_init(ram_addr_t ram_size,

                        const char *boot_device,

                        const char *kernel_filename,

                        const char *kernel_cmdline,

                        const char *initrd_filename,

                        const char *cpu_model)

{

    unsigned int pci_irq_nrs[4] = { 28, 27, 26, 25 };

    PCIBus *pcibus;

    CPUState *env;

    uint64_t elf_entry;

    uint64_t elf_lowaddr;

    target_phys_addr_t entry = 0;

    target_phys_addr_t loadaddr = 0;

    target_long kernel_size = 0;

    target_ulong initrd_base = 0;

    target_long initrd_size = 0;

    target_ulong dt_base = 0;

    void *fdt;

    int i;

    /* Setup CPU. */

    env = ppc440ep_init(&ram_size, &pcibus, pci_irq_nrs, 1, cpu_model);

    if (pcibus) {

        /* Register network interfaces. */

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

            /* There are no PCI NICs on the Bamboo board, but there are

             * PCI slots, so we can pick whatever default model we want. */

            pci_nic_init_nofail(&nd_table[i], "e1000", NULL);

        }

    }

    /* Load kernel. */

    if (kernel_filename) {

        kernel_size = load_uimage(kernel_filename, &entry, &loadaddr, NULL);

        if (kernel_size < 0) {

            kernel_size = load_elf(kernel_filename, 0, &elf_entry, &elf_lowaddr,

                                   NULL, 1, ELF_MACHINE, 0);

            entry = elf_entry;

            loadaddr = elf_lowaddr;

        }

        /* XXX try again as binary */

        if (kernel_size < 0) {

            fprintf(stderr, "qemu: could not load kernel '%s'\n",

                    kernel_filename);

            exit(1);

        }

    }

    /* Load initrd. */

    if (initrd_filename) {

        initrd_base = kernel_size + loadaddr;

        initrd_size = load_image_targphys(initrd_filename, initrd_base,

                                          ram_size - initrd_base);

        if (initrd_size < 0) {

            fprintf(stderr, "qemu: could not load initial ram disk '%s'\n",

                    initrd_filename);

            exit(1);

        }

    }

    /* If we're loading a kernel directly, we must load the device tree too. */

    if (kernel_filename) {

        if (initrd_base)

            dt_base = initrd_base + initrd_size;

        else

            dt_base = kernel_size + loadaddr;

        fdt = bamboo_load_device_tree(dt_base, ram_size,

                                      initrd_base, initrd_size, kernel_cmdline);

        if (fdt == NULL) {

            fprintf(stderr, "couldn't load device tree\n");

            exit(1);

        }

        cpu_synchronize_state(env);

        /* Set initial guest state. */

        env->gpr[1] = (16<<20) - 8;

        env->gpr[3] = dt_base;

        env->nip = entry;

        /* XXX we currently depend on KVM to create some initial TLB entries. */

    }

    if (kvm_enabled())

        kvmppc_init();

}


static int bochs_open(BlockDriverState *bs, QDict *options, int flags,

                      Error **errp)

{

    BDRVBochsState *s = bs->opaque;

    uint32_t i;

    struct bochs_header bochs;

    int ret;

    bs->file = bdrv_open_child(NULL, options, "file", bs, &child_file,

                               false, errp);

    if (!bs->file) {

        return -EINVAL;

    }

    bdrv_set_read_only(bs, true); /* no write support yet */

    ret = bdrv_pread(bs->file, 0, &bochs, sizeof(bochs));

    if (ret < 0) {

        return ret;

    }

    if (strcmp(bochs.magic, HEADER_MAGIC) ||

        strcmp(bochs.type, REDOLOG_TYPE) ||

        strcmp(bochs.subtype, GROWING_TYPE) ||

	((le32_to_cpu(bochs.version) != HEADER_VERSION) &&

	(le32_to_cpu(bochs.version) != HEADER_V1))) {

        error_setg(errp, "Image not in Bochs format");

        return -EINVAL;

    }

    if (le32_to_cpu(bochs.version) == HEADER_V1) {

        bs->total_sectors = le64_to_cpu(bochs.extra.redolog_v1.disk) / 512;

    } else {

        bs->total_sectors = le64_to_cpu(bochs.extra.redolog.disk) / 512;

    }

    /* Limit to 1M entries to avoid unbounded allocation. This is what is

     * needed for the largest image that bximage can create (~8 TB). */

    s->catalog_size = le32_to_cpu(bochs.catalog);

    if (s->catalog_size > 0x100000) {

        error_setg(errp, "Catalog size is too large");

        return -EFBIG;

    }

    s->catalog_bitmap = g_try_new(uint32_t, s->catalog_size);

    if (s->catalog_size && s->catalog_bitmap == NULL) {

        error_setg(errp, "Could not allocate memory for catalog");

        return -ENOMEM;

    }

    ret = bdrv_pread(bs->file, le32_to_cpu(bochs.header), s->catalog_bitmap,

                     s->catalog_size * 4);

    if (ret < 0) {

        goto fail;

    }

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

	le32_to_cpus(&s->catalog_bitmap[i]);

    s->data_offset = le32_to_cpu(bochs.header) + (s->catalog_size * 4);

    s->bitmap_blocks = 1 + (le32_to_cpu(bochs.bitmap) - 1) / 512;

    s->extent_blocks = 1 + (le32_to_cpu(bochs.extent) - 1) / 512;

    s->extent_size = le32_to_cpu(bochs.extent);

    if (s->extent_size < BDRV_SECTOR_SIZE) {

        /* bximage actually never creates extents smaller than 4k */

        error_setg(errp, "Extent size must be at least 512");

        ret = -EINVAL;

        goto fail;

    } else if (!is_power_of_2(s->extent_size)) {

        error_setg(errp, "Extent size %" PRIu32 " is not a power of two",

                   s->extent_size);

        ret = -EINVAL;

        goto fail;

    } else if (s->extent_size > 0x800000) {

        error_setg(errp, "Extent size %" PRIu32 " is too large",

                   s->extent_size);

        ret = -EINVAL;

        goto fail;

    }

    if (s->catalog_size < DIV_ROUND_UP(bs->total_sectors,

                                       s->extent_size / BDRV_SECTOR_SIZE))

    {

        error_setg(errp, "Catalog size is too small for this disk size");

        ret = -EINVAL;

        goto fail;

    }

    qemu_co_mutex_init(&s->lock);

    return 0;

fail:

    g_free(s->catalog_bitmap);

    return ret;

}


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

                                        const char *name,

                                        V9fsSynthNodeAttr *attr, int inode)

{

    V9fsSynthNode *node;

    /* Add directory type and remove write bits */

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

    node = g_malloc0(sizeof(V9fsSynthNode));

    if (attr) {

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

        node->attr = attr;

        node->attr->nlink++;

    } else {

        node->attr = &node->actual_attr;

        node->attr->inode = inode;

        node->attr->nlink = 1;

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

        node->attr->mode   = mode;

        node->attr->write = NULL;

        node->attr->read  = NULL;

    }

    node->private = node;

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

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

    return node;

}


void ff_eac3_output_frame_header(AC3EncodeContext *s)

{

    int blk, ch;

    AC3EncOptions *opt = &s->options;

    put_bits(&s->pb, 16, 0x0b77);                   /* sync word */

    /* BSI header */

    put_bits(&s->pb,  2, 0);                        /* stream type = independent */

    put_bits(&s->pb,  3, 0);                        /* substream id = 0 */

    put_bits(&s->pb, 11, (s->frame_size / 2) - 1);  /* frame size */

    if (s->bit_alloc.sr_shift) {

        put_bits(&s->pb, 2, 0x3);                   /* fscod2 */

        put_bits(&s->pb, 2, s->bit_alloc.sr_code);  /* sample rate code */

    } else {

        put_bits(&s->pb, 2, s->bit_alloc.sr_code);  /* sample rate code */

        put_bits(&s->pb, 2, 0x3);                   /* number of blocks = 6 */

    }

    put_bits(&s->pb, 3, s->channel_mode);           /* audio coding mode */

    put_bits(&s->pb, 1, s->lfe_on);                 /* LFE channel indicator */

    put_bits(&s->pb, 5, s->bitstream_id);           /* bitstream id (EAC3=16) */

    put_bits(&s->pb, 5, -opt->dialogue_level);      /* dialogue normalization level */

    put_bits(&s->pb, 1, 0);                         /* no compression gain */

    put_bits(&s->pb, 1, 0);                         /* no mixing metadata */

    /* TODO: mixing metadata */

    put_bits(&s->pb, 1, 0);                         /* no info metadata */

    /* TODO: info metadata */

    put_bits(&s->pb, 1, 0);                         /* no additional bit stream info */

    /* frame header */

    put_bits(&s->pb, 1, 1);                         /* exponent strategy syntax = each block */

    put_bits(&s->pb, 1, 0);                         /* aht enabled = no */

    put_bits(&s->pb, 2, 0);                         /* snr offset strategy = 1 */

    put_bits(&s->pb, 1, 0);                         /* transient pre-noise processing enabled = no */

    put_bits(&s->pb, 1, 0);                         /* block switch syntax enabled = no */

    put_bits(&s->pb, 1, 0);                         /* dither flag syntax enabled = no */

    put_bits(&s->pb, 1, 0);                         /* bit allocation model syntax enabled = no */

    put_bits(&s->pb, 1, 0);                         /* fast gain codes enabled = no */

    put_bits(&s->pb, 1, 0);                         /* dba syntax enabled = no */

    put_bits(&s->pb, 1, 0);                         /* skip field syntax enabled = no */

    put_bits(&s->pb, 1, 0);                         /* spx enabled = no */

    /* coupling strategy use flags */

    if (s->channel_mode > AC3_CHMODE_MONO) {

        put_bits(&s->pb, 1, s->blocks[0].cpl_in_use);

        for (blk = 1; blk < AC3_MAX_BLOCKS; blk++) {

            AC3Block *block = &s->blocks[blk];

            put_bits(&s->pb, 1, block->new_cpl_strategy);

            if (block->new_cpl_strategy)

                put_bits(&s->pb, 1, block->cpl_in_use);

        }

    }

    /* exponent strategy */

    for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)

        for (ch = !s->blocks[blk].cpl_in_use; ch <= s->fbw_channels; ch++)

            put_bits(&s->pb, 2, s->exp_strategy[ch][blk]);

    if (s->lfe_on) {

        for (blk = 0; blk < AC3_MAX_BLOCKS; blk++)

            put_bits(&s->pb, 1, s->exp_strategy[s->lfe_channel][blk]);

    }

    /* E-AC-3 to AC-3 converter exponent strategy (unfortunately not optional...) */

    for (ch = 1; ch <= s->fbw_channels; ch++)

        put_bits(&s->pb, 5, 0);

    /* snr offsets */

    put_bits(&s->pb, 6, s->coarse_snr_offset);

    put_bits(&s->pb, 4, s->fine_snr_offset[1]);

    /* block start info */

    put_bits(&s->pb, 1, 0);

}


static inline void gen_lods(DisasContext *s, int ot)

{

    gen_string_movl_A0_ESI(s);

    gen_op_ld_T0_A0(ot + s->mem_index);

    gen_op_mov_reg_T0(ot, R_EAX);

    gen_op_movl_T0_Dshift[ot]();

#ifdef TARGET_X86_64

    if (s->aflag == 2) {

        gen_op_addq_ESI_T0();

    } else

#endif

    if (s->aflag) {

        gen_op_addl_ESI_T0();

    } else {

        gen_op_addw_ESI_T0();

    }

}


static uint64_t hb_regs_read(void *opaque, target_phys_addr_t offset,

                             unsigned size)

{

    uint32_t *regs = opaque;

    uint32_t value = regs[offset/4];

    if ((offset == 0x100) || (offset == 0x108) || (offset == 0x10C)) {

        value |= 0x30000000;

    }

    return value;

}


size_t nbd_wr_sync(int fd, void *buffer, size_t size, bool do_read)

{

    size_t offset = 0;

    if (qemu_in_coroutine()) {

        if (do_read) {

            return qemu_co_recv(fd, buffer, size);

        } else {

            return qemu_co_send(fd, buffer, size);

        }

    }

    while (offset < size) {

        ssize_t len;

        if (do_read) {

            len = qemu_recv(fd, buffer + offset, size - offset, 0);

        } else {

            len = send(fd, buffer + offset, size - offset, 0);

        }

        if (len == -1)

            errno = socket_error();

        /* recoverable error */

        if (len == -1 && (errno == EAGAIN || errno == EINTR)) {

            continue;

        }

        /* eof */

        if (len == 0) {

            break;

        }

        /* unrecoverable error */

        if (len == -1) {

            return 0;

        }

        offset += len;

    }

    return offset;

}


static uint32_t vfio_pci_read_config(PCIDevice *pdev, uint32_t addr, int len)

{

    VFIODevice *vdev = DO_UPCAST(VFIODevice, pdev, pdev);

    uint32_t val = 0;

    /*

     * We only need QEMU PCI config support for the ROM BAR, the MSI and MSIX

     * capabilities, and the multifunction bit below.  We let VFIO handle

     * virtualizing everything else.  Performance is not a concern here.

     */

    if (ranges_overlap(addr, len, PCI_ROM_ADDRESS, 4) ||

        (pdev->cap_present & QEMU_PCI_CAP_MSIX &&

         ranges_overlap(addr, len, pdev->msix_cap, MSIX_CAP_LENGTH)) ||

        (pdev->cap_present & QEMU_PCI_CAP_MSI &&

         ranges_overlap(addr, len, pdev->msi_cap, vdev->msi_cap_size))) {

        val = pci_default_read_config(pdev, addr, len);

    } else {

        if (pread(vdev->fd, &val, len, vdev->config_offset + addr) != len) {

            error_report("%s(%04x:%02x:%02x.%x, 0x%x, 0x%x) failed: %m",

                         __func__, vdev->host.domain, vdev->host.bus,

                         vdev->host.slot, vdev->host.function, addr, len);

            return -errno;

        }

        val = le32_to_cpu(val);

    }

    /* Multifunction bit is virualized in QEMU */

    if (unlikely(ranges_overlap(addr, len, PCI_HEADER_TYPE, 1))) {

        uint32_t mask = PCI_HEADER_TYPE_MULTI_FUNCTION;

        if (len == 4) {

            mask <<= 16;

        }

        if (pdev->cap_present & QEMU_PCI_CAP_MULTIFUNCTION) {

            val |= mask;

        } else {

            val &= ~mask;

        }

    }

    DPRINTF("%s(%04x:%02x:%02x.%x, @0x%x, len=0x%x) %x\n", __func__,

            vdev->host.domain, vdev->host.bus, vdev->host.slot,

            vdev->host.function, addr, len, val);

    return val;

}


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

{

    CPUState *cs = CPU(dev);

    X86CPU *cpu = X86_CPU(dev);

    X86CPUClass *xcc = X86_CPU_GET_CLASS(dev);

    CPUX86State *env = &cpu->env;

    Error *local_err = NULL;

    static bool ht_warned;

    if (xcc->kvm_required && !kvm_enabled()) {

        char *name = x86_cpu_class_get_model_name(xcc);

        error_setg(&local_err, "CPU model '%s' requires KVM", name);

        g_free(name);

        goto out;

    }

    if (cpu->apic_id == UNASSIGNED_APIC_ID) {

        error_setg(errp, "apic-id property was not initialized properly");

        return;

    }

    x86_cpu_expand_features(cpu, &local_err);

    if (local_err) {

        goto out;

    }

    if (x86_cpu_filter_features(cpu) &&

        (cpu->check_cpuid || cpu->enforce_cpuid)) {

        x86_cpu_report_filtered_features(cpu);

        if (cpu->enforce_cpuid) {

            error_setg(&local_err,

                       kvm_enabled() ?

                           "Host doesn't support requested features" :

                           "TCG doesn't support requested features");

            goto out;

        }

    }

    /* On AMD CPUs, some CPUID[8000_0001].EDX bits must match the bits on

     * CPUID[1].EDX.

     */

    if (IS_AMD_CPU(env)) {

        env->features[FEAT_8000_0001_EDX] &= ~CPUID_EXT2_AMD_ALIASES;

        env->features[FEAT_8000_0001_EDX] |= (env->features[FEAT_1_EDX]

           & CPUID_EXT2_AMD_ALIASES);

    }

    /* For 64bit systems think about the number of physical bits to present.

     * ideally this should be the same as the host; anything other than matching

     * the host can cause incorrect guest behaviour.

     * QEMU used to pick the magic value of 40 bits that corresponds to

     * consumer AMD devices but nothing else.

     */

    if (env->features[FEAT_8000_0001_EDX] & CPUID_EXT2_LM) {

        if (kvm_enabled()) {

            uint32_t host_phys_bits = x86_host_phys_bits();

            static bool warned;

            if (cpu->host_phys_bits) {

                /* The user asked for us to use the host physical bits */

                cpu->phys_bits = host_phys_bits;

            }

            /* Print a warning if the user set it to a value that's not the

             * host value.

             */

            if (cpu->phys_bits != host_phys_bits && cpu->phys_bits != 0 &&

                !warned) {

                error_report("Warning: Host physical bits (%u)"

                                 " does not match phys-bits property (%u)",

                                 host_phys_bits, cpu->phys_bits);

                warned = true;

            }

            if (cpu->phys_bits &&

                (cpu->phys_bits > TARGET_PHYS_ADDR_SPACE_BITS ||

                cpu->phys_bits < 32)) {

                error_setg(errp, "phys-bits should be between 32 and %u "

                                 " (but is %u)",

                                 TARGET_PHYS_ADDR_SPACE_BITS, cpu->phys_bits);

                return;

            }

        } else {

            if (cpu->phys_bits && cpu->phys_bits != TCG_PHYS_ADDR_BITS) {

                error_setg(errp, "TCG only supports phys-bits=%u",

                                  TCG_PHYS_ADDR_BITS);

                return;

            }

        }

        /* 0 means it was not explicitly set by the user (or by machine

         * compat_props or by the host code above). In this case, the default

         * is the value used by TCG (40).

         */

        if (cpu->phys_bits == 0) {

            cpu->phys_bits = TCG_PHYS_ADDR_BITS;

        }

    } else {

        /* For 32 bit systems don't use the user set value, but keep

         * phys_bits consistent with what we tell the guest.

         */

        if (cpu->phys_bits != 0) {

            error_setg(errp, "phys-bits is not user-configurable in 32 bit");

            return;

        }

        if (env->features[FEAT_1_EDX] & CPUID_PSE36) {

            cpu->phys_bits = 36;

        } else {

            cpu->phys_bits = 32;

        }

    }

    cpu_exec_realizefn(cs, &local_err);

    if (local_err != NULL) {

        error_propagate(errp, local_err);

        return;

    }

    if (tcg_enabled()) {

        tcg_x86_init();

    }

#ifndef CONFIG_USER_ONLY

    qemu_register_reset(x86_cpu_machine_reset_cb, cpu);

    if (cpu->env.features[FEAT_1_EDX] & CPUID_APIC || smp_cpus > 1) {

        x86_cpu_apic_create(cpu, &local_err);

        if (local_err != NULL) {

            goto out;

        }

    }

#endif

    mce_init(cpu);

#ifndef CONFIG_USER_ONLY

    if (tcg_enabled()) {

        AddressSpace *as_normal = address_space_init_shareable(cs->memory,

                                                               "cpu-memory");

        AddressSpace *as_smm = g_new(AddressSpace, 1);

        cpu->cpu_as_mem = g_new(MemoryRegion, 1);

        cpu->cpu_as_root = g_new(MemoryRegion, 1);

        /* Outer container... */

        memory_region_init(cpu->cpu_as_root, OBJECT(cpu), "memory", ~0ull);

        memory_region_set_enabled(cpu->cpu_as_root, true);

        /* ... with two regions inside: normal system memory with low

         * priority, and...

         */

        memory_region_init_alias(cpu->cpu_as_mem, OBJECT(cpu), "memory",

                                 get_system_memory(), 0, ~0ull);

        memory_region_add_subregion_overlap(cpu->cpu_as_root, 0, cpu->cpu_as_mem, 0);

        memory_region_set_enabled(cpu->cpu_as_mem, true);

        address_space_init(as_smm, cpu->cpu_as_root, "CPU");

        cs->num_ases = 2;

        cpu_address_space_init(cs, as_normal, 0);

        cpu_address_space_init(cs, as_smm, 1);

        /* ... SMRAM with higher priority, linked from /machine/smram.  */

        cpu->machine_done.notify = x86_cpu_machine_done;

        qemu_add_machine_init_done_notifier(&cpu->machine_done);

    }

#endif

    qemu_init_vcpu(cs);

    /* Only Intel CPUs support hyperthreading. Even though QEMU fixes this

     * issue by adjusting CPUID_0000_0001_EBX and CPUID_8000_0008_ECX

     * based on inputs (sockets,cores,threads), it is still better to gives

     * users a warning.

     *

     * NOTE: the following code has to follow qemu_init_vcpu(). Otherwise

     * cs->nr_threads hasn't be populated yet and the checking is incorrect.

     */

    if (!IS_INTEL_CPU(env) && cs->nr_threads > 1 && !ht_warned) {

        error_report("AMD CPU doesn't support hyperthreading. Please configure"

                     " -smp options properly.");

        ht_warned = true;

    }

    x86_cpu_apic_realize(cpu, &local_err);

    if (local_err != NULL) {

        goto out;

    }

    cpu_reset(cs);

    xcc->parent_realize(dev, &local_err);

out:

    if (local_err != NULL) {

        error_propagate(errp, local_err);

        return;

    }

}


static void pci_realview_class_init(ObjectClass *class, void *data)

{

    DeviceClass *dc = DEVICE_CLASS(class);

    /* Reason: object_unref() hangs */

    dc->cannot_destroy_with_object_finalize_yet = true;

}