int ff_get_wav_header(AVFormatContext *s, AVIOContext *pb,

                      AVCodecContext *codec, int size, int big_endian)

{

    int id;

    uint64_t bitrate;

    if (size < 14) {

        avpriv_request_sample(codec, "wav header size < 14");

        return AVERROR_INVALIDDATA;

    }

    codec->codec_type  = AVMEDIA_TYPE_AUDIO;

    if (!big_endian) {

        id                 = avio_rl16(pb);

        if (id != 0x0165) {

            codec->channels    = avio_rl16(pb);

            codec->sample_rate = avio_rl32(pb);

            bitrate            = avio_rl32(pb) * 8LL;

            codec->block_align = avio_rl16(pb);

        }

    } else {

        id                 = avio_rb16(pb);

        codec->channels    = avio_rb16(pb);

        codec->sample_rate = avio_rb32(pb);

        bitrate            = avio_rb32(pb) * 8LL;

        codec->block_align = avio_rb16(pb);

    }

    if (size == 14) {  /* We're dealing with plain vanilla WAVEFORMAT */

        codec->bits_per_coded_sample = 8;

    } else {

        if (!big_endian) {

            codec->bits_per_coded_sample = avio_rl16(pb);

        } else {

            codec->bits_per_coded_sample = avio_rb16(pb);

        }

    }

    if (id == 0xFFFE) {

        codec->codec_tag = 0;

    } else {

        codec->codec_tag = id;

        codec->codec_id  = ff_wav_codec_get_id(id,

                                               codec->bits_per_coded_sample);

    }

    if (size >= 18 && id != 0x0165) {  /* We're obviously dealing with WAVEFORMATEX */

        int cbSize = avio_rl16(pb); /* cbSize */

        if (big_endian) {

            avpriv_report_missing_feature(codec, "WAVEFORMATEX support for RIFX files\n");

            return AVERROR_PATCHWELCOME;

        }

        size  -= 18;

        cbSize = FFMIN(size, cbSize);

        if (cbSize >= 22 && id == 0xfffe) { /* WAVEFORMATEXTENSIBLE */

            parse_waveformatex(pb, codec);

            cbSize -= 22;

            size   -= 22;

        }

        if (cbSize > 0) {

            av_freep(&codec->extradata);

            if (ff_get_extradata(codec, pb, cbSize) < 0)

                return AVERROR(ENOMEM);

            size -= cbSize;

        }

        /* It is possible for the chunk to contain garbage at the end */

        if (size > 0)

            avio_skip(pb, size);

    } else if (id == 0x0165 && size >= 32) {

        int nb_streams, i;

        size -= 4;

        av_freep(&codec->extradata);

        if (ff_get_extradata(codec, pb, size) < 0)

            return AVERROR(ENOMEM);

        nb_streams         = AV_RL16(codec->extradata + 4);

        codec->sample_rate = AV_RL32(codec->extradata + 12);

        codec->channels    = 0;

        bitrate            = 0;

        if (size < 8 + nb_streams * 20)

            return AVERROR_INVALIDDATA;

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

            codec->channels += codec->extradata[8 + i * 20 + 17];

    }

    if (bitrate > INT_MAX) {

        if (s->error_recognition & AV_EF_EXPLODE) {

            av_log(s, AV_LOG_ERROR,

                   "The bitrate %"PRIu64" is too large.\n",

                    bitrate);

            return AVERROR_INVALIDDATA;

        } else {

            av_log(s, AV_LOG_WARNING,

                   "The bitrate %"PRIu64" is too large, resetting to 0.",

                   bitrate);

            codec->bit_rate = 0;

        }

    } else {

        codec->bit_rate = bitrate;

    }

    if (codec->sample_rate <= 0) {

        av_log(s, AV_LOG_ERROR,

               "Invalid sample rate: %d\n", codec->sample_rate);

        return AVERROR_INVALIDDATA;

    }

    if (codec->codec_id == AV_CODEC_ID_AAC_LATM) {

        /* Channels and sample_rate values are those prior to applying SBR

         * and/or PS. */

        codec->channels    = 0;

        codec->sample_rate = 0;

    }

    /* override bits_per_coded_sample for G.726 */

    if (codec->codec_id == AV_CODEC_ID_ADPCM_G726 && codec->sample_rate)

        codec->bits_per_coded_sample = codec->bit_rate / codec->sample_rate;

    return 0;

}


static int xen_9pfs_connect(struct XenDevice *xendev)

{

    int i;

    Xen9pfsDev *xen_9pdev = container_of(xendev, Xen9pfsDev, xendev);

    V9fsState *s = &xen_9pdev->state;

    QemuOpts *fsdev;

    if (xenstore_read_fe_int(&xen_9pdev->xendev, "num-rings",

                             &xen_9pdev->num_rings) == -1 ||

        xen_9pdev->num_rings > MAX_RINGS || xen_9pdev->num_rings < 1) {

        return -1;

    }

    xen_9pdev->rings = g_malloc0(xen_9pdev->num_rings * sizeof(Xen9pfsRing));

    for (i = 0; i < xen_9pdev->num_rings; i++) {

        char *str;

        int ring_order;

        xen_9pdev->rings[i].priv = xen_9pdev;

        xen_9pdev->rings[i].evtchn = -1;

        xen_9pdev->rings[i].local_port = -1;

        str = g_strdup_printf("ring-ref%u", i);

        if (xenstore_read_fe_int(&xen_9pdev->xendev, str,

                                 &xen_9pdev->rings[i].ref) == -1) {

            goto out;

        }

        str = g_strdup_printf("event-channel-%u", i);

        if (xenstore_read_fe_int(&xen_9pdev->xendev, str,

                                 &xen_9pdev->rings[i].evtchn) == -1) {

            goto out;

        }

        xen_9pdev->rings[i].intf =  xengnttab_map_grant_ref(

                xen_9pdev->xendev.gnttabdev,

                xen_9pdev->xendev.dom,

                xen_9pdev->rings[i].ref,

                PROT_READ | PROT_WRITE);

        if (!xen_9pdev->rings[i].intf) {

            goto out;

        }

        ring_order = xen_9pdev->rings[i].intf->ring_order;

        if (ring_order > MAX_RING_ORDER) {

            goto out;

        }

        xen_9pdev->rings[i].ring_order = ring_order;

        xen_9pdev->rings[i].data = xengnttab_map_domain_grant_refs(

                xen_9pdev->xendev.gnttabdev,

                (1 << ring_order),

                xen_9pdev->xendev.dom,

                xen_9pdev->rings[i].intf->ref,

                PROT_READ | PROT_WRITE);

        if (!xen_9pdev->rings[i].data) {

            goto out;

        }

        xen_9pdev->rings[i].ring.in = xen_9pdev->rings[i].data;

        xen_9pdev->rings[i].ring.out = xen_9pdev->rings[i].data +

                                       XEN_FLEX_RING_SIZE(ring_order);

        xen_9pdev->rings[i].bh = qemu_bh_new(xen_9pfs_bh, &xen_9pdev->rings[i]);

        xen_9pdev->rings[i].out_cons = 0;

        xen_9pdev->rings[i].out_size = 0;

        xen_9pdev->rings[i].inprogress = false;

        xen_9pdev->rings[i].evtchndev = xenevtchn_open(NULL, 0);

        if (xen_9pdev->rings[i].evtchndev == NULL) {

            goto out;

        }

        fcntl(xenevtchn_fd(xen_9pdev->rings[i].evtchndev), F_SETFD, FD_CLOEXEC);

        xen_9pdev->rings[i].local_port = xenevtchn_bind_interdomain

                                            (xen_9pdev->rings[i].evtchndev,

                                             xendev->dom,

                                             xen_9pdev->rings[i].evtchn);

        if (xen_9pdev->rings[i].local_port == -1) {

            xen_pv_printf(xendev, 0,

                          "xenevtchn_bind_interdomain failed port=%d\n",

                          xen_9pdev->rings[i].evtchn);

            goto out;

        }

        xen_pv_printf(xendev, 2, "bind evtchn port %d\n", xendev->local_port);

        qemu_set_fd_handler(xenevtchn_fd(xen_9pdev->rings[i].evtchndev),

                xen_9pfs_evtchn_event, NULL, &xen_9pdev->rings[i]);

    }

    xen_9pdev->security_model = xenstore_read_be_str(xendev, "security_model");

    xen_9pdev->path = xenstore_read_be_str(xendev, "path");

    xen_9pdev->id = s->fsconf.fsdev_id =

        g_strdup_printf("xen9p%d", xendev->dev);

    xen_9pdev->tag = s->fsconf.tag = xenstore_read_fe_str(xendev, "tag");

    v9fs_register_transport(s, &xen_9p_transport);

    fsdev = qemu_opts_create(qemu_find_opts("fsdev"),

            s->fsconf.tag,

            1, NULL);

    qemu_opt_set(fsdev, "fsdriver", "local", NULL);

    qemu_opt_set(fsdev, "path", xen_9pdev->path, NULL);

    qemu_opt_set(fsdev, "security_model", xen_9pdev->security_model, NULL);

    qemu_opts_set_id(fsdev, s->fsconf.fsdev_id);

    qemu_fsdev_add(fsdev);

    v9fs_device_realize_common(s, NULL);

    return 0;

out:

    xen_9pfs_free(xendev);

    return -1;

}


static int subframe_count_exact(FlacEncodeContext *s, FlacSubframe *sub,

                                int pred_order)

{

    int p, porder, psize;

    int i, part_end;

    int count = 0;

    /* subframe header */

    count += 8;

    /* subframe */

    if (sub->type == FLAC_SUBFRAME_CONSTANT) {

        count += sub->obits;

    } else if (sub->type == FLAC_SUBFRAME_VERBATIM) {

        count += s->frame.blocksize * sub->obits;

    } else {

        /* warm-up samples */

        count += pred_order * sub->obits;

        /* LPC coefficients */

        if (sub->type == FLAC_SUBFRAME_LPC)

            count += 4 + 5 + pred_order * s->options.lpc_coeff_precision;

        /* rice-encoded block */

        count += 2;

        /* partition order */

        porder = sub->rc.porder;

        psize  = s->frame.blocksize >> porder;

        count += 4;

        /* residual */

        i        = pred_order;

        part_end = psize;

        for (p = 0; p < 1 << porder; p++) {

            int k = sub->rc.params[p];

            count += 4;

            count += rice_count_exact(&sub->residual[i], part_end - i, k);

            i = part_end;

            part_end = FFMIN(s->frame.blocksize, part_end + psize);

        }

    }

    return count;

}


static void ppc_spapr_init(QEMUMachineInitArgs *args)

