static void ppc_prep_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)

{

    CPUState *env = NULL;

    char *filename;

    nvram_t nvram;

    M48t59State *m48t59;

    int PPC_io_memory;

    int linux_boot, i, nb_nics1, bios_size;

    ram_addr_t ram_offset, bios_offset;

    uint32_t kernel_base, initrd_base;

    long kernel_size, initrd_size;

    PCIBus *pci_bus;

    qemu_irq *i8259;

    qemu_irq *cpu_exit_irq;

    int ppc_boot_device;

    DriveInfo *hd[MAX_IDE_BUS * MAX_IDE_DEVS];

    DriveInfo *fd[MAX_FD];

    sysctrl = qemu_mallocz(sizeof(sysctrl_t));

    linux_boot = (kernel_filename != NULL);

    /* init CPUs */

    if (cpu_model == NULL)

        cpu_model = "602";

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

        env = cpu_init(cpu_model);

        if (!env) {

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

            exit(1);

        }

        if (env->flags & POWERPC_FLAG_RTC_CLK) {

            /* POWER / PowerPC 601 RTC clock frequency is 7.8125 MHz */

            cpu_ppc_tb_init(env, 7812500UL);

        } else {

            /* Set time-base frequency to 100 Mhz */

            cpu_ppc_tb_init(env, 100UL * 1000UL * 1000UL);

        }

        qemu_register_reset((QEMUResetHandler*)&cpu_reset, env);

    }

    /* allocate RAM */

    ram_offset = qemu_ram_alloc(NULL, "ppc_prep.ram", ram_size);

    cpu_register_physical_memory(0, ram_size, ram_offset);

    /* allocate and load BIOS */

    bios_offset = qemu_ram_alloc(NULL, "ppc_prep.bios", BIOS_SIZE);

    if (bios_name == NULL)

        bios_name = BIOS_FILENAME;

    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);

    if (filename) {

        bios_size = get_image_size(filename);

    } else {

        bios_size = -1;

    }

    if (bios_size > 0 && bios_size <= BIOS_SIZE) {

        target_phys_addr_t bios_addr;

        bios_size = (bios_size + 0xfff) & ~0xfff;

        bios_addr = (uint32_t)(-bios_size);

        cpu_register_physical_memory(bios_addr, bios_size,

                                     bios_offset | IO_MEM_ROM);

        bios_size = load_image_targphys(filename, bios_addr, bios_size);

    }

    if (bios_size < 0 || bios_size > BIOS_SIZE) {

        hw_error("qemu: could not load PPC PREP bios '%s'\n", bios_name);

    }

    if (filename) {

        qemu_free(filename);

    }

    if (linux_boot) {

        kernel_base = KERNEL_LOAD_ADDR;

        /* now we can load the kernel */

        kernel_size = load_image_targphys(kernel_filename, kernel_base,

                                          ram_size - kernel_base);

        if (kernel_size < 0) {

            hw_error("qemu: could not load kernel '%s'\n", kernel_filename);

            exit(1);

        }

        /* load initrd */

        if (initrd_filename) {

            initrd_base = INITRD_LOAD_ADDR;

            initrd_size = load_image_targphys(initrd_filename, initrd_base,

                                              ram_size - initrd_base);

            if (initrd_size < 0) {

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

                          initrd_filename);

            }

        } else {

            initrd_base = 0;

            initrd_size = 0;

        }

        ppc_boot_device = 'm';

    } else {

        kernel_base = 0;

        kernel_size = 0;

        initrd_base = 0;

        initrd_size = 0;

        ppc_boot_device = '\0';

        /* For now, OHW cannot boot from the network. */

        for (i = 0; boot_device[i] != '\0'; i++) {

            if (boot_device[i] >= 'a' && boot_device[i] <= 'f') {

                ppc_boot_device = boot_device[i];

                break;

            }

        }

        if (ppc_boot_device == '\0') {

            fprintf(stderr, "No valid boot device for Mac99 machine\n");

            exit(1);

        }

    }

    isa_mem_base = 0xc0000000;

    if (PPC_INPUT(env) != PPC_FLAGS_INPUT_6xx) {

        hw_error("Only 6xx bus is supported on PREP machine\n");

    }

    i8259 = i8259_init(first_cpu->irq_inputs[PPC6xx_INPUT_INT]);

    pci_bus = pci_prep_init(i8259);

    /* Hmm, prep has no pci-isa bridge ??? */

    isa_bus_new(NULL);

    isa_bus_irqs(i8259);

    //    pci_bus = i440fx_init();

    /* Register 8 MB of ISA IO space (needed for non-contiguous map) */

    PPC_io_memory = cpu_register_io_memory(PPC_prep_io_read,

                                           PPC_prep_io_write, sysctrl,

                                           DEVICE_LITTLE_ENDIAN);

    cpu_register_physical_memory(0x80000000, 0x00800000, PPC_io_memory);

    /* init basic PC hardware */

    pci_vga_init(pci_bus);

    //    openpic = openpic_init(0x00000000, 0xF0000000, 1);

    //    pit = pit_init(0x40, i8259[0]);

    rtc_init(2000, NULL);

    if (serial_hds[0])

        serial_isa_init(0, serial_hds[0]);

    nb_nics1 = nb_nics;

    if (nb_nics1 > NE2000_NB_MAX)

        nb_nics1 = NE2000_NB_MAX;

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

        if (nd_table[i].model == NULL) {

	    nd_table[i].model = qemu_strdup("ne2k_isa");

        }

        if (strcmp(nd_table[i].model, "ne2k_isa") == 0) {

            isa_ne2000_init(ne2000_io[i], ne2000_irq[i], &nd_table[i]);

        } else {

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

        }

    }

    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++) {

        hd[i] = drive_get(IF_IDE, i / MAX_IDE_DEVS, i % MAX_IDE_DEVS);

    }

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

        isa_ide_init(ide_iobase[i], ide_iobase2[i], ide_irq[i],

                     hd[2 * i],

		     hd[2 * i + 1]);

    }

    isa_create_simple("i8042");

    cpu_exit_irq = qemu_allocate_irqs(cpu_request_exit, NULL, 1);

    DMA_init(1, cpu_exit_irq);

    //    SB16_init();

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

        fd[i] = drive_get(IF_FLOPPY, 0, i);

    }

    fdctrl_init_isa(fd);

    /* Register speaker port */

    register_ioport_read(0x61, 1, 1, speaker_ioport_read, NULL);

    register_ioport_write(0x61, 1, 1, speaker_ioport_write, NULL);

    /* Register fake IO ports for PREP */

    sysctrl->reset_irq = first_cpu->irq_inputs[PPC6xx_INPUT_HRESET];

    register_ioport_read(0x398, 2, 1, &PREP_io_read, sysctrl);

    register_ioport_write(0x398, 2, 1, &PREP_io_write, sysctrl);

    /* System control ports */

    register_ioport_read(0x0092, 0x01, 1, &PREP_io_800_readb, sysctrl);

    register_ioport_write(0x0092, 0x01, 1, &PREP_io_800_writeb, sysctrl);

    register_ioport_read(0x0800, 0x52, 1, &PREP_io_800_readb, sysctrl);

    register_ioport_write(0x0800, 0x52, 1, &PREP_io_800_writeb, sysctrl);

    /* PCI intack location */

    PPC_io_memory = cpu_register_io_memory(PPC_intack_read,

                                           PPC_intack_write, NULL,

                                           DEVICE_LITTLE_ENDIAN);

    cpu_register_physical_memory(0xBFFFFFF0, 0x4, PPC_io_memory);

    /* PowerPC control and status register group */

#if 0

    PPC_io_memory = cpu_register_io_memory(PPC_XCSR_read, PPC_XCSR_write,

                                           NULL, DEVICE_LITTLE_ENDIAN);

    cpu_register_physical_memory(0xFEFF0000, 0x1000, PPC_io_memory);

#endif

    if (usb_enabled) {

        usb_ohci_init_pci(pci_bus, -1);

    }

    m48t59 = m48t59_init(i8259[8], 0, 0x0074, NVRAM_SIZE, 59);

    if (m48t59 == NULL)

        return;

    sysctrl->nvram = m48t59;

    /* Initialise NVRAM */

    nvram.opaque = m48t59;

    nvram.read_fn = &m48t59_read;

    nvram.write_fn = &m48t59_write;

    PPC_NVRAM_set_params(&nvram, NVRAM_SIZE, "PREP", ram_size, ppc_boot_device,

                         kernel_base, kernel_size,

                         kernel_cmdline,

                         initrd_base, initrd_size,

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

                         0,

                         graphic_width, graphic_height, graphic_depth);

    /* Special port to get debug messages from Open-Firmware */

    register_ioport_write(0x0F00, 4, 1, &PPC_debug_write, NULL);

}


static void copy_picture_field(InterlaceContext *s,

                               AVFrame *src_frame, AVFrame *dst_frame,

                               AVFilterLink *inlink, enum FieldType field_type,

                               int lowpass)

{

    const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);

    int hsub = desc->log2_chroma_w;

    int vsub = desc->log2_chroma_h;

    int plane, j;

    for (plane = 0; plane < desc->nb_components; plane++) {

        int cols  = (plane == 1 || plane == 2) ? -(-inlink->w) >> hsub : inlink->w;

        int lines = (plane == 1 || plane == 2) ? -(-inlink->h) >> vsub : inlink->h;

        uint8_t *dstp = dst_frame->data[plane];

        const uint8_t *srcp = src_frame->data[plane];

        av_assert0(cols >= 0 || lines >= 0);

        lines = (lines + (field_type == FIELD_UPPER)) / 2;

        if (field_type == FIELD_LOWER)

            srcp += src_frame->linesize[plane];

        if (field_type == FIELD_LOWER)

            dstp += dst_frame->linesize[plane];

        if (lowpass) {

            int srcp_linesize = src_frame->linesize[plane] * 2;

            int dstp_linesize = dst_frame->linesize[plane] * 2;

            for (j = lines; j > 0; j--) {

                const uint8_t *srcp_above = srcp - src_frame->linesize[plane];

                const uint8_t *srcp_below = srcp + src_frame->linesize[plane];

                if (j == lines)

                    srcp_above = srcp; // there is no line above

                if (j == 1)

                    srcp_below = srcp; // there is no line below

                s->lowpass_line(dstp, cols, srcp, srcp_above, srcp_below);

                dstp += dstp_linesize;

                srcp += srcp_linesize;

            }

        } else {

            av_image_copy_plane(dstp, dst_frame->linesize[plane] * 2,

                                srcp, src_frame->linesize[plane] * 2,

                                cols, lines);

        }

    }

}


target_ulong helper_rdhwr_cpunum(CPUMIPSState *env)

{

    check_hwrena(env, 0);

    return env->CP0_EBase & 0x3ff;

}


void qmp_inject_nmi(Error **errp)

{

#if defined(TARGET_I386)

    CPUState *cs;

    CPU_FOREACH(cs) {

        X86CPU *cpu = X86_CPU(cs);

        if (!cpu->apic_state) {

            cpu_interrupt(cs, CPU_INTERRUPT_NMI);

        } else {

            apic_deliver_nmi(cpu->apic_state);

        }

    }

#elif defined(TARGET_S390X)

    CPUState *cs;

    S390CPU *cpu;

    CPU_FOREACH(cs) {

        cpu = S390_CPU(cs);

        if (cpu->env.cpu_num == monitor_get_cpu_index()) {

            if (s390_cpu_restart(S390_CPU(cs)) == -1) {

                error_set(errp, QERR_UNSUPPORTED);

                return;

            }

            break;

        }

    }

#else

    error_set(errp, QERR_UNSUPPORTED);

#endif

}


void helper_single_step(CPUX86State *env)

{

#ifndef CONFIG_USER_ONLY

    check_hw_breakpoints(env, 1);

    env->dr[6] |= DR6_BS;

#endif

    raise_exception(env, EXCP01_DB);

}


static av_always_inline void rv40_weak_loop_filter(uint8_t *src,

                                                   const int step,

                                                   const int stride,

                                                   const int filter_p1,

                                                   const int filter_q1,

                                                   const int alpha,

                                                   const int beta,

                                                   const int lim_p0q0,

                                                   const int lim_q1,

                                                   const int lim_p1)

{

    uint8_t *cm = ff_cropTbl + MAX_NEG_CROP;

    int i, t, u, diff;

    for (i = 0; i < 4; i++, src += stride) {

        int diff_p1p0 = src[-2*step] - src[-1*step];

        int diff_q1q0 = src[ 1*step] - src[ 0*step];

        int diff_p1p2 = src[-2*step] - src[-3*step];

        int diff_q1q2 = src[ 1*step] - src[ 2*step];

        t = src[0*step] - src[-1*step];

        if (!t)

            continue;

        u = (alpha * FFABS(t)) >> 7;

        if (u > 3 - (filter_p1 && filter_q1))

            continue;

        t <<= 2;

        if (filter_p1 && filter_q1)

            t += src[-2*step] - src[1*step];

        diff = CLIP_SYMM((t + 4) >> 3, lim_p0q0);

        src[-1*step] = cm[src[-1*step] + diff];

        src[ 0*step] = cm[src[ 0*step] - diff];

        if (filter_p1 && FFABS(diff_p1p2) <= beta) {

            t = (diff_p1p0 + diff_p1p2 - diff) >> 1;

            src[-2*step] = cm[src[-2*step] - CLIP_SYMM(t, lim_p1)];

        }

        if (filter_q1 && FFABS(diff_q1q2) <= beta) {

            t = (diff_q1q0 + diff_q1q2 + diff) >> 1;

            src[ 1*step] = cm[src[ 1*step] - CLIP_SYMM(t, lim_q1)];

        }

    }

}