{

    ram_addr_t ram_size = args->ram_size;

    const char *cpu_model = args->cpu_model;

    const char *kernel_filename = args->kernel_filename;

    const char *kernel_cmdline = args->kernel_cmdline;

    const char *initrd_filename = args->initrd_filename;

    const char *boot_device = args->boot_order;

    PowerPCCPU *cpu;

    CPUPPCState *env;

    PCIHostState *phb;

    int i;

    MemoryRegion *sysmem = get_system_memory();

    MemoryRegion *ram = g_new(MemoryRegion, 1);

    hwaddr rma_alloc_size;

    uint32_t initrd_base = 0;

    long kernel_size = 0, initrd_size = 0;

    long load_limit, rtas_limit, fw_size;

    bool kernel_le = false;

    char *filename;

    msi_supported = true;

    spapr = g_malloc0(sizeof(*spapr));

    QLIST_INIT(&spapr->phbs);

    cpu_ppc_hypercall = emulate_spapr_hypercall;

    /* Allocate RMA if necessary */

    rma_alloc_size = kvmppc_alloc_rma("ppc_spapr.rma", sysmem);

    if (rma_alloc_size == -1) {

        hw_error("qemu: Unable to create RMA\n");

        exit(1);

    }

    if (rma_alloc_size && (rma_alloc_size < ram_size)) {

        spapr->rma_size = rma_alloc_size;

    } else {

        spapr->rma_size = ram_size;

        /* With KVM, we don't actually know whether KVM supports an

         * unbounded RMA (PR KVM) or is limited by the hash table size

         * (HV KVM using VRMA), so we always assume the latter

         *

         * In that case, we also limit the initial allocations for RTAS

         * etc... to 256M since we have no way to know what the VRMA size

         * is going to be as it depends on the size of the hash table

         * isn't determined yet.

         */

        if (kvm_enabled()) {

            spapr->vrma_adjust = 1;

            spapr->rma_size = MIN(spapr->rma_size, 0x10000000);

        }

    }

    /* We place the device tree and RTAS just below either the top of the RMA,

     * or just below 2GB, whichever is lowere, so that it can be

     * processed with 32-bit real mode code if necessary */

    rtas_limit = MIN(spapr->rma_size, 0x80000000);

    spapr->rtas_addr = rtas_limit - RTAS_MAX_SIZE;

    spapr->fdt_addr = spapr->rtas_addr - FDT_MAX_SIZE;

    load_limit = spapr->fdt_addr - FW_OVERHEAD;

    /* We aim for a hash table of size 1/128 the size of RAM.  The

     * normal rule of thumb is 1/64 the size of RAM, but that's much

     * more than needed for the Linux guests we support. */

    spapr->htab_shift = 18; /* Minimum architected size */

    while (spapr->htab_shift <= 46) {

        if ((1ULL << (spapr->htab_shift + 7)) >= ram_size) {

            break;

        }

        spapr->htab_shift++;

    }

    /* Set up Interrupt Controller before we create the VCPUs */

    spapr->icp = xics_system_init(smp_cpus * kvmppc_smt_threads() / smp_threads,

                                  XICS_IRQS);

    spapr->next_irq = XICS_IRQ_BASE;

    /* init CPUs */

    if (cpu_model == NULL) {

        cpu_model = kvm_enabled() ? "host" : "POWER7";

    }

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

        cpu = cpu_ppc_init(cpu_model);

        if (cpu == NULL) {

            fprintf(stderr, "Unable to find PowerPC CPU definition\n");

            exit(1);

        }

        env = &cpu->env;

        xics_cpu_setup(spapr->icp, cpu);

        /* Set time-base frequency to 512 MHz */

        cpu_ppc_tb_init(env, TIMEBASE_FREQ);

        /* PAPR always has exception vectors in RAM not ROM. To ensure this,

         * MSR[IP] should never be set.

         */

        env->msr_mask &= ~(1 << 6);

        /* Tell KVM that we're in PAPR mode */

        if (kvm_enabled()) {

            kvmppc_set_papr(cpu);

        }

        qemu_register_reset(spapr_cpu_reset, cpu);

    }

    /* allocate RAM */

    spapr->ram_limit = ram_size;

    if (spapr->ram_limit > rma_alloc_size) {

        ram_addr_t nonrma_base = rma_alloc_size;

        ram_addr_t nonrma_size = spapr->ram_limit - rma_alloc_size;

        memory_region_init_ram(ram, NULL, "ppc_spapr.ram", nonrma_size);

        vmstate_register_ram_global(ram);

        memory_region_add_subregion(sysmem, nonrma_base, ram);

    }

    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, "spapr-rtas.bin");

    spapr->rtas_size = load_image_targphys(filename, spapr->rtas_addr,

                                           rtas_limit - spapr->rtas_addr);

    if (spapr->rtas_size < 0) {

        hw_error("qemu: could not load LPAR rtas '%s'\n", filename);

        exit(1);

    }

    if (spapr->rtas_size > RTAS_MAX_SIZE) {

        hw_error("RTAS too big ! 0x%lx bytes (max is 0x%x)\n",

                 spapr->rtas_size, RTAS_MAX_SIZE);

        exit(1);

    }

    g_free(filename);

    /* Set up EPOW events infrastructure */

    spapr_events_init(spapr);

    /* Set up VIO bus */

    spapr->vio_bus = spapr_vio_bus_init();

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

        if (serial_hds[i]) {

            spapr_vty_create(spapr->vio_bus, serial_hds[i]);

        }

    }

    /* We always have at least the nvram device on VIO */

    spapr_create_nvram(spapr);

    /* Set up PCI */

    spapr_pci_msi_init(spapr, SPAPR_PCI_MSI_WINDOW);

    spapr_pci_rtas_init();

    phb = spapr_create_phb(spapr, 0);

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

        NICInfo *nd = &nd_table[i];

        if (!nd->model) {

            nd->model = g_strdup("ibmveth");

        }

        if (strcmp(nd->model, "ibmveth") == 0) {

            spapr_vlan_create(spapr->vio_bus, nd);

        } else {

            pci_nic_init_nofail(&nd_table[i], phb->bus, nd->model, NULL);

        }

    }

    for (i = 0; i <= drive_get_max_bus(IF_SCSI); i++) {

        spapr_vscsi_create(spapr->vio_bus);

    }

    /* Graphics */

    if (spapr_vga_init(phb->bus)) {

        spapr->has_graphics = true;

    }

    if (usb_enabled(spapr->has_graphics)) {

        pci_create_simple(phb->bus, -1, "pci-ohci");

        if (spapr->has_graphics) {

            usbdevice_create("keyboard");

            usbdevice_create("mouse");

        }

    }

    if (spapr->rma_size < (MIN_RMA_SLOF << 20)) {

        fprintf(stderr, "qemu: pSeries SLOF firmware requires >= "

                "%ldM guest RMA (Real Mode Area memory)\n", MIN_RMA_SLOF);

        exit(1);

    }

    if (kernel_filename) {

        uint64_t lowaddr = 0;

        kernel_size = load_elf(kernel_filename, translate_kernel_address, NULL,

                               NULL, &lowaddr, NULL, 1, ELF_MACHINE, 0);

        if (kernel_size < 0) {

            kernel_size = load_elf(kernel_filename,

                                   translate_kernel_address, NULL,

                                   NULL, &lowaddr, NULL, 0, ELF_MACHINE, 0);

            kernel_le = kernel_size > 0;

        }

        if (kernel_size < 0) {

            kernel_size = load_image_targphys(kernel_filename,

                                              KERNEL_LOAD_ADDR,

                                              load_limit - KERNEL_LOAD_ADDR);

        }

        if (kernel_size < 0) {

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

                    kernel_filename);

            exit(1);

        }

        /* load initrd */

        if (initrd_filename) {

            /* Try to locate the initrd in the gap between the kernel

             * and the firmware. Add a bit of space just in case

             */

            initrd_base = (KERNEL_LOAD_ADDR + kernel_size + 0x1ffff) & ~0xffff;

            initrd_size = load_image_targphys(initrd_filename, initrd_base,

                                              load_limit - initrd_base);

            if (initrd_size < 0) {

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

                        initrd_filename);

                exit(1);

            }

        } else {

            initrd_base = 0;

            initrd_size = 0;

        }

    }

    if (bios_name == NULL) {

        bios_name = FW_FILE_NAME;

    }

    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);

    fw_size = load_image_targphys(filename, 0, FW_MAX_SIZE);

    if (fw_size < 0) {

        hw_error("qemu: could not load LPAR rtas '%s'\n", filename);

        exit(1);

    }

    g_free(filename);

    spapr->entry_point = 0x100;

    vmstate_register(NULL, 0, &vmstate_spapr, spapr);

    register_savevm_live(NULL, "spapr/htab", -1, 1,

                         &savevm_htab_handlers, spapr);

    /* Prepare the device tree */

    spapr->fdt_skel = spapr_create_fdt_skel(cpu_model,

                                            initrd_base, initrd_size,

                                            kernel_size, kernel_le,

                                            boot_device, kernel_cmdline,

                                            spapr->epow_irq);

    assert(spapr->fdt_skel != NULL);

}


static int mpeg1_decode_sequence(AVCodecContext *avctx,

                                 UINT8 *buf, int buf_size)

{

    Mpeg1Context *s1 = avctx->priv_data;

    MpegEncContext *s = &s1->mpeg_enc_ctx;

    int width, height, i, v, j;

    float aspect;

    init_get_bits(&s->gb, buf, buf_size);

    width = get_bits(&s->gb, 12);

    height = get_bits(&s->gb, 12);

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

    if(!s->mpeg2){

        aspect= mpeg1_aspect[s->aspect_ratio_info];

        if(aspect!=0.0) avctx->aspect_ratio= width/(aspect*height);

    }

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

    if (s->frame_rate_index == 0)

        return -1;

    s->bit_rate = get_bits(&s->gb, 18) * 400;

    if (get_bits1(&s->gb) == 0) /* marker */

        return -1;

    if (width <= 0 || height <= 0 ||

        (width % 2) != 0 || (height % 2) != 0)

        return -1;

    if (width != s->width ||

        height != s->height) {

        /* start new mpeg1 context decoding */

        s->out_format = FMT_MPEG1;

        if (s1->mpeg_enc_ctx_allocated) {

            MPV_common_end(s);

        }

        s->width = width;

        s->height = height;

        avctx->has_b_frames= 1;

        s->avctx = avctx;

        avctx->width = width;

        avctx->height = height;

        if (s->frame_rate_index >= 9) {

            /* at least give a valid frame rate (some old mpeg1 have this) */

            avctx->frame_rate = 25 * FRAME_RATE_BASE;

        } else {

            avctx->frame_rate = frame_rate_tab[s->frame_rate_index];

        }

        s->frame_rate = avctx->frame_rate;

        avctx->bit_rate = s->bit_rate;

        if (MPV_common_init(s) < 0)

            return -1;

        s1->mpeg_enc_ctx_allocated = 1;

    }

    skip_bits(&s->gb, 10); /* vbv_buffer_size */

    skip_bits(&s->gb, 1);

    /* get matrix */

    if (get_bits1(&s->gb)) {

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

            v = get_bits(&s->gb, 8);

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

            s->intra_matrix[j] = v;

            s->chroma_intra_matrix[j] = v;

        }

#ifdef DEBUG

        dprintf("intra matrix present\n");

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

            dprintf(" %d", s->intra_matrix[s->intra_scantable.permutated[i]]);

        printf("\n");

#endif

    } else {

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

            int j= s->idct_permutation[i];

            v = ff_mpeg1_default_intra_matrix[i];

            s->intra_matrix[j] = v;

            s->chroma_intra_matrix[j] = v;

        }

    }

    if (get_bits1(&s->gb)) {

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

            v = get_bits(&s->gb, 8);

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

            s->inter_matrix[j] = v;

            s->chroma_inter_matrix[j] = v;

        }

#ifdef DEBUG

        dprintf("non intra matrix present\n");

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

            dprintf(" %d", s->inter_matrix[s->intra_scantable.permutated[i]]);

        printf("\n");

#endif

    } else {

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

            int j= s->idct_permutation[i];

            v = ff_mpeg1_default_non_intra_matrix[i];

            s->inter_matrix[j] = v;

            s->chroma_inter_matrix[j] = v;

        }

    }

    /* we set mpeg2 parameters so that it emulates mpeg1 */

    s->progressive_sequence = 1;

    s->progressive_frame = 1;

    s->picture_structure = PICT_FRAME;

    s->frame_pred_frame_dct = 1;

    s->mpeg2 = 0;

    avctx->sub_id = 1; /* indicates mpeg1 */

    return 0;

}


static uint32_t drc_set_unusable(sPAPRDRConnector *drc)

{

    drc->allocation_state = SPAPR_DR_ALLOCATION_STATE_UNUSABLE;

    if (drc->awaiting_release) {

        uint32_t drc_index = spapr_drc_index(drc);

        trace_spapr_drc_set_allocation_state_finalizing(drc_index);

        spapr_drc_detach(drc);

    }

    return RTAS_OUT_SUCCESS;

}


static void scsi_read_request(SCSIDiskReq *r)

{

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

    uint32_t n;

    if (r->sector_count == (uint32_t)-1) {

        DPRINTF("Read buf_len=%zd\n", r->iov.iov_len);

        r->sector_count = 0;

        scsi_req_data(&r->req, r->iov.iov_len);

        return;

    }

    DPRINTF("Read sector_count=%d\n", r->sector_count);

    if (r->sector_count == 0) {

        scsi_command_complete(r, GOOD, NO_SENSE);

        return;

    }

    /* No data transfer may already be in progress */

    assert(r->req.aiocb == NULL);

    n = r->sector_count;

    if (n > SCSI_DMA_BUF_SIZE / 512)

        n = SCSI_DMA_BUF_SIZE / 512;

    r->iov.iov_len = n * 512;

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

    r->req.aiocb = bdrv_aio_readv(s->bs, r->sector, &r->qiov, n,

                              scsi_read_complete, r);

    if (r->req.aiocb == NULL) {

        scsi_read_complete(r, -EIO);

    }

}


static void lm32_evr_init(MachineState *machine)

{

    const char *cpu_model = machine->cpu_model;

    const char *kernel_filename = machine->kernel_filename;

    LM32CPU *cpu;

    CPULM32State *env;

    DriveInfo *dinfo;

    MemoryRegion *address_space_mem =  get_system_memory();

    MemoryRegion *phys_ram = g_new(MemoryRegion, 1);

    qemu_irq irq[32];

    ResetInfo *reset_info;

    int i;

    /* memory map */

    hwaddr flash_base  = 0x04000000;

    size_t flash_sector_size       = 256 * 1024;

    size_t flash_size              = 32 * 1024 * 1024;

    hwaddr ram_base    = 0x08000000;

    size_t ram_size                = 64 * 1024 * 1024;

    hwaddr timer0_base = 0x80002000;

    hwaddr uart0_base  = 0x80006000;

    hwaddr timer1_base = 0x8000a000;

    int uart0_irq                  = 0;

    int timer0_irq                 = 1;

    int timer1_irq                 = 3;

    reset_info = g_malloc0(sizeof(ResetInfo));

    if (cpu_model == NULL) {

        cpu_model = "lm32-full";

    }

    cpu = LM32_CPU(cpu_generic_init(TYPE_LM32_CPU, cpu_model));

    if (cpu == NULL) {

        fprintf(stderr, "qemu: unable to find CPU '%s'\n", cpu_model);

        exit(1);

    }

    env = &cpu->env;

    reset_info->cpu = cpu;

    reset_info->flash_base = flash_base;

    memory_region_allocate_system_memory(phys_ram, NULL, "lm32_evr.sdram",

                                         ram_size);

    memory_region_add_subregion(address_space_mem, ram_base, phys_ram);

    dinfo = drive_get(IF_PFLASH, 0, 0);

    /* Spansion S29NS128P */

    pflash_cfi02_register(flash_base, NULL, "lm32_evr.flash", flash_size,

                          dinfo ? blk_by_legacy_dinfo(dinfo) : NULL,

                          flash_sector_size, flash_size / flash_sector_size,

                          1, 2, 0x01, 0x7e, 0x43, 0x00, 0x555, 0x2aa, 1);

    /* create irq lines */

    env->pic_state = lm32_pic_init(qemu_allocate_irq(cpu_irq_handler, cpu, 0));

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

        irq[i] = qdev_get_gpio_in(env->pic_state, i);

    }

    lm32_uart_create(uart0_base, irq[uart0_irq], serial_hds[0]);

    sysbus_create_simple("lm32-timer", timer0_base, irq[timer0_irq]);

    sysbus_create_simple("lm32-timer", timer1_base, irq[timer1_irq]);

    /* make sure juart isn't the first chardev */

    env->juart_state = lm32_juart_init(serial_hds[1]);

    reset_info->bootstrap_pc = flash_base;

    if (kernel_filename) {

        uint64_t entry;

        int kernel_size;

        kernel_size = load_elf(kernel_filename, NULL, NULL, &entry, NULL, NULL,

                               1, EM_LATTICEMICO32, 0, 0);

        reset_info->bootstrap_pc = entry;

        if (kernel_size < 0) {

            kernel_size = load_image_targphys(kernel_filename, ram_base,

                                              ram_size);

            reset_info->bootstrap_pc = ram_base;

        }

        if (kernel_size < 0) {

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

                    kernel_filename);

            exit(1);

        }

    }

    qemu_register_reset(main_cpu_reset, reset_info);

}


aio_write_f(int argc, char **argv)

{

	char *p;

	int count = 0;

	int nr_iov, i, c;

	int pattern = 0xcd;

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

	BlockDriverAIOCB *acb;

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

		switch (c) {

		case 'C':

			ctx->Cflag = 1;

			break;

		case 'q':

			ctx->qflag = 1;

			break;

		case 'P':

			pattern = atoi(optarg);

			break;

		default:

			return command_usage(&aio_write_cmd);

		}

	}

	if (optind > argc - 2)

		return command_usage(&aio_write_cmd);

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

	if (ctx->offset < 0) {

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

		return 0;

	}

	optind++;

	if (ctx->offset & 0x1ff) {

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

			(long long)ctx->offset);

		return 0;

	}

	if (count & 0x1ff) {

		printf("count %d is not sector aligned\n",

			count);

		return 0;

	}

	for (i = optind; i < argc; i++) {

	        size_t len;

		len = cvtnum(argv[optind]);

		if (len < 0) {

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

			return 0;

		}

		count += len;

	}

	nr_iov = argc - optind;

	qemu_iovec_init(&ctx->qiov, nr_iov);

	ctx->buf = p = qemu_io_alloc(count, pattern);

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

	        size_t len;

		len = cvtnum(argv[optind]);

		if (len < 0) {

			printf("non-numeric length argument -- %s\n",

				argv[optind]);

			return 0;

		}

		qemu_iovec_add(&ctx->qiov, p, len);

		p += len;

		optind++;

	}

	gettimeofday(&ctx->t1, NULL);

	acb = bdrv_aio_writev(bs, ctx->offset >> 9, &ctx->qiov,

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

	if (!acb)

		return -EIO;

	return 0;

}


static void vc1_inv_trans_8x8_dc_c(uint8_t *dest, int linesize, DCTELEM *block)

{

    int i;

    int dc = block[0];

    const uint8_t *cm;

    dc = (3 * dc +  1) >> 1;

    dc = (3 * dc + 16) >> 5;

    cm = ff_cropTbl + MAX_NEG_CROP + dc;

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

        dest[0] = cm[dest[0]];

        dest[1] = cm[dest[1]];

        dest[2] = cm[dest[2]];

        dest[3] = cm[dest[3]];

        dest[4] = cm[dest[4]];

        dest[5] = cm[dest[5]];

        dest[6] = cm[dest[6]];

        dest[7] = cm[dest[7]];

        dest += linesize;

    }

}


static int vmdk_parse_extents(const char *desc, BlockDriverState *bs,

        const char *desc_file_path)

{

    int ret;

    char access[11];

    char type[11];

    char fname[512];

    const char *p = desc;

    int64_t sectors = 0;

    int64_t flat_offset;

    char extent_path[PATH_MAX];

    BlockDriverState *extent_file;

    Error *local_err = NULL;

    while (*p) {

        /* parse extent line:

         * RW [size in sectors] FLAT "file-name.vmdk" OFFSET

         * or

         * RW [size in sectors] SPARSE "file-name.vmdk"

         */

        flat_offset = -1;

        ret = sscanf(p, "%10s %" SCNd64 " %10s \"%511[^\n\r\"]\" %" SCNd64,

                access, &sectors, type, fname, &flat_offset);

        if (ret < 4 || strcmp(access, "RW")) {

            goto next_line;

        } else if (!strcmp(type, "FLAT")) {

            if (ret != 5 || flat_offset < 0) {

                return -EINVAL;

            }

        } else if (ret != 4) {

            return -EINVAL;

        }

        if (sectors <= 0 ||

            (strcmp(type, "FLAT") && strcmp(type, "SPARSE") &&

             strcmp(type, "VMFS") && strcmp(type, "VMFSSPARSE")) ||

            (strcmp(access, "RW"))) {

            goto next_line;

        }

        path_combine(extent_path, sizeof(extent_path),

                desc_file_path, fname);

        ret = bdrv_file_open(&extent_file, extent_path, NULL, bs->open_flags,

                             &local_err);

        if (ret) {

            qerror_report_err(local_err);

            error_free(local_err);

            return ret;

        }

        /* save to extents array */

        if (!strcmp(type, "FLAT") || !strcmp(type, "VMFS")) {

            /* FLAT extent */

            VmdkExtent *extent;

            ret = vmdk_add_extent(bs, extent_file, true, sectors,

                            0, 0, 0, 0, sectors, &extent);

            if (ret < 0) {

                return ret;

            }

            extent->flat_start_offset = flat_offset << 9;

        } else if (!strcmp(type, "SPARSE") || !strcmp(type, "VMFSSPARSE")) {

            /* SPARSE extent and VMFSSPARSE extent are both "COWD" sparse file*/

            ret = vmdk_open_sparse(bs, extent_file, bs->open_flags);

            if (ret) {

                bdrv_unref(extent_file);

                return ret;

            }

        } else {

            fprintf(stderr,

                "VMDK: Not supported extent type \"%s\""".\n", type);

            return -ENOTSUP;

        }

next_line:

        /* move to next line */

        while (*p && *p != '\n') {

            p++;

        }

        p++;

    }

    return 0;

}


static void compute_rematrixing_strategy(AC3EncodeContext *s)

{

    int nb_coefs;

    int blk, bnd, i;

    AC3Block *block, *block0;

    s->num_rematrixing_bands = 4;

    if (s->rematrixing & AC3_REMATRIXING_IS_STATIC)

        return;

    nb_coefs = FFMIN(s->nb_coefs[0], s->nb_coefs[1]);

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

        block = &s->blocks[blk];

        block->new_rematrixing_strategy = !blk;

        for (bnd = 0; bnd < s->num_rematrixing_bands; bnd++) {

            /* calculate calculate sum of squared coeffs for one band in one block */

            int start = ff_ac3_rematrix_band_tab[bnd];

            int end   = FFMIN(nb_coefs, ff_ac3_rematrix_band_tab[bnd+1]);

            CoefSumType sum[4] = {0,};

            for (i = start; i < end; i++) {

                CoefType lt = block->mdct_coef[0][i];

                CoefType rt = block->mdct_coef[1][i];

                CoefType md = lt + rt;

                CoefType sd = lt - rt;

                sum[0] += lt * lt;

                sum[1] += rt * rt;

                sum[2] += md * md;

                sum[3] += sd * sd;

            }

            /* compare sums to determine if rematrixing will be used for this band */

            if (FFMIN(sum[2], sum[3]) < FFMIN(sum[0], sum[1]))

                block->rematrixing_flags[bnd] = 1;

            else

                block->rematrixing_flags[bnd] = 0;

            /* determine if new rematrixing flags will be sent */

            if (blk &&

                block->rematrixing_flags[bnd] != block0->rematrixing_flags[bnd]) {

                block->new_rematrixing_strategy = 1;

            }

        }

        block0 = block;

    }

}