static void con_disconnect(struct XenDevice *xendev)

{

    struct XenConsole *con = container_of(xendev, struct XenConsole, xendev);

    if (con->chr) {

        qemu_chr_add_handlers(con->chr, NULL, NULL, NULL, NULL);

        qemu_chr_fe_release(con->chr);

    }

    xen_be_unbind_evtchn(&con->xendev);

    if (con->sring) {

        if (!xendev->dev) {

            munmap(con->sring, XC_PAGE_SIZE);

        } else {

            xengnttab_unmap(xendev->gnttabdev, con->sring, 1);

        }

        con->sring = NULL;

    }

}


static int normalize_bits(int num, int width)

{

    if (!num)

        return 0;

    if (num == -1)

        return width;

    if (num < 0)

        num = ~num;

    return width - av_log2(num);

}


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

{

    DeviceClass *dc = DEVICE_CLASS(klass);

    PCIDeviceClass *k = PCI_DEVICE_CLASS(klass);

    k->realize = xen_pt_realize;

    k->exit = xen_pt_unregister_device;

    k->config_read = xen_pt_pci_read_config;

    k->config_write = xen_pt_pci_write_config;

    set_bit(DEVICE_CATEGORY_MISC, dc->categories);

    dc->desc = "Assign an host PCI device with Xen";

    dc->props = xen_pci_passthrough_properties;

};


static int ohci_bus_start(OHCIState *ohci)

{

    ohci->eof_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL,

                    ohci_frame_boundary,

                    ohci);

    if (ohci->eof_timer == NULL) {

        trace_usb_ohci_bus_eof_timer_failed(ohci->name);

        ohci_die(ohci);

        return 0;

    }

    trace_usb_ohci_start(ohci->name);

    /* Delay the first SOF event by one frame time as

     * linux driver is not ready to receive it and

     * can meet some race conditions

     */

    ohci_eof_timer(ohci);

    return 1;

}


void bdrv_image_info_specific_dump(fprintf_function func_fprintf, void *f,

                                   ImageInfoSpecific *info_spec)

{

    QObject *obj, *data;

    Visitor *v = qmp_output_visitor_new(&obj);

    visit_type_ImageInfoSpecific(v, NULL, &info_spec, &error_abort);

    visit_complete(v, &obj);

    assert(qobject_type(obj) == QTYPE_QDICT);

    data = qdict_get(qobject_to_qdict(obj), "data");

    dump_qobject(func_fprintf, f, 1, data);

    visit_free(v);

}


static int srt_decode_frame(AVCodecContext *avctx,

                            void *data, int *got_sub_ptr, AVPacket *avpkt)

{

    AVSubtitle *sub = data;

    AVBPrint buffer;

    int x1 = -1, y1 = -1, x2 = -1, y2 = -1;

    int size, ret;

    const uint8_t *p = av_packet_get_side_data(avpkt, AV_PKT_DATA_SUBTITLE_POSITION, &size);

    FFASSDecoderContext *s = avctx->priv_data;

    if (p && size == 16) {

        x1 = AV_RL32(p     );

        y1 = AV_RL32(p +  4);

        x2 = AV_RL32(p +  8);

        y2 = AV_RL32(p + 12);

    }

    if (avpkt->size <= 0)

        return avpkt->size;

    av_bprint_init(&buffer, 0, AV_BPRINT_SIZE_UNLIMITED);

    srt_to_ass(avctx, &buffer, avpkt->data, x1, y1, x2, y2);

    ret = ff_ass_add_rect(sub, buffer.str, s->readorder++, 0, NULL, NULL);

    av_bprint_finalize(&buffer, NULL);

    if (ret < 0)

        return ret;

    *got_sub_ptr = sub->num_rects > 0;

    return avpkt->size;

}


static int filter_slice(AVFilterContext *ctx, void *arg, int jobnr, int nb_jobs)

{

    YADIFContext *s = ctx->priv;

    ThreadData *td  = arg;

    int refs = s->cur->linesize[td->plane];

    int df = (s->csp->comp[td->plane].depth_minus1 + 8) / 8;

    int pix_3 = 3 * df;

    int slice_h = td->h / nb_jobs;

    int slice_start = jobnr * slice_h;

    int slice_end   = (jobnr == nb_jobs - 1) ? td->h : (jobnr + 1) * slice_h;

    int y;

    /* filtering reads 3 pixels to the left/right; to avoid invalid reads,

     * we need to call the c variant which avoids this for border pixels

     */

    for (y = slice_start; y < slice_end; y++) {

        if ((y ^ td->parity) & 1) {

            uint8_t *prev = &s->prev->data[td->plane][y * refs];

            uint8_t *cur  = &s->cur ->data[td->plane][y * refs];

            uint8_t *next = &s->next->data[td->plane][y * refs];

            uint8_t *dst  = &td->frame->data[td->plane][y * td->frame->linesize[td->plane]];

            int     mode  = y == 1 || y + 2 == td->h ? 2 : s->mode;

            s->filter_line(dst + pix_3, prev + pix_3, cur + pix_3,

                           next + pix_3, td->w - 6,

                           y + 1 < td->h ? refs : -refs,

                           y ? -refs : refs,

                           td->parity ^ td->tff, mode);

            s->filter_edges(dst, prev, cur, next, td->w,

                            y + 1 < td->h ? refs : -refs,

                            y ? -refs : refs,

                            td->parity ^ td->tff, mode);

        } else {

            memcpy(&td->frame->data[td->plane][y * td->frame->linesize[td->plane]],

                   &s->cur->data[td->plane][y * refs], td->w * df);

        }

    }

    return 0;

}


int ppc64_v3_handle_mmu_fault(PowerPCCPU *cpu, vaddr eaddr, int rwx,

                              int mmu_idx)

{

    if (ppc64_radix_guest(cpu)) { /* Guest uses radix */

        /* TODO - Unsupported */

        error_report("Guest Radix Support Unimplemented");

        exit(1);

    } else { /* Guest uses hash */

        return ppc_hash64_handle_mmu_fault(cpu, eaddr, rwx, mmu_idx);

    }

}


int ff_img_read_packet(AVFormatContext *s1, AVPacket *pkt)

{

    VideoDemuxData *s = s1->priv_data;

    char filename_bytes[1024];

    char *filename = filename_bytes;

    int i;

    int size[3]           = { 0 }, ret[3] = { 0 };

    AVIOContext *f[3]     = { NULL };

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

    if (!s->is_pipe) {

        /* loop over input */

        if (s->loop && s->img_number > s->img_last) {

            s->img_number = s->img_first;

        }

        if (s->img_number > s->img_last)

            return AVERROR_EOF;

        if (s->use_glob) {

#if HAVE_GLOB

            filename = s->globstate.gl_pathv[s->img_number];

#endif

        } else {

        if (av_get_frame_filename(filename_bytes, sizeof(filename_bytes),

                                  s->path,

                                  s->img_number) < 0 && s->img_number > 1)

            return AVERROR(EIO);

        }

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

            if (avio_open2(&f[i], filename, AVIO_FLAG_READ,

                           &s1->interrupt_callback, NULL) < 0) {

                if (i >= 1)

                    break;

                av_log(s1, AV_LOG_ERROR, "Could not open file : %s\n",

                       filename);

                return AVERROR(EIO);

            }

            size[i] = avio_size(f[i]);

            if (!s->split_planes)

                break;

            filename[strlen(filename) - 1] = 'U' + i;

        }

        if (codec->codec_id == AV_CODEC_ID_NONE) {

            AVProbeData pd;

            AVInputFormat *ifmt;

            uint8_t header[PROBE_BUF_MIN + AVPROBE_PADDING_SIZE];

            int ret;

            int score = 0;

            ret = avio_read(f[0], header, PROBE_BUF_MIN);

            if (ret < 0)

                return ret;

            avio_skip(f[0], -ret);

            pd.buf = header;

            pd.buf_size = ret;

            pd.filename = filename;

            ifmt = av_probe_input_format3(&pd, 1, &score);

            if (ifmt && ifmt->read_packet == ff_img_read_packet && ifmt->raw_codec_id)

                codec->codec_id = ifmt->raw_codec_id;

        }

        if (codec->codec_id == AV_CODEC_ID_RAWVIDEO && !codec->width)

            infer_size(&codec->width, &codec->height, size[0]);

    } else {

        f[0] = s1->pb;

        if (url_feof(f[0]))

            return AVERROR(EIO);

        if (s->frame_size > 0) {

            size[0] = s->frame_size;

        } else {

            size[0] = 4096;

        }

    }

    if (av_new_packet(pkt, size[0] + size[1] + size[2]) < 0)

        return AVERROR(ENOMEM);

    pkt->stream_index = 0;

    pkt->flags       |= AV_PKT_FLAG_KEY;

    if (s->ts_from_file) {

        struct stat img_stat;

        if (stat(filename, &img_stat))

            return AVERROR(EIO);

        pkt->pts = (int64_t)img_stat.st_mtime;

        av_add_index_entry(s1->streams[0], s->img_number, pkt->pts, 0, 0, AVINDEX_KEYFRAME);

    } else if (!s->is_pipe) {

        pkt->pts      = s->pts;

    }

    pkt->size = 0;

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

        if (f[i]) {

            ret[i] = avio_read(f[i], pkt->data + pkt->size, size[i]);

            if (!s->is_pipe)

                avio_close(f[i]);

            if (ret[i] > 0)

                pkt->size += ret[i];

        }

    }

    if (ret[0] <= 0 || ret[1] < 0 || ret[2] < 0) {

        av_free_packet(pkt);

        return AVERROR(EIO); /* signal EOF */

    } else {

        s->img_count++;

        s->img_number++;

        s->pts++;

        return 0;

    }

}


void ide_data_writew(void *opaque, uint32_t addr, uint32_t val)

{

    IDEBus *bus = opaque;

    IDEState *s = idebus_active_if(bus);

    uint8_t *p;

    /* PIO data access allowed only when DRQ bit is set */

    if (!(s->status & DRQ_STAT))

        return;

    p = s->data_ptr;

    *(uint16_t *)p = le16_to_cpu(val);

    p += 2;

    s->data_ptr = p;

    if (p >= s->data_end)

        s->end_transfer_func(s);

}


static void quantize_and_encode_band_cost_SPAIR_mips(struct AACEncContext *s,

                                                     PutBitContext *pb, const float *in, float *out,

                                                     const float *scaled, int size, int scale_idx,

                                                     int cb, const float lambda, const float uplim,

                                                     int *bits, const float ROUNDING)

{

    const float Q34 = ff_aac_pow34sf_tab[POW_SF2_ZERO - scale_idx + SCALE_ONE_POS - SCALE_DIV_512];

    const float IQ  = ff_aac_pow2sf_tab [POW_SF2_ZERO + scale_idx - SCALE_ONE_POS + SCALE_DIV_512];

    int i;

    int qc1, qc2, qc3, qc4;

    uint8_t  *p_bits  = (uint8_t  *)ff_aac_spectral_bits[cb-1];

    uint16_t *p_codes = (uint16_t *)ff_aac_spectral_codes[cb-1];

    float    *p_vec   = (float    *)ff_aac_codebook_vectors[cb-1];

    abs_pow34_v(s->scoefs, in, size);

    scaled = s->scoefs;

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

        int curidx, curidx2;

        int *in_int = (int *)&in[i];

        uint8_t v_bits;

        unsigned int v_codes;

        int t0, t1, t2, t3, t4, t5, t6, t7;

        const float *vec1, *vec2;

        qc1 = scaled[i  ] * Q34 + ROUND_STANDARD;

        qc2 = scaled[i+1] * Q34 + ROUND_STANDARD;

        qc3 = scaled[i+2] * Q34 + ROUND_STANDARD;

        qc4 = scaled[i+3] * Q34 + ROUND_STANDARD;

        __asm__ volatile (

            ".set push                      \n\t"

            ".set noreorder                 \n\t"

            "ori    %[t4],  $zero,  4       \n\t"

            "slt    %[t0],  %[t4],  %[qc1]  \n\t"

            "slt    %[t1],  %[t4],  %[qc2]  \n\t"

            "slt    %[t2],  %[t4],  %[qc3]  \n\t"

            "slt    %[t3],  %[t4],  %[qc4]  \n\t"

            "movn   %[qc1], %[t4],  %[t0]   \n\t"

            "movn   %[qc2], %[t4],  %[t1]   \n\t"

            "movn   %[qc3], %[t4],  %[t2]   \n\t"

            "movn   %[qc4], %[t4],  %[t3]   \n\t"

            "lw     %[t0],  0(%[in_int])    \n\t"

            "lw     %[t1],  4(%[in_int])    \n\t"

            "lw     %[t2],  8(%[in_int])    \n\t"

            "lw     %[t3],  12(%[in_int])   \n\t"

            "srl    %[t0],  %[t0],  31      \n\t"

            "srl    %[t1],  %[t1],  31      \n\t"

            "srl    %[t2],  %[t2],  31      \n\t"

            "srl    %[t3],  %[t3],  31      \n\t"

            "subu   %[t4],  $zero,  %[qc1]  \n\t"

            "subu   %[t5],  $zero,  %[qc2]  \n\t"

            "subu   %[t6],  $zero,  %[qc3]  \n\t"

            "subu   %[t7],  $zero,  %[qc4]  \n\t"

            "movn   %[qc1], %[t4],  %[t0]   \n\t"

            "movn   %[qc2], %[t5],  %[t1]   \n\t"

            "movn   %[qc3], %[t6],  %[t2]   \n\t"

            "movn   %[qc4], %[t7],  %[t3]   \n\t"

            ".set pop                       \n\t"

            : [qc1]"+r"(qc1), [qc2]"+r"(qc2),

              [qc3]"+r"(qc3), [qc4]"+r"(qc4),

              [t0]"=&r"(t0), [t1]"=&r"(t1), [t2]"=&r"(t2), [t3]"=&r"(t3),

              [t4]"=&r"(t4), [t5]"=&r"(t5), [t6]"=&r"(t6), [t7]"=&r"(t7)

            : [in_int]"r"(in_int)

            : "memory"

        );

        curidx = 9 * qc1;

        curidx += qc2 + 40;

        curidx2 = 9 * qc3;

        curidx2 += qc4 + 40;

        v_codes = (p_codes[curidx] << p_bits[curidx2]) | (p_codes[curidx2]);

        v_bits  = p_bits[curidx] + p_bits[curidx2];

        put_bits(pb, v_bits, v_codes);

        if (out) {

           vec1 = &p_vec[curidx*2 ];

           vec2 = &p_vec[curidx2*2];

           out[i+0] = vec1[0] * IQ;

           out[i+1] = vec1[1] * IQ;

           out[i+2] = vec2[0] * IQ;

           out[i+3] = vec2[1] * IQ;

        }

    }

}