void OPPROTO op_udiv_T1_T0(void)
{
    uint64_t x0;
    uint32_t x1;
    x0 = T0 | ((uint64_t) (env->y) << 32);
    x1 = T1;
    x0 = x0 / x1;
    if (x0 > 0xffffffff) {
	T0 = 0xffffffff;
	T1 = 1;
    } else {
	T0 = x0;
	T1 = 0;
    FORCE_RET();


void cpu_x86_init_mmu(CPUX86State *env)

{

    a20_enabled = 1;

    a20_mask = 0xffffffff;

    last_pg_state = -1;

    cpu_x86_update_cr0(env);

}


int qemu_cpu_self(void *env)

{

    return 1;

}


static void net_vhost_link_down(VhostUserState *s, bool link_down)

{

    s->nc.link_down = link_down;

    if (s->nc.peer) {

        s->nc.peer->link_down = link_down;

    }

    if (s->nc.info->link_status_changed) {

        s->nc.info->link_status_changed(&s->nc);

    }

    if (s->nc.peer && s->nc.peer->info->link_status_changed) {

        s->nc.peer->info->link_status_changed(s->nc.peer);

    }

}


static int rv34_decode_mv(RV34DecContext *r, int block_type)

{

    MpegEncContext *s = &r->s;

    GetBitContext *gb = &s->gb;

    int i, j, k, l;

    int mv_pos = s->mb_x * 2 + s->mb_y * 2 * s->b8_stride;

    int next_bt;

    memset(r->dmv, 0, sizeof(r->dmv));

    for(i = 0; i < num_mvs[block_type]; i++){

        r->dmv[i][0] = svq3_get_se_golomb(gb);

        r->dmv[i][1] = svq3_get_se_golomb(gb);

    }

    switch(block_type){

    case RV34_MB_TYPE_INTRA:

    case RV34_MB_TYPE_INTRA16x16:

        ZERO8x2(s->current_picture_ptr->f.motion_val[0][s->mb_x * 2 + s->mb_y * 2 * s->b8_stride], s->b8_stride);

        return 0;

    case RV34_MB_SKIP:

        if(s->pict_type == AV_PICTURE_TYPE_P){

            ZERO8x2(s->current_picture_ptr->f.motion_val[0][s->mb_x * 2 + s->mb_y * 2 * s->b8_stride], s->b8_stride);

            rv34_mc_1mv (r, block_type, 0, 0, 0, 2, 2, 0);

            break;

        }

    case RV34_MB_B_DIRECT:

        //surprisingly, it uses motion scheme from next reference frame

        /* wait for the current mb row to be finished */

        if (HAVE_THREADS && (s->avctx->active_thread_type & FF_THREAD_FRAME))

            ff_thread_await_progress(&s->next_picture_ptr->f, s->mb_y - 1, 0);

        next_bt = s->next_picture_ptr->f.mb_type[s->mb_x + s->mb_y * s->mb_stride];

        if(IS_INTRA(next_bt) || IS_SKIP(next_bt)){

            ZERO8x2(s->current_picture_ptr->f.motion_val[0][s->mb_x * 2 + s->mb_y * 2 * s->b8_stride], s->b8_stride);

            ZERO8x2(s->current_picture_ptr->f.motion_val[1][s->mb_x * 2 + s->mb_y * 2 * s->b8_stride], s->b8_stride);

        }else

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

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

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

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

                            s->current_picture_ptr->f.motion_val[l][mv_pos + i + j*s->b8_stride][k] = calc_add_mv(r, l, s->next_picture_ptr->f.motion_val[0][mv_pos + i + j*s->b8_stride][k]);

        if(!(IS_16X8(next_bt) || IS_8X16(next_bt) || IS_8X8(next_bt))) //we can use whole macroblock MC

            rv34_mc_2mv(r, block_type);

        else

            rv34_mc_2mv_skip(r);

        ZERO8x2(s->current_picture_ptr->f.motion_val[0][s->mb_x * 2 + s->mb_y * 2 * s->b8_stride], s->b8_stride);

        break;

    case RV34_MB_P_16x16:

    case RV34_MB_P_MIX16x16:

        rv34_pred_mv(r, block_type, 0, 0);

        rv34_mc_1mv (r, block_type, 0, 0, 0, 2, 2, 0);

        break;

    case RV34_MB_B_FORWARD:

    case RV34_MB_B_BACKWARD:

        r->dmv[1][0] = r->dmv[0][0];

        r->dmv[1][1] = r->dmv[0][1];

        if(r->rv30)

            rv34_pred_mv_rv3(r, block_type, block_type == RV34_MB_B_BACKWARD);

        else

            rv34_pred_mv_b  (r, block_type, block_type == RV34_MB_B_BACKWARD);

        rv34_mc_1mv     (r, block_type, 0, 0, 0, 2, 2, block_type == RV34_MB_B_BACKWARD);

        break;

    case RV34_MB_P_16x8:

    case RV34_MB_P_8x16:

        rv34_pred_mv(r, block_type, 0, 0);

        rv34_pred_mv(r, block_type, 1 + (block_type == RV34_MB_P_16x8), 1);

        if(block_type == RV34_MB_P_16x8){

            rv34_mc_1mv(r, block_type, 0, 0, 0,            2, 1, 0);

            rv34_mc_1mv(r, block_type, 0, 8, s->b8_stride, 2, 1, 0);

        }

        if(block_type == RV34_MB_P_8x16){

            rv34_mc_1mv(r, block_type, 0, 0, 0, 1, 2, 0);

            rv34_mc_1mv(r, block_type, 8, 0, 1, 1, 2, 0);

        }

        break;

    case RV34_MB_B_BIDIR:

        rv34_pred_mv_b  (r, block_type, 0);

        rv34_pred_mv_b  (r, block_type, 1);

        rv34_mc_2mv     (r, block_type);

        break;

    case RV34_MB_P_8x8:

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

            rv34_pred_mv(r, block_type, i, i);

            rv34_mc_1mv (r, block_type, (i&1)<<3, (i&2)<<2, (i&1)+(i>>1)*s->b8_stride, 1, 1, 0);

        }

        break;

    }

    return 0;

}


static void mirror_start_job(BlockDriverState *bs, BlockDriverState *target,

                             const char *replaces,

                             int64_t speed, uint32_t granularity,

                             int64_t buf_size,

                             BlockdevOnError on_source_error,

                             BlockdevOnError on_target_error,

                             bool unmap,

                             BlockCompletionFunc *cb,

                             void *opaque, Error **errp,

                             const BlockJobDriver *driver,

                             bool is_none_mode, BlockDriverState *base)

{

    MirrorBlockJob *s;

    if (granularity == 0) {

        granularity = bdrv_get_default_bitmap_granularity(target);

    }

    assert ((granularity & (granularity - 1)) == 0);

    if ((on_source_error == BLOCKDEV_ON_ERROR_STOP ||

         on_source_error == BLOCKDEV_ON_ERROR_ENOSPC) &&

        (!bs->blk || !blk_iostatus_is_enabled(bs->blk))) {

        error_setg(errp, QERR_INVALID_PARAMETER, "on-source-error");

        return;

    }

    if (buf_size < 0) {

        error_setg(errp, "Invalid parameter 'buf-size'");

        return;

    }

    if (buf_size == 0) {

        buf_size = DEFAULT_MIRROR_BUF_SIZE;

    }

    /* We can't support this case as long as the block layer can't handle

     * multiple BlockBackends per BlockDriverState. */

    if (replaces) {

        replaced_bs = bdrv_lookup_bs(replaces, replaces, errp);

        if (replaced_bs == NULL) {

            return;

        }

    } else {

        replaced_bs = bs;

    }

    if (replaced_bs->blk && target->blk) {

        error_setg(errp, "Can't create node with two BlockBackends");

        return;

    }

    s = block_job_create(driver, bs, speed, cb, opaque, errp);

    if (!s) {

        return;

    }

    s->replaces = g_strdup(replaces);

    s->on_source_error = on_source_error;

    s->on_target_error = on_target_error;

    s->target = target;

    s->is_none_mode = is_none_mode;

    s->base = base;

    s->granularity = granularity;

    s->buf_size = ROUND_UP(buf_size, granularity);

    s->unmap = unmap;

    s->dirty_bitmap = bdrv_create_dirty_bitmap(bs, granularity, NULL, errp);

    if (!s->dirty_bitmap) {

        g_free(s->replaces);

        block_job_unref(&s->common);

        return;

    }

    bdrv_op_block_all(s->target, s->common.blocker);

    bdrv_set_enable_write_cache(s->target, true);

    if (s->target->blk) {

        blk_set_on_error(s->target->blk, on_target_error, on_target_error);

        blk_iostatus_enable(s->target->blk);

    }

    s->common.co = qemu_coroutine_create(mirror_run);

    trace_mirror_start(bs, s, s->common.co, opaque);

    qemu_coroutine_enter(s->common.co, s);

}


START_TEST(qint_get_int_test)

{

    QInt *qi;

    const int value = 123456;

    qi = qint_from_int(value);

    fail_unless(qint_get_int(qi) == value);

    QDECREF(qi);

}


static int read_code_table(CLLCContext *ctx, GetBitContext *gb, VLC *vlc)
{
    uint8_t symbols[256];
    uint8_t bits[256];
    uint16_t codes[256];
    int num_lens, num_codes, num_codes_sum, prefix;
    int i, j, count;
    prefix        = 0;
    count         = 0;
    num_codes_sum = 0;
    num_lens = get_bits(gb, 5);
    for (i = 0; i < num_lens; i++) {
        num_codes      = get_bits(gb, 9);
        num_codes_sum += num_codes;
        if (num_codes_sum > 256) {
            av_log(ctx->avctx, AV_LOG_ERROR,
                   "Too many VLCs (%d) to be read.\n", num_codes_sum);
        for (j = 0; j < num_codes; j++) {
            symbols[count] = get_bits(gb, 8);
            bits[count]    = i + 1;
            codes[count]   = prefix++;
            count++;
        if (prefix > (65535 - 256)/2) {
        prefix <<= 1;
    return ff_init_vlc_sparse(vlc, VLC_BITS, count, bits, 1, 1,
                              codes, 2, 2, symbols, 1, 1, 0);


static int cbs_h265_read_nal_unit(CodedBitstreamContext *ctx,

                                  CodedBitstreamUnit *unit)

{

    BitstreamContext bc;

    int err;

    err = bitstream_init(&bc, unit->data, 8 * unit->data_size);

    if (err < 0)

        return err;

    switch (unit->type) {

    case HEVC_NAL_VPS:

        {

            H265RawVPS *vps;

            vps = av_mallocz(sizeof(*vps));

            if (!vps)

                return AVERROR(ENOMEM);

            err = cbs_h265_read_vps(ctx, &bc, vps);

            if (err >= 0)

                err = cbs_h265_replace_vps(ctx, vps);

            if (err < 0) {

                av_free(vps);

                return err;

            }

            unit->content = vps;

        }

        break;

    case HEVC_NAL_SPS:

        {

            H265RawSPS *sps;

            sps = av_mallocz(sizeof(*sps));

            if (!sps)

                return AVERROR(ENOMEM);

            err = cbs_h265_read_sps(ctx, &bc, sps);

            if (err >= 0)

                err = cbs_h265_replace_sps(ctx, sps);

            if (err < 0) {

                av_free(sps);

                return err;

            }

            unit->content = sps;

        }

        break;

    case HEVC_NAL_PPS:

        {

            H265RawPPS *pps;

            pps = av_mallocz(sizeof(*pps));

            if (!pps)

                return AVERROR(ENOMEM);

            err = cbs_h265_read_pps(ctx, &bc, pps);

            if (err >= 0)

                err = cbs_h265_replace_pps(ctx, pps);

            if (err < 0) {

                av_free(pps);

                return err;

            }

            unit->content = pps;

        }

        break;

    case HEVC_NAL_TRAIL_N:

    case HEVC_NAL_TRAIL_R:

    case HEVC_NAL_TSA_N:

    case HEVC_NAL_TSA_R:

    case HEVC_NAL_STSA_N:

    case HEVC_NAL_STSA_R:

    case HEVC_NAL_RADL_N:

    case HEVC_NAL_RADL_R:

    case HEVC_NAL_RASL_N:

    case HEVC_NAL_RASL_R:

    case HEVC_NAL_BLA_W_LP:

    case HEVC_NAL_BLA_W_RADL:

    case HEVC_NAL_BLA_N_LP:

    case HEVC_NAL_IDR_W_RADL:

    case HEVC_NAL_IDR_N_LP:

    case HEVC_NAL_CRA_NUT:

        {

            H265RawSlice *slice;

            int pos, len;

            slice = av_mallocz(sizeof(*slice));

            if (!slice)

                return AVERROR(ENOMEM);

            err = cbs_h265_read_slice_segment_header(ctx, &bc, &slice->header);

            if (err < 0) {

                av_free(slice);

                return err;

            }

            pos = bitstream_tell(&bc);

            len = unit->data_size;

            if (!unit->data[len - 1]) {

                int z;

                for (z = 0; z < len && !unit->data[len - z - 1]; z++);

                av_log(ctx->log_ctx, AV_LOG_DEBUG, "Deleted %d trailing zeroes "

                       "from slice data.\n", z);

                len -= z;

            }

            slice->data_size = len - pos / 8;

            slice->data = av_malloc(slice->data_size);

            if (!slice->data) {

                av_free(slice);

                return AVERROR(ENOMEM);

            }

            memcpy(slice->data,

                   unit->data + pos / 8, slice->data_size);

            slice->data_bit_start = pos % 8;

            unit->content = slice;

        }

        break;

    case HEVC_NAL_AUD:

        {

            H265RawAUD *aud;

            aud = av_mallocz(sizeof(*aud));

            if (!aud)

                return AVERROR(ENOMEM);

            err = cbs_h265_read_aud(ctx, &bc, aud);

            if (err < 0) {

                av_free(aud);

                return err;

            }

            unit->content = aud;

        }

        break;

    default:

        return AVERROR(ENOSYS);

    }

    return 0;

}


static void qpa_audio_fini (void *opaque)

{

    (void) opaque;

}


static void usbredir_bulk_packet(void *priv, uint32_t id,

    struct usb_redir_bulk_packet_header *bulk_packet,

    uint8_t *data, int data_len)

{

    USBRedirDevice *dev = priv;

    uint8_t ep = bulk_packet->endpoint;

    int len = bulk_packet->length;

    AsyncURB *aurb;

    DPRINTF("bulk-in status %d ep %02X len %d id %u\n", bulk_packet->status,

            ep, len, id);

    aurb = async_find(dev, id);

    if (!aurb) {

        free(data);

        return;

    }

    if (aurb->bulk_packet.endpoint != bulk_packet->endpoint ||

            aurb->bulk_packet.stream_id != bulk_packet->stream_id) {

        ERROR("return bulk packet mismatch, please report this!\n");

        len = USB_RET_NAK;

    }

    if (aurb->packet) {

        len = usbredir_handle_status(dev, bulk_packet->status, len);

        if (len > 0) {

            usbredir_log_data(dev, "bulk data in:", data, data_len);

            if (data_len <= aurb->packet->len) {

                memcpy(aurb->packet->data, data, data_len);

            } else {

                ERROR("bulk buffer too small (%d > %d)\n", data_len,

                      aurb->packet->len);

                len = USB_RET_STALL;

            }

        }

        aurb->packet->len = len;

        usb_packet_complete(&dev->dev, aurb->packet);

    }

    async_free(dev, aurb);

    free(data);

}


static av_cold int hevc_init_context(AVCodecContext *avctx)
{
    HEVCContext *s = avctx->priv_data;
    int i;
    s->avctx = avctx;
    s->HEVClc = av_mallocz(sizeof(HEVCLocalContext));
    if (!s->HEVClc)
        goto fail;
    s->HEVClcList[0] = s->HEVClc;
    s->sList[0] = s;
    s->cabac_state = av_malloc(HEVC_CONTEXTS);
    if (!s->cabac_state)
        goto fail;
    s->output_frame = av_frame_alloc();
    if (!s->output_frame)
        goto fail;
    for (i = 0; i < FF_ARRAY_ELEMS(s->DPB); i++) {
        s->DPB[i].frame = av_frame_alloc();
        if (!s->DPB[i].frame)
            goto fail;
        s->DPB[i].tf.f = s->DPB[i].frame;
    }
    s->max_ra = INT_MAX;
    s->md5_ctx = av_md5_alloc();
    if (!s->md5_ctx)
        goto fail;
    ff_bswapdsp_init(&s->bdsp);
    s->context_initialized = 1;
    s->eos = 0;
    return 0;
fail:
    hevc_decode_free(avctx);
    return AVERROR(ENOMEM);
}


static int decode_plte_chunk(AVCodecContext *avctx, PNGDecContext *s,

                             uint32_t length)

{

    int n, i, r, g, b;

    if ((length % 3) != 0 || length > 256 * 3)

        return AVERROR_INVALIDDATA;

    /* read the palette */

    n = length / 3;

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

        r = bytestream2_get_byte(&s->gb);

        g = bytestream2_get_byte(&s->gb);

        b = bytestream2_get_byte(&s->gb);

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

    }

    for (; i < 256; i++)

        s->palette[i] = (0xFFU << 24);

    s->state |= PNG_PLTE;

    bytestream2_skip(&s->gb, 4);     /* crc */

    return 0;

}


static MemTxResult vtd_mem_ir_write(void *opaque, hwaddr addr,

                                    uint64_t value, unsigned size,

                                    MemTxAttrs attrs)

{

    int ret = 0;

    MSIMessage from = {0}, to = {0};

    from.address = (uint64_t) addr + VTD_INTERRUPT_ADDR_FIRST;

    from.data = (uint32_t) value;

    ret = vtd_interrupt_remap_msi(opaque, &from, &to);

    if (ret) {

        /* TODO: report error */

        VTD_DPRINTF(GENERAL, "int remap fail for addr 0x%"PRIx64

                    " data 0x%"PRIx32, from.address, from.data);

        /* Drop this interrupt */

        return MEMTX_ERROR;

    }

    VTD_DPRINTF(IR, "delivering MSI 0x%"PRIx64":0x%"PRIx32

                " for device sid 0x%04x",

                to.address, to.data, sid);

    if (dma_memory_write(&address_space_memory, to.address,

                         &to.data, size)) {

        VTD_DPRINTF(GENERAL, "error: fail to write 0x%"PRIx64

                    " value 0x%"PRIx32, to.address, to.data);

    }

    return MEMTX_OK;

}


void st_flush_trace_buffer(void)

{

    if (trace_file_enabled) {

        flush_trace_file();

    }

    /* Discard written trace records */

    trace_idx = 0;

}


VirtIODevice *virtio_blk_init(DeviceState *dev, BlockConf *conf,

                              char **serial)

{

    VirtIOBlock *s;

    int cylinders, heads, secs;

    static int virtio_blk_id;

    DriveInfo *dinfo;

    if (!conf->bs) {

        error_report("virtio-blk-pci: drive property not set");

        return NULL;

    }

    if (!bdrv_is_inserted(conf->bs)) {

        error_report("Device needs media, but drive is empty");

        return NULL;

    }

    if (!*serial) {

        /* try to fall back to value set with legacy -drive serial=... */

        dinfo = drive_get_by_blockdev(conf->bs);

        if (*dinfo->serial) {

            *serial = strdup(dinfo->serial);

        }

    }

    s = (VirtIOBlock *)virtio_common_init("virtio-blk", VIRTIO_ID_BLOCK,

                                          sizeof(struct virtio_blk_config),

                                          sizeof(VirtIOBlock));

    s->vdev.get_config = virtio_blk_update_config;

    s->vdev.get_features = virtio_blk_get_features;

    s->vdev.reset = virtio_blk_reset;

    s->bs = conf->bs;

    s->conf = conf;

    s->serial = *serial;

    s->rq = NULL;

    s->sector_mask = (s->conf->logical_block_size / BDRV_SECTOR_SIZE) - 1;

    bdrv_guess_geometry(s->bs, &cylinders, &heads, &secs);

    s->vq = virtio_add_queue(&s->vdev, 128, virtio_blk_handle_output);

    qemu_add_vm_change_state_handler(virtio_blk_dma_restart_cb, s);

    s->qdev = dev;

    register_savevm(dev, "virtio-blk", virtio_blk_id++, 2,

                    virtio_blk_save, virtio_blk_load, s);

    bdrv_set_dev_ops(s->bs, &virtio_block_ops, s);

    bdrv_set_buffer_alignment(s->bs, conf->logical_block_size);

    bdrv_iostatus_enable(s->bs);

    add_boot_device_path(conf->bootindex, dev, "/disk@0,0");

    return &s->vdev;

}


static size_t header_ext_add(char *buf, uint32_t magic, const void *s,

    size_t len, size_t buflen)

{

    QCowExtension *ext_backing_fmt = (QCowExtension*) buf;

    size_t ext_len = sizeof(QCowExtension) + ((len + 7) & ~7);

    if (buflen < ext_len) {

        return -ENOSPC;

    }

    *ext_backing_fmt = (QCowExtension) {

        .magic  = cpu_to_be32(magic),

        .len    = cpu_to_be32(len),

    };

    memcpy(buf + sizeof(QCowExtension), s, len);

    return ext_len;

}


static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom)

{

    AVStream *st;

    if (c->fc->nb_streams < 1)

        return 0;

    if (atom.size <= 40)

        return 0;

    st = c->fc->streams[c->fc->nb_streams-1];

    if ((uint64_t)atom.size > (1<<30))

        return AVERROR_INVALIDDATA;

    av_free(st->codec->extradata);

    st->codec->extradata = av_mallocz(atom.size - 40 + FF_INPUT_BUFFER_PADDING_SIZE);

    if (!st->codec->extradata)

        return AVERROR(ENOMEM);

    st->codec->extradata_size = atom.size - 40;

    avio_skip(pb, 40);

    avio_read(pb, st->codec->extradata, atom.size - 40);

    return 0;

}


static void mem_begin(MemoryListener *listener)

{

    AddressSpaceDispatch *d = container_of(listener, AddressSpaceDispatch, listener);

    d->phys_map.ptr = PHYS_MAP_NODE_NIL;

}


int net_init_tap(const Netdev *netdev, const char *name,

                 NetClientState *peer, Error **errp)

{

    const NetdevTapOptions *tap;

    int fd, vnet_hdr = 0, i = 0, queues;

    /* for the no-fd, no-helper case */

    const char *script = NULL; /* suppress wrong "uninit'd use" gcc warning */

    const char *downscript = NULL;

    Error *err = NULL;

    const char *vhostfdname;

    char ifname[128];

    assert(netdev->type == NET_CLIENT_DRIVER_TAP);

    tap = &netdev->u.tap;

    queues = tap->has_queues ? tap->queues : 1;

    vhostfdname = tap->has_vhostfd ? tap->vhostfd : NULL;

    /* QEMU vlans does not support multiqueue tap, in this case peer is set.

     * For -netdev, peer is always NULL. */

    if (peer && (tap->has_queues || tap->has_fds || tap->has_vhostfds)) {

        error_setg(errp, "Multiqueue tap cannot be used with QEMU vlans");

        return -1;

    }

    if (tap->has_fd) {

        if (tap->has_ifname || tap->has_script || tap->has_downscript ||

            tap->has_vnet_hdr || tap->has_helper || tap->has_queues ||

            tap->has_fds || tap->has_vhostfds) {

            error_setg(errp, "ifname=, script=, downscript=, vnet_hdr=, "

                       "helper=, queues=, fds=, and vhostfds= "

                       "are invalid with fd=");

            return -1;

        }

        fd = monitor_fd_param(cur_mon, tap->fd, &err);

        if (fd == -1) {

            error_propagate(errp, err);

            return -1;

        }

        fcntl(fd, F_SETFL, O_NONBLOCK);

        vnet_hdr = tap_probe_vnet_hdr(fd);

        net_init_tap_one(tap, peer, "tap", name, NULL,

                         script, downscript,

                         vhostfdname, vnet_hdr, fd, &err);

        if (err) {

            error_propagate(errp, err);

            return -1;

        }

    } else if (tap->has_fds) {

        char **fds = g_new0(char *, MAX_TAP_QUEUES);

        char **vhost_fds = g_new0(char *, MAX_TAP_QUEUES);

        int nfds, nvhosts;

        if (tap->has_ifname || tap->has_script || tap->has_downscript ||

            tap->has_vnet_hdr || tap->has_helper || tap->has_queues ||

            tap->has_vhostfd) {

            error_setg(errp, "ifname=, script=, downscript=, vnet_hdr=, "

                       "helper=, queues=, and vhostfd= "

                       "are invalid with fds=");

            return -1;

        }

        nfds = get_fds(tap->fds, fds, MAX_TAP_QUEUES);

        if (tap->has_vhostfds) {

            nvhosts = get_fds(tap->vhostfds, vhost_fds, MAX_TAP_QUEUES);

            if (nfds != nvhosts) {

                error_setg(errp, "The number of fds passed does not match "

                           "the number of vhostfds passed");

                goto free_fail;

            }

        }

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

            fd = monitor_fd_param(cur_mon, fds[i], &err);

            if (fd == -1) {

                error_propagate(errp, err);

                goto free_fail;

            }

            fcntl(fd, F_SETFL, O_NONBLOCK);

            if (i == 0) {

                vnet_hdr = tap_probe_vnet_hdr(fd);

            } else if (vnet_hdr != tap_probe_vnet_hdr(fd)) {

                error_setg(errp,

                           "vnet_hdr not consistent across given tap fds");

                goto free_fail;

            }

            net_init_tap_one(tap, peer, "tap", name, ifname,

                             script, downscript,

                             tap->has_vhostfds ? vhost_fds[i] : NULL,

                             vnet_hdr, fd, &err);

            if (err) {

                error_propagate(errp, err);

                goto free_fail;

            }

        }

        g_free(fds);

        g_free(vhost_fds);

        return 0;

free_fail:

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

            g_free(fds[i]);

            g_free(vhost_fds[i]);

        }

        g_free(fds);

        g_free(vhost_fds);

        return -1;

    } else if (tap->has_helper) {

        if (tap->has_ifname || tap->has_script || tap->has_downscript ||

            tap->has_vnet_hdr || tap->has_queues || tap->has_vhostfds) {

            error_setg(errp, "ifname=, script=, downscript=, vnet_hdr=, "

                       "queues=, and vhostfds= are invalid with helper=");

            return -1;

        }

        fd = net_bridge_run_helper(tap->helper,

                                   tap->has_br ?

                                   tap->br : DEFAULT_BRIDGE_INTERFACE,

                                   errp);

        if (fd == -1) {

            return -1;

        }

        fcntl(fd, F_SETFL, O_NONBLOCK);

        vnet_hdr = tap_probe_vnet_hdr(fd);

        net_init_tap_one(tap, peer, "bridge", name, ifname,

                         script, downscript, vhostfdname,

                         vnet_hdr, fd, &err);

        if (err) {

            error_propagate(errp, err);

            close(fd);

            return -1;

        }

    } else {

        if (tap->has_vhostfds) {

            error_setg(errp, "vhostfds= is invalid if fds= wasn't specified");

            return -1;

        }

        script = tap->has_script ? tap->script : DEFAULT_NETWORK_SCRIPT;

        downscript = tap->has_downscript ? tap->downscript :

            DEFAULT_NETWORK_DOWN_SCRIPT;

        if (tap->has_ifname) {

            pstrcpy(ifname, sizeof ifname, tap->ifname);

        } else {

            ifname[0] = '\0';

        }

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

            fd = net_tap_init(tap, &vnet_hdr, i >= 1 ? "no" : script,

                              ifname, sizeof ifname, queues > 1, errp);

            if (fd == -1) {

                return -1;

            }

            if (queues > 1 && i == 0 && !tap->has_ifname) {

                if (tap_fd_get_ifname(fd, ifname)) {

                    error_setg(errp, "Fail to get ifname");

                    close(fd);

                    return -1;

                }

            }

            net_init_tap_one(tap, peer, "tap", name, ifname,

                             i >= 1 ? "no" : script,

                             i >= 1 ? "no" : downscript,

                             vhostfdname, vnet_hdr, fd, &err);

            if (err) {

                error_propagate(errp, err);

                close(fd);

                return -1;

            }

        }

    }

    return 0;

}


void stream_start(const char *job_id, BlockDriverState *bs,

                  BlockDriverState *base, const char *backing_file_str,

                  int64_t speed, BlockdevOnError on_error,

                  BlockCompletionFunc *cb, void *opaque, Error **errp)

{

    StreamBlockJob *s;

    s = block_job_create(job_id, &stream_job_driver, bs, speed,

                         cb, opaque, errp);

    if (!s) {

        return;

    }

    s->base = base;

    s->backing_file_str = g_strdup(backing_file_str);

    s->on_error = on_error;

    s->common.co = qemu_coroutine_create(stream_run);

    trace_stream_start(bs, base, s, s->common.co, opaque);

    qemu_coroutine_enter(s->common.co, s);

}


int attribute_align_arg avcodec_decode_video2(AVCodecContext *avctx, AVFrame *picture,
                                              int *got_picture_ptr,
                                              AVPacket *avpkt)
{
    int ret;
    *got_picture_ptr = 0;
    if ((avctx->coded_width || avctx->coded_height) && av_image_check_size(avctx->coded_width, avctx->coded_height, 0, avctx))
        return -1;
    avctx->pkt = avpkt;
    apply_param_change(avctx, avpkt);
    if ((avctx->codec->capabilities & CODEC_CAP_DELAY) || avpkt->size || (avctx->active_thread_type & FF_THREAD_FRAME)) {
        if (HAVE_THREADS && avctx->active_thread_type & FF_THREAD_FRAME)
            ret = ff_thread_decode_frame(avctx, picture, got_picture_ptr,
                                         avpkt);
        else {
            ret = avctx->codec->decode(avctx, picture, got_picture_ptr,
                                       avpkt);
            picture->pkt_dts             = avpkt->dts;
            picture->sample_aspect_ratio = avctx->sample_aspect_ratio;
            picture->width               = avctx->width;
            picture->height              = avctx->height;
            picture->format              = avctx->pix_fmt;
        }
        emms_c(); //needed to avoid an emms_c() call before every return;
        if (*got_picture_ptr)
            avctx->frame_number++;
    } else
        ret = 0;
    /* many decoders assign whole AVFrames, thus overwriting extended_data;
     * make sure it's set correctly */
    picture->extended_data = picture->data;
    return ret;
}


static int omap_gpio_init(SysBusDevice *sbd)

{

    DeviceState *dev = DEVICE(sbd);

    struct omap_gpif_s *s = OMAP1_GPIO(dev);

    if (!s->clk) {

        hw_error("omap-gpio: clk not connected\n");

    }

    qdev_init_gpio_in(dev, omap_gpio_set, 16);

    qdev_init_gpio_out(dev, s->omap1.handler, 16);

    sysbus_init_irq(sbd, &s->omap1.irq);

    memory_region_init_io(&s->iomem, OBJECT(s), &omap_gpio_ops, &s->omap1,

                          "omap.gpio", 0x1000);

    sysbus_init_mmio(sbd, &s->iomem);

    return 0;

}


void omap_mcbsp_i2s_attach(struct omap_mcbsp_s *s, I2SCodec *slave)

{

    s->codec = slave;

    slave->rx_swallow = qemu_allocate_irqs(omap_mcbsp_i2s_swallow, s, 1)[0];

    slave->tx_start = qemu_allocate_irqs(omap_mcbsp_i2s_start, s, 1)[0];

}


int floatx80_eq(floatx80 a, floatx80 b, float_status *status)

{

    if (    (    ( extractFloatx80Exp( a ) == 0x7FFF )

              && (uint64_t) ( extractFloatx80Frac( a )<<1 ) )

         || (    ( extractFloatx80Exp( b ) == 0x7FFF )

              && (uint64_t) ( extractFloatx80Frac( b )<<1 ) )

       ) {

        float_raise(float_flag_invalid, status);

        return 0;

    }

    return

           ( a.low == b.low )

        && (    ( a.high == b.high )

             || (    ( a.low == 0 )

                  && ( (uint16_t) ( ( a.high | b.high )<<1 ) == 0 ) )

           );

}


void json_lexer_init(JSONLexer *lexer, JSONLexerEmitter func)

{

    lexer->emit = func;

    lexer->state = IN_START;

    lexer->token = qstring_new();

    lexer->x = lexer->y = 0;

}


BlockDriverAIOCB *paio_submit(BlockDriverState *bs, int fd,

        int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,

        BlockDriverCompletionFunc *cb, void *opaque, int type)

{

    struct qemu_paiocb *acb;

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

    if (!acb)

        return NULL;

    acb->aio_type = type;

    acb->aio_fildes = fd;

    acb->ev_signo = SIGUSR2;

    acb->async_context_id = get_async_context_id();

    if (qiov) {

        acb->aio_iov = qiov->iov;

        acb->aio_niov = qiov->niov;

    }

    acb->aio_nbytes = nb_sectors * 512;

    acb->aio_offset = sector_num * 512;

    acb->next = posix_aio_state->first_aio;

    posix_aio_state->first_aio = acb;

    trace_paio_submit(acb, opaque, sector_num, nb_sectors, type);

    qemu_paio_submit(acb);

    return &acb->common;

}


static int crypto_open(URLContext *h, const char *uri, int flags)

{

    const char *nested_url;

    int ret;

    CryptoContext *c = h->priv_data;

    if (!av_strstart(uri, "crypto+", &nested_url) &&

        !av_strstart(uri, "crypto:", &nested_url)) {

        av_log(h, AV_LOG_ERROR, "Unsupported url %s\n", uri);

        ret = AVERROR(EINVAL);

        goto err;

    }

    if (c->keylen < BLOCKSIZE || c->ivlen < BLOCKSIZE) {

        av_log(h, AV_LOG_ERROR, "Key or IV not set\n");

        ret = AVERROR(EINVAL);

        goto err;

    }

    if (flags & AVIO_FLAG_WRITE) {

        av_log(h, AV_LOG_ERROR, "Only decryption is supported currently\n");

        ret = AVERROR(ENOSYS);

        goto err;

    }

    if ((ret = ffurl_open(&c->hd, nested_url, AVIO_FLAG_READ)) < 0) {

        av_log(h, AV_LOG_ERROR, "Unable to open input\n");

        goto err;

    }

    c->aes = av_mallocz(av_aes_size);

    if (!c->aes) {

        ret = AVERROR(ENOMEM);

        goto err;

    }

    av_aes_init(c->aes, c->key, 128, 1);

    h->is_streamed = 1;

    return 0;

err:

    av_free(c->key);

    av_free(c->iv);

    return ret;

}


int ff_alloc_entries(AVCodecContext *avctx, int count)

{

    int i;

    if (avctx->active_thread_type & FF_THREAD_SLICE)  {

        SliceThreadContext *p = avctx->internal->thread_ctx;

        p->thread_count  = avctx->thread_count;

        p->entries       = av_mallocz_array(count, sizeof(int));

        if (!p->entries) {

            return AVERROR(ENOMEM);

        }

        p->entries_count  = count;

        p->progress_mutex = av_malloc_array(p->thread_count, sizeof(pthread_mutex_t));

        p->progress_cond  = av_malloc_array(p->thread_count, sizeof(pthread_cond_t));

        for (i = 0; i < p->thread_count; i++) {

            pthread_mutex_init(&p->progress_mutex[i], NULL);

            pthread_cond_init(&p->progress_cond[i], NULL);

        }

    }

    return 0;

}


static int floppy_probe_device(const char *filename)

{

    int fd, ret;

    int prio = 0;

    struct floppy_struct fdparam;

    struct stat st;

    if (strstart(filename, "/dev/fd", NULL) &&

        !strstart(filename, "/dev/fdset/", NULL)) {

        prio = 50;

    }

    fd = qemu_open(filename, O_RDONLY | O_NONBLOCK);

    if (fd < 0) {

        goto out;

    }

    ret = fstat(fd, &st);

    if (ret == -1 || !S_ISBLK(st.st_mode)) {

        goto outc;

    }

    /* Attempt to detect via a floppy specific ioctl */

    ret = ioctl(fd, FDGETPRM, &fdparam);

    if (ret >= 0)

        prio = 100;

outc:

    qemu_close(fd);

out:

    return prio;

}


static void sun4uv_init(ram_addr_t RAM_size,

                        const char *boot_devices,

                        const char *kernel_filename, const char *kernel_cmdline,

                        const char *initrd_filename, const char *cpu_model,

                        const struct hwdef *hwdef)

{

    CPUState *env;

    char *filename;

    m48t59_t *nvram;

    int ret, linux_boot;

    unsigned int i;

    ram_addr_t ram_offset, prom_offset;

    long initrd_size, kernel_size;

    PCIBus *pci_bus, *pci_bus2, *pci_bus3;

    QEMUBH *bh;

    qemu_irq *irq;

    int drive_index;

    BlockDriverState *hd[MAX_IDE_BUS * MAX_IDE_DEVS];

    BlockDriverState *fd[MAX_FD];

    void *fw_cfg;

    ResetData *reset_info;

    linux_boot = (kernel_filename != NULL);

    /* init CPUs */

    if (!cpu_model)

        cpu_model = hwdef->default_cpu_model;

    env = cpu_init(cpu_model);

    if (!env) {

        fprintf(stderr, "Unable to find Sparc CPU definition\n");

        exit(1);

    }

    bh = qemu_bh_new(tick_irq, env);

    env->tick = ptimer_init(bh);

    ptimer_set_period(env->tick, 1ULL);

    bh = qemu_bh_new(stick_irq, env);

    env->stick = ptimer_init(bh);

    ptimer_set_period(env->stick, 1ULL);

    bh = qemu_bh_new(hstick_irq, env);

    env->hstick = ptimer_init(bh);

    ptimer_set_period(env->hstick, 1ULL);

    reset_info = qemu_mallocz(sizeof(ResetData));

    reset_info->env = env;

    reset_info->reset_addr = hwdef->prom_addr + 0x40ULL;

    qemu_register_reset(main_cpu_reset, reset_info);

    main_cpu_reset(reset_info);

    // Override warm reset address with cold start address

    env->pc = hwdef->prom_addr + 0x20ULL;

    env->npc = env->pc + 4;

    /* allocate RAM */

    ram_offset = qemu_ram_alloc(RAM_size);

    cpu_register_physical_memory(0, RAM_size, ram_offset);

    prom_offset = qemu_ram_alloc(PROM_SIZE_MAX);

    cpu_register_physical_memory(hwdef->prom_addr,

                                 (PROM_SIZE_MAX + TARGET_PAGE_SIZE) &

                                 TARGET_PAGE_MASK,

                                 prom_offset | IO_MEM_ROM);

    if (bios_name == NULL)

        bios_name = PROM_FILENAME;

    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);

    if (filename) {

        ret = load_elf(filename, hwdef->prom_addr - PROM_VADDR,

                       NULL, NULL, NULL);

        if (ret < 0) {

            ret = load_image_targphys(filename, hwdef->prom_addr,

                                      (PROM_SIZE_MAX + TARGET_PAGE_SIZE) &

                                  TARGET_PAGE_MASK);

        }

        qemu_free(filename);

    } else {

        ret = -1;

    }

    if (ret < 0) {

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

                bios_name);

        exit(1);

    }

    kernel_size = 0;

    initrd_size = 0;

    if (linux_boot) {

        /* XXX: put correct offset */

        kernel_size = load_elf(kernel_filename, 0, NULL, NULL, NULL);

        if (kernel_size < 0)

            kernel_size = load_aout(kernel_filename, KERNEL_LOAD_ADDR,

                                    ram_size - KERNEL_LOAD_ADDR);

        if (kernel_size < 0)

            kernel_size = load_image_targphys(kernel_filename,

                                              KERNEL_LOAD_ADDR,

                                              ram_size - KERNEL_LOAD_ADDR);

        if (kernel_size < 0) {

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

                    kernel_filename);

            exit(1);

        }

        /* load initrd */

        if (initrd_filename) {

            initrd_size = load_image_targphys(initrd_filename,

                                              INITRD_LOAD_ADDR,

                                              ram_size - INITRD_LOAD_ADDR);

            if (initrd_size < 0) {

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

                        initrd_filename);

                exit(1);

            }

        }

        if (initrd_size > 0) {

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

                if (ldl_phys(KERNEL_LOAD_ADDR + i) == 0x48647253) { // HdrS

                    stl_phys(KERNEL_LOAD_ADDR + i + 16, INITRD_LOAD_ADDR);

                    stl_phys(KERNEL_LOAD_ADDR + i + 20, initrd_size);

                    break;

                }

            }

        }

    }

    pci_bus = pci_apb_init(APB_SPECIAL_BASE, APB_MEM_BASE, NULL, &pci_bus2,

                           &pci_bus3);

    isa_mem_base = VGA_BASE;

    pci_vga_init(pci_bus, 0, 0);

    // XXX Should be pci_bus3

    pci_ebus_init(pci_bus, -1);

    i = 0;

    if (hwdef->console_serial_base) {

        serial_mm_init(hwdef->console_serial_base, 0, NULL, 115200,

                       serial_hds[i], 1);

        i++;

    }

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

        if (serial_hds[i]) {

            serial_init(serial_io[i], NULL/*serial_irq[i]*/, 115200,

                        serial_hds[i]);

        }

    }

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

        if (parallel_hds[i]) {

            parallel_init(parallel_io[i], NULL/*parallel_irq[i]*/,

                          parallel_hds[i]);

        }

    }

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

        pci_nic_init(&nd_table[i], "ne2k_pci", NULL);

    irq = qemu_allocate_irqs(cpu_set_irq, env, MAX_PILS);

    if (drive_get_max_bus(IF_IDE) >= MAX_IDE_BUS) {

        fprintf(stderr, "qemu: too many IDE bus\n");

        exit(1);

    }

    for(i = 0; i < MAX_IDE_BUS * MAX_IDE_DEVS; i++) {

        drive_index = drive_get_index(IF_IDE, i / MAX_IDE_DEVS,

                                      i % MAX_IDE_DEVS);

       if (drive_index != -1)

           hd[i] = drives_table[drive_index].bdrv;

       else

           hd[i] = NULL;

    }

    pci_cmd646_ide_init(pci_bus, hd, 1);

    /* FIXME: wire up interrupts.  */

    i8042_init(NULL/*1*/, NULL/*12*/, 0x60);

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

        drive_index = drive_get_index(IF_FLOPPY, 0, i);

       if (drive_index != -1)

           fd[i] = drives_table[drive_index].bdrv;

       else

           fd[i] = NULL;

    }

    floppy_controller = fdctrl_init(NULL/*6*/, 2, 0, 0x3f0, fd);

    nvram = m48t59_init(NULL/*8*/, 0, 0x0074, NVRAM_SIZE, 59);

    sun4u_NVRAM_set_params(nvram, NVRAM_SIZE, "Sun4u", RAM_size, boot_devices,

                           KERNEL_LOAD_ADDR, kernel_size,

                           kernel_cmdline,

                           INITRD_LOAD_ADDR, initrd_size,

                           /* XXX: need an option to load a NVRAM image */

                           0,

                           graphic_width, graphic_height, graphic_depth,

                           (uint8_t *)&nd_table[0].macaddr);

    fw_cfg = fw_cfg_init(BIOS_CFG_IOPORT, BIOS_CFG_IOPORT + 1, 0, 0);

    fw_cfg_add_i32(fw_cfg, FW_CFG_ID, 1);

    fw_cfg_add_i64(fw_cfg, FW_CFG_RAM_SIZE, (uint64_t)ram_size);

    fw_cfg_add_i16(fw_cfg, FW_CFG_MACHINE_ID, hwdef->machine_id);

    fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_ADDR, KERNEL_LOAD_ADDR);

    fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_SIZE, kernel_size);

    if (kernel_cmdline) {

        fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_CMDLINE, CMDLINE_ADDR);

        pstrcpy_targphys(CMDLINE_ADDR, TARGET_PAGE_SIZE, kernel_cmdline);

    } else {

        fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_CMDLINE, 0);

    }

    fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_ADDR, INITRD_LOAD_ADDR);

    fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_SIZE, initrd_size);

    fw_cfg_add_i16(fw_cfg, FW_CFG_BOOT_DEVICE, boot_devices[0]);

    qemu_register_boot_set(fw_cfg_boot_set, fw_cfg);

}


static void fpu_init (CPUMIPSState *env, const mips_def_t *def)

{

    int i;

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

        env->fpus[i].fcr0 = def->CP1_fcr0;

    memcpy(&env->active_fpu, &env->fpus[0], sizeof(env->active_fpu));

    if (env->user_mode_only) {

        if (env->CP0_Config1 & (1 << CP0C1_FP))

            env->hflags |= MIPS_HFLAG_FPU;

#ifdef TARGET_MIPS64

        if (env->active_fpu.fcr0 & (1 << FCR0_F64))

            env->hflags |= MIPS_HFLAG_F64;

#endif

    }

}


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

                            int *data_size, AVPacket *avpkt)

{

    const uint8_t *buf = avpkt->data, *buf_end = avpkt->data + avpkt->size;

    int buf_size = avpkt->size;

    BFIContext *bfi = avctx->priv_data;

    uint8_t *dst = bfi->dst;

    uint8_t *src, *dst_offset, colour1, colour2;

    uint8_t *frame_end = bfi->dst + avctx->width * avctx->height;

    uint32_t *pal;

    int i, j, height = avctx->height;

    if (bfi->frame.data[0])

        avctx->release_buffer(avctx, &bfi->frame);

    bfi->frame.reference = 1;

    if (avctx->get_buffer(avctx, &bfi->frame) < 0) {

        av_log(avctx, AV_LOG_ERROR, "get_buffer() failed\n");

        return -1;

    }

    /* Set frame parameters and palette, if necessary */

    if (!avctx->frame_number) {

        bfi->frame.pict_type = AV_PICTURE_TYPE_I;

        bfi->frame.key_frame = 1;

        /* Setting the palette */

        if (avctx->extradata_size > 768) {

            av_log(NULL, AV_LOG_ERROR, "Palette is too large.\n");

            return -1;

        }

        pal = (uint32_t *)bfi->frame.data[1];

        for (i = 0; i < avctx->extradata_size / 3; i++) {

            int shift = 16;

            *pal = 0;

            for (j = 0; j < 3; j++, shift -= 8)

                *pal +=

                    ((avctx->extradata[i * 3 + j] << 2) |

                    (avctx->extradata[i * 3 + j] >> 4)) << shift;

            pal++;

        }

        bfi->frame.palette_has_changed = 1;

    } else {

        bfi->frame.pict_type = AV_PICTURE_TYPE_P;

        bfi->frame.key_frame = 0;

    }

    buf += 4; // Unpacked size, not required.

    while (dst != frame_end) {

        static const uint8_t lentab[4] = { 0, 2, 0, 1 };

        unsigned int byte   = *buf++, av_uninit(offset);

        unsigned int code   = byte >> 6;

        unsigned int length = byte & ~0xC0;

        if (buf >= buf_end) {

            av_log(avctx, AV_LOG_ERROR,

                   "Input resolution larger than actual frame.\n");

            return -1;

        }

        /* Get length and offset(if required) */

        if (length == 0) {

            if (code == 1) {

                length = bytestream_get_byte(&buf);

                offset = bytestream_get_le16(&buf);

            } else {

                length = bytestream_get_le16(&buf);

                if (code == 2 && length == 0)

                    break;

            }

        } else {

            if (code == 1)

                offset = bytestream_get_byte(&buf);

        }

        /* Do boundary check */

        if (dst + (length << lentab[code]) > frame_end)

            break;

        switch (code) {

        case 0:                //Normal Chain

            if (length >= buf_end - buf) {

                av_log(avctx, AV_LOG_ERROR, "Frame larger than buffer.\n");

                return -1;

            }

            bytestream_get_buffer(&buf, dst, length);

            dst += length;

            break;

        case 1:                //Back Chain

            dst_offset = dst - offset;

            length *= 4;        //Convert dwords to bytes.

            if (dst_offset < bfi->dst)

                break;

            while (length--)

                *dst++ = *dst_offset++;

            break;

        case 2:                //Skip Chain

            dst += length;

            break;

        case 3:                //Fill Chain

            colour1 = bytestream_get_byte(&buf);

            colour2 = bytestream_get_byte(&buf);

            while (length--) {

                *dst++ = colour1;

                *dst++ = colour2;

            }

            break;

        }

    }

    src = bfi->dst;

    dst = bfi->frame.data[0];

    while (height--) {

        memcpy(dst, src, avctx->width);

        src += avctx->width;

        dst += bfi->frame.linesize[0];

    }

    *data_size = sizeof(AVFrame);

    *(AVFrame *)data = bfi->frame;

    return buf_size;

}