static int stream_component_open(PlayerState *is, int stream_index)

{

    AVFormatContext *ic = is->ic;

    AVCodecContext *avctx;

    AVCodec *codec;

    SDL_AudioSpec wanted_spec, spec;

    AVDictionary *opts;

    AVDictionaryEntry *t = NULL;

    int ret = 0;

    if (stream_index < 0 || stream_index >= ic->nb_streams)

        return -1;

    avctx = ic->streams[stream_index]->codec;

    opts = filter_codec_opts(codec_opts, avctx->codec_id, ic, ic->streams[stream_index], NULL);

    codec = avcodec_find_decoder(avctx->codec_id);

    avctx->workaround_bugs   = workaround_bugs;

    avctx->idct_algo         = idct;

    avctx->skip_frame        = skip_frame;

    avctx->skip_idct         = skip_idct;

    avctx->skip_loop_filter  = skip_loop_filter;

    avctx->error_concealment = error_concealment;

    if (fast)

        avctx->flags2 |= AV_CODEC_FLAG2_FAST;

    if (!av_dict_get(opts, "threads", NULL, 0))

        av_dict_set(&opts, "threads", "auto", 0);

    if (avctx->codec_type == AVMEDIA_TYPE_VIDEO)

        av_dict_set(&opts, "refcounted_frames", "1", 0);

    if (!codec ||

        (ret = avcodec_open2(avctx, codec, &opts)) < 0) {

        goto fail;

    }

    if ((t = av_dict_get(opts, "", NULL, AV_DICT_IGNORE_SUFFIX))) {

        av_log(NULL, AV_LOG_ERROR, "Option %s not found.\n", t->key);

        ret =  AVERROR_OPTION_NOT_FOUND;

        goto fail;

    }

    /* prepare audio output */

    if (avctx->codec_type == AVMEDIA_TYPE_AUDIO) {

        is->sdl_sample_rate = avctx->sample_rate;

        if (!avctx->channel_layout)

            avctx->channel_layout = av_get_default_channel_layout(avctx->channels);

        if (!avctx->channel_layout) {

            fprintf(stderr, "unable to guess channel layout\n");

            ret = AVERROR_INVALIDDATA;

            goto fail;

        }

        if (avctx->channels == 1)

            is->sdl_channel_layout = AV_CH_LAYOUT_MONO;

        else

            is->sdl_channel_layout = AV_CH_LAYOUT_STEREO;

        is->sdl_channels = av_get_channel_layout_nb_channels(is->sdl_channel_layout);

        wanted_spec.format = AUDIO_S16SYS;

        wanted_spec.freq = is->sdl_sample_rate;

        wanted_spec.channels = is->sdl_channels;

        wanted_spec.silence = 0;

        wanted_spec.samples = SDL_AUDIO_BUFFER_SIZE;

        wanted_spec.callback = sdl_audio_callback;

        wanted_spec.userdata = is;

        if (SDL_OpenAudio(&wanted_spec, &spec) < 0) {

            fprintf(stderr, "SDL_OpenAudio: %s\n", SDL_GetError());

            ret = AVERROR_UNKNOWN;

            goto fail;

        }

        is->audio_hw_buf_size = spec.size;

        is->sdl_sample_fmt          = AV_SAMPLE_FMT_S16;

        is->resample_sample_fmt     = is->sdl_sample_fmt;

        is->resample_channel_layout = avctx->channel_layout;

        is->resample_sample_rate    = avctx->sample_rate;

    }

    ic->streams[stream_index]->discard = AVDISCARD_DEFAULT;

    switch (avctx->codec_type) {

    case AVMEDIA_TYPE_AUDIO:

        is->audio_stream = stream_index;

        is->audio_st = ic->streams[stream_index];

        is->audio_buf_size  = 0;

        is->audio_buf_index = 0;

        /* init averaging filter */

        is->audio_diff_avg_coef  = exp(log(0.01) / AUDIO_DIFF_AVG_NB);

        is->audio_diff_avg_count = 0;

        /* since we do not have a precise anough audio fifo fullness,

           we correct audio sync only if larger than this threshold */

        is->audio_diff_threshold = 2.0 * SDL_AUDIO_BUFFER_SIZE / avctx->sample_rate;

        memset(&is->audio_pkt, 0, sizeof(is->audio_pkt));

        packet_queue_init(&is->audioq);

        SDL_PauseAudio(0);

        break;

    case AVMEDIA_TYPE_VIDEO:

        is->video_stream = stream_index;

        is->video_st = ic->streams[stream_index];

        packet_queue_init(&is->videoq);

        is->video_tid = SDL_CreateThread(video_thread, is);

        break;

    case AVMEDIA_TYPE_SUBTITLE:

        is->subtitle_stream = stream_index;

        is->subtitle_st = ic->streams[stream_index];

        packet_queue_init(&is->subtitleq);

        is->subtitle_tid = SDL_CreateThread(subtitle_thread, is);

        break;

    default:

        break;

    }

fail:

    av_dict_free(&opts);

    return ret;

}


static void keyword_literal(void)

{

    QObject *obj;

    QBool *qbool;

    QObject *null;

    QString *str;

    obj = qobject_from_json("true", NULL);

    qbool = qobject_to_qbool(obj);

    g_assert(qbool);

    g_assert(qbool_get_bool(qbool) == true);

    str = qobject_to_json(obj);

    g_assert(strcmp(qstring_get_str(str), "true") == 0);

    QDECREF(str);

    QDECREF(qbool);

    obj = qobject_from_json("false", NULL);

    qbool = qobject_to_qbool(obj);

    g_assert(qbool);

    g_assert(qbool_get_bool(qbool) == false);

    str = qobject_to_json(obj);

    g_assert(strcmp(qstring_get_str(str), "false") == 0);

    QDECREF(str);

    QDECREF(qbool);

    qbool = qobject_to_qbool(qobject_from_jsonf("%i", false));

    g_assert(qbool);

    g_assert(qbool_get_bool(qbool) == false);

    QDECREF(qbool);

    /* Test that non-zero values other than 1 get collapsed to true */

    qbool = qobject_to_qbool(qobject_from_jsonf("%i", 2));

    g_assert(qbool);

    g_assert(qbool_get_bool(qbool) == true);

    QDECREF(qbool);

    obj = qobject_from_json("null", NULL);

    g_assert(obj != NULL);

    g_assert(qobject_type(obj) == QTYPE_QNULL);

    null = qnull();

    g_assert(null == obj);

    qobject_decref(obj);

    qobject_decref(null);

}


static void ppc_core99_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)