DeviceState *qdev_device_add(QemuOpts *opts)

{

    ObjectClass *oc;

    DeviceClass *dc;

    const char *driver, *path, *id;

    DeviceState *dev;

    BusState *bus = NULL;

    Error *err = NULL;

    driver = qemu_opt_get(opts, "driver");

    if (!driver) {

        qerror_report(QERR_MISSING_PARAMETER, "driver");

        return NULL;

    }

    /* find driver */

    oc = object_class_by_name(driver);

    if (!oc) {

        const char *typename = find_typename_by_alias(driver);

        if (typename) {

            driver = typename;

            oc = object_class_by_name(driver);

        }

    }

    if (!object_class_dynamic_cast(oc, TYPE_DEVICE)) {

        qerror_report(ERROR_CLASS_GENERIC_ERROR,

                      "'%s' is not a valid device model name", driver);

        return NULL;

    }

    if (object_class_is_abstract(oc)) {

        qerror_report(QERR_INVALID_PARAMETER_VALUE, "driver",

                      "non-abstract device type");

        return NULL;

    }

    dc = DEVICE_CLASS(oc);

    if (dc->cannot_instantiate_with_device_add_yet) {

        qerror_report(QERR_INVALID_PARAMETER_VALUE, "driver",

                      "pluggable device type");

        return NULL;

    }

    /* find bus */

    path = qemu_opt_get(opts, "bus");

    if (path != NULL) {

        bus = qbus_find(path);

        if (!bus) {

            return NULL;

        }

        if (!object_dynamic_cast(OBJECT(bus), dc->bus_type)) {

            qerror_report(QERR_BAD_BUS_FOR_DEVICE,

                          driver, object_get_typename(OBJECT(bus)));

            return NULL;

        }

    } else if (dc->bus_type != NULL) {

        bus = qbus_find_recursive(sysbus_get_default(), NULL, dc->bus_type);

        if (!bus) {

            qerror_report(QERR_NO_BUS_FOR_DEVICE,

                          dc->bus_type, driver);

            return NULL;

        }

    }

    if (qdev_hotplug && bus && !bus->allow_hotplug) {

        qerror_report(QERR_BUS_NO_HOTPLUG, bus->name);

        return NULL;

    }

    /* create device, set properties */

    dev = DEVICE(object_new(driver));

    if (bus) {

        qdev_set_parent_bus(dev, bus);

    }

    id = qemu_opts_id(opts);

    if (id) {

        dev->id = id;

    }

    if (qemu_opt_foreach(opts, set_property, dev, 1) != 0) {

        object_unparent(OBJECT(dev));

        object_unref(OBJECT(dev));

        return NULL;

    }

    if (dev->id) {

        object_property_add_child(qdev_get_peripheral(), dev->id,

                                  OBJECT(dev), NULL);

    } else {

        static int anon_count;

        gchar *name = g_strdup_printf("device[%d]", anon_count++);

        object_property_add_child(qdev_get_peripheral_anon(), name,

                                  OBJECT(dev), NULL);

        g_free(name);

    }

    dev->opts = opts;

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

    if (err != NULL) {

        qerror_report_err(err);

        error_free(err);

        dev->opts = NULL;

        object_unparent(OBJECT(dev));

        object_unref(OBJECT(dev));

        qerror_report(QERR_DEVICE_INIT_FAILED, driver);

        return NULL;

    }

    return dev;

}


void thread_pool_submit(ThreadPoolFunc *func, void *arg)

{

    thread_pool_submit_aio(func, arg, NULL, NULL);

}


static void pl061_register_devices(void)

{

    sysbus_register_dev("pl061", sizeof(pl061_state),

                        pl061_init_arm);

    sysbus_register_dev("pl061_luminary", sizeof(pl061_state),

                        pl061_init_luminary);

}


int cpu_exec(CPUState *cpu)

{

    CPUClass *cc = CPU_GET_CLASS(cpu);

    int ret;

    SyncClocks sc;

    /* replay_interrupt may need current_cpu */

    current_cpu = cpu;

    if (cpu_handle_halt(cpu)) {

        return EXCP_HALTED;

    }

    rcu_read_lock();

    cc->cpu_exec_enter(cpu);

    /* Calculate difference between guest clock and host clock.

     * This delay includes the delay of the last cycle, so

     * what we have to do is sleep until it is 0. As for the

     * advance/delay we gain here, we try to fix it next time.

     */

    init_delay_params(&sc, cpu);

    /* prepare setjmp context for exception handling */

    if (sigsetjmp(cpu->jmp_env, 0) != 0) {

#if defined(__clang__) || !QEMU_GNUC_PREREQ(4, 6)

        /* Some compilers wrongly smash all local variables after

         * siglongjmp. There were bug reports for gcc 4.5.0 and clang.

         * Reload essential local variables here for those compilers.

         * Newer versions of gcc would complain about this code (-Wclobbered). */

        cpu = current_cpu;

        cc = CPU_GET_CLASS(cpu);

#else /* buggy compiler */

        /* Assert that the compiler does not smash local variables. */

        g_assert(cpu == current_cpu);

        g_assert(cc == CPU_GET_CLASS(cpu));

#endif /* buggy compiler */

        cpu->can_do_io = 1;

        tb_lock_reset();

        if (qemu_mutex_iothread_locked()) {

            qemu_mutex_unlock_iothread();

        }

    }

    /* if an exception is pending, we execute it here */

    while (!cpu_handle_exception(cpu, &ret)) {

        TranslationBlock *last_tb = NULL;

        int tb_exit = 0;

        while (!cpu_handle_interrupt(cpu, &last_tb)) {

            TranslationBlock *tb = tb_find(cpu, last_tb, tb_exit);

            cpu_loop_exec_tb(cpu, tb, &last_tb, &tb_exit, &sc);

            /* Try to align the host and virtual clocks

               if the guest is in advance */

            align_clocks(&sc, cpu);

        }

    }

    cc->cpu_exec_exit(cpu);

    rcu_read_unlock();

    /* fail safe : never use current_cpu outside cpu_exec() */

    current_cpu = NULL;

    return ret;

}