{

    CPUState *env = NULL, *envs[MAX_CPUS];

    char *filename;

    qemu_irq *pic, **openpic_irqs;

    int unin_memory;

    int linux_boot, i;

    ram_addr_t ram_offset, bios_offset, vga_bios_offset;

    uint32_t kernel_base, kernel_size, initrd_base, initrd_size;

    PCIBus *pci_bus;

    MacIONVRAMState *nvr;

    int nvram_mem_index;

    int vga_bios_size, bios_size;

    int pic_mem_index, dbdma_mem_index, cuda_mem_index, escc_mem_index;

    int ide_mem_index[3];

    int ppc_boot_device;

    DriveInfo *hd[MAX_IDE_BUS * MAX_IDE_DEVS];

    void *fw_cfg;

    void *dbdma;

    uint8_t *vga_bios_ptr;

    int machine_arch;

    linux_boot = (kernel_filename != NULL);

    /* init CPUs */

    if (cpu_model == NULL)

#ifdef TARGET_PPC64

        cpu_model = "970fx";

#else

        cpu_model = "G4";

#endif

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

        env = cpu_init(cpu_model);

        if (!env) {

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

            exit(1);

        }

        /* Set time-base frequency to 100 Mhz */

        cpu_ppc_tb_init(env, 100UL * 1000UL * 1000UL);

#if 0

        env->osi_call = vga_osi_call;

#endif

        qemu_register_reset((QEMUResetHandler*)&cpu_reset, env);

        envs[i] = env;

    }

    /* allocate RAM */

    ram_offset = qemu_ram_alloc(NULL, "ppc_core99.ram", ram_size);

    cpu_register_physical_memory(0, ram_size, ram_offset);

    /* allocate and load BIOS */

    bios_offset = qemu_ram_alloc(NULL, "ppc_core99.bios", BIOS_SIZE);

    if (bios_name == NULL)

        bios_name = PROM_FILENAME;

    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);

    cpu_register_physical_memory(PROM_ADDR, BIOS_SIZE, bios_offset | IO_MEM_ROM);

    /* Load OpenBIOS (ELF) */

    if (filename) {

        bios_size = load_elf(filename, NULL, NULL, NULL,

                             NULL, NULL, 1, ELF_MACHINE, 0);

        qemu_free(filename);

    } else {

        bios_size = -1;

    }

    if (bios_size < 0 || bios_size > BIOS_SIZE) {

        hw_error("qemu: could not load PowerPC bios '%s'\n", bios_name);

        exit(1);

    }

    /* allocate and load VGA BIOS */

    vga_bios_offset = qemu_ram_alloc(NULL, "ppc_core99.vbios", VGA_BIOS_SIZE);

    vga_bios_ptr = qemu_get_ram_ptr(vga_bios_offset);

    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, VGABIOS_FILENAME);

    if (filename) {

        vga_bios_size = load_image(filename, vga_bios_ptr + 8);

        qemu_free(filename);

    } else {

        vga_bios_size = -1;

    }

    if (vga_bios_size < 0) {

        /* if no bios is present, we can still work */

        fprintf(stderr, "qemu: warning: could not load VGA bios '%s'\n",

                VGABIOS_FILENAME);

        vga_bios_size = 0;

    } else {

        /* set a specific header (XXX: find real Apple format for NDRV

           drivers) */

        vga_bios_ptr[0] = 'N';

        vga_bios_ptr[1] = 'D';

        vga_bios_ptr[2] = 'R';

        vga_bios_ptr[3] = 'V';

        cpu_to_be32w((uint32_t *)(vga_bios_ptr + 4), vga_bios_size);

        vga_bios_size += 8;

        /* Round to page boundary */

        vga_bios_size = (vga_bios_size + TARGET_PAGE_SIZE - 1) &

            TARGET_PAGE_MASK;

    }

    if (linux_boot) {

        uint64_t lowaddr = 0;

        int bswap_needed;

#ifdef BSWAP_NEEDED

        bswap_needed = 1;

#else

        bswap_needed = 0;

#endif

        kernel_base = KERNEL_LOAD_ADDR;

        kernel_size = load_elf(kernel_filename, translate_kernel_address, NULL,

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

        if (kernel_size < 0)

            kernel_size = load_aout(kernel_filename, kernel_base,

                                    ram_size - kernel_base, bswap_needed,

                                    TARGET_PAGE_SIZE);

        if (kernel_size < 0)

            kernel_size = load_image_targphys(kernel_filename,

                                              kernel_base,

                                              ram_size - kernel_base);

        if (kernel_size < 0) {

            hw_error("qemu: could not load kernel '%s'\n", kernel_filename);

            exit(1);

        }

        /* load initrd */

        if (initrd_filename) {

            initrd_base = INITRD_LOAD_ADDR;

            initrd_size = load_image_targphys(initrd_filename, initrd_base,

                                              ram_size - initrd_base);

            if (initrd_size < 0) {

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

                         initrd_filename);

                exit(1);

            }

        } else {

            initrd_base = 0;

            initrd_size = 0;

        }

        ppc_boot_device = 'm';

    } else {

        kernel_base = 0;

        kernel_size = 0;

        initrd_base = 0;

        initrd_size = 0;

        ppc_boot_device = '\0';

        /* We consider that NewWorld PowerMac never have any floppy drive

         * For now, OHW cannot boot from the network.

         */

        for (i = 0; boot_device[i] != '\0'; i++) {

            if (boot_device[i] >= 'c' && boot_device[i] <= 'f') {

                ppc_boot_device = boot_device[i];

                break;

            }

        }

        if (ppc_boot_device == '\0') {

            fprintf(stderr, "No valid boot device for Mac99 machine\n");

            exit(1);

        }

    }

    isa_mem_base = 0x80000000;

    /* Register 8 MB of ISA IO space */

    isa_mmio_init(0xf2000000, 0x00800000, 1);

    /* UniN init */

    unin_memory = cpu_register_io_memory(unin_read, unin_write, NULL);

    cpu_register_physical_memory(0xf8000000, 0x00001000, unin_memory);

    openpic_irqs = qemu_mallocz(smp_cpus * sizeof(qemu_irq *));

    openpic_irqs[0] =

        qemu_mallocz(smp_cpus * sizeof(qemu_irq) * OPENPIC_OUTPUT_NB);

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

        /* Mac99 IRQ connection between OpenPIC outputs pins

         * and PowerPC input pins

         */

        switch (PPC_INPUT(env)) {

        case PPC_FLAGS_INPUT_6xx:

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

            openpic_irqs[i][OPENPIC_OUTPUT_INT] =

                ((qemu_irq *)env->irq_inputs)[PPC6xx_INPUT_INT];

            openpic_irqs[i][OPENPIC_OUTPUT_CINT] =

                ((qemu_irq *)env->irq_inputs)[PPC6xx_INPUT_INT];

            openpic_irqs[i][OPENPIC_OUTPUT_MCK] =

                ((qemu_irq *)env->irq_inputs)[PPC6xx_INPUT_MCP];

            /* Not connected ? */

            openpic_irqs[i][OPENPIC_OUTPUT_DEBUG] = NULL;

            /* Check this */

            openpic_irqs[i][OPENPIC_OUTPUT_RESET] =

                ((qemu_irq *)env->irq_inputs)[PPC6xx_INPUT_HRESET];

            break;

#if defined(TARGET_PPC64)

        case PPC_FLAGS_INPUT_970:

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

            openpic_irqs[i][OPENPIC_OUTPUT_INT] =

                ((qemu_irq *)env->irq_inputs)[PPC970_INPUT_INT];

            openpic_irqs[i][OPENPIC_OUTPUT_CINT] =

                ((qemu_irq *)env->irq_inputs)[PPC970_INPUT_INT];

            openpic_irqs[i][OPENPIC_OUTPUT_MCK] =

                ((qemu_irq *)env->irq_inputs)[PPC970_INPUT_MCP];

            /* Not connected ? */

            openpic_irqs[i][OPENPIC_OUTPUT_DEBUG] = NULL;

            /* Check this */

            openpic_irqs[i][OPENPIC_OUTPUT_RESET] =

                ((qemu_irq *)env->irq_inputs)[PPC970_INPUT_HRESET];

            break;

#endif /* defined(TARGET_PPC64) */

        default:

            hw_error("Bus model not supported on mac99 machine\n");

            exit(1);

        }

    }

    pic = openpic_init(NULL, &pic_mem_index, smp_cpus, openpic_irqs, NULL);

    if (PPC_INPUT(env) == PPC_FLAGS_INPUT_970) {

        /* 970 gets a U3 bus */

        pci_bus = pci_pmac_u3_init(pic);

        machine_arch = ARCH_MAC99_U3;

    } else {

        pci_bus = pci_pmac_init(pic);

        machine_arch = ARCH_MAC99;

    }

    /* init basic PC hardware */

    pci_vga_init(pci_bus, vga_bios_offset, vga_bios_size);

    escc_mem_index = escc_init(0x80013000, pic[0x25], pic[0x24],

                               serial_hds[0], serial_hds[1], ESCC_CLOCK, 4);

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

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

    if (drive_get_max_bus(IF_IDE) >= MAX_IDE_BUS) {

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

        exit(1);

    }

    dbdma = DBDMA_init(&dbdma_mem_index);

    /* We only emulate 2 out of 3 IDE controllers for now */

    ide_mem_index[0] = -1;

    hd[0] = drive_get(IF_IDE, 0, 0);

    hd[1] = drive_get(IF_IDE, 0, 1);

    ide_mem_index[1] = pmac_ide_init(hd, pic[0x0d], dbdma, 0x16, pic[0x02]);

    hd[0] = drive_get(IF_IDE, 1, 0);

    hd[1] = drive_get(IF_IDE, 1, 1);

    ide_mem_index[2] = pmac_ide_init(hd, pic[0x0e], dbdma, 0x1a, pic[0x02]);

    /* cuda also initialize ADB */

    if (machine_arch == ARCH_MAC99_U3) {

        usb_enabled = 1;

    }

    cuda_init(&cuda_mem_index, pic[0x19]);

    adb_kbd_init(&adb_bus);

    adb_mouse_init(&adb_bus);

    macio_init(pci_bus, PCI_DEVICE_ID_APPLE_UNI_N_KEYL, 0, pic_mem_index,

               dbdma_mem_index, cuda_mem_index, NULL, 3, ide_mem_index,

               escc_mem_index);

    if (usb_enabled) {

        usb_ohci_init_pci(pci_bus, -1);

    }

    /* U3 needs to use USB for input because Linux doesn't support via-cuda

       on PPC64 */

    if (machine_arch == ARCH_MAC99_U3) {

        usbdevice_create("keyboard");

        usbdevice_create("mouse");

    }

    if (graphic_depth != 15 && graphic_depth != 32 && graphic_depth != 8)

        graphic_depth = 15;

    /* The NewWorld NVRAM is not located in the MacIO device */

    nvr = macio_nvram_init(&nvram_mem_index, 0x2000, 1);

    pmac_format_nvram_partition(nvr, 0x2000);

    macio_nvram_map(nvr, 0xFFF04000);

    /* No PCI init: the BIOS will do it */

    fw_cfg = fw_cfg_init(0, 0, CFG_ADDR, CFG_ADDR + 2);

    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, machine_arch);

    fw_cfg_add_i32(fw_cfg, FW_CFG_KERNEL_ADDR, kernel_base);

    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", 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_base);

    fw_cfg_add_i32(fw_cfg, FW_CFG_INITRD_SIZE, initrd_size);

    fw_cfg_add_i16(fw_cfg, FW_CFG_BOOT_DEVICE, ppc_boot_device);

    fw_cfg_add_i16(fw_cfg, FW_CFG_PPC_WIDTH, graphic_width);

    fw_cfg_add_i16(fw_cfg, FW_CFG_PPC_HEIGHT, graphic_height);

    fw_cfg_add_i16(fw_cfg, FW_CFG_PPC_DEPTH, graphic_depth);

    fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_IS_KVM, kvm_enabled());

    if (kvm_enabled()) {

#ifdef CONFIG_KVM

        uint8_t *hypercall;

        fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_TBFREQ, kvmppc_get_tbfreq());

        hypercall = qemu_malloc(16);

        kvmppc_get_hypercall(env, hypercall, 16);

        fw_cfg_add_bytes(fw_cfg, FW_CFG_PPC_KVM_HC, hypercall, 16);

        fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_KVM_PID, getpid());

#endif

    } else {

        fw_cfg_add_i32(fw_cfg, FW_CFG_PPC_TBFREQ, get_ticks_per_sec());

    }

    qemu_register_boot_set(fw_cfg_boot_set, fw_cfg);

}


void DMA_run(void)

{

    /* XXXXX */

}


INLINE int16 extractFloat64Exp( float64 a )

{

    return ( a>>52 ) & 0x7FF;

}


uint32_t helper_fcmp_un(uint32_t a, uint32_t b)

{

    CPU_FloatU fa, fb;

    uint32_t r = 0;

    fa.l = a;

    fb.l = b;

    if (float32_is_signaling_nan(fa.f) || float32_is_signaling_nan(fb.f)) {

        update_fpu_flags(float_flag_invalid);

        r = 1;

    }

    if (float32_is_nan(fa.f) || float32_is_nan(fb.f)) {

        r = 1;

    }

    return r;

}


static int vhost_user_start(VhostUserState *s)

{

    VhostNetOptions options;

    if (vhost_user_running(s)) {

        return 0;

    }

    options.backend_type = VHOST_BACKEND_TYPE_USER;

    options.net_backend = &s->nc;

    options.opaque = s->chr;

    s->vhost_net = vhost_net_init(&options);

    return vhost_user_running(s) ? 0 : -1;

}


static int alac_set_info(ALACContext *alac)

{

    GetByteContext gb;

    bytestream2_init(&gb, alac->avctx->extradata,

                     alac->avctx->extradata_size);

    bytestream2_skipu(&gb, 12); // size:4, alac:4, version:4

    alac->max_samples_per_frame = bytestream2_get_be32u(&gb);

    if (alac->max_samples_per_frame >= UINT_MAX/4){

        av_log(alac->avctx, AV_LOG_ERROR,

               "max_samples_per_frame too large\n");

        return AVERROR_INVALIDDATA;

    }

    bytestream2_skipu(&gb, 1);  // compatible version

    alac->sample_size          = bytestream2_get_byteu(&gb);

    alac->rice_history_mult    = bytestream2_get_byteu(&gb);

    alac->rice_initial_history = bytestream2_get_byteu(&gb);

    alac->rice_limit           = bytestream2_get_byteu(&gb);

    alac->channels             = bytestream2_get_byteu(&gb);

    bytestream2_get_be16u(&gb); // maxRun

    bytestream2_get_be32u(&gb); // max coded frame size

    bytestream2_get_be32u(&gb); // average bitrate

    bytestream2_get_be32u(&gb); // samplerate

    return 0;

}


static void sdhci_send_command(SDHCIState *s)

{

    SDRequest request;

    uint8_t response[16];

    int rlen;

    s->errintsts = 0;

    s->acmd12errsts = 0;

    request.cmd = s->cmdreg >> 8;

    request.arg = s->argument;

    DPRINT_L1("sending CMD%u ARG[0x%08x]\n", request.cmd, request.arg);

    rlen = sdbus_do_command(&s->sdbus, &request, response);

    if (s->cmdreg & SDHC_CMD_RESPONSE) {

        if (rlen == 4) {

            s->rspreg[0] = (response[0] << 24) | (response[1] << 16) |

                           (response[2] << 8)  |  response[3];

            s->rspreg[1] = s->rspreg[2] = s->rspreg[3] = 0;

            DPRINT_L1("Response: RSPREG[31..0]=0x%08x\n", s->rspreg[0]);

        } else if (rlen == 16) {

            s->rspreg[0] = (response[11] << 24) | (response[12] << 16) |

                           (response[13] << 8) |  response[14];

            s->rspreg[1] = (response[7] << 24) | (response[8] << 16) |

                           (response[9] << 8)  |  response[10];

            s->rspreg[2] = (response[3] << 24) | (response[4] << 16) |

                           (response[5] << 8)  |  response[6];

            s->rspreg[3] = (response[0] << 16) | (response[1] << 8) |

                            response[2];

            DPRINT_L1("Response received:\n RSPREG[127..96]=0x%08x, RSPREG[95.."

                  "64]=0x%08x,\n RSPREG[63..32]=0x%08x, RSPREG[31..0]=0x%08x\n",

                  s->rspreg[3], s->rspreg[2], s->rspreg[1], s->rspreg[0]);

        } else {

            ERRPRINT("Timeout waiting for command response\n");

            if (s->errintstsen & SDHC_EISEN_CMDTIMEOUT) {

                s->errintsts |= SDHC_EIS_CMDTIMEOUT;

                s->norintsts |= SDHC_NIS_ERR;

            }

        }

        if ((s->norintstsen & SDHC_NISEN_TRSCMP) &&

            (s->cmdreg & SDHC_CMD_RESPONSE) == SDHC_CMD_RSP_WITH_BUSY) {

            s->norintsts |= SDHC_NIS_TRSCMP;

        }

    }

    if (s->norintstsen & SDHC_NISEN_CMDCMP) {

        s->norintsts |= SDHC_NIS_CMDCMP;

    }

    sdhci_update_irq(s);

    if (s->blksize && (s->cmdreg & SDHC_CMD_DATA_PRESENT)) {

        s->data_count = 0;

        sdhci_data_transfer(s);

    }

}


static void test_dealloc_types(void)

{

    UserDefOne *ud1test, *ud1a, *ud1b;

    UserDefOneList *ud1list;

    ud1test = g_malloc0(sizeof(UserDefOne));

    ud1test->base = g_new0(UserDefZero, 1);

    ud1test->base->integer = 42;

    ud1test->string = g_strdup("hi there 42");

    qapi_free_UserDefOne(ud1test);

    ud1a = g_malloc0(sizeof(UserDefOne));

    ud1a->base = g_new0(UserDefZero, 1);

    ud1a->base->integer = 43;

    ud1a->string = g_strdup("hi there 43");

    ud1b = g_malloc0(sizeof(UserDefOne));

    ud1b->base = g_new0(UserDefZero, 1);

    ud1b->base->integer = 44;

    ud1b->string = g_strdup("hi there 44");

    ud1list = g_malloc0(sizeof(UserDefOneList));

    ud1list->value = ud1a;

    ud1list->next = g_malloc0(sizeof(UserDefOneList));

    ud1list->next->value = ud1b;

    qapi_free_UserDefOneList(ud1list);

}