static void copy_irb_to_guest(IRB *dest, const IRB *src, PMCW *pmcw)

{

    int i;

    uint16_t stctl = src->scsw.ctrl & SCSW_CTRL_MASK_STCTL;

    uint16_t actl = src->scsw.ctrl & SCSW_CTRL_MASK_ACTL;

    copy_scsw_to_guest(&dest->scsw, &src->scsw);

    for (i = 0; i < ARRAY_SIZE(dest->esw); i++) {

        dest->esw[i] = cpu_to_be32(src->esw[i]);

    }

    for (i = 0; i < ARRAY_SIZE(dest->ecw); i++) {

        dest->ecw[i] = cpu_to_be32(src->ecw[i]);

    }

    /* extended measurements enabled? */

    if ((src->scsw.flags & SCSW_FLAGS_MASK_ESWF) ||

        !(pmcw->flags & PMCW_FLAGS_MASK_TF) ||

        !(pmcw->chars & PMCW_CHARS_MASK_XMWME)) {

        return;

    }

    /* extended measurements pending? */

    if (!(stctl & SCSW_STCTL_STATUS_PEND)) {

        return;

    }

    if ((stctl & SCSW_STCTL_PRIMARY) ||

        (stctl == SCSW_STCTL_SECONDARY) ||

        ((stctl & SCSW_STCTL_INTERMEDIATE) && (actl & SCSW_ACTL_SUSP))) {

        for (i = 0; i < ARRAY_SIZE(dest->emw); i++) {

            dest->emw[i] = cpu_to_be32(src->emw[i]);

        }

    }

}


static int process_input_packet(InputStream *ist, const AVPacket *pkt)

{

    int i;

    int got_output;

    AVPacket avpkt;

    if (ist->next_dts == AV_NOPTS_VALUE)

        ist->next_dts = ist->last_dts;

    if (pkt == NULL) {

        /* EOF handling */

        av_init_packet(&avpkt);

        avpkt.data = NULL;

        avpkt.size = 0;

        goto handle_eof;

    } else {

        avpkt = *pkt;

    }

    if (pkt->dts != AV_NOPTS_VALUE)

        ist->next_dts = ist->last_dts = av_rescale_q(pkt->dts, ist->st->time_base, AV_TIME_BASE_Q);

    // while we have more to decode or while the decoder did output something on EOF

    while (ist->decoding_needed && (avpkt.size > 0 || (!pkt && got_output))) {

        int ret = 0;

    handle_eof:

        ist->last_dts = ist->next_dts;

        if (avpkt.size && avpkt.size != pkt->size &&

            !(ist->dec->capabilities & CODEC_CAP_SUBFRAMES)) {

            av_log(NULL, ist->showed_multi_packet_warning ? AV_LOG_VERBOSE : AV_LOG_WARNING,

                   "Multiple frames in a packet from stream %d\n", pkt->stream_index);

            ist->showed_multi_packet_warning = 1;

        }

        switch (ist->dec_ctx->codec_type) {

        case AVMEDIA_TYPE_AUDIO:

            ret = decode_audio    (ist, &avpkt, &got_output);

            break;

        case AVMEDIA_TYPE_VIDEO:

            ret = decode_video    (ist, &avpkt, &got_output);

            if (avpkt.duration)

                ist->next_dts += av_rescale_q(avpkt.duration, ist->st->time_base, AV_TIME_BASE_Q);

            else if (ist->st->avg_frame_rate.num)

                ist->next_dts += av_rescale_q(1, av_inv_q(ist->st->avg_frame_rate),

                                              AV_TIME_BASE_Q);

            else if (ist->dec_ctx->time_base.num != 0) {

                int ticks      = ist->st->parser ? ist->st->parser->repeat_pict + 1 :

                                                   ist->dec_ctx->ticks_per_frame;

                ist->next_dts += av_rescale_q(ticks, ist->dec_ctx->time_base, AV_TIME_BASE_Q);

            }

            break;

        case AVMEDIA_TYPE_SUBTITLE:

            ret = transcode_subtitles(ist, &avpkt, &got_output);

            break;

        default:

            return -1;

        }

        if (ret < 0)

            return ret;

        // touch data and size only if not EOF

        if (pkt) {

            avpkt.data += ret;

            avpkt.size -= ret;

        }

        if (!got_output) {

            continue;

        }

    }

    /* handle stream copy */

    if (!ist->decoding_needed) {

        ist->last_dts = ist->next_dts;

        switch (ist->dec_ctx->codec_type) {

        case AVMEDIA_TYPE_AUDIO:

            ist->next_dts += ((int64_t)AV_TIME_BASE * ist->dec_ctx->frame_size) /

                             ist->dec_ctx->sample_rate;

            break;

        case AVMEDIA_TYPE_VIDEO:

            if (ist->dec_ctx->time_base.num != 0) {

                int ticks = ist->st->parser ? ist->st->parser->repeat_pict + 1 : ist->dec_ctx->ticks_per_frame;

                ist->next_dts += ((int64_t)AV_TIME_BASE *

                                  ist->dec_ctx->time_base.num * ticks) /

                                  ist->dec_ctx->time_base.den;

            }

            break;

        }

    }

    for (i = 0; pkt && i < nb_output_streams; i++) {

        OutputStream *ost = output_streams[i];

        if (!check_output_constraints(ist, ost) || ost->encoding_needed)

            continue;

        do_streamcopy(ist, ost, pkt);

    }

    return 0;

}