void net_checksum_calculate(uint8_t *data, int length)

{

    int hlen, plen, proto, csum_offset;

    uint16_t csum;

    if ((data[14] & 0xf0) != 0x40)

	return; /* not IPv4 */

    hlen  = (data[14] & 0x0f) * 4;

    plen  = (data[16] << 8 | data[17]) - hlen;

    proto = data[23];

    switch (proto) {

    case PROTO_TCP:

	csum_offset = 16;

	break;

    case PROTO_UDP:

	csum_offset = 6;

	break;

    default:

	return;

    }

    if (plen < csum_offset+2)

	return;

    data[14+hlen+csum_offset]   = 0;

    data[14+hlen+csum_offset+1] = 0;

    csum = net_checksum_tcpudp(plen, proto, data+14+12, data+14+hlen);

    data[14+hlen+csum_offset]   = csum >> 8;

    data[14+hlen+csum_offset+1] = csum & 0xff;

}


static void x86_cpu_parse_featurestr(const char *typename, char *features,

                                     Error **errp)

{

    char *featurestr; /* Single 'key=value" string being parsed */

    static bool cpu_globals_initialized;

    bool ambiguous = false;

    if (cpu_globals_initialized) {

        return;

    }

    cpu_globals_initialized = true;

    if (!features) {

        return;

    }

    for (featurestr = strtok(features, ",");

         featurestr;

         featurestr = strtok(NULL, ",")) {

        const char *name;

        const char *val = NULL;

        char *eq = NULL;

        char num[32];

        GlobalProperty *prop;

        /* Compatibility syntax: */

        if (featurestr[0] == '+') {

            plus_features = g_list_append(plus_features,

                                          g_strdup(featurestr + 1));

            continue;

        } else if (featurestr[0] == '-') {

            minus_features = g_list_append(minus_features,

                                           g_strdup(featurestr + 1));

            continue;

        }

        eq = strchr(featurestr, '=');

        if (eq) {

            *eq++ = 0;

            val = eq;

        } else {

            val = "on";

        }

        feat2prop(featurestr);

        name = featurestr;

        if (g_list_find_custom(plus_features, name, compare_string)) {

            error_report("warning: Ambiguous CPU model string. "

                         "Don't mix both \"+%s\" and \"%s=%s\"",

                         name, name, val);

            ambiguous = true;

        }

        if (g_list_find_custom(minus_features, name, compare_string)) {

            error_report("warning: Ambiguous CPU model string. "

                         "Don't mix both \"-%s\" and \"%s=%s\"",

                         name, name, val);

            ambiguous = true;

        }

        /* Special case: */

        if (!strcmp(name, "tsc-freq")) {

            int64_t tsc_freq;

            tsc_freq = qemu_strtosz_metric(val, NULL);

            if (tsc_freq < 0) {

                error_setg(errp, "bad numerical value %s", val);

                return;

            }

            snprintf(num, sizeof(num), "%" PRId64, tsc_freq);

            val = num;

            name = "tsc-frequency";

        }

        prop = g_new0(typeof(*prop), 1);

        prop->driver = typename;

        prop->property = g_strdup(name);

        prop->value = g_strdup(val);

        prop->errp = &error_fatal;

        qdev_prop_register_global(prop);

    }

    if (ambiguous) {

        error_report("warning: Compatibility of ambiguous CPU model "

                     "strings won't be kept on future QEMU versions");

    }

}


static VirtIOSCSIVring *virtio_scsi_vring_init(VirtIOSCSI *s,

                                               VirtQueue *vq,

                                               EventNotifierHandler *handler,

                                               int n)

{

    BusState *qbus = BUS(qdev_get_parent_bus(DEVICE(s)));

    VirtioBusClass *k = VIRTIO_BUS_GET_CLASS(qbus);

    VirtIOSCSIVring *r = g_slice_new(VirtIOSCSIVring);

    int rc;

    /* Set up virtqueue notify */

    rc = k->set_host_notifier(qbus->parent, n, true);

    if (rc != 0) {

        fprintf(stderr, "virtio-scsi: Failed to set host notifier (%d)\n",

                rc);

        exit(1);

    }

    r->host_notifier = *virtio_queue_get_host_notifier(vq);

    r->guest_notifier = *virtio_queue_get_guest_notifier(vq);

    aio_set_event_notifier(s->ctx, &r->host_notifier, handler);

    r->parent = s;

    if (!vring_setup(&r->vring, VIRTIO_DEVICE(s), n)) {

        fprintf(stderr, "virtio-scsi: VRing setup failed\n");

        exit(1);

    }

    return r;

}


void qemu_net_queue_purge(NetQueue *queue, NetClientState *from)

{

    NetPacket *packet, *next;

    QTAILQ_FOREACH_SAFE(packet, &queue->packets, entry, next) {

        if (packet->sender == from) {

            QTAILQ_REMOVE(&queue->packets, packet, entry);

            g_free(packet);

        }

    }

}


static ssize_t vnc_client_read_tls(gnutls_session_t *session, uint8_t *data,

                                   size_t datalen)

{

    ssize_t ret = gnutls_read(*session, data, datalen);

    if (ret < 0) {

        if (ret == GNUTLS_E_AGAIN) {

            errno = EAGAIN;

        } else {

            errno = EIO;

        }

        ret = -1;

    }

    return ret;

}


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

{

    Mpeg1Context *s1  = avctx->priv_data;

    MpegEncContext *s = &s1->mpeg_enc_ctx;

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

        return 0;

    if (s->avctx->hwaccel) {

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

            av_log(avctx, AV_LOG_ERROR,

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

    }

#if FF_API_XVMC

FF_DISABLE_DEPRECATION_WARNINGS

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

        ff_xvmc_field_end(s);

FF_ENABLE_DEPRECATION_WARNINGS

#endif /* FF_API_XVMC */

    /* end of slice reached */

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

        /* end of image */

        ff_er_frame_end(&s->er);

        ff_MPV_frame_end(s);

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

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

            if (ret < 0)

                return ret;

            ff_print_debug_info(s, s->current_picture_ptr);

        } else {

            if (avctx->active_thread_type & FF_THREAD_FRAME)

                s->picture_number++;

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

            /* XXX: use another variable than picture_number */

            if (s->last_picture_ptr != NULL) {

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

                if (ret < 0)

                    return ret;

                ff_print_debug_info(s, s->last_picture_ptr);

            }

        }

        return 1;

    } else {

        return 0;

    }

}


static inline int mpeg2_fast_decode_block_non_intra(MpegEncContext *s,

                                                    int16_t *block, int n)

{

    int level, i, j, run;

    RLTable *rl = &ff_rl_mpeg1;

    uint8_t * const scantable = s->intra_scantable.permutated;

    const int qscale          = s->qscale;

    OPEN_READER(re, &s->gb);

    i = -1;

    // special case for first coefficient, no need to add second VLC table

    UPDATE_CACHE(re, &s->gb);

    if (((int32_t)GET_CACHE(re, &s->gb)) < 0) {

        level = (3 * qscale) >> 1;

        if (GET_CACHE(re, &s->gb) & 0x40000000)

            level = -level;

        block[0] = level;

        i++;

        SKIP_BITS(re, &s->gb, 2);

        if (((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)

            goto end;

    }

    /* now quantify & encode AC coefficients */

    for (;;) {

        GET_RL_VLC(level, run, re, &s->gb, rl->rl_vlc[0], TEX_VLC_BITS, 2, 0);

        if (level != 0) {

            i += run;

            j  = scantable[i];

            level = ((level * 2 + 1) * qscale) >> 1;

            level = (level ^ SHOW_SBITS(re, &s->gb, 1)) - SHOW_SBITS(re, &s->gb, 1);

            SKIP_BITS(re, &s->gb, 1);

        } else {

            /* escape */

            run = SHOW_UBITS(re, &s->gb, 6) + 1; LAST_SKIP_BITS(re, &s->gb, 6);

            UPDATE_CACHE(re, &s->gb);

            level = SHOW_SBITS(re, &s->gb, 12); SKIP_BITS(re, &s->gb, 12);

            i += run;

            j  = scantable[i];

            if (level < 0) {

                level = ((-level * 2 + 1) * qscale) >> 1;

                level = -level;

            } else {

                level = ((level * 2 + 1) * qscale) >> 1;

            }

        }

        block[j] = level;

        if (((int32_t)GET_CACHE(re, &s->gb)) <= (int32_t)0xBFFFFFFF)

            break;

        UPDATE_CACHE(re, &s->gb);

    }

end:

    LAST_SKIP_BITS(re, &s->gb, 2);

    CLOSE_READER(re, &s->gb);

    s->block_last_index[n] = i;

    return 0;

}


static void stream_close(VideoState *is)

{

    VideoPicture *vp;

    int i;

    /* XXX: use a special url_shutdown call to abort parse cleanly */

    is->abort_request = 1;

    SDL_WaitThread(is->read_tid, NULL);

    SDL_WaitThread(is->refresh_tid, NULL);

    packet_queue_destroy(&is->videoq);

    packet_queue_destroy(&is->audioq);

    packet_queue_destroy(&is->subtitleq);

    /* free all pictures */

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

        vp = &is->pictq[i];

#if CONFIG_AVFILTER

        avfilter_unref_bufferp(&vp->picref);

#endif

        if (vp->bmp) {

            SDL_FreeYUVOverlay(vp->bmp);

            vp->bmp = NULL;

        }

    }

    SDL_DestroyMutex(is->pictq_mutex);

    SDL_DestroyCond(is->pictq_cond);

    SDL_DestroyMutex(is->subpq_mutex);

    SDL_DestroyCond(is->subpq_cond);

    SDL_DestroyCond(is->continue_read_thread);

#if !CONFIG_AVFILTER

    sws_freeContext(is->img_convert_ctx);

#endif

    av_free(is);

}


static void init_gain_table(COOKContext *q) {

    int i;

    q->gain_size_factor = q->samples_per_channel/8;

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

        q->gain_table[i] = pow((double)q->pow2tab[i+52] ,

                               (1.0/(double)q->gain_size_factor));

    }

    memset(&q->gain_copy, 0, sizeof(COOKgain));

    memset(&q->gain_current, 0, sizeof(COOKgain));

    memset(&q->gain_now, 0, sizeof(COOKgain));

    memset(&q->gain_previous, 0, sizeof(COOKgain));

}


static void qpa_fini_out (HWVoiceOut *hw)

{

    void *ret;

    PAVoiceOut *pa = (PAVoiceOut *) hw;

    audio_pt_lock (&pa->pt, AUDIO_FUNC);

    pa->done = 1;

    audio_pt_unlock_and_signal (&pa->pt, AUDIO_FUNC);

    audio_pt_join (&pa->pt, &ret, AUDIO_FUNC);

    if (pa->s) {

        pa_simple_free (pa->s);

        pa->s = NULL;

    }

    audio_pt_fini (&pa->pt, AUDIO_FUNC);

    g_free (pa->pcm_buf);

    pa->pcm_buf = NULL;

}


static int scsi_device_init(SCSIDevice *s)

{

    SCSIDeviceClass *sc = SCSI_DEVICE_GET_CLASS(s);

    if (sc->init) {

        return sc->init(s);

    }

    return 0;

}


static void set_dirty_bitmap(BlockDriverState *bs, int64_t sector_num,

                             int nb_sectors, int dirty)

{

    int64_t start, end;

    unsigned long val, idx, bit;

    start = sector_num / BDRV_SECTORS_PER_DIRTY_CHUNK;

    end = (sector_num + nb_sectors - 1) / BDRV_SECTORS_PER_DIRTY_CHUNK;

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

        idx = start / (sizeof(unsigned long) * 8);

        bit = start % (sizeof(unsigned long) * 8);

        val = bs->dirty_bitmap[idx];

        if (dirty) {

            val |= 1 << bit;

        } else {

            val &= ~(1 << bit);

        }

        bs->dirty_bitmap[idx] = val;

    }

}


static size_t net_tx_pkt_fetch_fragment(struct NetTxPkt *pkt,

    int *src_idx, size_t *src_offset, struct iovec *dst, int *dst_idx)

{

    size_t fetched = 0;

    struct iovec *src = pkt->vec;

    *dst_idx = NET_TX_PKT_FRAGMENT_HEADER_NUM;

    while (fetched < pkt->virt_hdr.gso_size) {

        /* no more place in fragment iov */

        if (*dst_idx == NET_MAX_FRAG_SG_LIST) {

            break;

        }

        /* no more data in iovec */

        if (*src_idx == (pkt->payload_frags + NET_TX_PKT_PL_START_FRAG)) {

            break;

        }

        dst[*dst_idx].iov_base = src[*src_idx].iov_base + *src_offset;

        dst[*dst_idx].iov_len = MIN(src[*src_idx].iov_len - *src_offset,

            pkt->virt_hdr.gso_size - fetched);

        *src_offset += dst[*dst_idx].iov_len;

        fetched += dst[*dst_idx].iov_len;

        if (*src_offset == src[*src_idx].iov_len) {

            *src_offset = 0;

            (*src_idx)++;

        }

        (*dst_idx)++;

    }

    return fetched;

}


static void lsi_ram_write(void *opaque, target_phys_addr_t addr,

                          uint64_t val, unsigned size)

{

    LSIState *s = opaque;

    uint32_t newval;

    uint32_t mask;

    int shift;

    newval = s->script_ram[addr >> 2];

    shift = (addr & 3) * 8;

    mask = ((uint64_t)1 << (size * 8)) - 1;

    newval &= ~(mask << shift);

    newval |= val << shift;

    s->script_ram[addr >> 2] = newval;

}


static int get_buffer_sao(HEVCContext *s, AVFrame *frame, const HEVCSPS *sps)

{

    int ret, i;

    frame->width  = s->avctx->width  + 2;

    frame->height = s->avctx->height + 2;

    if ((ret = ff_get_buffer(s->avctx, frame, AV_GET_BUFFER_FLAG_REF)) < 0)

        return ret;

    for (i = 0; frame->data[i]; i++) {

        int offset = frame->linesize[i] + (1 << sps->pixel_shift);

        frame->data[i] += offset;

    }

    frame->width  = s->avctx->width;

    frame->height = s->avctx->height;

    return 0;

}


static void avc_luma_vt_16w_msa(const uint8_t *src, int32_t src_stride,

                                uint8_t *dst, int32_t dst_stride,

                                int32_t height)

{

    int32_t loop_cnt;

    int16_t filt_const0 = 0xfb01;

    int16_t filt_const1 = 0x1414;

    int16_t filt_const2 = 0x1fb;

    v16i8 src0, src1, src2, src3, src4, src5, src6, src7, src8;

    v16i8 src10_r, src32_r, src54_r, src76_r, src21_r, src43_r, src65_r;

    v16i8 src87_r, src10_l, src32_l, src54_l, src76_l, src21_l, src43_l;

    v16i8 src65_l, src87_l;

    v8i16 out0_r, out1_r, out2_r, out3_r, out0_l, out1_l, out2_l, out3_l;

    v16u8 res0, res1, res2, res3;

    v16i8 filt0, filt1, filt2;

    filt0 = (v16i8) __msa_fill_h(filt_const0);

    filt1 = (v16i8) __msa_fill_h(filt_const1);

    filt2 = (v16i8) __msa_fill_h(filt_const2);

    LD_SB5(src, src_stride, src0, src1, src2, src3, src4);

    src += (5 * src_stride);

    XORI_B5_128_SB(src0, src1, src2, src3, src4);

    ILVR_B4_SB(src1, src0, src2, src1, src3, src2, src4, src3,

               src10_r, src21_r, src32_r, src43_r);

    ILVL_B4_SB(src1, src0, src2, src1, src3, src2, src4, src3,

               src10_l, src21_l, src32_l, src43_l);

    for (loop_cnt = (height >> 2); loop_cnt--;) {

        LD_SB4(src, src_stride, src5, src6, src7, src8);

        src += (4 * src_stride);

        XORI_B4_128_SB(src5, src6, src7, src8);

        ILVR_B4_SB(src5, src4, src6, src5, src7, src6, src8, src7,

                   src54_r, src65_r, src76_r, src87_r);

        ILVL_B4_SB(src5, src4, src6, src5, src7, src6, src8, src7,

                   src54_l, src65_l, src76_l, src87_l);

        out0_r = DPADD_SH3_SH(src10_r, src32_r, src54_r, filt0, filt1, filt2);

        out1_r = DPADD_SH3_SH(src21_r, src43_r, src65_r, filt0, filt1, filt2);

        out2_r = DPADD_SH3_SH(src32_r, src54_r, src76_r, filt0, filt1, filt2);

        out3_r = DPADD_SH3_SH(src43_r, src65_r, src87_r, filt0, filt1, filt2);

        out0_l = DPADD_SH3_SH(src10_l, src32_l, src54_l, filt0, filt1, filt2);

        out1_l = DPADD_SH3_SH(src21_l, src43_l, src65_l, filt0, filt1, filt2);

        out2_l = DPADD_SH3_SH(src32_l, src54_l, src76_l, filt0, filt1, filt2);

        out3_l = DPADD_SH3_SH(src43_l, src65_l, src87_l, filt0, filt1, filt2);

        SRARI_H4_SH(out0_r, out1_r, out2_r, out3_r, 5);

        SAT_SH4_SH(out0_r, out1_r, out2_r, out3_r, 7);

        SRARI_H4_SH(out0_l, out1_l, out2_l, out3_l, 5);

        SAT_SH4_SH(out0_l, out1_l, out2_l, out3_l, 7);

        PCKEV_B4_UB(out0_l, out0_r, out1_l, out1_r, out2_l, out2_r, out3_l,

                    out3_r, res0, res1, res2, res3);

        XORI_B4_128_UB(res0, res1, res2, res3);

        ST_UB4(res0, res1, res2, res3, dst, dst_stride);

        dst += (4 * dst_stride);

        src10_r = src54_r;

        src32_r = src76_r;

        src21_r = src65_r;

        src43_r = src87_r;

        src10_l = src54_l;

        src32_l = src76_l;

        src21_l = src65_l;

        src43_l = src87_l;

        src4 = src8;

    }

}


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

{

    int c, ret, flags;

    const char *filename, *fmt, *cache, *base;

    BlockBackend *blk;

    BlockDriverState *bs, *base_bs;

    bool progress = false, quiet = false, drop = false;

    bool writethrough;

    Error *local_err = NULL;

    CommonBlockJobCBInfo cbi;

    bool image_opts = false;

    AioContext *aio_context;

    fmt = NULL;

    cache = BDRV_DEFAULT_CACHE;

    base = NULL;

    for(;;) {

        static const struct option long_options[] = {

            {"help", no_argument, 0, 'h'},

            {"object", required_argument, 0, OPTION_OBJECT},

            {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},

            {0, 0, 0, 0}

        };

        c = getopt_long(argc, argv, "f:ht:b:dpq",

                        long_options, NULL);

        if (c == -1) {

            break;

        }

        switch(c) {

        case '?':

        case 'h':

            help();

            break;

        case 'f':

            fmt = optarg;

            break;

        case 't':

            cache = optarg;

            break;

        case 'b':

            base = optarg;

            /* -b implies -d */

            drop = true;

            break;

        case 'd':

            drop = true;

            break;

        case 'p':

            progress = true;

            break;

        case 'q':

            quiet = true;

            break;

        case OPTION_OBJECT: {

            QemuOpts *opts;

            opts = qemu_opts_parse_noisily(&qemu_object_opts,

                                           optarg, true);

            if (!opts) {

                return 1;

            }

        }   break;

        case OPTION_IMAGE_OPTS:

            image_opts = true;

            break;

        }

    }

    /* Progress is not shown in Quiet mode */

    if (quiet) {

        progress = false;

    }

    if (optind != argc - 1) {

        error_exit("Expecting one image file name");

    }

    filename = argv[optind++];

    if (qemu_opts_foreach(&qemu_object_opts,

                          user_creatable_add_opts_foreach,

                          NULL, NULL)) {

        return 1;

    }

    flags = BDRV_O_RDWR | BDRV_O_UNMAP;

    ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);

    if (ret < 0) {

        error_report("Invalid cache option: %s", cache);

        return 1;

    }

    blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet);

    if (!blk) {

        return 1;

    }

    bs = blk_bs(blk);

    qemu_progress_init(progress, 1.f);

    qemu_progress_print(0.f, 100);

    if (base) {

        base_bs = bdrv_find_backing_image(bs, base);

        if (!base_bs) {

            error_setg(&local_err, QERR_BASE_NOT_FOUND, base);

            goto done;

        }

    } else {

        /* This is different from QMP, which by default uses the deepest file in

         * the backing chain (i.e., the very base); however, the traditional

         * behavior of qemu-img commit is using the immediate backing file. */

        base_bs = backing_bs(bs);

        if (!base_bs) {

            error_setg(&local_err, "Image does not have a backing file");

            goto done;

        }

    }

    cbi = (CommonBlockJobCBInfo){

        .errp = &local_err,

        .bs   = bs,

    };

    aio_context = bdrv_get_aio_context(bs);

    aio_context_acquire(aio_context);

    commit_active_start("commit", bs, base_bs, BLOCK_JOB_DEFAULT, 0,

                        BLOCKDEV_ON_ERROR_REPORT, common_block_job_cb, &cbi,

                        &local_err, false);

    aio_context_release(aio_context);

    if (local_err) {

        goto done;

    }

    /* When the block job completes, the BlockBackend reference will point to

     * the old backing file. In order to avoid that the top image is already

     * deleted, so we can still empty it afterwards, increment the reference

     * counter here preemptively. */

    if (!drop) {

        bdrv_ref(bs);

    }

    run_block_job(bs->job, &local_err);

    if (local_err) {

        goto unref_backing;

    }

    if (!drop && bs->drv->bdrv_make_empty) {

        ret = bs->drv->bdrv_make_empty(bs);

        if (ret) {

            error_setg_errno(&local_err, -ret, "Could not empty %s",

                             filename);

            goto unref_backing;

        }

    }

unref_backing:

    if (!drop) {

        bdrv_unref(bs);

    }

done:

    qemu_progress_end();

    blk_unref(blk);

    if (local_err) {

        error_report_err(local_err);

        return 1;

    }

    qprintf(quiet, "Image committed.\n");

    return 0;

}


unsigned long setup_arg_pages(void * mh, char ** argv, char ** env)

{

    unsigned long stack_base, error, size;

    int i;

    int * stack;

    int argc, envc;

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

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

     */

    size = stack_size;

    error = target_mmap(0,

                        size + qemu_host_page_size,

                        PROT_READ | PROT_WRITE,

                        MAP_PRIVATE | MAP_ANONYMOUS,

                        -1, 0);

    if (error == -1)

        qerror("stk mmap");

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

    target_mprotect(error + size, qemu_host_page_size, PROT_NONE);

    stack_base = error + size;

    stack = (void*)stack_base;

/*

 *    | STRING AREA |

 *    +-------------+

 *    |      0      |

*    +-------------+

 *    |  apple[n]   |

 *    +-------------+

 *           :

 *    +-------------+

 *    |  apple[0]   |

 *    +-------------+

 *    |      0      |

 *    +-------------+

 *    |    env[n]   |

 *    +-------------+

 *           :

 *           :

 *    +-------------+

 *    |    env[0]   |

 *    +-------------+

 *    |      0      |

 *    +-------------+

 *    | arg[argc-1] |

 *    +-------------+

 *           :

 *           :

 *    +-------------+

 *    |    arg[0]   |

 *    +-------------+

 *    |     argc    |

 *    +-------------+

 * sp->    |      mh     | address of where the a.out's file offset 0 is in memory

 *    +-------------+

*/

    /* Construct the stack Stack grows down */

    stack--;

    /* XXX: string should go up there */

    *stack = 0;

    stack--;

    /* Push the absolute path of our executable */

    DPRINTF("pushing apple %s (0x%x)\n", (char*)argv[0], (int)argv[0]);

    stl(stack, (int) argv[0]);

    stack--;

    stl(stack, 0);

    stack--;

    /* Get envc */

    for(envc = 0; env[envc]; envc++);

    for(i = envc-1; i >= 0; i--)

    {

        DPRINTF("pushing env %s (0x%x)\n", (char*)env[i], (int)env[i]);

        stl(stack, (int)env[i]);

        stack--;

        /* XXX: remove that when string will be on top of the stack */

        page_set_flags((int)env[i], (int)(env[i]+strlen(env[i])), PROT_READ | PAGE_VALID);

    }

    /* Add on the stack the interp_prefix choosen if so */

    if(interp_prefix[0])

    {

        char *dyld_root;

        asprintf(&dyld_root, "DYLD_ROOT_PATH=%s", interp_prefix);

        page_set_flags((int)dyld_root, (int)(dyld_root+strlen(interp_prefix)+1), PROT_READ | PAGE_VALID);

        stl(stack, (int)dyld_root);

        stack--;

    }

#ifdef DONT_USE_DYLD_SHARED_MAP

    {

        char *shared_map_mode;

        asprintf(&shared_map_mode, "DYLD_SHARED_REGION=avoid");

        page_set_flags((int)shared_map_mode, (int)(shared_map_mode+strlen(shared_map_mode)+1), PROT_READ | PAGE_VALID);

        stl(stack, (int)shared_map_mode);

        stack--;

    }

#endif

#ifdef ACTIVATE_DYLD_TRACE

    char * extra_env_static[] = {"DYLD_DEBUG_TRACE=yes",

    "DYLD_PREBIND_DEBUG=3", "DYLD_UNKNOW_TRACE=yes",

    "DYLD_PRINT_INITIALIZERS=yes",

    "DYLD_PRINT_SEGMENTS=yes", "DYLD_PRINT_REBASINGS=yes", "DYLD_PRINT_BINDINGS=yes", "DYLD_PRINT_INITIALIZERS=yes", "DYLD_PRINT_WARNINGS=yes" };

    char ** extra_env = malloc(sizeof(extra_env_static));

    bcopy(extra_env_static, extra_env, sizeof(extra_env_static));

    page_set_flags((int)extra_env, (int)((void*)extra_env+sizeof(extra_env_static)), PROT_READ | PAGE_VALID);

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

    {

        DPRINTF("pushing (extra) env %s (0x%x)\n", (char*)extra_env[i], (int)extra_env[i]);

        stl(stack, (int) extra_env[i]);

        stack--;

    }

#endif

    stl(stack, 0);

    stack--;

    /* Get argc */

    for(argc = 0; argv[argc]; argc++);

    for(i = argc-1; i >= 0; i--)

    {

        DPRINTF("pushing arg %s (0x%x)\n", (char*)argv[i], (int)argv[i]);

        stl(stack, (int) argv[i]);

        stack--;

        /* XXX: remove that when string will be on top of the stack */

        page_set_flags((int)argv[i], (int)(argv[i]+strlen(argv[i])), PROT_READ | PAGE_VALID);

    }

    DPRINTF("pushing argc %d \n", argc);

    stl(stack, argc);

    stack--;

    DPRINTF("pushing mh 0x%x \n", (int)mh);

    stl(stack, (int) mh);

    /* Stack points on the mh */

    return (unsigned long)stack;

}


int sd_do_command(SDState *sd, SDRequest *req,

                  uint8_t *response) {

    uint32_t last_status = sd->card_status;

    sd_rsp_type_t rtype;

    int rsplen;

    if (!sd->bdrv || !bdrv_is_inserted(sd->bdrv) || !sd->enable) {

        return 0;

    }

    if (sd_req_crc_validate(req)) {

        sd->card_status |= COM_CRC_ERROR;

        rtype = sd_illegal;

        goto send_response;

    }

    sd->card_status &= ~CARD_STATUS_B;

    sd_set_status(sd);

    if (last_status & CARD_IS_LOCKED) {

        if (!cmd_valid_while_locked(sd, req)) {

            sd->card_status |= ILLEGAL_COMMAND;

            fprintf(stderr, "SD: Card is locked\n");

            rtype = sd_illegal;

            goto send_response;

        }

    }

    if (last_status & APP_CMD) {

        rtype = sd_app_command(sd, *req);

        sd->card_status &= ~APP_CMD;

    } else

        rtype = sd_normal_command(sd, *req);

    if (rtype == sd_illegal) {

        sd->card_status |= ILLEGAL_COMMAND;

    }

    sd->current_cmd = req->cmd;

send_response:

    switch (rtype) {

    case sd_r1:

    case sd_r1b:

        sd_response_r1_make(sd, response, last_status);

        rsplen = 4;

        break;

    case sd_r2_i:

        memcpy(response, sd->cid, sizeof(sd->cid));

        rsplen = 16;

        break;

    case sd_r2_s:

        memcpy(response, sd->csd, sizeof(sd->csd));

        rsplen = 16;

        break;

    case sd_r3:

        sd_response_r3_make(sd, response);

        rsplen = 4;

        break;

    case sd_r6:

        sd_response_r6_make(sd, response);

        rsplen = 4;

        break;

    case sd_r7:

        sd_response_r7_make(sd, response);

        rsplen = 4;

        break;

    case sd_r0:

    case sd_illegal:

    default:

        rsplen = 0;

        break;

    }

#ifdef DEBUG_SD

    if (rsplen) {

        int i;

        DPRINTF("Response:");

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

            printf(" %02x", response[i]);

        printf(" state %d\n", sd->state);

    } else {

        DPRINTF("No response %d\n", sd->state);

    }

#endif

    return rsplen;

}


void cpu_x86_cpuid(CPUX86State *env, uint32_t index, uint32_t count,

                   uint32_t *eax, uint32_t *ebx,

                   uint32_t *ecx, uint32_t *edx)

{

    X86CPU *cpu = x86_env_get_cpu(env);

    CPUState *cs = CPU(cpu);

    uint32_t pkg_offset;

    /* test if maximum index reached */

    if (index & 0x80000000) {

        if (index > env->cpuid_xlevel) {

            if (env->cpuid_xlevel2 > 0) {

                /* Handle the Centaur's CPUID instruction. */

                if (index > env->cpuid_xlevel2) {

                    index = env->cpuid_xlevel2;

                } else if (index < 0xC0000000) {

                    index = env->cpuid_xlevel;

                }

            } else {

                /* Intel documentation states that invalid EAX input will

                 * return the same information as EAX=cpuid_level

                 * (Intel SDM Vol. 2A - Instruction Set Reference - CPUID)

                 */

                index =  env->cpuid_level;

            }

        }

    } else {

        if (index > env->cpuid_level)

            index = env->cpuid_level;

    }

    switch(index) {

    case 0:

        *eax = env->cpuid_level;

        *ebx = env->cpuid_vendor1;

        *edx = env->cpuid_vendor2;

        *ecx = env->cpuid_vendor3;

        break;

    case 1:

        *eax = env->cpuid_version;

        *ebx = (cpu->apic_id << 24) |

               8 << 8; /* CLFLUSH size in quad words, Linux wants it. */

        *ecx = env->features[FEAT_1_ECX];

        if ((*ecx & CPUID_EXT_XSAVE) && (env->cr[4] & CR4_OSXSAVE_MASK)) {

            *ecx |= CPUID_EXT_OSXSAVE;

        }

        *edx = env->features[FEAT_1_EDX];

        if (cs->nr_cores * cs->nr_threads > 1) {

            *ebx |= (cs->nr_cores * cs->nr_threads) << 16;

            *edx |= CPUID_HT;

        }

        break;

    case 2:

        /* cache info: needed for Pentium Pro compatibility */

        if (cpu->cache_info_passthrough) {

            host_cpuid(index, 0, eax, ebx, ecx, edx);

            break;

        }

        *eax = 1; /* Number of CPUID[EAX=2] calls required */

        *ebx = 0;

        if (!cpu->enable_l3_cache) {

            *ecx = 0;

        } else {

            *ecx = L3_N_DESCRIPTOR;

        }

        *edx = (L1D_DESCRIPTOR << 16) | \

               (L1I_DESCRIPTOR <<  8) | \

               (L2_DESCRIPTOR);

        break;

    case 4:

        /* cache info: needed for Core compatibility */

        if (cpu->cache_info_passthrough) {

            host_cpuid(index, count, eax, ebx, ecx, edx);

            *eax &= ~0xFC000000;

        } else {

            *eax = 0;

            switch (count) {

            case 0: /* L1 dcache info */

                *eax |= CPUID_4_TYPE_DCACHE | \

                        CPUID_4_LEVEL(1) | \

                        CPUID_4_SELF_INIT_LEVEL;

                *ebx = (L1D_LINE_SIZE - 1) | \

                       ((L1D_PARTITIONS - 1) << 12) | \

                       ((L1D_ASSOCIATIVITY - 1) << 22);

                *ecx = L1D_SETS - 1;

                *edx = CPUID_4_NO_INVD_SHARING;

                break;

            case 1: /* L1 icache info */

                *eax |= CPUID_4_TYPE_ICACHE | \

                        CPUID_4_LEVEL(1) | \

                        CPUID_4_SELF_INIT_LEVEL;

                *ebx = (L1I_LINE_SIZE - 1) | \

                       ((L1I_PARTITIONS - 1) << 12) | \

                       ((L1I_ASSOCIATIVITY - 1) << 22);

                *ecx = L1I_SETS - 1;

                *edx = CPUID_4_NO_INVD_SHARING;

                break;

            case 2: /* L2 cache info */

                *eax |= CPUID_4_TYPE_UNIFIED | \

                        CPUID_4_LEVEL(2) | \

                        CPUID_4_SELF_INIT_LEVEL;

                if (cs->nr_threads > 1) {

                    *eax |= (cs->nr_threads - 1) << 14;

                }

                *ebx = (L2_LINE_SIZE - 1) | \

                       ((L2_PARTITIONS - 1) << 12) | \

                       ((L2_ASSOCIATIVITY - 1) << 22);

                *ecx = L2_SETS - 1;

                *edx = CPUID_4_NO_INVD_SHARING;

                break;

            case 3: /* L3 cache info */

                if (!cpu->enable_l3_cache) {

                    *eax = 0;

                    *ebx = 0;

                    *ecx = 0;

                    *edx = 0;

                    break;

                }

                *eax |= CPUID_4_TYPE_UNIFIED | \

                        CPUID_4_LEVEL(3) | \

                        CPUID_4_SELF_INIT_LEVEL;

                pkg_offset = apicid_pkg_offset(cs->nr_cores, cs->nr_threads);

                *eax |= ((1 << pkg_offset) - 1) << 14;

                *ebx = (L3_N_LINE_SIZE - 1) | \

                       ((L3_N_PARTITIONS - 1) << 12) | \

                       ((L3_N_ASSOCIATIVITY - 1) << 22);

                *ecx = L3_N_SETS - 1;

                *edx = CPUID_4_INCLUSIVE | CPUID_4_COMPLEX_IDX;

                break;

            default: /* end of info */

                *eax = 0;

                *ebx = 0;

                *ecx = 0;

                *edx = 0;

                break;

            }

        }

        /* QEMU gives out its own APIC IDs, never pass down bits 31..26.  */

        if ((*eax & 31) && cs->nr_cores > 1) {

            *eax |= (cs->nr_cores - 1) << 26;

        }

        break;

    case 5:

        /* mwait info: needed for Core compatibility */

        *eax = 0; /* Smallest monitor-line size in bytes */

        *ebx = 0; /* Largest monitor-line size in bytes */

        *ecx = CPUID_MWAIT_EMX | CPUID_MWAIT_IBE;

        *edx = 0;

        break;

    case 6:

        /* Thermal and Power Leaf */

        *eax = env->features[FEAT_6_EAX];

        *ebx = 0;

        *ecx = 0;

        *edx = 0;

        break;

    case 7:

        /* Structured Extended Feature Flags Enumeration Leaf */

        if (count == 0) {

            *eax = 0; /* Maximum ECX value for sub-leaves */

            *ebx = env->features[FEAT_7_0_EBX]; /* Feature flags */

            *ecx = env->features[FEAT_7_0_ECX]; /* Feature flags */

            if ((*ecx & CPUID_7_0_ECX_PKU) && env->cr[4] & CR4_PKE_MASK) {

                *ecx |= CPUID_7_0_ECX_OSPKE;

            }

            *edx = 0; /* Reserved */

        } else {

            *eax = 0;

            *ebx = 0;

            *ecx = 0;

            *edx = 0;

        }

        break;

    case 9:

        /* Direct Cache Access Information Leaf */

        *eax = 0; /* Bits 0-31 in DCA_CAP MSR */

        *ebx = 0;

        *ecx = 0;

        *edx = 0;

        break;

    case 0xA:

        /* Architectural Performance Monitoring Leaf */

        if (kvm_enabled() && cpu->enable_pmu) {

            KVMState *s = cs->kvm_state;

            *eax = kvm_arch_get_supported_cpuid(s, 0xA, count, R_EAX);

            *ebx = kvm_arch_get_supported_cpuid(s, 0xA, count, R_EBX);

            *ecx = kvm_arch_get_supported_cpuid(s, 0xA, count, R_ECX);

            *edx = kvm_arch_get_supported_cpuid(s, 0xA, count, R_EDX);

        } else {

            *eax = 0;

            *ebx = 0;

            *ecx = 0;

            *edx = 0;

        }

        break;

    case 0xB:

        /* Extended Topology Enumeration Leaf */

        if (!cpu->enable_cpuid_0xb) {

                *eax = *ebx = *ecx = *edx = 0;

                break;

        }

        *ecx = count & 0xff;

        *edx = cpu->apic_id;

        switch (count) {

        case 0:

            *eax = apicid_core_offset(cs->nr_cores, cs->nr_threads);

            *ebx = cs->nr_threads;

            *ecx |= CPUID_TOPOLOGY_LEVEL_SMT;

            break;

        case 1:

            *eax = apicid_pkg_offset(cs->nr_cores, cs->nr_threads);

            *ebx = cs->nr_cores * cs->nr_threads;

            *ecx |= CPUID_TOPOLOGY_LEVEL_CORE;

            break;

        default:

            *eax = 0;

            *ebx = 0;

            *ecx |= CPUID_TOPOLOGY_LEVEL_INVALID;

        }

        assert(!(*eax & ~0x1f));

        *ebx &= 0xffff; /* The count doesn't need to be reliable. */

        break;

    case 0xD: {

        KVMState *s = cs->kvm_state;

        uint64_t ena_mask;

        int i;

        /* Processor Extended State */

        *eax = 0;

        *ebx = 0;

        *ecx = 0;

        *edx = 0;

        if (!(env->features[FEAT_1_ECX] & CPUID_EXT_XSAVE)) {

            break;

        }

        if (kvm_enabled()) {

            ena_mask = kvm_arch_get_supported_cpuid(s, 0xd, 0, R_EDX);

            ena_mask <<= 32;

            ena_mask |= kvm_arch_get_supported_cpuid(s, 0xd, 0, R_EAX);

        } else {

            ena_mask = -1;

        }

        if (count == 0) {

            *ecx = 0x240;

            for (i = 2; i < ARRAY_SIZE(x86_ext_save_areas); i++) {

                const ExtSaveArea *esa = &x86_ext_save_areas[i];

                if ((env->features[esa->feature] & esa->bits) == esa->bits

                    && ((ena_mask >> i) & 1) != 0) {

                    if (i < 32) {

                        *eax |= 1u << i;

                    } else {

                        *edx |= 1u << (i - 32);

                    }

                    *ecx = MAX(*ecx, esa->offset + esa->size);

                }

            }

            *eax |= ena_mask & (XSTATE_FP_MASK | XSTATE_SSE_MASK);

            *ebx = *ecx;

        } else if (count == 1) {

            *eax = env->features[FEAT_XSAVE];

        } else if (count < ARRAY_SIZE(x86_ext_save_areas)) {

            const ExtSaveArea *esa = &x86_ext_save_areas[count];

            if ((env->features[esa->feature] & esa->bits) == esa->bits

                && ((ena_mask >> count) & 1) != 0) {

                *eax = esa->size;

                *ebx = esa->offset;

            }

        }

        break;

    }

    case 0x80000000:

        *eax = env->cpuid_xlevel;

        *ebx = env->cpuid_vendor1;

        *edx = env->cpuid_vendor2;

        *ecx = env->cpuid_vendor3;

        break;

    case 0x80000001:

        *eax = env->cpuid_version;

        *ebx = 0;

        *ecx = env->features[FEAT_8000_0001_ECX];

        *edx = env->features[FEAT_8000_0001_EDX];

        /* The Linux kernel checks for the CMPLegacy bit and

         * discards multiple thread information if it is set.

         * So don't set it here for Intel to make Linux guests happy.

         */

        if (cs->nr_cores * cs->nr_threads > 1) {

            if (env->cpuid_vendor1 != CPUID_VENDOR_INTEL_1 ||

                env->cpuid_vendor2 != CPUID_VENDOR_INTEL_2 ||

                env->cpuid_vendor3 != CPUID_VENDOR_INTEL_3) {

                *ecx |= 1 << 1;    /* CmpLegacy bit */

            }

        }

        break;

    case 0x80000002:

    case 0x80000003:

    case 0x80000004:

        *eax = env->cpuid_model[(index - 0x80000002) * 4 + 0];

        *ebx = env->cpuid_model[(index - 0x80000002) * 4 + 1];

        *ecx = env->cpuid_model[(index - 0x80000002) * 4 + 2];

        *edx = env->cpuid_model[(index - 0x80000002) * 4 + 3];

        break;

    case 0x80000005:

        /* cache info (L1 cache) */

        if (cpu->cache_info_passthrough) {

            host_cpuid(index, 0, eax, ebx, ecx, edx);

            break;

        }

        *eax = (L1_DTLB_2M_ASSOC << 24) | (L1_DTLB_2M_ENTRIES << 16) | \

               (L1_ITLB_2M_ASSOC <<  8) | (L1_ITLB_2M_ENTRIES);

        *ebx = (L1_DTLB_4K_ASSOC << 24) | (L1_DTLB_4K_ENTRIES << 16) | \

               (L1_ITLB_4K_ASSOC <<  8) | (L1_ITLB_4K_ENTRIES);

        *ecx = (L1D_SIZE_KB_AMD << 24) | (L1D_ASSOCIATIVITY_AMD << 16) | \

               (L1D_LINES_PER_TAG << 8) | (L1D_LINE_SIZE);

        *edx = (L1I_SIZE_KB_AMD << 24) | (L1I_ASSOCIATIVITY_AMD << 16) | \

               (L1I_LINES_PER_TAG << 8) | (L1I_LINE_SIZE);

        break;

    case 0x80000006:

        /* cache info (L2 cache) */

        if (cpu->cache_info_passthrough) {

            host_cpuid(index, 0, eax, ebx, ecx, edx);

            break;

        }

        *eax = (AMD_ENC_ASSOC(L2_DTLB_2M_ASSOC) << 28) | \

               (L2_DTLB_2M_ENTRIES << 16) | \

               (AMD_ENC_ASSOC(L2_ITLB_2M_ASSOC) << 12) | \

               (L2_ITLB_2M_ENTRIES);

        *ebx = (AMD_ENC_ASSOC(L2_DTLB_4K_ASSOC) << 28) | \

               (L2_DTLB_4K_ENTRIES << 16) | \

               (AMD_ENC_ASSOC(L2_ITLB_4K_ASSOC) << 12) | \

               (L2_ITLB_4K_ENTRIES);

        *ecx = (L2_SIZE_KB_AMD << 16) | \

               (AMD_ENC_ASSOC(L2_ASSOCIATIVITY) << 12) | \

               (L2_LINES_PER_TAG << 8) | (L2_LINE_SIZE);

        if (!cpu->enable_l3_cache) {

            *edx = ((L3_SIZE_KB / 512) << 18) | \

                   (AMD_ENC_ASSOC(L3_ASSOCIATIVITY) << 12) | \

                   (L3_LINES_PER_TAG << 8) | (L3_LINE_SIZE);

        } else {

            *edx = ((L3_N_SIZE_KB_AMD / 512) << 18) | \

                   (AMD_ENC_ASSOC(L3_N_ASSOCIATIVITY) << 12) | \

                   (L3_N_LINES_PER_TAG << 8) | (L3_N_LINE_SIZE);

        }

        break;

    case 0x80000007:

        *eax = 0;

        *ebx = 0;

        *ecx = 0;

        *edx = env->features[FEAT_8000_0007_EDX];

        break;

    case 0x80000008:

        /* virtual & phys address size in low 2 bytes. */

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

            /* 64 bit processor, 48 bits virtual, configurable

             * physical bits.

             */

            *eax = 0x00003000 + cpu->phys_bits;

        } else {

            *eax = cpu->phys_bits;

        }

        *ebx = 0;

        *ecx = 0;

        *edx = 0;

        if (cs->nr_cores * cs->nr_threads > 1) {

            *ecx |= (cs->nr_cores * cs->nr_threads) - 1;

        }

        break;

    case 0x8000000A:

        if (env->features[FEAT_8000_0001_ECX] & CPUID_EXT3_SVM) {

            *eax = 0x00000001; /* SVM Revision */

            *ebx = 0x00000010; /* nr of ASIDs */

            *ecx = 0;

            *edx = env->features[FEAT_SVM]; /* optional features */

        } else {

            *eax = 0;

            *ebx = 0;

            *ecx = 0;

            *edx = 0;

        }

        break;

    case 0xC0000000:

        *eax = env->cpuid_xlevel2;

        *ebx = 0;

        *ecx = 0;

        *edx = 0;

        break;

    case 0xC0000001:

        /* Support for VIA CPU's CPUID instruction */

        *eax = env->cpuid_version;

        *ebx = 0;

        *ecx = 0;

        *edx = env->features[FEAT_C000_0001_EDX];

        break;

    case 0xC0000002:

    case 0xC0000003:

    case 0xC0000004:

        /* Reserved for the future, and now filled with zero */

        *eax = 0;

        *ebx = 0;

        *ecx = 0;

        *edx = 0;

        break;

    default:

        /* reserved values: zero */

        *eax = 0;

        *ebx = 0;

        *ecx = 0;

        *edx = 0;

        break;

    }

}


static void prepare_app_arguments(int *argc_ptr, char ***argv_ptr)

{

    char *argstr_flat;

    wchar_t **argv_w;

    int i, buffsize = 0, offset = 0;

    if (win32_argv_utf8) {

        *argc_ptr = win32_argc;

        *argv_ptr = win32_argv_utf8;

        return;

    }

    win32_argc = 0;

    argv_w = CommandLineToArgvW(GetCommandLineW(), &win32_argc);

    if (win32_argc <= 0 || !argv_w)

        return;

    /* determine the UTF-8 buffer size (including NULL-termination symbols) */

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

        buffsize += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,

                                        NULL, 0, NULL, NULL);

    win32_argv_utf8 = av_mallocz(sizeof(char *) * (win32_argc + 1) + buffsize);

    argstr_flat     = (char *)win32_argv_utf8 + sizeof(char *) * (win32_argc + 1);

    if (win32_argv_utf8 == NULL) {

        LocalFree(argv_w);

        return;

    }

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

        win32_argv_utf8[i] = &argstr_flat[offset];

        offset += WideCharToMultiByte(CP_UTF8, 0, argv_w[i], -1,

                                      &argstr_flat[offset],

                                      buffsize - offset, NULL, NULL);

    }

    win32_argv_utf8[i] = NULL;

    LocalFree(argv_w);

    *argc_ptr = win32_argc;

    *argv_ptr = win32_argv_utf8;

}


static inline void gen_neon_addl_saturate(TCGv op0, TCGv op1, int size)

{

    switch (size) {

    case 1: gen_helper_neon_addl_saturate_s32(op0, cpu_env, op0, op1); break;

    case 2: gen_helper_neon_addl_saturate_s64(op0, cpu_env, op0, op1); break;

    default: abort();

    }

}


int MP3lame_encode_frame(AVCodecContext *avctx,

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

{

	Mp3AudioContext *s = avctx->priv_data;

	int num, i;

//av_log(avctx, AV_LOG_DEBUG, "%X %d %X\n", (int)frame, buf_size, (int)data);

//        if(data==NULL)

//            return lame_encode_flush(s->gfp, frame, buf_size);

	/* lame 3.91 dies on '1-channel interleaved' data */

	if (s->stereo) {

		num = lame_encode_buffer_interleaved(s->gfp, data,

			MPA_FRAME_SIZE, frame, buf_size);

	} else {

		num = lame_encode_buffer(s->gfp, data, data, MPA_FRAME_SIZE,

			frame, buf_size);

/*av_log(avctx, AV_LOG_DEBUG, "in:%d out:%d\n", MPA_FRAME_SIZE, num);

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

    av_log(avctx, AV_LOG_DEBUG, "%2X ", frame[i]);

}*/

	}

	return num;

}


int qemu_chr_fe_read_all(CharDriverState *s, uint8_t *buf, int len)

{

    int offset = 0, counter = 10;

    int res;

    if (!s->chr_sync_read) {

        return 0;

    }

    if (s->replay && replay_mode == REPLAY_MODE_PLAY) {

        return replay_char_read_all_load(buf);

    }

    while (offset < len) {

        do {

            res = s->chr_sync_read(s, buf + offset, len - offset);

            if (res == -1 && errno == EAGAIN) {

                g_usleep(100);

            }

        } while (res == -1 && errno == EAGAIN);

        if (res == 0) {

            break;

        }

        if (res < 0) {

            if (s->replay && replay_mode == REPLAY_MODE_RECORD) {

                replay_char_read_all_save_error(res);

            }

            return res;

        }

        offset += res;

        if (!counter--) {

            break;

        }

    }

    if (s->replay && replay_mode == REPLAY_MODE_RECORD) {

        replay_char_read_all_save_buf(buf, offset);

    }

    return offset;

}


static int decode_b_picture_secondary_header(VC9Context *v)

{

    GetBitContext *gb = &v->s.gb;

    int status;

    bitplane_decoding(&v->skip_mb_plane, v);

    if (status < 0) return -1;

#if TRACE

    if (v->mv_mode == MV_PMODE_MIXED_MV)

    {

        status = bitplane_decoding(&v->mv_type_mb_plane, v);

        if (status < 0)

            return -1;

#if TRACE

        av_log(v->s.avctx, AV_LOG_DEBUG, "MB MV Type plane encoding: "

               "Imode: %i, Invert: %i\n", status>>1, status&1);

#endif

    }

    //bitplane

    status = bitplane_decoding(&v->direct_mb_plane, v);

    if (status < 0) return -1;

#if TRACE

    av_log(v->s.avctx, AV_LOG_DEBUG, "MB Direct plane encoding: "

           "Imode: %i, Invert: %i\n", status>>1, status&1);

#endif

    av_log(v->s.avctx, AV_LOG_DEBUG, "Skip MB plane encoding: "

           "Imode: %i, Invert: %i\n", status>>1, status&1);

#endif

    /* FIXME: what is actually chosen for B frames ? */

    v->s.mv_table_index = get_bits(gb, 2); //but using vc9_ tables

    v->cbpcy_vlc = &vc9_cbpcy_p_vlc[get_bits(gb, 2)];

    if (v->dquant)

    {

        vop_dquant_decoding(v);

    }

    if (v->vstransform)

    {

        v->ttmbf = get_bits(gb, 1);

        if (v->ttmbf)

        {

            v->ttfrm = get_bits(gb, 2);

            av_log(v->s.avctx, AV_LOG_INFO, "Transform used: %ix%i\n",

                   (v->ttfrm & 2) ? 4 : 8, (v->ttfrm & 1) ? 4 : 8);

        }

    }

    /* Epilog (AC/DC syntax) should be done in caller */

    return 0;

}


static int mxf_get_stream_index(AVFormatContext *s, KLVPacket *klv)

{

    int i;

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

        MXFTrack *track = s->streams[i]->priv_data;

        /* SMPTE 379M 7.3 */

        if (!memcmp(klv->key + sizeof(mxf_essence_element_key), track->track_number, sizeof(track->track_number)))

            return i;

    }

    /* return 0 if only one stream, for OP Atom files with 0 as track number */

    return s->nb_streams == 1 ? 0 : -1;

}